diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml new file mode 100644 index 000000000..e19902e8c --- /dev/null +++ b/.github/workflows/formats.yml @@ -0,0 +1,111 @@ +name: Shared format crates + +on: + push: + branches: [main] + paths: + - "crates/xml/**" + - "crates/mime/**" + - "crates/cfb/**" + - "crates/mesh/**" + - "crates/metafile/**" + - "crates/dxf/**" + - "crates/gcode/**" + - "crates/svg-paths/**" + - "crates/silhouette-studio/**" + - "crates/tiff/**" + - "crates/heif/**" + - "crates/cms/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/formats.yml" + pull_request: + paths: + - "crates/xml/**" + - "crates/mime/**" + - "crates/cfb/**" + - "crates/mesh/**" + - "crates/metafile/**" + - "crates/dxf/**" + - "crates/gcode/**" + - "crates/svg-paths/**" + - "crates/silhouette-studio/**" + - "crates/tiff/**" + - "crates/heif/**" + - "crates/cms/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/formats.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # Pull requests share one group per branch, so a newer push cancels the older run. Every other + # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it + # always gets to save the cache. + group: shared-formats-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + check: + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + # `features`: each is linted alone, so code that needs another feature fails here. + - { crate: craft-xml, features: "" } + - { crate: craft-mime, features: "" } + - { crate: craft-cfb, features: "" } + - { crate: craft-mesh, features: "stl obj ply gltf" } + - { crate: craft-metafile, features: "write" } + - { crate: craft-dxf, features: "" } + - { crate: craft-gcode, features: "" } + - { crate: craft-svg-paths, features: "" } + - { crate: craft-silhouette-studio, features: "" } + - { crate: craft-tiff, features: "" } + - { crate: craft-heif, features: "testdata" } + - { crate: craft-cms, features: "" } + name: ${{ matrix.crate }} lint, tests, WASM + runs-on: ubuntu-latest + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + with: + components: rustfmt, clippy + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: ${{ matrix.crate }} + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo fmt -p "$CRATE" --check + env: + CRATE: ${{ matrix.crate }} + - name: Clippy, default features and each feature alone + env: + CRATE: ${{ matrix.crate }} + FEATURES: ${{ matrix.features }} + run: | + cargo clippy -p "$CRATE" --all-targets --locked -- -D warnings + for f in $FEATURES; do + echo "::group::feature: $f" + cargo clippy -p "$CRATE" --all-targets --locked --no-default-features --features "$f" -- -D warnings + echo "::endgroup::" + done + - run: cargo clippy -p "$CRATE" --all-targets --locked --all-features -- -D warnings + env: + CRATE: ${{ matrix.crate }} + - run: cargo test -p "$CRATE" --all-features --locked + env: + CRATE: ${{ matrix.crate }} + - run: cargo check -p "$CRATE" --all-features --locked --target wasm32-unknown-unknown + env: + CRATE: ${{ matrix.crate }} diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 1f88bd5d1..654fe4c02 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -20,4 +20,8 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main with: pdf-test-fonts: true + # The codec and format code behind features that are off by default. Without these the + # coverage build never compiles it, and new code there reads as untested. + cargo-features: >- + craft-video/dnx,craft-video/vp8,craft-video/prores,craft-video/h264,craft-video/hevc,craft-video/vp9,craft-video/av1,craft-video/threads,craft-audio/decode,craft-audio/encode,craft-audio/peaks,craft-audio/rayon,craft-audio/serde,craft-media/matroska,craft-media/ogg,craft-media/bitstream,craft-media/serde,craft-mesh/stl,craft-mesh/obj,craft-mesh/ply,craft-mesh/gltf,craft-metafile/write secrets: inherit diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index 1c4e063d1..ec1c16eda 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -40,7 +40,7 @@ jobs: # Each feature on its own, so code that needs another feature fails here. - name: Clippy, each feature alone run: | - for f in "" dnx vp8 prores h264 hevc vp9 av1 threads; do + for f in "" dnx vp8 prores h264 hevc vp9 vp9-decode vp9-encode av1 threads; do echo "::group::features: ${f:-none}" cargo clippy -p craft-video --all-targets --locked --no-default-features ${f:+--features "$f"} -- -D warnings echo "::endgroup::" diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index bfe2b07c7..817cbff2a 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -28,6 +28,7 @@ author, source and license. Library code and original assets are under the repos | `crates/crw/tests/samples.json` (manifest only; the 11 raw files are not bundled, `scripts/fetch-crw-samples.py` downloads them outside the checkout) | The photographers who contributed each file to raw.pixls.us (Canon EOS D30, D60, 10D ×3, 300D ×2, Digital Rebel, PowerShot G1, G5, G6) | [raw.pixls.us](https://raw.pixls.us/), each file's `getfile.php` URL and SHA-256 in the manifest | CC0-1.0 (as published by raw.pixls.us for each file) | | `crates/crw/src/tables.rs`, `crates/crw/clean-room/logs/table_sel*.json` | craft-crw contributors (derived in LightCraft, 2026-10, by known-plaintext alignment of the sample files' entropy streams; `crates/crw/clean-room/02-crw-format.md`) | this repository | MIT OR Apache-2.0 | | `crates/crw/clean-room/logs/private-corpus.tsv` (file names, sizes and SHA-256 of the maintainer's own EOS D60 files; no image content) | craft-crw contributors (LightCraft derivation record) | this repository | MIT OR Apache-2.0 | +| `crates/prc/src/acof/table.rs` (the rows of the PRC `Double` prefix-code table, reformatted as Rust tuples) | Kristof Ralovich (prc-rs); the table is defined by ISO 14739-1 | [ralovich/prc-rs@287b671](https://github.com/ralovich/prc-rs/blob/287b671bb5b31b05efb5ec1b98f7c359b9e4dd7d/src/double.rs), through [PdfCraft `crates/prc`](https://github.com/storytold/pdfcraft/tree/80e26e674d1aa33078e83c8139875047f3289eb6/crates/prc) | MIT (`licenses/prc-rs/LICENSE.txt`; the notice is also in the file header) | Original assets are covered by the repository licence. @@ -79,6 +80,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso | `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged | | `crates/audio/src/ac3/golden_frames.bin` | FilmCraft contributors (original work: 12 AC-3 and E-AC-3 syncframes that ffmpeg's `ac3` and `eac3` encoders made from tones and seeded noise synthesised by ffmpeg's lavfi generators; no third-party or recorded audio) | [FilmCraft `crates/ac3`](https://github.com/storytold/filmcraft/tree/1c9c2e82/crates/ac3/src) | MIT OR Apache-2.0 | | `crates/audio/tests/fixtures/` | SoundCraft and craft-libs contributors (original work: 0.1 s test tones from ffmpeg's `sine` generator and hand-built silent MPEG frames; no third-party or recorded audio; commands in `crates/audio/tests/fixtures/README.md`) | [SoundCraft `crates/audio-io/tests/fixtures`](https://github.com/storytold/soundcraft/tree/e86d09a/crates/audio-io/tests/fixtures); `tone.mov`, `tone.mka`, `tone.opus`, `tone.ac3` and `tone.eac3` made in this repository | MIT OR Apache-2.0 | +| `crates/raster-codecs/src/xpm/x11_colors.rs` | X.Org Foundation and X11 contributors (X11 `rgb.txt` colour names and values, normalised into a lookup table) | , via [PhotoCraft `crates/codecs`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/codecs/src/codecs/xpm) | MIT (X.Org app/rgb) | | `crates/psd/tests/fixtures/atn/*.atn` (seven synthetic action sets, encoded field by field; `crates/psd/tests/fixtures/atn/README.md`) | PhotoCraft contributors | [PhotoCraft `crates/psd/tests/fixtures/atn`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/psd/tests/fixtures/atn) | MIT OR Apache-2.0 | | `crates/lottie/tests/fixtures/` | EffectCraft contributors (original work: four hand-written Lottie JSON documents, written from the public Lottie format description; not exported from any Adobe product or third-party file) | [EffectCraft `crates/lottie/tests/fixtures`](https://github.com/storytold/effectcraft/tree/e18f48fb/crates/lottie/tests/fixtures) | MIT OR Apache-2.0 | | `crates/affinity/tests/support/corpus.tsv`, `crates/affinity/tests/support/affinity3-signatures.txt` (manifest and measured signatures only; the 51 documents are not bundled, `scripts/fetch-affinity-corpus.sh` downloads them outside the checkout) | The authors of each document: samuel-etver (vector-art), Seth A. Robinson (Patchy fixtures), Nick Beeuwsaert (AFDesignLoad), Jeremy Cantu (Branding), eviltwo (AssetStoreTemplate), Square (leakcanary) | each file's pinned upstream URL and SHA-256 in the manifest; list carried over from [VectorCraft `xtask/src/affinity_corpus.rs`](https://github.com/storytold/vectorcraft/blob/6e873b806c9d5b3f2b55f651df57bd97933b579a/xtask/src/affinity_corpus.rs) | CC0-1.0, MIT or Apache-2.0 (per file, in the manifest) | diff --git a/Cargo.lock b/Cargo.lock index 2f68525f8..cb35096ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -29,6 +29,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "ahash" version = "0.8.12" @@ -392,6 +403,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -602,6 +622,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + [[package]] name = "cmake" version = "0.1.58" @@ -611,6 +641,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cmpv2" version = "0.2.0" @@ -629,7 +665,7 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "spki", "x509-cert", @@ -705,6 +741,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "constant_time_eq" version = "0.4.2" @@ -776,6 +818,12 @@ dependencies = [ "libm", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -794,6 +842,16 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-aaf" +version = "0.1.0" +dependencies = [ + "craft-audio", + "craft-cfb", + "craft-timeline", + "thiserror 2.0.21", +] + [[package]] name = "craft-aep" version = "0.1.0" @@ -807,7 +865,7 @@ dependencies = [ "image", "proptest", "ruzstd", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -868,7 +926,7 @@ version = "0.1.0" name = "craft-cms" version = "0.1.0" dependencies = [ - "md-5", + "md-5 0.10.6", "moxcms", "rayon", ] @@ -880,7 +938,7 @@ dependencies = [ "proptest", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", ] @@ -923,6 +981,13 @@ dependencies = [ name = "craft-docpath" version = "0.1.0" +[[package]] +name = "craft-dpx" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-drawingml" version = "0.1.0" @@ -930,6 +995,7 @@ dependencies = [ "craft-xml", "kurbo 0.13.1", "serde", + "serde_json", ] [[package]] @@ -950,16 +1016,27 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-eps" +version = "0.1.0" + [[package]] name = "craft-epub" version = "0.1.0" dependencies = [ "craft-xml", - "flate2", + "craft-zip", "thiserror 2.0.21", "zip", ] +[[package]] +name = "craft-exr" +version = "0.1.0" +dependencies = [ + "serde_json", +] + [[package]] name = "craft-fig" version = "0.1.0" @@ -1012,7 +1089,7 @@ dependencies = [ "ruzstd", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "skrifa 0.47.0", "tar", "thiserror 2.0.21", @@ -1051,6 +1128,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-gif" +version = "0.1.0" +dependencies = [ + "image", +] + +[[package]] +name = "craft-hdr" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-heif" version = "0.1.0" @@ -1059,6 +1150,13 @@ dependencies = [ "rayon", ] +[[package]] +name = "craft-html" +version = "0.1.0" +dependencies = [ + "proptest", +] + [[package]] name = "craft-i18n" version = "0.1.0" @@ -1082,12 +1180,20 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-ical" +version = "0.1.0" +dependencies = [ + "chrono", + "proptest", +] + [[package]] name = "craft-idml" version = "0.1.0" dependencies = [ "craft-xml", - "flate2", + "craft-zip", "thiserror 2.0.21", "zip", ] @@ -1113,7 +1219,7 @@ dependencies = [ "image", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tempfile", ] @@ -1121,6 +1227,16 @@ dependencies = [ name = "craft-kiwi" version = "0.1.0" +[[package]] +name = "craft-kra" +version = "0.1.0" +dependencies = [ + "craft-xml", + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-lottie" version = "0.1.0" @@ -1161,10 +1277,24 @@ dependencies = [ name = "craft-mesh" version = "0.1.0" dependencies = [ + "craft-opc", + "craft-xml", "miniz_oxide 0.9.1", "serde_json", ] +[[package]] +name = "craft-metadata" +version = "0.1.0" +dependencies = [ + "chrono", + "craft-tiff", + "proptest", + "quick-xml 0.41.0", + "serde", + "serde_json", +] + [[package]] name = "craft-metafile" version = "0.1.0" @@ -1194,6 +1324,39 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-odf" +version = "0.1.0" +dependencies = [ + "aes", + "base64 0.23.1", + "craft-xml", + "flate2", + "getrandom 0.3.4", + "hmac", + "sha1 0.11.0", + "sha2 0.11.1", + "thiserror 2.0.21", + "zeroize", + "zip", +] + +[[package]] +name = "craft-offcrypto" +version = "0.1.0" +dependencies = [ + "aes", + "base64 0.23.1", + "craft-cfb", + "craft-xml", + "getrandom 0.3.4", + "hmac", + "sha1 0.11.0", + "sha2 0.11.1", + "thiserror 2.0.21", + "zeroize", +] + [[package]] name = "craft-opc" version = "0.1.0" @@ -1205,6 +1368,16 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-ora" +version = "0.1.0" +dependencies = [ + "craft-xml", + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-pcraft-format" version = "0.1.0" @@ -1218,6 +1391,7 @@ dependencies = [ name = "craft-pdf" version = "0.1.0" dependencies = [ + "aes", "bytemuck", "hayro", "hayro-cmap", @@ -1225,9 +1399,23 @@ dependencies = [ "hayro-syntax", "krilla", "kurbo 0.13.1", + "md-5 0.11.0", + "proptest", + "sha2 0.11.1", + "stringprep", "thiserror 2.0.21", "ttf-parser", "wasm-bindgen-test", + "zeroize", +] + +[[package]] +name = "craft-pdn" +version = "0.1.0" +dependencies = [ + "flate2", + "proptest", + "thiserror 2.0.21", ] [[package]] @@ -1278,6 +1466,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-prc" +version = "0.1.0" +dependencies = [ + "flate2", + "proptest", + "thiserror 2.0.21", +] + [[package]] name = "craft-prepress" version = "0.1.0" @@ -1327,6 +1524,13 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pst" +version = "0.1.0" +dependencies = [ + "proptest", +] + [[package]] name = "craft-quit" version = "0.1.0" @@ -1338,6 +1542,14 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-raster-codecs" +version = "0.1.0" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-raw" version = "0.1.0" @@ -1361,7 +1573,9 @@ dependencies = [ name = "craft-rtf" version = "0.1.0" dependencies = [ + "craft-mime", "encoding_rs", + "proptest", ] [[package]] @@ -1375,6 +1589,10 @@ dependencies = [ "toml_edit", ] +[[package]] +name = "craft-sheet" +version = "0.1.0" + [[package]] name = "craft-silhouette-studio" version = "0.1.0" @@ -1393,6 +1611,18 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-stream-codecs" +version = "0.1.0" +dependencies = [ + "fax", + "hayro-ccitt", + "hayro-jbig2", + "proptest", + "thiserror 2.0.21", + "weezl 0.2.1", +] + [[package]] name = "craft-svg" version = "0.1.0" @@ -1402,6 +1632,7 @@ dependencies = [ "kurbo 0.13.1", "roxmltree 0.21.2", "thiserror 2.0.21", + "usvg 0.48.1", ] [[package]] @@ -1426,6 +1657,13 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "craft-tga" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1489,7 +1727,7 @@ dependencies = [ "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tar", "tempfile", "ureq", @@ -1499,6 +1737,15 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-vcard" +version = "0.1.0" +dependencies = [ + "chrono", + "craft-mime", + "proptest", +] + [[package]] name = "craft-vectorcraft-format" version = "0.1.0" @@ -1565,11 +1812,30 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "craft-xcf" +version = "0.1.0" +dependencies = [ + "flate2", + "thiserror 2.0.21", +] + [[package]] name = "craft-xls" version = "0.1.0" dependencies = [ "craft-cfb", + "craft-sheet", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xlsx" +version = "0.1.0" +dependencies = [ + "craft-opc", + "craft-sheet", + "craft-xml", "thiserror 2.0.21", ] @@ -1581,6 +1847,23 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-y4m" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +dependencies = [ + "craft-zip", + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1652,6 +1935,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1670,7 +1971,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der_derive", "flagset", "pem-rfc7468", @@ -1713,8 +2014,20 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -2283,6 +2596,27 @@ dependencies = [ "serde", ] +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree 0.20.0", +] + +[[package]] +name = "fontdb" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" +dependencies = [ + "fontconfig-parser", + "log", + "slotmap", + "tinyvec", +] + [[package]] name = "fontique" version = "0.11.1" @@ -2469,9 +2803,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] @@ -2495,7 +2831,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" dependencies = [ "color_quant", - "weezl", + "weezl 0.1.12", ] [[package]] @@ -2824,6 +3160,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.5.0" @@ -2863,6 +3208,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -3238,6 +3592,12 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c" +[[package]] +name = "imagesize" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" + [[package]] name = "indexmap" version = "2.14.2" @@ -3248,6 +3608,15 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "hybrid-array", +] + [[package]] name = "io-extras" version = "0.19.0" @@ -3783,7 +4152,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", ] [[package]] @@ -5160,9 +5539,9 @@ dependencies = [ "log", "pico-args", "rgb", - "svgtypes", + "svgtypes 0.15.3", "tiny-skia", - "usvg", + "usvg 0.45.1", ] [[package]] @@ -5578,7 +5957,18 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -5589,7 +5979,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -5643,12 +6044,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" dependencies = [ "aws-lc-rs", "base64 0.22.1", - "const-oid", + "const-oid 0.9.6", "der", - "digest", + "digest 0.10.7", "pem", "rand_core 0.10.1", - "sha2", + "sha2 0.10.9", "signature", "sigstore-types", "spki", @@ -5717,7 +6118,7 @@ dependencies = [ "chrono", "cmpv2", "cms", - "const-oid", + "const-oid 0.9.6", "der", "hex", "rand", @@ -5756,7 +6157,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cms", - "const-oid", + "const-oid 0.9.6", "hex", "pem", "rustls-pki-types", @@ -6009,6 +6410,16 @@ dependencies = [ "siphasher", ] +[[package]] +name = "svgtypes" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" +dependencies = [ + "kurbo 0.13.1", + "siphasher", +] + [[package]] name = "symphonia" version = "0.6.1" @@ -6374,7 +6785,7 @@ dependencies = [ "flate2", "half", "quick-error 2.0.1", - "weezl", + "weezl 0.1.12", "zune-jpeg", ] @@ -6767,6 +7178,12 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + [[package]] name = "unicode-width" version = "0.2.2" @@ -6844,11 +7261,38 @@ dependencies = [ "simplecss", "siphasher", "strict-num", - "svgtypes", + "svgtypes 0.15.3", "tiny-skia-path 0.11.4", "xmlwriter", ] +[[package]] +name = "usvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" +dependencies = [ + "base64 0.23.1", + "data-url", + "fontdb", + "harfrust", + "imagesize 0.15.0", + "kurbo 0.13.1", + "log", + "pico-args", + "roxmltree 0.21.2", + "simplecss", + "siphasher", + "skrifa 0.44.0", + "strict-num", + "svgtypes 0.16.2", + "tiny-skia-path 0.12.0", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + [[package]] name = "utf16_iter" version = "1.0.5" @@ -7200,6 +7644,12 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + [[package]] name = "wgpu" version = "30.0.1" @@ -7789,9 +8239,9 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", - "sha1", + "sha1 0.10.7", "signature", "spki", "tls_codec", diff --git a/Cargo.toml b/Cargo.toml index 485004f47..9f46a4741 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } craft-ai-core = { path = "crates/ai-core" } craft-pdf = { path = "crates/pdf", version = "=0.1.0" } +craft-pdn = { path = "crates/pdn" } craft-plate-test = { path = "crates/plate-test" } krilla = { version = "=0.8.2", default-features = false, features = ["raster-images"] } hayro = { version = "=0.7.1", default-features = false } @@ -25,6 +26,7 @@ hayro-syntax = { version = "=0.7.2", default-features = false, features = ["std" bytemuck = "1" kurbo = "0.13" thiserror = "2" +craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } @@ -34,58 +36,81 @@ craft-csv = { path = "crates/csv" } craft-dialogs = { path = "crates/dialogs" } craft-dxf = { path = "crates/dxf" } craft-drawingml = { path = "crates/drawingml" } +craft-eps = { path = "crates/eps" } craft-doc = { path = "crates/doc" } craft-docpath = { path = "crates/docpath" } +craft-dpx = { path = "crates/dpx" } craft-ecproj-format = { path = "crates/ecproj-format" } +craft-exr = { path = "crates/exr" } craft-font-catalog = { path = "crates/font-catalog" } craft-font-manager = { path = "crates/font-manager" } craft-font-store = { path = "crates/font-store" } craft-gainmap = { path = "crates/gainmap" } craft-gcode = { path = "crates/gcode" } +craft-gif = { path = "crates/gif" } +craft-hdr = { path = "crates/hdr" } craft-mesh = { path = "crates/mesh" } +craft-html = { path = "crates/html" } craft-heif = { path = "crates/heif" } craft-fig = { path = "crates/fig" } craft-fonts-build = { path = "crates/fonts-build" } craft-i18n = { path = "crates/i18n" } craft-idml = { path = "crates/idml" } +craft-ical = { path = "crates/ical" } craft-jpeg = { path = "crates/jpeg" } craft-kiwi = { path = "crates/kiwi" } craft-keymap = { path = "crates/keymap" } craft-assuan = { path = "crates/assuan" } +craft-kra = { path = "crates/kra" } craft-audio = { path = "crates/audio" } # No default features, so craft-audio's `encode` builds craft-media without `isobmff`. craft-media = { path = "crates/media", default-features = false } craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } craft-mime = { path = "crates/mime" } +craft-odf = { path = "crates/odf" } +craft-prc = { path = "crates/prc" } craft-lottie = { path = "crates/lottie" } craft-menu = { path = "crates/menu" } craft-metafile = { path = "crates/metafile" } +craft-offcrypto = { path = "crates/offcrypto" } craft-opc = { path = "crates/opc" } +craft-ora = { path = "crates/ora" } craft-penpot = { path = "crates/penpot" } craft-pcraft-format = { path = "crates/pcraft-format" } craft-plotter = { path = "crates/plotter" } craft-prepress = { path = "crates/prepress" } craft-print = { path = "crates/print" } craft-proof = { path = "crates/proof" } +craft-raster-codecs = { path = "crates/raster-codecs" } craft-psd = { path = "crates/psd" } +craft-pst = { path = "crates/pst" } craft-quit = { path = "crates/quit" } craft-rtf = { path = "crates/rtf" } craft-raw = { path = "crates/raw" } +craft-sheet = { path = "crates/sheet" } craft-sketch = { path = "crates/sketch" } craft-settings = { path = "crates/settings" } craft-silhouette-studio = { path = "crates/silhouette-studio" } craft-svg = { path = "crates/svg" } craft-svg-paths = { path = "crates/svg-paths" } +craft-stream-codecs = { path = "crates/stream-codecs" } craft-text = { path = "crates/text" } +craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } craft-tiff = { path = "crates/tiff" } +craft-metadata = { path = "crates/metadata" } craft-ui = { path = "crates/ui" } craft-update = { path = "crates/update" } +craft-vcard = { path = "crates/vcard" } craft-vectorcraft-format = { path = "crates/vectorcraft-format" } craft-vectordrawable = { path = "crates/vectordrawable" } craft-xls = { path = "crates/xls" } +craft-xlsx = { path = "crates/xlsx" } +craft-xcf = { path = "crates/xcf" } craft-xml = { path = "crates/xml" } +craft-zip = { path = "crates/zip" } +craft-y4m = { path = "crates/y4m" } craft-epub = { path = "crates/epub" } craft-video = { path = "crates/video" } craft-web-api = { path = "crates/web-api" } diff --git a/NOTICE b/NOTICE index 6729833e3..eb22134a2 100644 --- a/NOTICE +++ b/NOTICE @@ -93,7 +93,7 @@ crates/raw (craft-raw) is moved from LightCraft, with behaviour ported from two - LightCraft, crates/raw (src/lib.rs, dng.rs, dngwrite.rs, tiffraw.rs, unpack.rs, ljpeg.rs, jxl.rs, opcodes.rs, profile.rs, gaintable.rs, semantic.rs, preview.rs, vendor/crw.rs, vendor/hasselblad.rs, vendor.rs (shared level helpers), vendor/mrw.rs, vendor/erf.rs, vendor/mef.rs, vendor/kodak.rs, vendor/pef.rs, - vendor/srw.rs, tests/it/vendor_robust.rs and their tests) and crates/meta/src/mrw.rs (the MRW block container), + vendor/srw.rs, vendor/cr2.rs, vendor/cr2/sraw.rs, vendor/nef.rs, vendor/nefc.rs, vendor/nef_lens.rs, docs/nikon-lens-corrections.md, kelvin_presets.rs (the preset ordering), tests/it/vendor_robust.rs and their tests) and crates/meta/src/mrw.rs (the MRW block container), revision 5ff567a4a2e067bef1b6bce152c11e7f727ccbaf. https://github.com/storytold/lightcraft Copyright (c) 2026 ArtCraft Team and the LightCraft contributors. diff --git a/README.md b/README.md index 024d28593..1784d1e47 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = "` form on craft-xml elements, value codecs and the package writer; and InDesign Tagged Text, read and written. +- [`craft-ical`](crates/ical/README.md): iCalendar (RFC 5545) building blocks, from MailCraft: content + lines, DATE/DATE-TIME values, durations, TEXT escaping, the common subset of recurrence rules, + and `VTIMEZONE` definitions read and written. No time-zone database; what events and to-dos + mean stays in each app. Bounded and panic-free on hostile input. +- [`craft-stream-codecs`](crates/stream-codecs/README.md): byte-stream and bi-level image codecs that + PDF, PostScript and TIFF share: LZW, ASCII85, ASCIIHex, RunLength, TIFF and PNG predictors, + CCITT Group 3 and 4 decoding and Group 4 encoding, lossless JBIG2 encoding. Every + decoder is bounded and returns its partial output on damage. From PdfCraft; a PDF filter chain + is built on it in `craft-pdf`. - [`craft-timeline`](crates/timeline/README.md): editorial timeline interchange: exact media time and SMPTE timecode, import/export reports, media path and `file://` URL handling, Avid Log Exchange (ALE) and CMX 3600 EDL documents, format detection. From FilmCraft. +- [`craft-metadata`](crates/metadata/README.md): photo metadata, from LightCraft: EXIF (read and write, + maker-note lens and focus point, every tag by name), IPTC-IIM, XMP packets (read, write, and a merge + that keeps what another program wrote), GPX track logs, and the blocks that carry them in JPEG, PNG, + WebP, TIFF-based, RAF and CR3 files. One `Metadata` model for all of them. Built on `craft-tiff`. - [`craft-tiff`](crates/tiff/README.md): TIFF and BigTIFF IFD reader and writer, from LightCraft: every field type, the IFD chain, SubIFDs and Exif/GPS/Interop pointer IFDs, maker-note IFDs (Canon, Nikon, Sony, Fujifilm, Olympus, Panasonic, Pentax), strip and tile layout. Bounded and @@ -136,6 +175,10 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = "`/`` instances and the CSS cascade as Bézier paths in millimetres, each tagged by the caller); `color` parses CSS colours; `write` writes documents - (elements with escaping, path data, numbers). + (elements with escaping, path data, numbers). Feature `tree`: the full parser, usvg at the one + version every Craft app uses, re-exported behind an entry point that runs those checks first + (plus nesting with references followed, attribute counts, bounded embedded SVGs), and a budget + check for drawing a tree with resvg. Apps take usvg from here, not as their own dependency. - [`craft-svg-paths`](crates/svg-paths/src/lib.rs): the former name of `craft-svg`'s `paths`, `color` and `write`; re-exports them for existing users. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds @@ -212,6 +273,11 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " { + pub identity: Identity<'a>, + /// Write 512-byte sectors (compound file version 3) instead of 4096-byte sectors. + pub small_sectors: bool, +} + +/// Write `doc` as an AAF file: its first composition is the top-level one, with every nested +/// composition and every source it uses. Times that are not on whole edit units are rounded and +/// reported. +pub fn write(doc: &Document, opts: &WriteOptions<'_>, report: &mut Report) -> Result> { + let version = if opts.small_sectors { craft_cfb::Version::V3 } else { craft_cfb::Version::V4 }; + write::write(doc, version, &opts.identity, report) +} + +/// Read an AAF file: its top-level compositions, the compositions nested in them and their +/// sources. What cannot be represented is skipped and named in `report`. +pub fn read(bytes: &[u8], report: &mut Report) -> Result { + read::read(bytes, report) +} + +/// Whether `bytes` look like an AAF file (a compound file whose root has the AAF root class or a +/// `Header-2` storage). +pub fn sniff(bytes: &[u8]) -> bool { + if !craft_cfb::sniff(bytes) { + return false; + } + match craft_cfb::CompoundFile::open(bytes) { + Ok(cf) => cf.root().clsid == ids::ROOT || cf.find("Header-2").is_ok(), + Err(_) => false, + } +} + +#[cfg(test)] +mod hostile_tests; +#[cfg(test)] +mod tests; diff --git a/crates/aaf/src/aaf/hostile_tests.rs b/crates/aaf/src/aaf/hostile_tests.rs new file mode 100644 index 000000000..853b0000c --- /dev/null +++ b/crates/aaf/src/aaf/hostile_tests.rs @@ -0,0 +1,110 @@ +//! Hostile object trees: a crafted file must give an error, never a crash, a hang or an +//! allocation sized by a count in the file (AGENTS.md §0). + +use craft_cfb::{Version, Writer}; + +use super::store::{self, SF_STRONG_VECTOR, SF_WEAK_SET, SF_WEAK_VECTOR, Value, utf16z}; + +const PID: u16 = 0x0007; + +/// A root object whose one property `PID` is a weak reference vector or set (stored form `sf`) +/// named `Keys`, with `index` as its `Keys index` stream. +fn weak_collection_file(sf: u16, index: Vec) -> Vec { + let name = utf16z("Keys"); + // byte order 'L', format version, 1 entry { pid, stored form, value length }, the value + let mut props = vec![0x4C, 0x20]; + for x in [1, PID, sf, name.len() as u16] { + props.extend_from_slice(&x.to_le_bytes()); + } + props.extend_from_slice(&name); + let mut w = Writer::new(Version::V3); + w.stream(Writer::ROOT, "properties", props).unwrap(); + w.stream(Writer::ROOT, "Keys index", index).unwrap(); + w.finish() +} + +/// A weak collection index: u32 count, u16 tag, u16 key pid, u8 key size, then the keys. +fn index(count: u32, size: u8, keys: &[u8]) -> Vec { + let mut v = count.to_le_bytes().to_vec(); + v.extend_from_slice(&0u16.to_le_bytes()); + v.extend_from_slice(&0x1B01u16.to_le_bytes()); + v.push(size); + v.extend_from_slice(keys); + v +} + +fn read_keys(sf: u16, index: Vec) -> Result>, String> { + match store::read(&weak_collection_file(sf, index))?.get(PID) { + Some(Value::WeakVec(_, _, keys)) => Ok(keys.clone()), + other => panic!("not a weak collection: {other:?}"), + } +} + +/// With a key size of 0 every key fits, so the count alone drove the loop: up to 4.29 billion +/// empty keys (about 100 GB) from a 9-byte index. A million is enough to show it, cheaply. +#[test] +fn zero_size_weak_collection_keys_are_an_error() { + for sf in [SF_WEAK_VECTOR, SF_WEAK_SET] { + match read_keys(sf, index(1_000_000, 0, &[])) { + Err(e) => assert!(e.contains("zero-size"), "{e}"), + Ok(keys) => panic!("read {} empty keys instead of an error", keys.len()), + } + } +} + +#[test] +fn weak_collection_count_beyond_the_index_is_an_error() { + for sf in [SF_WEAK_VECTOR, SF_WEAK_SET] { + let e = read_keys(sf, index(u32::MAX, 4, &[1, 2, 3, 4, 5, 6, 7, 8])).unwrap_err(); + assert!(e.contains("short weak collection index"), "{e}"); + } +} + +#[test] +fn weak_collections_within_the_index_are_read() { + for sf in [SF_WEAK_VECTOR, SF_WEAK_SET] { + assert_eq!(read_keys(sf, index(0, 0, &[])).unwrap(), Vec::>::new()); + assert_eq!(read_keys(sf, index(2, 4, &[1, 2, 3, 4, 5, 6, 7, 8])).unwrap(), [vec![1, 2, 3, 4], vec![5, 6, 7, 8]]); + } +} + +/// A strong vector whose entries all name the same child storage would rebuild that subtree once +/// per entry; a storage has one owner, so the repeat is an error. +#[test] +fn a_storage_owned_twice_is_an_error() { + let name = utf16z("Items"); + let mut props = vec![0x4C, 0x20]; + for x in [1, PID, SF_STRONG_VECTOR, name.len() as u16] { + props.extend_from_slice(&x.to_le_bytes()); + } + props.extend_from_slice(&name); + // count, next free key, last key, then the entry keys + let mut idx = 3u32.to_le_bytes().to_vec(); + idx.extend_from_slice(&[0; 8]); + for _ in 0..3 { + idx.extend_from_slice(&1u32.to_le_bytes()); + } + let mut w = Writer::new(Version::V3); + w.stream(Writer::ROOT, "properties", props).unwrap(); + w.stream(Writer::ROOT, "Items index", idx).unwrap(); + let child = w.storage(Writer::ROOT, "Items{1}", [0; 16]).unwrap(); + w.stream(child, "properties", vec![0x4C, 0x20, 0, 0]).unwrap(); + let e = store::read(&w.finish()).unwrap_err(); + assert!(e.contains("more than one reference"), "{e}"); +} + +/// Objects nest through strong references; a chain deeper than the reader follows is an error, +/// and one within it reads. +#[test] +fn objects_nested_too_deeply_are_an_error() { + let chain = |depth: usize| { + let mut o = store::Obj::new([1; 16]); + for _ in 0..depth { + o = store::Obj::new([1; 16]).with(PID, Value::Strong(Box::new(o))); + } + store::write(&o, Version::V4).unwrap() + }; + assert!(store::read(&chain(150)).is_ok()); + let e = store::read(&chain(250)).unwrap_err(); + assert!(e.contains("nested too deeply"), "{e}"); +} diff --git a/crates/aaf/src/aaf/ids.rs b/crates/aaf/src/aaf/ids.rs new file mode 100644 index 000000000..70a184060 --- /dev/null +++ b/crates/aaf/src/aaf/ids.rs @@ -0,0 +1,262 @@ +//! Class ids, property ids and definition ids of the AAF object model subset read and +//! writes (AAF Object Specification v1.1, AAF Edit Protocol). Class and data definition AUIDs are +//! SMPTE labels (RP 224 / RP 210 registers) in AUID byte order; property ids are the AAF / ST 377-1 +//! local tags. + +use super::store::Auid; + +/// AUID of a SMPTE universal label: the label's last 8 bytes become Data1–Data3 (stored +/// little-endian), its first 8 bytes Data4. +pub(crate) const fn ul(b: [u8; 16]) -> Auid { + [b[11], b[10], b[9], b[8], b[13], b[12], b[15], b[14], b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]] +} + +/// A GUID `{d1-d2-d3-d4}` in AUID byte order. +pub(crate) const fn guid(d1: u32, d2: u16, d3: u16, d4: [u8; 8]) -> Auid { + let a = d1.to_le_bytes(); + let b = d2.to_le_bytes(); + let c = d3.to_le_bytes(); + [a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d4[0], d4[1], d4[2], d4[3], d4[4], d4[5], d4[6], d4[7]] +} + +/// Class AUID: SMPTE label 06.0E.2B.34.02.06.01.01.0D.01.01.01.01.01.xx.00. +pub(crate) const fn class(xx: u8) -> Auid { + ul([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x06, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x01, 0x01, 0x01, xx, 0x00]) +} + +/// The root object's class (the storage class of the file's root). +pub(crate) const ROOT: Auid = guid(0xB3B398A5, 0x1C90, 0x11D4, [0x80, 0x53, 0x08, 0x00, 0x36, 0x21, 0x08, 0x04]); +/// The meta-dictionary (class 0x25 of the meta-model, 06.0E.2B.34.02.06.01.01.0D.01.01.01.02.25.00.00). +pub(crate) const META_DICTIONARY: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x06, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x01, 0x02, 0x25, 0x00, 0x00]); + +#[allow(dead_code)] +pub(crate) mod cls { + use super::class; + use crate::aaf::store::Auid; + pub const COMMENT_MARKER: Auid = class(0x08); + pub const FILLER: Auid = class(0x09); + pub const OPERATION_GROUP: Auid = class(0x0A); + pub const NESTED_SCOPE: Auid = class(0x0B); + pub const SCOPE_REFERENCE: Auid = class(0x0D); + pub const SELECTOR: Auid = class(0x0E); + pub const SEQUENCE: Auid = class(0x0F); + pub const SOURCE_CLIP: Auid = class(0x11); + pub const TIMECODE: Auid = class(0x14); + pub const TRANSITION: Auid = class(0x17); + pub const CONTENT_STORAGE: Auid = class(0x18); + pub const CONTROL_POINT: Auid = class(0x19); + pub const DATA_DEFINITION: Auid = class(0x1B); + pub const OPERATION_DEFINITION: Auid = class(0x1C); + pub const PARAMETER_DEFINITION: Auid = class(0x1D); + pub const CONTAINER_DEFINITION: Auid = class(0x20); + pub const INTERPOLATION_DEFINITION: Auid = class(0x21); + pub const DICTIONARY: Auid = class(0x22); + pub const ESSENCE_DATA: Auid = class(0x23); + pub const CDCI_DESCRIPTOR: Auid = class(0x28); + pub const TAPE_DESCRIPTOR: Auid = class(0x2E); + pub const HEADER: Auid = class(0x2F); + pub const IDENTIFICATION: Auid = class(0x30); + pub const NETWORK_LOCATOR: Auid = class(0x32); + pub const COMPOSITION_MOB: Auid = class(0x35); + pub const MASTER_MOB: Auid = class(0x36); + pub const SOURCE_MOB: Auid = class(0x37); + pub const EVENT_MOB_SLOT: Auid = class(0x39); + pub const TIMELINE_MOB_SLOT: Auid = class(0x3B); + pub const CONSTANT_VALUE: Auid = class(0x3D); + pub const VARYING_VALUE: Auid = class(0x3E); + pub const TAGGED_VALUE: Auid = class(0x3F); + pub const DESCRIPTIVE_MARKER: Auid = class(0x41); + pub const PCM_DESCRIPTOR: Auid = class(0x48); + pub const IMPORT_DESCRIPTOR: Auid = class(0x4A); + /// Classes with a `Locator` and media properties read as file descriptors. + pub const WAVE_DESCRIPTOR: Auid = class(0x2C); + pub const AIFC_DESCRIPTOR: Auid = class(0x26); + pub const SOUND_DESCRIPTOR: Auid = class(0x42); + pub const RGBA_DESCRIPTOR: Auid = class(0x29); + pub const MULTIPLE_DESCRIPTOR: Auid = class(0x44); +} + +/// Property ids. +#[allow(dead_code)] +pub(crate) mod pid { + // Root + pub const ROOT_META_DICTIONARY: u16 = 0x0001; + pub const ROOT_HEADER: u16 = 0x0002; + // MetaDictionary and MetaDefinition + pub const META_CLASS_DEFINITIONS: u16 = 0x0003; + pub const META_TYPE_DEFINITIONS: u16 = 0x0004; + pub const META_IDENTIFICATION: u16 = 0x0005; + // Header + pub const BYTE_ORDER: u16 = 0x3B01; + pub const LAST_MODIFIED: u16 = 0x3B02; + pub const CONTENT: u16 = 0x3B03; + pub const DICTIONARY: u16 = 0x3B04; + pub const VERSION: u16 = 0x3B05; + pub const IDENTIFICATION_LIST: u16 = 0x3B06; + pub const OBJECT_MODEL_VERSION: u16 = 0x3B07; + pub const OPERATIONAL_PATTERN: u16 = 0x3B09; + // Identification + pub const COMPANY_NAME: u16 = 0x3C01; + pub const PRODUCT_NAME: u16 = 0x3C02; + pub const PRODUCT_VERSION_STRING: u16 = 0x3C04; + pub const PRODUCT_ID: u16 = 0x3C05; + pub const DATE: u16 = 0x3C06; + pub const PLATFORM: u16 = 0x3C08; + pub const GENERATION_AUID: u16 = 0x3C09; + // ContentStorage + pub const MOBS: u16 = 0x1901; + pub const ESSENCE_DATA: u16 = 0x1902; + // Dictionary + pub const OPERATION_DEFINITIONS: u16 = 0x2603; + pub const PARAMETER_DEFINITIONS: u16 = 0x2604; + pub const DATA_DEFINITIONS: u16 = 0x2605; + pub const CONTAINER_DEFINITIONS: u16 = 0x2608; + pub const INTERPOLATION_DEFINITIONS: u16 = 0x2609; + // DefinitionObject + pub const IDENTIFICATION: u16 = 0x1B01; + pub const NAME: u16 = 0x1B02; + pub const DESCRIPTION: u16 = 0x1B03; + // OperationDefinition + pub const OPDEF_DATA_DEFINITION: u16 = 0x1E01; + pub const OPDEF_IS_TIME_WARP: u16 = 0x1E02; + pub const OPDEF_NUMBER_INPUTS: u16 = 0x1E07; + pub const OPDEF_PARAMETERS_DEFINED: u16 = 0x1E09; + // ParameterDefinition + pub const PARAMDEF_DISPLAY_UNITS: u16 = 0x1F03; + // Mob + pub const MOB_ID: u16 = 0x4401; + pub const MOB_NAME: u16 = 0x4402; + pub const SLOTS: u16 = 0x4403; + pub const MOB_LAST_MODIFIED: u16 = 0x4404; + pub const MOB_CREATION_TIME: u16 = 0x4405; + pub const MOB_USER_COMMENTS: u16 = 0x4406; + pub const USAGE_CODE: u16 = 0x4408; + // SourceMob + pub const ESSENCE_DESCRIPTION: u16 = 0x4701; + // MobSlot + pub const SLOT_ID: u16 = 0x4801; + pub const SLOT_NAME: u16 = 0x4802; + pub const SEGMENT: u16 = 0x4803; + pub const PHYSICAL_TRACK_NUMBER: u16 = 0x4804; + // TimelineMobSlot / EventMobSlot + pub const EDIT_RATE: u16 = 0x4B01; + pub const ORIGIN: u16 = 0x4B02; + pub const EVENT_EDIT_RATE: u16 = 0x4901; + // Component + pub const DATA_DEFINITION: u16 = 0x0201; + pub const LENGTH: u16 = 0x0202; + pub const COMPONENT_USER_COMMENTS: u16 = 0x0204; + // Sequence + pub const COMPONENTS: u16 = 0x1001; + // SourceReference / SourceClip + pub const SOURCE_ID: u16 = 0x1101; + pub const SOURCE_MOB_SLOT_ID: u16 = 0x1102; + pub const START_TIME: u16 = 0x1201; + // Event + pub const POSITION: u16 = 0x0601; + pub const COMMENT: u16 = 0x0602; + // Timecode + pub const TC_START: u16 = 0x1501; + pub const TC_FPS: u16 = 0x1502; + pub const TC_DROP: u16 = 0x1503; + // Transition + pub const OPERATION_GROUP: u16 = 0x1801; + pub const CUT_POINT: u16 = 0x1802; + // OperationGroup + pub const OPERATION: u16 = 0x0B01; + pub const INPUT_SEGMENTS: u16 = 0x0B02; + pub const PARAMETERS: u16 = 0x0B03; + // Selector / NestedScope + pub const SELECTED: u16 = 0x0F01; + pub const NESTED_SLOTS: u16 = 0x0C01; + // Parameter / ConstantValue / VaryingValue / ControlPoint + pub const PARAMETER_DEFINITION: u16 = 0x4C01; + pub const CONSTANT_VALUE: u16 = 0x4D01; + pub const INTERPOLATION: u16 = 0x4E01; + pub const POINT_LIST: u16 = 0x4E02; + pub const CP_VALUE: u16 = 0x1A02; + pub const CP_TIME: u16 = 0x1A03; + pub const CP_EDIT_HINT: u16 = 0x1A04; + // TaggedValue + pub const TAG_NAME: u16 = 0x5001; + pub const TAG_VALUE: u16 = 0x5003; + // EssenceDescriptor / FileDescriptor + pub const LOCATOR: u16 = 0x2F01; + pub const SAMPLE_RATE: u16 = 0x3001; + pub const FILE_LENGTH: u16 = 0x3002; + pub const CONTAINER_FORMAT: u16 = 0x3004; + pub const STORED_HEIGHT: u16 = 0x3202; + pub const STORED_WIDTH: u16 = 0x3203; + pub const FRAME_LAYOUT: u16 = 0x320C; + pub const VIDEO_LINE_MAP: u16 = 0x320D; + pub const IMAGE_ASPECT_RATIO: u16 = 0x320E; + pub const COMPONENT_WIDTH: u16 = 0x3301; + pub const HORIZONTAL_SUBSAMPLING: u16 = 0x3302; + pub const QUANTIZATION_BITS: u16 = 0x3D01; + pub const LOCKED: u16 = 0x3D02; + pub const AUDIO_SAMPLING_RATE: u16 = 0x3D03; + pub const CHANNELS: u16 = 0x3D07; + pub const AVERAGE_BPS: u16 = 0x3D09; + pub const BLOCK_ALIGN: u16 = 0x3D0A; + // NetworkLocator + pub const URL_STRING: u16 = 0x4001; + // EssenceData + pub const ESSENCE_MOB_ID: u16 = 0x2701; + pub const ESSENCE_STREAM: u16 = 0x2702; +} + +/// Data definitions (SMPTE RP 224 labels 06.0E.2B.34.04.01.01.01.01.03.02.xx.yy). +pub(crate) mod ddef { + use super::{guid, ul}; + use crate::aaf::store::Auid; + pub const PICTURE: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00]); + pub const SOUND: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00]); + pub const TIMECODE: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00]); + pub const DESCRIPTIVE_METADATA: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x10, 0x00, 0x00, 0x00]); + /// Pre-SMPTE ("legacy") data definitions written by older applications. + pub const LEGACY_PICTURE: Auid = guid(0x6F3C8CE1, 0x6CEF, 0x11D2, [0x80, 0x7D, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]); + pub const LEGACY_SOUND: Auid = guid(0x78E1EBE1, 0x6CEF, 0x11D2, [0x80, 0x7D, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]); + pub const LEGACY_TIMECODE: Auid = guid(0x7F275E81, 0x77E5, 0x11D2, [0x80, 0x7F, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]); +} + +/// Operation, parameter, interpolation and container definitions. +pub(crate) mod def { + use super::guid; + use crate::aaf::store::Auid; + const AV: [u8; 8] = [0x8A, 0x09, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]; + pub const VIDEO_DISSOLVE: Auid = guid(0x0C3BEA41, 0xFC05, 0x11D2, AV); + pub const VIDEO_FADE_TO_BLACK: Auid = guid(0x0C3BEA40, 0xFC05, 0x11D2, AV); + pub const SMPTE_VIDEO_WIPE: Auid = guid(0x0C3BEA43, 0xFC05, 0x11D2, AV); + pub const MONO_AUDIO_DISSOLVE: Auid = guid(0x0C3BEA44, 0xFC05, 0x11D2, AV); + const AG: [u8; 8] = [0x8A, 0x38, 0x00, 0x50, 0x04, 0x0E, 0xF7, 0xD2]; + pub const MONO_AUDIO_GAIN: Auid = guid(0x9D2EA893, 0x0968, 0x11D3, AG); + const PD: [u8; 8] = [0x8A, 0x4C, 0x00, 0x50, 0x04, 0x0E, 0xF7, 0xD2]; + pub const PARAM_LEVEL: Auid = guid(0xE4962320, 0x2267, 0x11D3, PD); + pub const PARAM_AMPLITUDE: Auid = guid(0xE4962321, 0x2267, 0x11D3, PD); + const IP: [u8; 8] = [0x80, 0xA9, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]; + pub const INTERP_LINEAR: Auid = guid(0x5B6C85A4, 0x0EDE, 0x11D3, IP); + pub const INTERP_CONSTANT: Auid = guid(0x5B6C85A5, 0x0EDE, 0x11D3, IP); + const CD: [u8; 8] = [0x80, 0x9B, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]; + pub const CONTAINER_AAF: Auid = guid(0x4313B571, 0xD8BA, 0x11D2, CD); + pub const CONTAINER_EXTERNAL: Auid = guid(0x4313B572, 0xD8BA, 0x11D2, CD); + /// Type ids of indirect values (SMPTE RP 210 type labels). + pub const TYPE_RATIONAL: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]); + pub const TYPE_STRING: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00]); + /// Edit Protocol operational pattern (`AAFEditProtocol`) and mob usage codes (`Usage_TopLevel`), + /// as in the SMPTE Labels register. + pub const OP_EDIT_PROTOCOL: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x05, 0x0D, 0x01, 0x12, 0x01, 0x01, 0x00, 0x00, 0x00]); + pub const USAGE_TOP_LEVEL: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x02, 0x01, 0x01, 0x07, 0x00]); + /// The label FilmCraft 0.16 and earlier wrote as the top-level usage code (in no register). + /// Import reads it as top-level too. + pub const USAGE_TOP_LEVEL_OLD: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x05, 0x0D, 0x01, 0x12, 0x01, 0x02, 0x03, 0x00, 0x00]); +} + +/// Weak reference target paths (pids from the root object). +pub(crate) mod path { + use super::pid; + pub const DATA_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::DATA_DEFINITIONS]; + pub const OPERATION_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::OPERATION_DEFINITIONS]; + pub const PARAMETER_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::PARAMETER_DEFINITIONS]; + pub const INTERPOLATION_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::INTERPOLATION_DEFINITIONS]; + pub const CONTAINER_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::CONTAINER_DEFINITIONS]; +} diff --git a/crates/aaf/src/aaf/read.rs b/crates/aaf/src/aaf/read.rs new file mode 100644 index 000000000..206c2ead3 --- /dev/null +++ b/crates/aaf/src/aaf/read.rs @@ -0,0 +1,722 @@ +//! AAF objects → composition model. + +use std::collections::{HashMap, HashSet}; + +use craft_timeline::time::{FrameRate, Tick}; + +use super::ids::{cls, ddef, def, pid}; +use super::store::{self, Auid, Obj, Value, rational_of, utf16_of}; +use crate::model::{CClip, CItem, CKind, CMarker, CTrack, CTransition, Composition, Document, Gain, Source, units_to_ticks}; +use crate::{Error, Report, Result}; + +type MobId = [u8; 32]; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum DataKind { + Picture, + Sound, + Timecode, + Other, +} + +fn data_kind(o: &Obj) -> DataKind { + match o.weak_key(pid::DATA_DEFINITION).and_then(|k| ::try_from(k).ok()) { + Some(k) if k == ddef::PICTURE || k == ddef::LEGACY_PICTURE => DataKind::Picture, + Some(k) if k == ddef::SOUND || k == ddef::LEGACY_SOUND => DataKind::Sound, + Some(k) if k == ddef::TIMECODE || k == ddef::LEGACY_TIMECODE => DataKind::Timecode, + Some(_) => DataKind::Other, + None => DataKind::Other, + } +} + +fn len_of(o: &Obj) -> i64 { + o.i64(pid::LENGTH).unwrap_or(0).max(0) +} + +/// The value of an indirect property: (type id, bytes). +fn indirect(d: &[u8]) -> Option<(Auid, &[u8])> { + if d.len() >= 17 && (d[0] == 0x4C || d[0] == 0x42) { + return Some((d[1..17].try_into().ok()?, &d[17..])); + } + if d.len() >= 16 { + return Some((d[..16].try_into().ok()?, &d[16..])); + } + None +} + +fn tagged_values(o: &Obj, p: u16) -> Vec<(String, String)> { + o.objs(p) + .iter() + .filter_map(|t| { + let name = t.string(pid::TAG_NAME)?; + let (ty, v) = indirect(t.data(pid::TAG_VALUE)?)?; + let value = if ty == def::TYPE_STRING || v.len() % 2 == 0 { utf16_of(v) } else { String::new() }; + Some((name, value)) + }) + .collect() +} + +fn indirect_f64(d: &[u8]) -> Option { + let (_, v) = indirect(d)?; + match v.len() { + 8 => rational_of(v).filter(|r| r.1 != 0).map(|(n, d)| n as f64 / d as f64), + 4 => Some(i32::from_le_bytes(v.try_into().ok()?) as f64), + _ => None, + } +} + +struct R<'a> { + report: &'a mut Report, + mobs: HashMap, + essence: HashMap, + doc: Document, + /// (file mob id, slot id, master key) → source index + sources: HashMap<(MobId, u32, String), usize>, + /// Composition mobs read as nested compositions: their index in `doc.nested`. + nests: HashMap, + /// The compositions being read, outermost first. + open: Vec, +} + +struct NestClip<'a> { + mob_id: MobId, + slot_id: u32, + rate: (i64, i64), + kind: CKind, + name: String, + mob: &'a Obj, +} + +/// Compositions nested deeper than this are read as gaps. +const MAX_NESTING: usize = 16; + +pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { + let root = store::read(bytes).map_err(|e| Error::Parse { format: "AAF", message: e })?; + let header = root.strong(pid::ROOT_HEADER).ok_or_else(|| Error::Parse { format: "AAF", message: "no header object".into() })?; + let content = header.strong(pid::CONTENT).ok_or_else(|| Error::Parse { format: "AAF", message: "no content storage".into() })?; + let mut mobs = HashMap::new(); + for m in content.objs(pid::MOBS) { + if let Some(id) = m.mob_id(pid::MOB_ID) { + mobs.insert(id, m); + } + } + let mut essence = HashMap::new(); + for e in content.objs(pid::ESSENCE_DATA) { + if let (Some(id), Some(d)) = (e.mob_id(pid::ESSENCE_MOB_ID), e.stream(pid::ESSENCE_STREAM)) { + essence.insert(id, d); + } + } + let mut r = R { report, mobs, essence, doc: Document::default(), sources: HashMap::new(), nests: HashMap::new(), open: Vec::new() }; + // Top-level compositions: those no other composition uses, among the ones tagged top-level + // when any are. (Premiere Pro tags a nested sequence's composition top-level too; it is still + // only a nested sequence.) Compositions that only use each other in a circle all count. The + // label older FilmCraft versions wrote for top-level counts as top-level too. + let comps: Vec<&Obj> = content.objs(pid::MOBS).iter().filter(|m| m.class == cls::COMPOSITION_MOB).collect(); + let mut referenced = HashSet::new(); + for c in &comps { + collect_refs(c, &mut referenced); + } + let is_top = |c: &&Obj| c.auid(pid::USAGE_CODE).is_some_and(|u| u == def::USAGE_TOP_LEVEL || u == def::USAGE_TOP_LEVEL_OLD); + let tagged_top: Vec<&Obj> = comps.iter().copied().filter(is_top).collect(); + let pool = if tagged_top.is_empty() { comps } else { tagged_top }; + let unused: Vec<&Obj> = pool.iter().copied().filter(|c| c.mob_id(pid::MOB_ID).is_none_or(|id| !referenced.contains(&id))).collect(); + let top = if unused.is_empty() { pool } else { unused }; + for c in top { + r.open.extend(c.mob_id(pid::MOB_ID)); + let comp = r.composition(c); + r.open.clear(); + r.doc.compositions.push(comp); + } + if r.doc.compositions.is_empty() { + return Err(Error::Empty); + } + Ok(r.doc) +} + +fn collect_refs(o: &Obj, out: &mut HashSet) { + if o.class == cls::SOURCE_CLIP + && let Some(id) = o.mob_id(pid::SOURCE_ID) + { + out.insert(id); + } + for (_, v) in &o.props { + match v { + Value::Strong(c) => collect_refs(c, out), + Value::StrongVec(v) | Value::StrongSet(v, _) => v.iter().for_each(|c| collect_refs(c, out)), + _ => {} + } + } +} + +fn rate_of(o: &Obj, p: u16) -> Option<(i64, i64)> { + o.rational(p).filter(|r| r.0 > 0 && r.1 > 0) +} + +impl R<'_> { + fn composition(&mut self, c: &Obj) -> Composition { + let name = c.string(pid::MOB_NAME).unwrap_or_else(|| "Sequence".into()); + let slots = c.objs(pid::SLOTS); + let pic_rate = slots + .iter() + .filter(|s| s.class == cls::TIMELINE_MOB_SLOT) + .find(|s| s.strong(pid::SEGMENT).is_some_and(|g| matches!(data_kind(g), DataKind::Picture | DataKind::Timecode))) + .and_then(|s| rate_of(s, pid::EDIT_RATE)) + .or_else(|| slots.iter().find_map(|s| rate_of(s, pid::EDIT_RATE))) + .unwrap_or((25, 1)); + let rate = FrameRate::new(pic_rate.0, pic_rate.1); + let tags = tagged_values(c, pid::MOB_USER_COMMENTS); + let tag = |n: &str| tags.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone()); + let (mut width, mut height) = tag("FilmCraft Frame Size") + .and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.trim().parse().ok()?, b.trim().parse().ok()?)))) + .unwrap_or((0, 0)); + let mut sample_rate = tag("FilmCraft Audio Sample Rate").and_then(|s| s.parse().ok()).unwrap_or(0u32); + let mut comp = Composition { + name, + rate, + sample_rate: 48_000, + width: 1920, + height: 1080, + start_tc: 0, + drop: false, + tracks: Vec::new(), + markers: Vec::new(), + }; + let (mut nv, mut na) = (0, 0); + for s in slots { + let Some(seg) = s.strong(pid::SEGMENT) else { continue }; + if s.class == cls::EVENT_MOB_SLOT { + let er = rate_of(s, pid::EVENT_EDIT_RATE).unwrap_or(pic_rate); + comp.markers.extend(markers_of(seg, er)); + continue; + } + let er = rate_of(s, pid::EDIT_RATE).unwrap_or(pic_rate); + let origin = s.i64(pid::ORIGIN).unwrap_or(0); + match data_kind(seg) { + DataKind::Timecode => { + if let Some(tc) = find_class(seg, cls::TIMECODE) { + comp.start_tc = tc.i64(pid::TC_START).unwrap_or(0); + comp.drop = tc.u8(pid::TC_DROP).unwrap_or(0) != 0; + } + } + kind @ (DataKind::Picture | DataKind::Sound) => { + let ckind = if kind == DataKind::Picture { CKind::Picture } else { CKind::Sound }; + if ckind == CKind::Sound && sample_rate == 0 && er.1 == 1 && er.0 >= 8000 { + sample_rate = er.0 as u32; + } + // Premiere Pro writes every video track into one slot: a nested scope with a + // segment per track, the lowest track first. (A scope whose last segment + // refers to the others is an effect over layers: one track, as before.) + let layers: Vec<&Obj> = if ckind == CKind::Picture && seg.class == cls::NESTED_SCOPE && !refers_to_scope(seg, 0) { + seg.objs(pid::NESTED_SLOTS).iter().collect() + } else { + Vec::new() + }; + let layered = !layers.is_empty(); + let whole = units_to_ticks(len_of(seg), er.0, er.1); + for layer in if layered { layers } else { vec![seg] } { + let mut items = self.segment(layer, er, ckind, 0); + if layered { + fit(&mut items, whole); + } + if origin > 0 { + // material before the origin is not shown + trim_front(&mut items, units_to_ticks(origin, er.0, er.1)); + } + let number = s.u32(pid::PHYSICAL_TRACK_NUMBER).unwrap_or(0); + let name = s.string(pid::SLOT_NAME).unwrap_or_default(); + let channels = if ckind == CKind::Sound { + items + .iter() + .filter_map(|i| match i { + CItem::Clip(c) => self.doc.sources.get(c.source).map(|s| s.channels), + _ => None, + }) + .max() + .unwrap_or(1) + .min(6) + } else { + 0 + }; + let n = if ckind == CKind::Picture { + nv += 1; + nv + } else { + na += 1; + na + }; + comp.tracks.push(CTrack { kind: ckind, name, number: if number > 0 && !layered { number } else { n }, channels, items }); + } + } + DataKind::Other => self.report.info("a slot of an unsupported data kind was skipped"), + } + } + if width == 0 { + // no size in the file: that of the first picture this composition shows, else of any + let own = comp.tracks.iter().filter(|t| t.kind == CKind::Picture).flat_map(|t| &t.items).find_map(|i| match i { + CItem::Clip(c) => self.doc.sources.get(c.source).filter(|s| s.kind == CKind::Picture && s.width > 0 && s.nested.is_none()), + _ => None, + }); + let pic = own.or_else(|| self.doc.sources.iter().find(|s| s.kind == CKind::Picture && s.width > 0)); + (width, height) = pic.map_or((1920, 1080), |p| (p.width, p.height)); + } + comp.width = width; + comp.height = height; + if sample_rate > 0 { + comp.sample_rate = sample_rate; + } + comp + } + + /// Items of a segment (a sequence or a single component). + fn segment(&mut self, seg: &Obj, rate: (i64, i64), kind: CKind, depth: usize) -> Vec { + if depth > 32 { + self.report.warn("segments nested too deeply were skipped"); + return vec![CItem::Filler(units_to_ticks(len_of(seg), rate.0, rate.1))]; + } + if seg.class == cls::SEQUENCE { + let mut out = Vec::new(); + for c in seg.objs(pid::COMPONENTS) { + out.extend(self.component(c, rate, kind, depth + 1)); + } + return out; + } + self.component(seg, rate, kind, depth + 1) + } + + fn component(&mut self, c: &Obj, rate: (i64, i64), kind: CKind, depth: usize) -> Vec { + let len = units_to_ticks(len_of(c), rate.0, rate.1); + match c.class { + x if x == cls::FILLER => vec![CItem::Filler(len)], + x if x == cls::SOURCE_CLIP => vec![self.clip(c, rate, kind, None)], + x if x == cls::SEQUENCE => self.segment(c, rate, kind, depth), + x if x == cls::TRANSITION => { + let cut = units_to_ticks(c.i64(pid::CUT_POINT).unwrap_or(0), rate.0, rate.1); + let og = c.strong(pid::OPERATION_GROUP); + let effect = og + .and_then(|o| tagged_values(o, pid::COMPONENT_USER_COMMENTS).into_iter().find(|(k, _)| k == "FilmCraft Effect").map(|(_, v)| v)) + .unwrap_or_else(|| { + let op = og.and_then(|o| o.weak_key(pid::OPERATION)).and_then(|k| ::try_from(k).ok()); + match (kind, op) { + (CKind::Sound, _) => "constant_power".into(), + (_, Some(o)) if o == def::VIDEO_FADE_TO_BLACK => "dip_to_black".into(), + (_, Some(o)) if o == def::SMPTE_VIDEO_WIPE => "wipe".into(), + _ => "cross_dissolve".into(), + } + }); + vec![CItem::Transition(CTransition { len, cut: cut.clamp(Tick::ZERO, len), effect })] + } + x if x == cls::OPERATION_GROUP => { + let op = c.weak_key(pid::OPERATION).and_then(|k| ::try_from(k).ok()); + let inputs = c.objs(pid::INPUT_SEGMENTS); + let Some(input) = inputs.first() else { + self.report.info("an effect without input was imported as a gap"); + return vec![CItem::Filler(len)]; + }; + let gain = if op == Some(def::MONO_AUDIO_GAIN) { + self.gain(c, len, rate) + } else { + self.report.warn("effects other than audio gain are not imported (their first input is used)"); + None + }; + let mut items = self.segment(input, rate, kind, depth); + // the operation's length rules + fit(&mut items, len); + if let Some(g) = gain { + match items.as_mut_slice() { + [CItem::Clip(cl)] => cl.gain = Some(g), + _ => self.report.warn("audio gain around several clips was not imported"), + } + } + items + } + x if x == cls::SELECTOR => match c.strong(pid::SELECTED) { + Some(s) => { + let mut items = self.segment(s, rate, kind, depth); + fit(&mut items, len); + items + } + None => vec![CItem::Filler(len)], + }, + x if x == cls::NESTED_SCOPE => match c.objs(pid::NESTED_SLOTS).last() { + Some(s) => { + let mut items = self.segment(s, rate, kind, depth); + fit(&mut items, len); + items + } + None => vec![CItem::Filler(len)], + }, + _ => { + self.report.info("an unsupported component was imported as a gap"); + vec![CItem::Filler(len)] + } + } + } + + fn gain(&mut self, og: &Obj, len: Tick, _rate: (i64, i64)) -> Option { + let p = og + .objs(pid::PARAMETERS) + .iter() + .find(|p| p.auid(pid::PARAMETER_DEFINITION) == Some(def::PARAM_AMPLITUDE)) + .or_else(|| og.objs(pid::PARAMETERS).first())?; + if p.class == cls::CONSTANT_VALUE { + return p.data(pid::CONSTANT_VALUE).and_then(indirect_f64).map(Gain::Constant); + } + if p.class == cls::VARYING_VALUE { + let linear = p.weak_key(pid::INTERPOLATION).and_then(|k| ::try_from(k).ok()) != Some(def::INTERP_CONSTANT); + let points: Vec<(Tick, f64)> = p + .objs(pid::POINT_LIST) + .iter() + .filter_map(|cp| { + let (n, d) = cp.rational(pid::CP_TIME).filter(|r| r.1 != 0)?; + let v = cp.data(pid::CP_VALUE).and_then(indirect_f64)?; + Some((Tick((len.0 as i128 * n as i128 / d as i128).clamp(-(1i128 << 56), 1i128 << 56) as i64), v)) + }) + .collect(); + return (!points.is_empty()).then_some(Gain::Varying { linear, points }); + } + None + } + + fn clip(&mut self, c: &Obj, rate: (i64, i64), kind: CKind, master_key: Option) -> CItem { + let len = units_to_ticks(len_of(c), rate.0, rate.1); + let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), rate.0, rate.1); + let name = tagged_values(c, pid::COMPONENT_USER_COMMENTS).into_iter().find(|(k, _)| k == "Clip Name").map(|(_, v)| v).unwrap_or_default(); + let (Some(id), Some(slot)) = (c.mob_id(pid::SOURCE_ID), c.u32(pid::SOURCE_MOB_SLOT_ID)) else { return CItem::Filler(len) }; + if id == [0; 32] { + return CItem::Filler(len); + } + if let Some(mob) = self.mobs.get(&id).copied().filter(|m| m.class == cls::COMPOSITION_MOB) { + return self.nest_clip(c, NestClip { mob, mob_id: id, slot_id: slot, rate, kind, name }); + } + match self.resolve(id, slot, start, kind, master_key, 0) { + Some((source, t)) => CItem::Clip(CClip { len, source, start: t, gain: None, name }), + None => CItem::Filler(len), + } + } + + /// A source clip that points at a composition: a nested sequence (Premiere Pro writes its + /// nested sequences this way). The composition is read once, however many clips use it. + fn nest_clip(&mut self, c: &Obj, clip: NestClip<'_>) -> CItem { + let NestClip { mob, mob_id: id, slot_id, rate, kind, name } = clip; + let len = units_to_ticks(len_of(c), rate.0, rate.1); + let index = match self.nests.get(&id) { + Some(&i) => i, + None => { + if self.open.contains(&id) || self.open.len() >= MAX_NESTING { + self.report.warn("a composition nested in itself or nested too deeply was imported as a gap"); + return CItem::Filler(len); + } + self.open.push(id); + let comp = self.composition(mob); + self.open.pop(); + let i = self.doc.nested.len(); + self.doc.nested.push(comp); + self.nests.insert(id, i); + i + } + }; + // the start counts edit units of the slot the clip points at + let slot_rate = + mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot_id)).and_then(|s| rate_of(s, pid::EDIT_RATE)).unwrap_or(rate); + let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), slot_rate.0, slot_rate.1); + let skey = (id, if kind == CKind::Picture { 0 } else { 1 }, "composition".to_string()); + let source = match self.sources.get(&skey) { + Some(&i) => i, + None => { + let Some(comp) = self.doc.nested.get(index) else { return CItem::Filler(len) }; + let length = comp + .tracks + .iter() + .map(|t| { + Tick(t.items.iter().fold(0i64, |a, i| { + if matches!(i, CItem::Transition(_)) { a.saturating_sub(i.len().0) } else { a.saturating_add(i.len().0) } + })) + }) + .max() + .unwrap_or(Tick::ZERO); + let channels = if kind == CKind::Sound { 2 } else { 0 }; + let s = Source { + key: format!("composition:{}", hex(&id)), + name: comp.name.clone(), + kind, + path: None, + channel: None, + channels, + file_channels: channels, + width: comp.width, + height: comp.height, + frame_rate: comp.rate, + sample_rate: comp.sample_rate, + bits: 16, + length, + offset: Tick::ZERO, + start_tc: None, + tc_rate: comp.rate, + embedded: None, + markers: Vec::new(), + nested: Some(index), + }; + let i = self.doc.sources.len(); + self.doc.sources.push(s); + self.sources.insert(skey, i); + i + } + }; + CItem::Clip(CClip { len, source, start, gain: None, name }) + } + + /// Follow a source reference to a file source mob: (source index, file time). + fn resolve(&mut self, id: MobId, slot_id: u32, start: Tick, kind: CKind, master_key: Option, depth: usize) -> Option<(usize, Tick)> { + if depth > 16 { + return None; + } + let Some(mob) = self.mobs.get(&id).copied() else { + self.report.warn("a clip references a mob that is not in the file (imported as a gap)"); + return None; + }; + let slot = mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot_id))?; + let rate = rate_of(slot, pid::EDIT_RATE).unwrap_or((25, 1)); + let seg = slot.strong(pid::SEGMENT)?; + if mob.class == cls::COMPOSITION_MOB { + self.report.warn("nested compositions are not supported (imported as gaps)"); + return None; + } + if mob.class == cls::MASTER_MOB { + let key = master_key.unwrap_or_else(|| hex(&id)); + let clip = first_clip(seg)?; + let inner = units_to_ticks(clip.i64(pid::START_TIME).unwrap_or(0), rate.0, rate.1); + let next = clip.mob_id(pid::SOURCE_ID)?; + let next_slot = clip.u32(pid::SOURCE_MOB_SLOT_ID)?; + if next == [0; 32] { + return None; + } + let markers = mob + .objs(pid::SLOTS) + .iter() + .filter(|s| s.class == cls::EVENT_MOB_SLOT) + .flat_map(|s| s.strong(pid::SEGMENT).map(|g| markers_of(g, rate_of(s, pid::EVENT_EDIT_RATE).unwrap_or(rate))).unwrap_or_default()) + .collect::>(); + let r = self.resolve(next, next_slot, start + inner, kind, Some(key), depth + 1)?; + let src = &mut self.doc.sources[r.0]; + if src.markers.is_empty() { + src.markers = markers; + } + if src.name.is_empty() + && let Some(n) = mob.string(pid::MOB_NAME) + { + src.name = n; + } + return Some(r); + } + // a source mob: file (has a file descriptor) or physical (tape / import) + let desc = mob.strong(pid::ESSENCE_DESCRIPTION); + let is_file = desc.is_some_and(|d| d.get(pid::SAMPLE_RATE).is_some() || d.get(pid::LOCATOR).is_some() || self.essence.contains_key(&id)); + if !is_file { + return None; + } + let key = master_key.unwrap_or_else(|| hex(&id)); + let skey = (id, slot_id, key.clone()); + if let Some(&i) = self.sources.get(&skey) { + return Some((i, start)); + } + let d = desc?; + let seg_kind = match data_kind(seg) { + DataKind::Picture => CKind::Picture, + DataKind::Sound => CKind::Sound, + _ => kind, + }; + let path = d.objs(pid::LOCATOR).iter().find_map(|l| l.string(pid::URL_STRING)).map(|u| craft_timeline::path::file_url_to_path(&u)); + let file_rate = rate_of(d, pid::SAMPLE_RATE).unwrap_or(rate); + let length = d + .i64(pid::FILE_LENGTH) + .map(|l| units_to_ticks(l, file_rate.0, file_rate.1)) + .unwrap_or_else(|| units_to_ticks(len_of(seg), rate.0, rate.1)); + let sound_slots = mob.objs(pid::SLOTS).iter().filter(|s| s.strong(pid::SEGMENT).is_some_and(|g| data_kind(g) == DataKind::Sound)).count(); + let file_channels = d.u32(pid::CHANNELS).unwrap_or(1).max(1); + let channel = (seg_kind == CKind::Sound && file_channels > 1 && sound_slots > 1) + .then(|| slot.u32(pid::PHYSICAL_TRACK_NUMBER).unwrap_or(slot_id).saturating_sub(1).min(file_channels - 1)); + let mut layout = d.u8(pid::FRAME_LAYOUT).unwrap_or(0); + if layout > 4 { + layout = 0; + } + let stored_h = d.u32(pid::STORED_HEIGHT).unwrap_or(0); + let fr = FrameRate::new(file_rate.0, file_rate.1); + // timecode from the physical source mob + let tc = first_clip(seg).and_then(|clip| { + let tid = clip.mob_id(pid::SOURCE_ID)?; + let tape = self.mobs.get(&tid)?; + let tslot = tape.objs(pid::SLOTS).iter().find_map(|s| { + let g = s.strong(pid::SEGMENT)?; + let t = find_class(g, cls::TIMECODE)?; + Some((t.i64(pid::TC_START).unwrap_or(0), t.u16(pid::TC_FPS).unwrap_or(25).max(1) as i64, rate_of(s, pid::EDIT_RATE))) + })?; + let off = units_to_ticks(clip.i64(pid::START_TIME).unwrap_or(0), rate.0, rate.1); + let tcr = tslot.2.map(|r| FrameRate::new(r.0, r.1)).unwrap_or_else(|| FrameRate::new(tslot.1, 1)); + Some((tslot.0 + tcr.frame_at(off), tcr)) + }); + let mut s = Source { + key, + name: mob.string(pid::MOB_NAME).unwrap_or_default(), + kind: seg_kind, + path, + channel, + channels: if channel.is_some() { 1 } else { file_channels }, + file_channels, + width: d.u32(pid::STORED_WIDTH).unwrap_or(0), + height: if matches!(layout, 1 | 3) { stored_h.saturating_mul(2) } else { stored_h }, + frame_rate: if seg_kind == CKind::Picture { fr } else { FrameRate::FPS_25 }, + sample_rate: d + .rational(pid::AUDIO_SAMPLING_RATE) + .filter(|r| r.1 > 0 && r.0 > 0) + .map(|r| (r.0 / r.1) as u32) + .unwrap_or(file_rate.0 as u32), + bits: d.u32(pid::QUANTIZATION_BITS).unwrap_or(16).clamp(8, 32) as u16, + length, + offset: Tick::ZERO, + start_tc: tc.map(|t| t.0), + tc_rate: tc.map(|t| t.1).unwrap_or(fr), + embedded: None, + markers: Vec::new(), + nested: None, + }; + if s.kind == CKind::Sound { + s.frame_rate = FrameRate::FPS_25; + if let Some(data) = self.essence.get(&id) { + s.embedded = Some(data.to_vec()); + // embedded essence may be a whole WAVE / AIFF file + if let Some((pcm, ch, sr, bits)) = crate::pcm::parse_wav(data) { + s.embedded = Some(pcm); + s.file_channels = ch as u32; + s.channels = if s.channel.is_some() { 1 } else { ch as u32 }; + s.sample_rate = sr; + s.bits = bits; + } + } + } + if s.kind == CKind::Picture && s.width == 0 { + s.width = 1920; + s.height = 1080; + } + let i = self.doc.sources.len(); + self.doc.sources.push(s); + self.sources.insert(skey, i); + Some((i, start)) + } +} + +/// Drop `t` from the front of a track's items (slot origin). +fn trim_front(items: &mut Vec, mut t: Tick) { + while t > Tick::ZERO && !items.is_empty() { + let l = items[0].len(); + if matches!(items[0], CItem::Transition(_)) { + items.remove(0); + continue; + } + if l <= t { + items.remove(0); + t -= l; + } else { + match &mut items[0] { + CItem::Filler(x) => *x -= t, + CItem::Clip(c) => { + c.len -= t; + c.start += t; + } + CItem::Transition(_) => {} + } + t = Tick::ZERO; + } + } +} + +/// Make the items exactly `len` long (an operation group / selector is as long as itself). +fn fit(items: &mut Vec, len: Tick) { + let total = Tick( + items.iter().fold(0i64, |a, i| if matches!(i, CItem::Transition(_)) { a.saturating_sub(i.len().0) } else { a.saturating_add(i.len().0) }), + ); + if total == len || items.is_empty() { + if items.is_empty() { + items.push(CItem::Filler(len)); + } + return; + } + if total < len { + items.push(CItem::Filler(len - total)); + return; + } + let mut excess = total - len; + while excess > Tick::ZERO { + match items.last_mut() { + Some(CItem::Filler(x)) | Some(CItem::Clip(CClip { len: x, .. })) if *x > excess => { + *x -= excess; + excess = Tick::ZERO; + } + Some(CItem::Transition(_)) => { + items.pop(); + } + Some(other) => { + excess -= other.len(); + items.pop(); + } + None => break, + } + } +} + +/// Whether anything inside `o` is a scope reference (a nested scope used as an effect's layers). +fn refers_to_scope(o: &Obj, depth: usize) -> bool { + if o.class == cls::SCOPE_REFERENCE { + return true; + } + if depth > 32 { + return false; + } + o.props.iter().any(|(_, v)| match v { + Value::Strong(c) => refers_to_scope(c, depth + 1), + Value::StrongVec(v) | Value::StrongSet(v, _) => v.iter().any(|c| refers_to_scope(c, depth + 1)), + _ => false, + }) +} + +fn first_clip(seg: &Obj) -> Option<&Obj> { + if seg.class == cls::SOURCE_CLIP { + return Some(seg); + } + if seg.class == cls::SEQUENCE { + return seg.objs(pid::COMPONENTS).iter().find_map(first_clip); + } + // essence group (choices 0x0501) / operation group inputs + seg.objs(0x0501).iter().find_map(first_clip).or_else(|| seg.objs(pid::INPUT_SEGMENTS).iter().find_map(first_clip)) +} + +fn find_class(seg: &Obj, class: Auid) -> Option<&Obj> { + if seg.class == class { + return Some(seg); + } + seg.objs(pid::COMPONENTS).iter().find_map(|c| find_class(c, class)) +} + +fn markers_of(seg: &Obj, rate: (i64, i64)) -> Vec { + let events: Vec<&Obj> = if seg.class == cls::SEQUENCE { seg.objs(pid::COMPONENTS).iter().collect() } else { vec![seg] }; + events + .into_iter() + .filter(|e| e.class == cls::COMMENT_MARKER || e.class == cls::DESCRIPTIVE_MARKER || e.get(pid::POSITION).is_some()) + .map(|e| { + let tags = tagged_values(e, pid::COMPONENT_USER_COMMENTS); + let tag = |n: &str| tags.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone()); + let comment = e.string(pid::COMMENT).unwrap_or_default(); + let start = units_to_ticks(e.i64(pid::POSITION).unwrap_or(0), rate.0, rate.1); + CMarker { + start, + duration: units_to_ticks(e.i64(pid::LENGTH).unwrap_or(0).max(0), rate.0, rate.1), + name: tag("Name").unwrap_or_else(|| comment.clone()), + comment: tag("Comment").unwrap_or_else(|| if tags.is_empty() { String::new() } else { comment.clone() }), + color: tag("Color"), + } + }) + .collect() +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} diff --git a/crates/aaf/src/aaf/store.rs b/crates/aaf/src/aaf/store.rs new file mode 100644 index 000000000..46ab95dae --- /dev/null +++ b/crates/aaf/src/aaf/store.rs @@ -0,0 +1,538 @@ +//! AAF objects in structured storage (the AAF Low-Level Container Specification): every object +//! is a storage whose class id is the object's class AUID, holding a `properties` stream; strong +//! references are child storages, collections have an index stream, weak references name a key +//! in a target collection through the root's `referenced properties` table. +//! +//! `properties` stream (little-endian): +//! +//! ```text +//! u8 byte order (0x4C 'L') u8 format version (0x20) u16 entry count +//! entry count × { u16 pid, u16 stored form, u16 value length } the values, in entry order +//! ``` +//! +//! | stored form | value | +//! |---|---| +//! | 0x82 data | the property's bytes | +//! | 0x22 strong reference | UTF-16 name of the child storage | +//! | 0x32 strong reference vector | UTF-16 collection name; storages `name{key}`, stream `name index`: u32 count, u32 first free key, u32 last free key, count × u32 local key | +//! | 0x3A strong reference set | as a vector; the index adds u16 key pid, u8 key size, and each entry is u32 local key, u32 reference count, key bytes | +//! | 0x02 weak reference | u16 referenced-property tag, u16 key pid, u8 key size, key bytes | +//! | 0x12 / 0x1A weak reference vector / set | UTF-16 collection name; stream `name index`: u32 count, u16 tag, u16 key pid, u8 key size, count × key | +//! | 0x42 data stream | u8 byte order, UTF-16 name of the stream | +//! +//! `referenced properties` (root stream): u8 byte order, u16 path count, u32 pid count, then the +//! pids of each path (from the root object) terminated by a 0 pid. + +use craft_cfb::{CompoundFile, EntryKind, NodeId, Version, Writer}; + +pub(crate) type Auid = [u8; 16]; + +pub(crate) const SF_DATA: u16 = 0x82; +pub(crate) const SF_DATA_STREAM: u16 = 0x42; +pub(crate) const SF_STRONG: u16 = 0x22; +pub(crate) const SF_STRONG_VECTOR: u16 = 0x32; +pub(crate) const SF_STRONG_SET: u16 = 0x3A; +pub(crate) const SF_WEAK: u16 = 0x02; +pub(crate) const SF_WEAK_VECTOR: u16 = 0x12; +pub(crate) const SF_WEAK_SET: u16 = 0x1A; + +const BYTE_ORDER_LE: u8 = 0x4C; +const FORMAT_VERSION: u8 = 0x20; + +/// A property value. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Value { + Data(Vec), + Strong(Box), + StrongVec(Vec), + /// Objects keyed by the data property `key_pid` of each. + StrongSet(Vec, u16), + /// (path of pids from the root to the target collection, key pid, key) + Weak(Vec, u16, Vec), + WeakVec(Vec, u16, Vec>), + Stream(Vec), +} + +/// An AAF object: its class and properties. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Obj { + pub class: Auid, + pub props: Vec<(u16, Value)>, +} + +impl Obj { + pub fn new(class: Auid) -> Obj { + Obj { class, props: Vec::new() } + } + pub fn set(&mut self, pid: u16, v: Value) -> &mut Obj { + match self.props.iter_mut().find(|(p, _)| *p == pid) { + Some(slot) => slot.1 = v, + None => self.props.push((pid, v)), + } + self + } + pub fn with(mut self, pid: u16, v: Value) -> Obj { + self.set(pid, v); + self + } + pub fn data_prop(mut self, pid: u16, d: Vec) -> Obj { + self.set(pid, Value::Data(d)); + self + } + pub fn get(&self, pid: u16) -> Option<&Value> { + self.props.iter().find(|(p, _)| *p == pid).map(|(_, v)| v) + } + pub fn data(&self, pid: u16) -> Option<&[u8]> { + match self.get(pid)? { + Value::Data(d) => Some(d), + _ => None, + } + } + pub fn strong(&self, pid: u16) -> Option<&Obj> { + match self.get(pid)? { + Value::Strong(o) => Some(o), + _ => None, + } + } + /// Elements of a strong vector or set (empty when absent). + pub fn objs(&self, pid: u16) -> &[Obj] { + match self.get(pid) { + Some(Value::StrongVec(v)) | Some(Value::StrongSet(v, _)) => v, + _ => &[], + } + } + pub fn weak_key(&self, pid: u16) -> Option<&[u8]> { + match self.get(pid)? { + Value::Weak(_, _, k) => Some(k), + _ => None, + } + } + pub fn stream(&self, pid: u16) -> Option<&[u8]> { + match self.get(pid)? { + Value::Stream(d) => Some(d), + _ => None, + } + } + pub fn u8(&self, pid: u16) -> Option { + self.data(pid).and_then(|d| d.first().copied()) + } + pub fn u16(&self, pid: u16) -> Option { + self.data(pid).filter(|d| d.len() >= 2).map(|d| u16::from_le_bytes([d[0], d[1]])) + } + pub fn u32(&self, pid: u16) -> Option { + self.data(pid).filter(|d| d.len() >= 4).map(|d| u32::from_le_bytes([d[0], d[1], d[2], d[3]])) + } + pub fn i64(&self, pid: u16) -> Option { + let d = self.data(pid)?; + match d.len() { + 8.. => Some(i64::from_le_bytes(d[..8].try_into().ok()?)), + 4..=7 => Some(i32::from_le_bytes(d[..4].try_into().ok()?) as i64), + _ => None, + } + } + pub fn rational(&self, pid: u16) -> Option<(i64, i64)> { + self.data(pid).and_then(rational_of) + } + pub fn string(&self, pid: u16) -> Option { + self.data(pid).map(utf16_of) + } + pub fn auid(&self, pid: u16) -> Option { + self.data(pid).and_then(|d| d.get(..16)).and_then(|d| d.try_into().ok()) + } + pub fn mob_id(&self, pid: u16) -> Option<[u8; 32]> { + self.data(pid).and_then(|d| d.get(..32)).and_then(|d| d.try_into().ok()) + } +} + +pub(crate) fn rational_of(d: &[u8]) -> Option<(i64, i64)> { + (d.len() >= 8).then(|| (i32::from_le_bytes([d[0], d[1], d[2], d[3]]) as i64, i32::from_le_bytes([d[4], d[5], d[6], d[7]]) as i64)) +} + +pub(crate) fn rational(num: i64, den: i64) -> Vec { + let mut v = (num.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_le_bytes().to_vec(); + v.extend_from_slice(&(den.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_le_bytes()); + v +} + +/// UTF-16LE with a terminating NUL. +pub(crate) fn utf16z(s: &str) -> Vec { + let mut v: Vec = s.encode_utf16().flat_map(u16::to_le_bytes).collect(); + v.extend_from_slice(&[0, 0]); + v +} + +pub(crate) fn utf16_of(d: &[u8]) -> String { + let u: Vec = d.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&c| c != 0).collect(); + String::from_utf16_lossy(&u) +} + +/// Short property names used to name storages and streams (any name is valid: readers follow +/// the names stored in the property values). +fn prop_name(pid: u16) -> &'static str { + match pid { + 0x0001 => "MetaDictionary", + 0x0002 => "Header", + 0x0003 => "ClassDefinitions", + 0x0004 => "TypeDefinitions", + 0x3B03 => "Content", + 0x3B04 => "Dictionary", + 0x3B06 => "IdentificationList", + 0x1901 => "Mobs", + 0x1902 => "EssenceData", + 0x2603 => "OperationDefinitions", + 0x2604 => "ParameterDefinitions", + 0x2605 => "DataDefinitions", + 0x2607 => "CodecDefinitions", + 0x2608 => "ContainerDefinitions", + 0x2609 => "InterpolationDefs", + 0x4403 => "Slots", + 0x4406 => "UserComments", + 0x4803 => "Segment", + 0x1001 => "Components", + 0x1801 => "OperationGroup", + 0x0B02 => "InputSegments", + 0x0B03 => "Parameters", + 0x4E02 => "PointList", + 0x4701 => "EssenceDescription", + 0x2F01 => "Locator", + 0x2702 => "Data", + 0x0204 => "ComponentComments", + 0x1E09 => "ParametersDefined", + _ => "Property", + } +} + +/// The key size of a strong reference set keyed by `key_pid`, for a set with no entry to take it +/// from: AUIDs (definitions) are 16 bytes, MobIDs 32. +fn set_key_size(key_pid: u16) -> usize { + match key_pid { + 0x0005 | 0x1B01 => 16, + 0x4401 | 0x2701 => 32, + _ => 0, + } +} + +fn storage_name(pid: u16) -> String { + let suffix = format!("-{pid:x}"); + let name: String = prop_name(pid).chars().take(22 - suffix.len()).collect(); + format!("{name}{suffix}") +} + +/// Errors while reading the object tree. +fn bad(s: impl Into) -> String { + s.into() +} + +// --------------------------------------------------------------------------------------------- +// Writing +// --------------------------------------------------------------------------------------------- + +struct W { + cfb: Writer, + paths: Vec>, +} + +/// Serialise `root` (the Root object: MetaDictionary 0x0001, Header 0x0002) into a compound file. +pub(crate) fn write(root: &Obj, version: Version) -> Result, String> { + let mut w = W { cfb: Writer::new(version), paths: Vec::new() }; + w.obj(Writer::ROOT, root)?; + let mut rp = vec![BYTE_ORDER_LE]; + rp.extend_from_slice(&(w.paths.len() as u16).to_le_bytes()); + let n: usize = w.paths.iter().map(|p| p.len() + 1).sum(); + rp.extend_from_slice(&(n as u32).to_le_bytes()); + for p in &w.paths { + for pid in p { + rp.extend_from_slice(&pid.to_le_bytes()); + } + rp.extend_from_slice(&0u16.to_le_bytes()); + } + w.cfb.stream(Writer::ROOT, "referenced properties", rp).map_err(|e| e.to_string())?; + Ok(w.cfb.finish()) +} + +impl W { + fn tag(&mut self, path: &[u16]) -> u16 { + match self.paths.iter().position(|p| p == path) { + Some(i) => i as u16, + None => { + self.paths.push(path.to_vec()); + (self.paths.len() - 1) as u16 + } + } + } + + fn obj(&mut self, node: NodeId, o: &Obj) -> Result<(), String> { + self.cfb.set_clsid(node, o.class); + let mut entries: Vec<(u16, u16, Vec)> = Vec::new(); + for (pid, v) in &o.props { + let pid = *pid; + let (sf, value) = match v { + Value::Data(d) => (SF_DATA, d.clone()), + Value::Strong(child) => { + let name = storage_name(pid); + let s = self.cfb.storage(node, &name, child.class).map_err(|e| e.to_string())?; + self.obj(s, child)?; + (SF_STRONG, utf16z(&name)) + } + Value::StrongVec(items) | Value::StrongSet(items, _) => { + let name = storage_name(pid); + let mut index = Vec::new(); + index.extend_from_slice(&(items.len() as u32).to_le_bytes()); + index.extend_from_slice(&(items.len() as u32).to_le_bytes()); // first free key + index.extend_from_slice(&u32::MAX.to_le_bytes()); // last free key + let set_key = if let Value::StrongSet(_, k) = v { Some(*k) } else { None }; + let key_size = set_key.map(|k| items.first().and_then(|i| i.data(k)).map_or_else(|| set_key_size(k), <[u8]>::len)).unwrap_or(0); + if let Some(k) = set_key { + index.extend_from_slice(&k.to_le_bytes()); + index.push(key_size as u8); + } + for (i, item) in items.iter().enumerate() { + let s = self.cfb.storage(node, &format!("{name}{{{i:x}}}"), item.class).map_err(|e| e.to_string())?; + self.obj(s, item)?; + index.extend_from_slice(&(i as u32).to_le_bytes()); + if let Some(k) = set_key { + index.extend_from_slice(&1u32.to_le_bytes()); + let mut key = item.data(k).unwrap_or(&[]).to_vec(); + key.resize(key_size, 0); + index.extend_from_slice(&key); + } + } + self.cfb.stream(node, &format!("{name} index"), index).map_err(|e| e.to_string())?; + (if set_key.is_some() { SF_STRONG_SET } else { SF_STRONG_VECTOR }, utf16z(&name)) + } + Value::Weak(path, key_pid, key) => { + let mut d = self.tag(path).to_le_bytes().to_vec(); + d.extend_from_slice(&key_pid.to_le_bytes()); + d.push(key.len() as u8); + d.extend_from_slice(key); + (SF_WEAK, d) + } + Value::WeakVec(path, key_pid, keys) => { + let name = storage_name(pid); + let tag = self.tag(path); + let size = keys.first().map_or(0, Vec::len); + let mut index = (keys.len() as u32).to_le_bytes().to_vec(); + index.extend_from_slice(&tag.to_le_bytes()); + index.extend_from_slice(&key_pid.to_le_bytes()); + index.push(size as u8); + for k in keys { + let mut k = k.clone(); + k.resize(size, 0); + index.extend_from_slice(&k); + } + self.cfb.stream(node, &format!("{name} index"), index).map_err(|e| e.to_string())?; + (SF_WEAK_VECTOR, utf16z(&name)) + } + Value::Stream(data) => { + let name = storage_name(pid); + self.cfb.stream(node, &name, data.clone()).map_err(|e| e.to_string())?; + let mut d = vec![BYTE_ORDER_LE]; + d.extend_from_slice(&utf16z(&name)); + (SF_DATA_STREAM, d) + } + }; + if value.len() > u16::MAX as usize { + return Err(format!("property {pid:#06x} is {} bytes (the limit is 65535)", value.len())); + } + entries.push((pid, sf, value)); + } + let mut props = vec![BYTE_ORDER_LE, FORMAT_VERSION]; + props.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + for (pid, sf, v) in &entries { + props.extend_from_slice(&pid.to_le_bytes()); + props.extend_from_slice(&sf.to_le_bytes()); + props.extend_from_slice(&(v.len() as u16).to_le_bytes()); + } + for (_, _, v) in &entries { + props.extend_from_slice(v); + } + self.cfb.stream(node, "properties", props).map_err(|e| e.to_string())?; + Ok(()) + } +} + +// --------------------------------------------------------------------------------------------- +// Reading +// --------------------------------------------------------------------------------------------- + +struct R<'a> { + cf: CompoundFile<'a>, + paths: Vec>, + objects: usize, + materialized_stream_bytes: usize, + /// Storages already read: a storage is owned by one parent, so a second strong reference to it + /// (which would rebuild its whole subtree again) is refused. + owned: std::collections::HashSet, + /// Bytes of weak-reference target paths copied into the tree so far. + path_bytes: usize, +} + +const MAX_DEPTH: usize = 200; +const MAX_OBJECTS: usize = 2_000_000; +const MAX_MATERIALIZED_STREAM_BYTES: usize = 256 << 20; +/// Each weak reference carries its own copy of its target path (real paths are a handful of +/// property ids); the copies together may not exceed this. +const MAX_PATH_BYTES: usize = 64 << 20; + +/// Parse the object tree of an AAF compound file (the root object). +pub(crate) fn read(bytes: &[u8]) -> Result { + let cf = CompoundFile::open(bytes).map_err(|e| e.to_string())?; + let mut paths = Vec::new(); + if let Ok(rp) = cf.read_path("referenced properties") + && rp.len() >= 7 + { + let count = u16::from_le_bytes([rp[1], rp[2]]) as usize; + let mut cur = Vec::new(); + for c in rp[7..].as_chunks::<2>().0 { + let pid = u16::from_le_bytes([c[0], c[1]]); + if pid == 0 { + paths.push(std::mem::take(&mut cur)); + if paths.len() == count { + break; + } + } else { + cur.push(pid); + } + } + } + let mut r = R { cf, paths, objects: 0, materialized_stream_bytes: 0, owned: Default::default(), path_bytes: 0 }; + r.obj(0, 0) +} + +fn rd_u16(b: &[u8], at: usize) -> Option { + b.get(at..at + 2).map(|s| u16::from_le_bytes([s[0], s[1]])) +} +fn rd_u32(b: &[u8], at: usize) -> Option { + b.get(at..at + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) +} + +impl R<'_> { + fn child(&self, parent: usize, name: &str) -> Result { + self.cf.child(parent, name).ok_or_else(|| bad(format!("missing storage or stream \"{name}\""))) + } + + fn stream(&mut self, parent: usize, name: &str) -> Result, String> { + let id = self.child(parent, name)?; + let data = self.cf.read(id).map_err(|e| e.to_string())?; + self.materialized_stream_bytes = self + .materialized_stream_bytes + .checked_add(data.len()) + .filter(|&n| n <= MAX_MATERIALIZED_STREAM_BYTES) + .ok_or_else(|| bad("AAF materialized stream data exceeds the memory limit"))?; + Ok(data) + } + + /// A copy of weak-reference path `tag`, counted against [`MAX_PATH_BYTES`]. + fn path(&mut self, tag: u16) -> Result, String> { + let path = self.paths.get(tag as usize).cloned().unwrap_or_default(); + self.path_bytes = self.path_bytes.saturating_add(path.len() * 2); + if self.path_bytes > MAX_PATH_BYTES { + return Err(bad("weak reference paths exceed the memory limit")); + } + Ok(path) + } + + fn obj(&mut self, entry: usize, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err(bad("objects nested too deeply")); + } + if !self.owned.insert(entry) { + return Err(bad("a storage is owned by more than one reference")); + } + self.objects += 1; + if self.objects > MAX_OBJECTS { + return Err(bad("too many objects")); + } + let e = self.cf.entry(entry).ok_or_else(|| bad("bad directory entry"))?; + if !matches!(e.kind, EntryKind::Root | EntryKind::Storage) { + return Err(bad(format!("\"{}\" is not a storage", e.name))); + } + let mut o = Obj::new(e.clsid); + let props = self.stream(entry, "properties")?; + if props.len() < 4 { + return Err(bad("short properties stream")); + } + if props[0] != BYTE_ORDER_LE { + return Err(bad("big-endian AAF files are not supported")); + } + let n = rd_u16(&props, 2).unwrap_or(0) as usize; + let mut at = 4 + n * 6; + if at > props.len() { + return Err(bad("truncated property index")); + } + for i in 0..n { + let (Some(pid), Some(sf), Some(len)) = (rd_u16(&props, 4 + i * 6), rd_u16(&props, 6 + i * 6), rd_u16(&props, 8 + i * 6)) else { + return Err(bad("truncated property index")); + }; + if o.props.iter().any(|(previous, _)| *previous == pid) { + return Err(bad("duplicate property id")); + } + let v = props.get(at..at + len as usize).ok_or_else(|| bad("truncated property value"))?; + at += len as usize; + let value = match sf { + SF_STRONG => { + let c = self.child(entry, &utf16_of(v))?; + Value::Strong(Box::new(self.obj(c, depth + 1)?)) + } + SF_STRONG_VECTOR | SF_STRONG_SET => { + let name = utf16_of(v); + let idx = self.stream(entry, &format!("{name} index"))?; + let count = rd_u32(&idx, 0).ok_or_else(|| bad("short collection index"))? as usize; + let mut items = Vec::new(); + if sf == SF_STRONG_VECTOR { + for k in 0..count { + let key = rd_u32(&idx, 12 + k * 4).ok_or_else(|| bad("short vector index"))?; + let c = self.child(entry, &format!("{name}{{{key:x}}}"))?; + items.push(self.obj(c, depth + 1)?); + } + Value::StrongVec(items) + } else { + let key_pid = rd_u16(&idx, 12).ok_or_else(|| bad("short set index"))?; + let key_size = *idx.get(14).ok_or_else(|| bad("short set index"))? as usize; + let stride = 8 + key_size; + for k in 0..count { + let key = rd_u32(&idx, 15 + k * stride).ok_or_else(|| bad("short set index"))?; + let c = self.child(entry, &format!("{name}{{{key:x}}}"))?; + items.push(self.obj(c, depth + 1)?); + } + Value::StrongSet(items, key_pid) + } + } + SF_WEAK => { + let (Some(tag), Some(key_pid), Some(&size)) = (rd_u16(v, 0), rd_u16(v, 2), v.get(4)) else { + return Err(bad("short weak reference")); + }; + let key = v.get(5..5 + size as usize).ok_or_else(|| bad("short weak reference"))?.to_vec(); + Value::Weak(self.path(tag)?, key_pid, key) + } + SF_WEAK_VECTOR | SF_WEAK_SET => { + let name = utf16_of(v); + let idx = self.stream(entry, &format!("{name} index"))?; + let (Some(count), Some(tag), Some(key_pid), Some(&size)) = (rd_u32(&idx, 0), rd_u16(&idx, 4), rd_u16(&idx, 6), idx.get(8)) else { + return Err(bad("short weak collection index")); + }; + let size = size as usize; + if count > 0 && size == 0 { + return Err(bad("zero-size weak collection key")); + } + // every key must lie in the index, so its length (not the count) bounds the loop + if (count as usize).checked_mul(size).and_then(|n| n.checked_add(9)).is_none_or(|end| end > idx.len()) { + return Err(bad("short weak collection index")); + } + let mut keys = Vec::new(); + for k in 0..count as usize { + keys.push(idx.get(9 + k * size..9 + (k + 1) * size).ok_or_else(|| bad("short weak collection index"))?.to_vec()); + } + Value::WeakVec(self.path(tag)?, key_pid, keys) + } + SF_DATA_STREAM => { + let name = utf16_of(v.get(1..).unwrap_or(&[])); + Value::Stream(self.stream(entry, &name)?) + } + _ => Value::Data(v.to_vec()), + }; + o.props.push((pid, value)); + } + Ok(o) + } +} diff --git a/crates/aaf/src/aaf/tests.rs b/crates/aaf/src/aaf/tests.rs new file mode 100644 index 000000000..2773fda6d --- /dev/null +++ b/crates/aaf/src/aaf/tests.rs @@ -0,0 +1,467 @@ +//! Structural checks of written AAF files against the required properties and rules of the AAF +//! Object Specification v1.1 and the Edit Protocol, read back through the compound file reader. + +use std::collections::HashSet; + +use craft_timeline::time::FrameRate; + +use super::ids::{self, cls, ddef, def, path, pid}; +use super::store::{self, Obj, Value}; +use super::*; +use crate::model::{CItem, CKind}; +use crate::testdoc::{IDENTITY, clip, composition, picture_and_sound_cut, source, track}; + +fn document() -> Document { + // two 48-frame clips from source frames 10 and 200, a 12-frame transition + picture_and_sound_cut(FrameRate::FPS_24, 48, 12, (10, 200)) +} + +fn written(doc: &Document, small_sectors: bool) -> Vec { + let mut report = Report::default(); + let bytes = write(doc, &WriteOptions { identity: IDENTITY, small_sectors }, &mut report).unwrap(); + assert!(!report.has_warnings(), "{report}"); + bytes +} + +fn read_clean(bytes: &[u8]) -> Document { + let mut report = Report::default(); + let doc = read(bytes, &mut report).unwrap(); + assert!(!report.has_warnings(), "{report}"); + doc +} + +fn walk<'a>(o: &'a Obj, out: &mut Vec<&'a Obj>) { + out.push(o); + for (_, v) in &o.props { + match v { + Value::Strong(c) => walk(c, out), + Value::StrongVec(v) | Value::StrongSet(v, _) => v.iter().for_each(|c| walk(c, out)), + _ => {} + } + } +} + +fn keys(dict: &Obj, p: u16) -> HashSet> { + dict.objs(p).iter().filter_map(|d| d.data(pid::IDENTIFICATION).map(<[u8]>::to_vec)).collect() +} + +/// filmcraft#323: readers that load the meta-dictionary (pyaaf2) need its ClassDefinitions and +/// TypeDefinitions sets. They are empty: everything written uses the baseline classes and types +/// those readers already know. +#[test] +fn the_meta_dictionary_has_its_class_and_type_definition_sets() { + for small in [false, true] { + let bytes = written(&document(), small); + let cf = craft_cfb::CompoundFile::open(&bytes).unwrap(); + assert_eq!(cf.entries[cf.find("MetaDictionary-1").unwrap()].clsid, ids::META_DICTIONARY); + for name in ["ClassDefinitions-3", "TypeDefinitions-4"] { + // u32 count, u32 first free key, u32 last free key, u16 key pid, u8 key size + let index = cf.read_path(&format!("MetaDictionary-1/{name} index")).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(index.len(), 15, "{name}: an empty set"); + assert_eq!(index[0..4], 0u32.to_le_bytes(), "{name}: no entries"); + assert_eq!(u16::from_le_bytes([index[12], index[13]]), pid::META_IDENTIFICATION, "{name}: keyed by the definition's AUID"); + assert_eq!(index[14], 16, "{name}: 16-byte keys"); + } + let root = store::read(&bytes).unwrap(); + let meta = root.strong(pid::ROOT_META_DICTIONARY).unwrap(); + for set in [pid::META_CLASS_DEFINITIONS, pid::META_TYPE_DEFINITIONS] { + assert!(matches!(meta.get(set), Some(Value::StrongSet(items, k)) if items.is_empty() && *k == pid::META_IDENTIFICATION), "{set:#06x}"); + } + } +} + +#[test] +fn written_files_have_the_required_structure() { + for small in [false, true] { + let bytes = written(&document(), small); + assert_written_file(&bytes, small); + } +} + +/// The top-level composition is tagged `Usage_TopLevel`, which the SMPTE Labels register gives as +/// urn:smpte:ul:060e2b34.04010101.0d010102.01010700, stored as the AUID +/// {0d010102-0101-0700-060e-2b3404010101}. Readers that look for it (LibAAF) find no sequence +/// without it. +#[test] +fn the_top_level_composition_has_the_registered_usage_code() { + let bytes = written(&document(), false); + let root = store::read(&bytes).unwrap(); + let content = root.strong(pid::ROOT_HEADER).unwrap().strong(pid::CONTENT).unwrap(); + let comp = content.objs(pid::MOBS).iter().find(|m| m.class == cls::COMPOSITION_MOB).unwrap(); + let usage = [0x02, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x00, 0x07, 0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01]; + assert_eq!(comp.data(pid::USAGE_CODE), Some(&usage[..])); +} + +/// Files from FilmCraft 0.16 and earlier tag the top-level composition with the unregistered label +/// 060e2b34.04010105.0d011201.02030000. They still import: the composition no other one uses is +/// the edit. +#[test] +fn files_with_the_old_usage_code_still_import() { + let bytes = written(&document(), false); + let mut root = store::read(&bytes).unwrap(); + let content = strong_mut(strong_mut(&mut root, pid::ROOT_HEADER), pid::CONTENT); + for mob in objs_mut(content, pid::MOBS).iter_mut().filter(|m| m.class == cls::COMPOSITION_MOB) { + mob.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL_OLD.to_vec())); + } + let old_file = store::write(&root, craft_cfb::Version::V4).unwrap(); + let got = read_clean(&old_file); + assert_eq!(got.compositions.len(), 1); + assert_eq!(got, read_clean(&bytes)); +} + +/// A file that holds one edit tagged with each label (a tool merged a composition from an older +/// file into a newer one) imports both edits. +#[test] +fn edits_tagged_with_either_usage_code_both_import() { + let bytes = written(&document(), false); + let mut root = store::read(&bytes).unwrap(); + let content = strong_mut(strong_mut(&mut root, pid::ROOT_HEADER), pid::CONTENT); + let mobs = objs_mut(content, pid::MOBS); + let mut old = mobs.iter().find(|m| m.class == cls::COMPOSITION_MOB).unwrap().clone(); + let mut id = old.mob_id(pid::MOB_ID).unwrap(); + id[31] ^= 0xFF; + old.set(pid::MOB_ID, Value::Data(id.to_vec())); + old.set(pid::MOB_NAME, Value::Data(store::utf16z("Old"))); + old.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL_OLD.to_vec())); + mobs.push(old); + let mixed = store::write(&root, craft_cfb::Version::V4).unwrap(); + let mut names: Vec = read_clean(&mixed).compositions.into_iter().map(|c| c.name).collect(); + names.sort(); + assert_eq!(names, ["Old", "S"]); +} + +fn assert_written_file(bytes: &[u8], small: bool) { + assert_compound_file(bytes, small); + let root = store::read(bytes).unwrap(); + assert!(root.strong(pid::ROOT_META_DICTIONARY).is_some()); + let header = root.strong(pid::ROOT_HEADER).unwrap(); + let content = assert_header(header); + let dict = header.strong(pid::DICTIONARY).unwrap(); + let definitions = Definitions { + data: keys(dict, pid::DATA_DEFINITIONS), + operations: keys(dict, pid::OPERATION_DEFINITIONS), + interpolation: keys(dict, pid::INTERPOLATION_DEFINITIONS), + containers: keys(dict, pid::CONTAINER_DEFINITIONS), + parameters: keys(dict, pid::PARAMETER_DEFINITIONS), + }; + let mobs = content.objs(pid::MOBS); + let comp = assert_mob_set(content, mobs); + for mob in mobs { + assert_mob(mob, mobs, &definitions); + } + assert_composition(comp); +} + +fn assert_compound_file(bytes: &[u8], small: bool) { + let cf = craft_cfb::CompoundFile::open(bytes).unwrap(); + assert_eq!(cf.version, if small { 3 } else { 4 }); + assert_eq!(cf.root().clsid, ids::ROOT); + let references = cf.read_path("referenced properties").unwrap(); + let pids: Vec = references[7..].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + assert!(pids.windows(3).any(|w| w == path::DATA_DEFS)); + let header = cf.find("Header-2").unwrap(); + assert_eq!(cf.entries[header].clsid, cls::HEADER); + assert!(cf.read_path("Header-2/properties").unwrap().starts_with(&[0x4C, 0x20])); +} + +fn assert_header(header: &Obj) -> &Obj { + for req in [pid::BYTE_ORDER, pid::LAST_MODIFIED, pid::CONTENT, pid::DICTIONARY, pid::VERSION, pid::IDENTIFICATION_LIST, pid::OBJECT_MODEL_VERSION] + { + assert!(header.get(req).is_some(), "Header property {req:#06x}"); + } + assert_eq!(header.auid(pid::OPERATIONAL_PATTERN), Some(def::OP_EDIT_PROTOCOL)); + let ident = &header.objs(pid::IDENTIFICATION_LIST)[0]; + for req in [pid::COMPANY_NAME, pid::PRODUCT_NAME, pid::PRODUCT_VERSION_STRING, pid::PRODUCT_ID, pid::DATE, pid::GENERATION_AUID] { + assert!(ident.get(req).is_some(), "Identification property {req:#06x}"); + } + header.strong(pid::CONTENT).unwrap() +} + +struct Definitions { + data: HashSet>, + operations: HashSet>, + interpolation: HashSet>, + containers: HashSet>, + parameters: HashSet>, +} + +fn assert_mob_set<'a>(content: &Obj, mobs: &'a [Obj]) -> &'a Obj { + let mob_ids: Vec<[u8; 32]> = mobs.iter().map(|m| m.mob_id(pid::MOB_ID).unwrap()).collect(); + assert_eq!(mob_ids.iter().collect::>().len(), mob_ids.len(), "unique mob ids"); + assert!(matches!(content.get(pid::MOBS), Some(Value::StrongSet(_, k)) if *k == pid::MOB_ID)); + let compositions: Vec<&Obj> = mobs.iter().filter(|m| m.class == cls::COMPOSITION_MOB).collect(); + assert_eq!(compositions.len(), 1); + assert_eq!(compositions[0].auid(pid::USAGE_CODE), Some(def::USAGE_TOP_LEVEL)); + assert_eq!(mobs.iter().filter(|m| m.class == cls::MASTER_MOB).count(), 1); + assert_eq!(mobs.iter().filter(|m| m.class == cls::SOURCE_MOB).count(), 3, "picture file, sound file, tape"); + compositions[0] +} + +fn assert_mob(mob: &Obj, mobs: &[Obj], definitions: &Definitions) { + for req in [pid::MOB_ID, pid::MOB_NAME, pid::SLOTS, pid::MOB_LAST_MODIFIED, pid::MOB_CREATION_TIME] { + assert!(mob.get(req).is_some(), "Mob property {req:#06x}"); + } + assert_source_descriptor(mob, &definitions.containers); + for slot in mob.objs(pid::SLOTS) { + assert!(slot.get(pid::SLOT_ID).is_some() && slot.get(pid::SEGMENT).is_some()); + if slot.class == cls::TIMELINE_MOB_SLOT { + assert!(slot.rational(pid::EDIT_RATE).is_some_and(|r| r.0 > 0 && r.1 > 0)); + assert!(slot.get(pid::ORIGIN).is_some()); + } + } + let mut all = Vec::new(); + walk(mob, &mut all); + for component in all { + assert_component(component, mobs, definitions); + } +} + +fn assert_source_descriptor(mob: &Obj, containers: &HashSet>) { + if mob.class != cls::SOURCE_MOB { + return; + } + let descriptor = mob.strong(pid::ESSENCE_DESCRIPTION).expect("SourceMob::EssenceDescription"); + if descriptor.class != cls::TAPE_DESCRIPTOR { + for req in [pid::SAMPLE_RATE, pid::FILE_LENGTH, pid::CONTAINER_FORMAT] { + assert!(descriptor.get(req).is_some(), "FileDescriptor property {req:#06x}"); + } + assert!(containers.contains(descriptor.weak_key(pid::CONTAINER_FORMAT).unwrap())); + let url = descriptor.objs(pid::LOCATOR)[0].string(pid::URL_STRING).unwrap(); + assert_eq!(url, "file:///m/a.mov"); + } + if descriptor.class == cls::PCM_DESCRIPTOR { + assert_eq!(descriptor.u32(pid::CHANNELS), Some(2)); + assert_eq!(descriptor.u32(pid::QUANTIZATION_BITS), Some(24)); + assert_eq!(descriptor.u16(pid::BLOCK_ALIGN), Some(6)); + } +} + +fn assert_component(o: &Obj, mobs: &[Obj], definitions: &Definitions) { + if is_component(o) { + let dd = o.weak_key(pid::DATA_DEFINITION).expect("Component::DataDefinition"); + assert!(definitions.data.contains(dd), "data definition in the dictionary"); + let event_seq = o.class == cls::SEQUENCE && dd == ddef::DESCRIPTIVE_METADATA; + assert!(event_seq || o.get(pid::LENGTH).is_some(), "Component::Length"); + } + if o.class == cls::SOURCE_CLIP { + assert_source_clip(o, mobs); + } else if o.class == cls::OPERATION_GROUP { + assert_operation_group(o, definitions); + } else if o.class == cls::SEQUENCE && o.get(pid::LENGTH).is_some() { + assert_sequence_length(o); + } +} + +fn is_component(o: &Obj) -> bool { + [cls::FILLER, cls::SOURCE_CLIP, cls::SEQUENCE, cls::TRANSITION, cls::OPERATION_GROUP, cls::TIMECODE, cls::COMMENT_MARKER].contains(&o.class) +} + +fn assert_source_clip(clip: &Obj, mobs: &[Obj]) { + let id = clip.mob_id(pid::SOURCE_ID).unwrap(); + let slot = clip.u32(pid::SOURCE_MOB_SLOT_ID).unwrap(); + assert!(clip.get(pid::START_TIME).is_some()); + if id != [0; 32] { + let target = mobs.iter().find(|m| m.mob_id(pid::MOB_ID) == Some(id)).expect("source clip target in the file"); + assert!(target.objs(pid::SLOTS).iter().any(|s| s.u32(pid::SLOT_ID) == Some(slot)), "target slot exists"); + } +} + +fn assert_operation_group(group: &Obj, definitions: &Definitions) { + assert!(definitions.operations.contains(group.weak_key(pid::OPERATION).unwrap())); + for parameter in group.objs(pid::PARAMETERS) { + assert!(definitions.parameters.contains(parameter.auid(pid::PARAMETER_DEFINITION).unwrap().as_slice())); + if parameter.class == cls::VARYING_VALUE { + assert!(definitions.interpolation.contains(parameter.weak_key(pid::INTERPOLATION).unwrap())); + assert!(!parameter.objs(pid::POINT_LIST).is_empty()); + } + } +} + +fn assert_sequence_length(sequence: &Obj) { + let components = sequence.objs(pid::COMPONENTS); + let sum = components + .iter() + .enumerate() + .map(|(i, component)| { + let len = component.i64(pid::LENGTH).unwrap(); + if component.class == cls::TRANSITION { + assert!(i > 0 && i + 1 < components.len(), "transition at a sequence end"); + assert!(components[i - 1].class != cls::TRANSITION && components[i + 1].class != cls::TRANSITION); + assert!(components[i - 1].i64(pid::LENGTH).unwrap() >= len && components[i + 1].i64(pid::LENGTH).unwrap() >= len); + let cut = component.i64(pid::CUT_POINT).unwrap(); + assert!((0..=len).contains(&cut)); + assert!(component.strong(pid::OPERATION_GROUP).is_some()); + -len + } else { + len + } + }) + .sum::(); + assert_eq!(sum, sequence.i64(pid::LENGTH).unwrap(), "sequence length = segments − transitions"); +} + +fn assert_composition(comp: &Obj) { + let slots = comp.objs(pid::SLOTS); + let tc = slots[0].strong(pid::SEGMENT).unwrap(); + assert_eq!(tc.class, cls::TIMECODE); + assert_eq!(tc.u16(pid::TC_FPS), Some(24)); + let video = slots[1].strong(pid::SEGMENT).unwrap().objs(pid::COMPONENTS); + assert_eq!(video.iter().map(|c| c.class).collect::>(), vec![cls::SOURCE_CLIP, cls::TRANSITION, cls::SOURCE_CLIP]); + assert_eq!(video[0].i64(pid::LENGTH), Some(54), "outgoing clip extends to the transition end"); + assert_eq!(video[2].i64(pid::LENGTH), Some(54), "incoming clip starts at the transition start"); + assert_eq!(video[2].i64(pid::START_TIME), Some(194)); + assert_eq!(video[1].i64(pid::CUT_POINT), Some(6)); + assert_eq!(video[1].strong(pid::OPERATION_GROUP).unwrap().weak_key(pid::OPERATION), Some(&def::VIDEO_DISSOLVE[..])); + assert_audio_composition_slot(&slots[2]); +} + +fn assert_audio_composition_slot(slot: &Obj) { + let audio = slot.strong(pid::SEGMENT).unwrap().objs(pid::COMPONENTS); + assert_eq!(slot.rational(pid::EDIT_RATE), Some((48_000, 1))); + assert_eq!(audio[2].class, cls::OPERATION_GROUP); + assert_eq!(audio[2].weak_key(pid::OPERATION), Some(&def::MONO_AUDIO_GAIN[..])); + let amplitude = audio[2].objs(pid::PARAMETERS)[0].data(pid::CONSTANT_VALUE).unwrap(); + let (numerator, denominator) = store::rational_of(&litude[17..]).unwrap(); + assert!((numerator as f64 / denominator as f64 - 10f64.powf(-3.0 / 20.0)).abs() < 1e-4); + assert_eq!(audio[1].strong(pid::OPERATION_GROUP).unwrap().weak_key(pid::OPERATION), Some(&def::MONO_AUDIO_DISSOLVE[..])); +} + +#[test] +fn store_round_trips_every_stored_form() { + let leaf = |n: u8| Obj::new([n; 16]).data_prop(0x1B01, vec![n; 16]); + let root = Obj::new(ids::ROOT) + .data_prop(0x0003, vec![1, 2, 3]) + .with(0x0004, Value::Strong(Box::new(leaf(1).with(0x0005, Value::StrongVec(vec![leaf(2), leaf(3)]))))) + .with( + 0x0002, + Value::Strong(Box::new( + Obj::new([9; 16]) + .with(0x3B04, Value::Strong(Box::new(Obj::new([8; 16]).with(0x2605, Value::StrongSet(vec![leaf(4), leaf(5)], 0x1B01))))), + )), + ) + .with(0x0006, Value::Weak(path::DATA_DEFS.to_vec(), 0x1B01, vec![5; 16])) + .with(0x0007, Value::WeakVec(path::DATA_DEFS.to_vec(), 0x1B01, vec![vec![4; 16], vec![5; 16]])) + .with(0x0008, Value::Stream((0..10_000u32).map(|i| i as u8).collect())); + for v in [craft_cfb::Version::V3, craft_cfb::Version::V4] { + let bytes = store::write(&root, v).unwrap(); + assert_eq!(store::read(&bytes).unwrap(), root); + } + // a data value longer than a property can hold is an error, not a panic + assert!(store::write(&Obj::new(ids::ROOT).data_prop(1, vec![0; 70_000]), craft_cfb::Version::V4).is_err()); +} + +/// The property `p` of `o` as a list of objects, to change. +fn objs_mut(o: &mut Obj, p: u16) -> &mut Vec { + match o.props.iter_mut().find(|(k, _)| *k == p).map(|(_, v)| v) { + Some(Value::StrongVec(v)) | Some(Value::StrongSet(v, _)) => v, + _ => panic!("no object list {p:#06x}"), + } +} + +fn strong_mut(o: &mut Obj, p: u16) -> &mut Obj { + match o.props.iter_mut().find(|(k, _)| *k == p).map(|(_, v)| v) { + Some(Value::Strong(v)) => v, + _ => panic!("no object {p:#06x}"), + } +} + +fn is_picture(o: &Obj) -> bool { + o.weak_key(pid::DATA_DEFINITION) == Some(&ddef::PICTURE[..]) +} + +/// How Premiere Pro 26.5.2 lays a sequence with a nested sequence out in AAF (seen in a file it +/// exported): every composition is tagged top-level, the nested one too; all video tracks of a +/// composition are in ONE slot, a nested scope with a segment per track, lowest first; a clip of +/// the nested sequence is a source clip that points at its composition. Our own file is rewritten +/// into that layout and must read back as the same edit. +#[test] +fn premiere_style_layers_and_nested_compositions_are_read() { + let r = FrameRate::FPS_24; + // "Outer": media on V1 and V3, the sequence "S" nested on V2 with its sound on A1 + let inner = document(); + let mut sources = inner.sources.clone(); + for kind in [CKind::Picture, CKind::Sound] { + let mut nest = source("seq:2", "S", kind, r, 16, None); + (nest.path, nest.nested, nest.length, nest.width, nest.height) = (None, Some(0), r.tick_of(96), 1920, 1080); + sources.push(nest); + } + let gap = |frames: i64| CItem::Filler(r.tick_of(frames)); + let outer = composition( + "Outer", + r, + vec![ + track(CKind::Picture, "V1", 1, vec![clip(r, 0, 5, 30, "a")]), + track(CKind::Picture, "V2", 2, vec![gap(10), clip(r, 2, 12, 40, "S")]), + track(CKind::Picture, "V3", 3, vec![gap(60), clip(r, 0, 100, 20, "a")]), + track(CKind::Sound, "A1", 1, vec![gap(10), clip(r, 3, 12, 40, "S")]), + ], + ); + let ours = written(&Document { compositions: vec![outer], sources, nested: inner.compositions }, false); + + let mut root = store::read(&ours).unwrap(); + let content = strong_mut(strong_mut(&mut root, pid::ROOT_HEADER), pid::CONTENT); + let mut compositions = 0; + for mob in objs_mut(content, pid::MOBS).iter_mut().filter(|m| m.class == cls::COMPOSITION_MOB) { + compositions += 1; + mob.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL.to_vec())); + let slots = objs_mut(mob, pid::SLOTS); + let picture: Vec = slots.iter().enumerate().filter(|(_, s)| s.strong(pid::SEGMENT).is_some_and(is_picture)).map(|(i, _)| i).collect(); + let layers: Vec = picture.iter().map(|&i| slots[i].strong(pid::SEGMENT).unwrap().clone()).collect(); + let length = layers.iter().filter_map(|l| l.i64(pid::LENGTH)).max().unwrap_or(0); + let scope = Obj::new(cls::NESTED_SCOPE) + .with(pid::DATA_DEFINITION, Value::Weak(path::DATA_DEFS.to_vec(), pid::IDENTIFICATION, ddef::PICTURE.to_vec())) + .data_prop(pid::LENGTH, length.to_le_bytes().to_vec()) + .with(pid::NESTED_SLOTS, Value::StrongVec(layers)); + // the first video slot keeps its id (clips of the nested sequence point at it) and holds + // every layer; the other video slots go + slots[picture[0]].set(pid::SEGMENT, Value::Strong(Box::new(scope))); + for &i in picture[1..].iter().rev() { + slots.remove(i); + } + } + assert_eq!(compositions, 2); + let theirs = store::write(&root, craft_cfb::Version::V4).unwrap(); + assert_ne!(theirs, ours); + + let want = read_clean(&ours); + let got = read_clean(&theirs); + // one edit; the nested composition is one it uses, not a second edit + assert_eq!(got.compositions.len(), 1); + assert_eq!(got.nested.len(), 1); + // layers of one slot share its name and are all as long as the scope: the same edit apart + // from picture track names and gaps after the last clip + let edit = |mut doc: Document| { + for t in doc.compositions.iter_mut().chain(&mut doc.nested).flat_map(|c| &mut c.tracks).filter(|t| t.kind == CKind::Picture) { + t.name.clear(); + while matches!(t.items.last(), Some(CItem::Filler(_))) { + t.items.pop(); + } + } + doc + }; + assert_eq!(edit(got.clone()), edit(want)); + // and that edit is the one that was written: three video tracks, the nest on the second + let q = &got.compositions[0]; + let picture: Vec<_> = q.tracks.iter().filter(|t| t.kind == CKind::Picture).collect(); + assert_eq!(picture.iter().map(|t| t.items.iter().filter(|i| matches!(i, CItem::Clip(_))).count()).collect::>(), [1, 1, 1]); + let nest_of = |kind: CKind| { + let t = q.tracks.iter().filter(|t| t.kind == kind).nth(if kind == CKind::Picture { 1 } else { 0 }).unwrap(); + let [CItem::Filler(gap), CItem::Clip(c), ..] = &t.items[..] else { panic!("{:?}", t.items) }; + (*gap, c.len, c.start, got.sources[c.source].nested, got.sources[c.source].name.clone()) + }; + assert_eq!(nest_of(CKind::Picture), (r.tick_of(10), r.tick_of(40), r.tick_of(12), Some(0), "S".to_string())); + assert_eq!(nest_of(CKind::Sound), nest_of(CKind::Picture)); + assert_eq!(got.nested[0].name, "S"); +} + +/// A slot's name is the track's name, whatever it starts with; a track without one reads back +/// without one. +#[test] +fn audio_tracks_keep_their_names() { + for name in ["Dialogue.Dialogue-1", "Dialogue.Dialogue-1 L", "", "é", "音声", "🎤 Dialogue", "Ä1"] { + let mut doc = document(); + doc.compositions[0].tracks[1].name = name.into(); + let back = read_clean(&written(&doc, false)); + assert_eq!(back.compositions[0].tracks[1].name, name); + } +} diff --git a/crates/aaf/src/aaf/write.rs b/crates/aaf/src/aaf/write.rs new file mode 100644 index 000000000..7ab51cea9 --- /dev/null +++ b/crates/aaf/src/aaf/write.rs @@ -0,0 +1,800 @@ +//! Composition model → AAF objects. + +use std::collections::HashMap; + +use craft_timeline::time::{FrameRate, Tick}; + +use super::ids::{META_DICTIONARY, ROOT, cls, ddef, def, path, pid}; +use super::store::{self, Auid, Obj, Value, rational, utf16z}; +use crate::model::{CItem, CKind, CMarker, Composition, Document, Gain, Source, ticks_to_units}; +use crate::{Error, Identity, Report, Result}; + +/// UMID-style mob id (SMPTE 330 basic UMID): label, length 0x13, instance 0, material number. +pub(crate) fn mob_id(seed: u64, n: u64) -> [u8; 32] { + let mut id = [0u8; 32]; + id[..12].copy_from_slice(&[0x06, 0x0A, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x01, 0x0F, 0x20]); + id[12] = 0x13; + let a = mix(seed ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15)); + let b = mix(a ^ 0xD6E8_FEB8_6659_FD93); + id[16..24].copy_from_slice(&a.to_le_bytes()); + id[24..32].copy_from_slice(&b.to_le_bytes()); + // a "random" material number per RFC 4122 v4 layout keeps it a valid UUID + id[22] = (id[22] & 0x0F) | 0x40; + id[24] = (id[24] & 0x3F) | 0x80; + id +} + +fn mix(mut z: u64) -> u64 { + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +pub(crate) fn fnv(s: &[u8], h: u64) -> u64 { + s.iter().fold(h, |h, &b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01B3)) +} + +fn timestamp() -> Vec { + // 1970-01-01 00:00:00.00: written files are reproducible + let mut v = 1970i16.to_le_bytes().to_vec(); + v.extend_from_slice(&[1, 1, 0, 0, 0, 0]); + v +} + +fn weak(path: [u16; 3], key: Auid) -> Value { + Value::Weak(path.to_vec(), pid::IDENTIFICATION, key.to_vec()) +} + +fn data_def(kind: CKind) -> Auid { + match kind { + CKind::Picture => ddef::PICTURE, + CKind::Sound => ddef::SOUND, + } +} + +/// An indirect value: byte order, type id, value. +pub(crate) fn indirect(ty: Auid, v: &[u8]) -> Vec { + let mut d = vec![0x4C]; + d.extend_from_slice(&ty); + d.extend_from_slice(v); + d +} + +fn tagged(name: &str, value: &str) -> Obj { + Obj::new(cls::TAGGED_VALUE).data_prop(pid::TAG_NAME, utf16z(name)).data_prop(pid::TAG_VALUE, indirect(def::TYPE_STRING, &utf16z(value))) +} + +fn gain_rational(g: f64) -> Vec { + rational((g.max(0.0) * 65536.0).round().min(i32::MAX as f64) as i64, 65536) +} + +fn definition(class: Auid, id: Auid, name: &str) -> Obj { + Obj::new(class).data_prop(pid::IDENTIFICATION, id.to_vec()).data_prop(pid::NAME, utf16z(name)).data_prop(pid::DESCRIPTION, utf16z("")) +} + +struct W<'a> { + report: &'a mut Report, + inexact: bool, +} + +struct IdGen { + seed: u64, + next: u64, +} + +impl IdGen { + fn for_document(doc: &Document, comp: &Composition) -> Self { + let mut seed = fnv(comp.name.as_bytes(), 0xCBF2_9CE4_8422_2325); + for source in &doc.sources { + seed = fnv(source.path.as_deref().unwrap_or("").as_bytes(), fnv(source.key.as_bytes(), seed)); + } + seed = fnv(&(comp.tracks.len() as u64).to_le_bytes(), seed); + Self { seed, next: 0 } + } + + fn next(&mut self) -> [u8; 32] { + self.next += 1; + mob_id(self.seed, self.next) + } +} + +struct MediaOutput { + mobs: Vec, + essence: Vec, + master_ref: HashMap, +} + +type FileMob = ((Option, usize, CKind), [u8; 32], Vec, usize); + +struct GroupSlots { + master_id: [u8; 32], + tape_id: [u8; 32], + timecode: Option<(i64, FrameRate)>, + master_slots: Vec, + tape_slots: Vec, + files: Vec, + master_ref: HashMap, +} + +struct GroupSlotBuilder<'a, 'b> { + doc: &'a Document, + master_id: [u8; 32], + tape_id: [u8; 32], + ids: &'b mut IdGen, + files: &'b mut Vec, + master_slots: &'b mut Vec, + tape_slots: &'b mut Vec, + master_ref: &'b mut HashMap, +} + +struct FileSlotInput<'a> { + source: &'a Source, + file_slot: u32, + length: i64, + has_timecode: bool, + tape_id: [u8; 32], + member_index: usize, + slots: &'a mut Vec, + rate: (i64, i64), +} + +impl W<'_> { + /// Edit units at `rate` of tick `t`. + fn u(&mut self, t: Tick, rate: (i64, i64)) -> i64 { + let (n, exact) = ticks_to_units(t, rate.0, rate.1); + if !exact { + self.inexact = true; + } + n + } +} + +fn source_rate(s: &Source) -> (i64, i64) { + match s.kind { + CKind::Picture => (s.frame_rate.num, s.frame_rate.den), + CKind::Sound => (s.sample_rate.max(1) as i64, 1), + } +} + +fn write_media(doc: &Document, w: &mut W<'_>, ids: &mut IdGen) -> MediaOutput { + let mut groups: Vec<(String, Vec)> = Vec::new(); + for (index, source) in doc.sources.iter().enumerate() { + if source.nested.is_some() { + continue; + } + match groups.iter_mut().find(|(key, _)| *key == source.key) { + Some((_, members)) => members.push(index), + None => groups.push((source.key.clone(), vec![index])), + } + } + + let mut output = MediaOutput { mobs: Vec::new(), essence: Vec::new(), master_ref: HashMap::new() }; + for (_, members) in groups { + write_source_group(doc, &members, w, ids, &mut output); + } + output +} + +fn write_source_group(doc: &Document, members: &[usize], w: &mut W<'_>, ids: &mut IdGen, output: &mut MediaOutput) { + let first = &doc.sources[members[0]]; + let slots = build_group_slots(doc, members, w, ids); + output.master_ref.extend(slots.master_ref); + let mut master_slots = slots.master_slots; + add_master_markers(doc, members, w, &mut master_slots); + output.mobs.push( + Obj::new(cls::MASTER_MOB) + .data_prop(pid::MOB_ID, slots.master_id.to_vec()) + .data_prop(pid::MOB_NAME, utf16z(&first.name)) + .data_prop(pid::MOB_LAST_MODIFIED, timestamp()) + .data_prop(pid::MOB_CREATION_TIME, timestamp()) + .with(pid::SLOTS, Value::StrongVec(master_slots)), + ); + let tape_id = slots.tape_id; + let timecode = slots.timecode; + let tape_slots = slots.tape_slots; + add_file_mobs(doc, slots.files, w, output); + add_tape_mob(first, tape_id, timecode, tape_slots, output); +} + +fn build_group_slots(doc: &Document, members: &[usize], w: &mut W<'_>, ids: &mut IdGen) -> GroupSlots { + let master_id = ids.next(); + let tape_id = ids.next(); + let timecode = members.iter().find_map(|&i| doc.sources[i].start_tc.map(|t| (t, doc.sources[i].tc_rate))); + let mut tape_slots = Vec::new(); + if let Some((start, rate)) = timecode { + tape_slots.push(timecode_slot(members, doc, w, start, rate)); + } + let mut files: Vec = Vec::new(); + let mut master_slots = Vec::new(); + let mut master_ref = HashMap::new(); + let mut builder = GroupSlotBuilder { + doc, + master_id, + tape_id, + ids, + files: &mut files, + master_slots: &mut master_slots, + tape_slots: &mut tape_slots, + master_ref: &mut master_ref, + }; + for (member_index, &source_index) in members.iter().enumerate() { + builder.add_source(source_index, member_index, timecode.is_some(), w); + } + GroupSlots { master_id, tape_id, timecode, master_slots, tape_slots, files, master_ref } +} + +fn timecode_slot(members: &[usize], doc: &Document, w: &mut W<'_>, start: i64, rate: FrameRate) -> Obj { + let edit_rate = (rate.num, rate.den); + let len = members.iter().map(|&i| doc.sources[i].length).max().unwrap_or(Tick::ZERO); + let units = w.u(len, edit_rate); + timeline_slot( + 1, + "TC1", + 0, + edit_rate, + Obj::new(cls::TIMECODE) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::TIMECODE)) + .data_prop(pid::LENGTH, units.to_le_bytes().to_vec()) + .data_prop(pid::TC_START, start.to_le_bytes().to_vec()) + .data_prop(pid::TC_FPS, (rate.timecode_base().clamp(1, u16::MAX as i64) as u16).to_le_bytes().to_vec()) + .data_prop(pid::TC_DROP, vec![0]), + ) +} + +impl GroupSlotBuilder<'_, '_> { + fn add_source(&mut self, source_index: usize, member_index: usize, has_timecode: bool, w: &mut W<'_>) { + let source = &self.doc.sources[source_index]; + let rate = source_rate(source); + let embedded_key = if source.embedded.is_some() { source_index } else { usize::MAX }; + let file_key = (source.path.clone(), embedded_key, source.kind); + let file_slot = source.channel.map_or(1, |channel| channel + 1); + let len_units = w.u(source.length, rate); + let file_index = match self.files.iter().position(|file| file.0 == file_key) { + Some(index) => index, + None => { + self.files.push((file_key, self.ids.next(), Vec::new(), source_index)); + self.files.len() - 1 + } + }; + let file_id = self.files[file_index].1; + add_file_slot(FileSlotInput { + source, + file_slot, + length: len_units, + has_timecode, + tape_id: self.tape_id, + member_index, + slots: &mut self.files[file_index].2, + rate, + }); + if has_timecode { + let tape_slot_id = 2 + member_index as u32; + self.tape_slots.push(timeline_slot( + tape_slot_id, + &slot_name(source.kind, member_index as u32 + 1), + member_index as u32 + 1, + rate, + source_clip(source.kind, len_units, [0; 32], 0, 0), + )); + } + let master_slot = member_index as u32 + 1; + self.master_slots.push(timeline_slot( + master_slot, + &slot_name(source.kind, master_slot), + master_slot, + rate, + source_clip(source.kind, len_units, file_id, file_slot, 0), + )); + self.master_ref.insert(source_index, (self.master_id, master_slot)); + } +} + +fn add_file_slot(input: FileSlotInput<'_>) { + let FileSlotInput { source, file_slot, length, has_timecode, tape_id, member_index, slots, rate } = input; + if slots.iter().any(|slot| slot.u32(pid::SLOT_ID) == Some(file_slot)) { + return; + } + let tape_slot_id = if has_timecode { 2 + member_index as u32 } else { 0 }; + let mob_id = if has_timecode { tape_id } else { [0; 32] }; + let clip = source_clip(source.kind, length, mob_id, tape_slot_id, 0); + slots.push(timeline_slot(file_slot, &slot_name(source.kind, file_slot), file_slot, rate, clip)); +} + +fn add_master_markers(doc: &Document, members: &[usize], w: &mut W<'_>, master_slots: &mut Vec) { + let first = &doc.sources[members[0]]; + let marker_rate = + members.iter().map(|&i| &doc.sources[i]).find(|source| source.kind == CKind::Picture).map(source_rate).unwrap_or_else(|| source_rate(first)); + let markers: Vec<&CMarker> = members.iter().flat_map(|&i| doc.sources[i].markers.iter()).collect(); + if markers.is_empty() { + return; + } + let mut unique: Vec = markers.into_iter().cloned().collect(); + unique.sort_by(|a, b| (a.start, &a.name).cmp(&(b.start, &b.name))); + unique.dedup(); + master_slots.push(event_slot(w, members.len() as u32 + 1, marker_rate, &unique)); +} + +fn add_file_mobs(doc: &Document, files: Vec, w: &mut W<'_>, output: &mut MediaOutput) { + for (_, file_id, slots, source_index) in files { + let source = &doc.sources[source_index]; + let desc = descriptor(w, source); + output.mobs.push( + Obj::new(cls::SOURCE_MOB) + .data_prop(pid::MOB_ID, file_id.to_vec()) + .data_prop(pid::MOB_NAME, utf16z(&source.name)) + .data_prop(pid::MOB_LAST_MODIFIED, timestamp()) + .data_prop(pid::MOB_CREATION_TIME, timestamp()) + .with(pid::SLOTS, Value::StrongVec(slots)) + .with(pid::ESSENCE_DESCRIPTION, Value::Strong(Box::new(desc))), + ); + if let Some(data) = &source.embedded { + output.essence.push( + Obj::new(cls::ESSENCE_DATA).data_prop(pid::ESSENCE_MOB_ID, file_id.to_vec()).with(pid::ESSENCE_STREAM, Value::Stream(data.clone())), + ); + } + } +} + +fn add_tape_mob(first: &Source, tape_id: [u8; 32], timecode: Option<(i64, FrameRate)>, tape_slots: Vec, output: &mut MediaOutput) { + let Some(_) = timecode else { return }; + let reel = first.path.as_deref().map(craft_timeline::path::file_stem).unwrap_or(&first.name).to_string(); + output.mobs.push( + Obj::new(cls::SOURCE_MOB) + .data_prop(pid::MOB_ID, tape_id.to_vec()) + .data_prop(pid::MOB_NAME, utf16z(&reel)) + .data_prop(pid::MOB_LAST_MODIFIED, timestamp()) + .data_prop(pid::MOB_CREATION_TIME, timestamp()) + .with(pid::SLOTS, Value::StrongVec(tape_slots)) + .with(pid::ESSENCE_DESCRIPTION, Value::Strong(Box::new(Obj::new(cls::TAPE_DESCRIPTOR)))), + ); +} + +/// Serialise a composition document. +pub(crate) fn write(doc: &Document, version: craft_cfb::Version, identity: &Identity<'_>, report: &mut Report) -> Result> { + let comp = doc.compositions.first().ok_or(Error::Empty)?; + let mut w = W { report, inexact: false }; + let mut ids = IdGen::for_document(doc, comp); + let MediaOutput { mut mobs, essence, master_ref } = write_media(doc, &mut w, &mut ids); + let mut used_ops: Vec = Vec::new(); + let mut uses_varying = false; + + // ---- nested compositions: a clip refers to one as it does to a master mob, through the + // composition's first track of the clip's kind (a broken-out channel: that channel's track) + let mut refs = Refs { mobs: master_ref, rates: HashMap::new() }; + let nested_ids: Vec<[u8; 32]> = doc.nested.iter().map(|_| ids.next()).collect(); + for (si, s) in doc.sources.iter().enumerate() { + let Some((comp, id)) = s.nested.and_then(|n| Some((doc.nested.get(n)?, nested_ids.get(n)?))) else { continue }; + let of_kind: Vec = comp.tracks.iter().enumerate().filter(|(_, t)| t.kind == s.kind).map(|(i, _)| i).collect(); + let Some(&track) = s.channel.and_then(|c| of_kind.get(c as usize)).or(of_kind.first()) else { continue }; + let rate = match s.kind { + CKind::Picture => (comp.rate.num, comp.rate.den), + CKind::Sound => (comp.sample_rate.max(1) as i64, 1), + }; + refs.mobs.insert(si, (*id, track as u32 + 2)); + refs.rates.insert(si, rate); + } + + // ---- the compositions: the exported sequence first + let comp_id = ids.next(); + let composition_mobs = { + let mut composition_writer = CompositionWriter { w: &mut w, doc, refs: &refs, used_ops: &mut used_ops, uses_varying: &mut uses_varying }; + let mut output = vec![composition_writer.write(comp, comp_id, true)]; + output.extend(doc.nested.iter().zip(&nested_ids).map(|(nested, id)| composition_writer.write(nested, *id, false))); + output + }; + mobs.splice(0..0, composition_mobs); + if w.inexact { + w.report.info("some times are not on whole edit units and were rounded"); + } + + // ---- dictionary + let mut ddefs = Vec::new(); + for (id, name) in + [(ddef::PICTURE, "Picture"), (ddef::SOUND, "Sound"), (ddef::TIMECODE, "Timecode"), (ddef::DESCRIPTIVE_METADATA, "DescriptiveMetadata")] + { + ddefs.push(definition(cls::DATA_DEFINITION, id, name)); + } + let mut opdefs = Vec::new(); + for op in &used_ops { + let (name, dd, inputs) = match *op { + x if x == def::VIDEO_DISSOLVE => ("Video Dissolve", ddef::PICTURE, 2), + x if x == def::VIDEO_FADE_TO_BLACK => ("Video Fade To Black", ddef::PICTURE, 1), + x if x == def::SMPTE_VIDEO_WIPE => ("SMPTE Video Wipe", ddef::PICTURE, 2), + x if x == def::MONO_AUDIO_DISSOLVE => ("Mono Audio Dissolve", ddef::SOUND, 2), + _ => ("Mono Audio Gain", ddef::SOUND, 1i32), + }; + let params: Vec> = if *op == def::MONO_AUDIO_GAIN { + vec![def::PARAM_AMPLITUDE.to_vec()] + } else if *op == def::VIDEO_DISSOLVE { + vec![def::PARAM_LEVEL.to_vec()] + } else { + Vec::new() + }; + let mut o = definition(cls::OPERATION_DEFINITION, *op, name) + .with(pid::OPDEF_DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::OPDEF_IS_TIME_WARP, vec![0]) + .data_prop(pid::OPDEF_NUMBER_INPUTS, inputs.to_le_bytes().to_vec()); + if !params.is_empty() { + o.set(pid::OPDEF_PARAMETERS_DEFINED, Value::WeakVec(path::PARAMETER_DEFS.to_vec(), pid::IDENTIFICATION, params)); + } + opdefs.push(o); + } + let pdefs = vec![ + definition(cls::PARAMETER_DEFINITION, def::PARAM_LEVEL, "Level").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")), + definition(cls::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE, "Amplitude").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")), + ]; + let idefs = if uses_varying || !used_ops.is_empty() { + vec![ + definition(cls::INTERPOLATION_DEFINITION, def::INTERP_LINEAR, "Linear"), + definition(cls::INTERPOLATION_DEFINITION, def::INTERP_CONSTANT, "Constant"), + ] + } else { + Vec::new() + }; + let cdefs = vec![ + definition(cls::CONTAINER_DEFINITION, def::CONTAINER_EXTERNAL, "External Container"), + definition(cls::CONTAINER_DEFINITION, def::CONTAINER_AAF, "AAF Container"), + ]; + let mut dict = Obj::new(cls::DICTIONARY) + .with(pid::DATA_DEFINITIONS, Value::StrongSet(ddefs, pid::IDENTIFICATION)) + .with(pid::PARAMETER_DEFINITIONS, Value::StrongSet(pdefs, pid::IDENTIFICATION)) + .with(pid::CONTAINER_DEFINITIONS, Value::StrongSet(cdefs, pid::IDENTIFICATION)); + if !opdefs.is_empty() { + dict.set(pid::OPERATION_DEFINITIONS, Value::StrongSet(opdefs, pid::IDENTIFICATION)); + } + if !idefs.is_empty() { + dict.set(pid::INTERPOLATION_DEFINITIONS, Value::StrongSet(idefs, pid::IDENTIFICATION)); + } + + let mut content = Obj::new(cls::CONTENT_STORAGE).with(pid::MOBS, Value::StrongSet(mobs, pid::MOB_ID)); + if !essence.is_empty() { + content.set(pid::ESSENCE_DATA, Value::StrongSet(essence, pid::ESSENCE_MOB_ID)); + } + let ident = Obj::new(cls::IDENTIFICATION) + .data_prop(pid::COMPANY_NAME, utf16z(identity.company)) + .data_prop(pid::PRODUCT_NAME, utf16z(identity.product)) + .data_prop(pid::PRODUCT_VERSION_STRING, utf16z(identity.version)) + .data_prop(pid::PRODUCT_ID, identity.product_id.to_vec()) + .data_prop(pid::DATE, timestamp()) + .data_prop(pid::PLATFORM, utf16z(identity.platform)) + .data_prop(pid::GENERATION_AUID, mob_id(ids.seed, 0)[16..].to_vec()); + let header = Obj::new(cls::HEADER) + .data_prop(pid::BYTE_ORDER, 0x4949i16.to_le_bytes().to_vec()) + .data_prop(pid::LAST_MODIFIED, timestamp()) + .data_prop(pid::VERSION, vec![1, 1]) + .data_prop(pid::OBJECT_MODEL_VERSION, 1u32.to_le_bytes().to_vec()) + .data_prop(pid::OPERATIONAL_PATTERN, def::OP_EDIT_PROTOCOL.to_vec()) + .with(pid::CONTENT, Value::Strong(Box::new(content))) + .with(pid::DICTIONARY, Value::Strong(Box::new(dict))) + .with(pid::IDENTIFICATION_LIST, Value::StrongVec(vec![ident])); + // The meta-dictionary holds only extensions to the baseline object model, and everything written + // here is baseline, so its class and type definition sets are empty; readers that load them + // (pyaaf2) still need the sets to be there (filmcraft#323). + let meta = Obj::new(META_DICTIONARY) + .with(pid::META_CLASS_DEFINITIONS, Value::StrongSet(Vec::new(), pid::META_IDENTIFICATION)) + .with(pid::META_TYPE_DEFINITIONS, Value::StrongSet(Vec::new(), pid::META_IDENTIFICATION)); + let root = Obj::new(ROOT).with(pid::ROOT_META_DICTIONARY, Value::Strong(Box::new(meta))).with(pid::ROOT_HEADER, Value::Strong(Box::new(header))); + store::write(&root, version).map_err(Error::Other) +} + +/// Where clips find their sources: source index → (mob id, slot id), and for nested compositions +/// the edit rate of that slot. +#[derive(Default)] +struct Refs { + mobs: HashMap, + rates: HashMap, +} + +/// The composition mob of `comp`. Slot 1 is its timecode; its tracks follow from slot 2 in order. +struct CompositionWriter<'a, 'b, 'c> { + w: &'a mut W<'c>, + doc: &'b Document, + refs: &'b Refs, + used_ops: &'a mut Vec, + uses_varying: &'a mut bool, +} + +impl CompositionWriter<'_, '_, '_> { + fn write(&mut self, comp: &Composition, id: [u8; 32], top: bool) -> Obj { + let w = &mut *self.w; + let doc = self.doc; + let refs = self.refs; + let used_ops = &mut *self.used_ops; + let uses_varying = &mut *self.uses_varying; + let crate_rate = (comp.rate.num, comp.rate.den); + let mut slots = Vec::new(); + let total = comp + .tracks + .iter() + .map(|t| { + let mut c = Tick::ZERO; + for i in &t.items { + match i { + CItem::Transition(x) => c -= x.len, + other => c += other.len(), + } + } + c + }) + .max() + .unwrap_or(Tick::ZERO); + let total_units = w.u(total, crate_rate); + slots.push(timeline_slot( + 1, + "TC1", + 0, + crate_rate, + Obj::new(cls::TIMECODE) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::TIMECODE)) + .data_prop(pid::LENGTH, total_units.to_le_bytes().to_vec()) + .data_prop(pid::TC_START, comp.start_tc.to_le_bytes().to_vec()) + .data_prop(pid::TC_FPS, (comp.rate.timecode_base().clamp(1, u16::MAX as i64) as u16).to_le_bytes().to_vec()) + .data_prop(pid::TC_DROP, vec![comp.drop as u8]), + )); + let mut slot_id = 2u32; + for t in &comp.tracks { + let rate = match t.kind { + CKind::Picture => crate_rate, + CKind::Sound => (comp.sample_rate.max(1) as i64, 1), + }; + let dd = data_def(t.kind); + let mut comps = Vec::new(); + let mut cursor = Tick::ZERO; + for it in &t.items { + match it { + CItem::Filler(l) => { + let n = w.u(cursor + *l, rate) - w.u(cursor, rate); + cursor += *l; + comps.push( + Obj::new(cls::FILLER) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, n.to_le_bytes().to_vec()), + ); + } + CItem::Clip(c) => { + let n = w.u(cursor + c.len, rate) - w.u(cursor, rate); + let s = &doc.sources[c.source]; + let (mid, mslot) = refs.mobs.get(&c.source).copied().unwrap_or(([0; 32], 0)); + // (a nested composition counts the start in its own slot's edit units) + let start = w.u(c.start, refs.rates.get(&c.source).copied().unwrap_or(rate)); + let mut sc = source_clip(t.kind, n, mid, mslot, start); + if !c.name.is_empty() && c.name != s.name { + sc.set(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(vec![tagged("Clip Name", &c.name)])); + } + let seg = match (&c.gain, t.kind) { + (Some(g), CKind::Sound) => { + if !used_ops.contains(&def::MONO_AUDIO_GAIN) { + used_ops.push(def::MONO_AUDIO_GAIN); + } + let param = match g { + Gain::Constant(a) => Obj::new(cls::CONSTANT_VALUE) + .data_prop(pid::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE.to_vec()) + .data_prop(pid::CONSTANT_VALUE, indirect(def::TYPE_RATIONAL, &gain_rational(*a))), + Gain::Varying { linear, points } => { + *uses_varying = true; + let pts = points + .iter() + .map(|(off, a)| { + let o = w.u(cursor + *off, rate) - w.u(cursor, rate); + Obj::new(cls::CONTROL_POINT) + .data_prop(pid::CP_TIME, rational(o, n.max(1))) + .data_prop(pid::CP_VALUE, indirect(def::TYPE_RATIONAL, &gain_rational(*a))) + .data_prop(pid::CP_EDIT_HINT, vec![0]) + }) + .collect(); + Obj::new(cls::VARYING_VALUE) + .data_prop(pid::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE.to_vec()) + .with( + pid::INTERPOLATION, + weak(path::INTERPOLATION_DEFS, if *linear { def::INTERP_LINEAR } else { def::INTERP_CONSTANT }), + ) + .with(pid::POINT_LIST, Value::StrongVec(pts)) + } + }; + Obj::new(cls::OPERATION_GROUP) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, n.to_le_bytes().to_vec()) + .with(pid::OPERATION, weak(path::OPERATION_DEFS, def::MONO_AUDIO_GAIN)) + .with(pid::INPUT_SEGMENTS, Value::StrongVec(vec![sc])) + .with(pid::PARAMETERS, Value::StrongVec(vec![param])) + } + _ => sc, + }; + comps.push(seg); + cursor += c.len; + } + CItem::Transition(x) => { + let ts = cursor - x.len; + let n = w.u(cursor, rate) - w.u(ts, rate); + let cut = w.u(ts + x.cut, rate) - w.u(ts, rate); + cursor = ts; + let op = transition_op(t.kind, &x.effect); + if !used_ops.contains(&op) { + used_ops.push(op); + } + let mut og = Obj::new(cls::OPERATION_GROUP) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, n.to_le_bytes().to_vec()) + .with(pid::OPERATION, weak(path::OPERATION_DEFS, op)) + .with(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(vec![tagged("FilmCraft Effect", &x.effect)])); + if op == def::VIDEO_DISSOLVE { + *uses_varying = true; + let pts = [(0, 0), (1, 1)] + .iter() + .map(|&(t, v)| { + Obj::new(cls::CONTROL_POINT) + .data_prop(pid::CP_TIME, rational(t, 1)) + .data_prop(pid::CP_VALUE, indirect(def::TYPE_RATIONAL, &rational(v, 1))) + .data_prop(pid::CP_EDIT_HINT, vec![0]) + }) + .collect(); + og.set( + pid::PARAMETERS, + Value::StrongVec(vec![ + Obj::new(cls::VARYING_VALUE) + .data_prop(pid::PARAMETER_DEFINITION, def::PARAM_LEVEL.to_vec()) + .with(pid::INTERPOLATION, weak(path::INTERPOLATION_DEFS, def::INTERP_LINEAR)) + .with(pid::POINT_LIST, Value::StrongVec(pts)), + ]), + ); + } + comps.push( + Obj::new(cls::TRANSITION) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, n.to_le_bytes().to_vec()) + .data_prop(pid::CUT_POINT, cut.to_le_bytes().to_vec()) + .with(pid::OPERATION_GROUP, Value::Strong(Box::new(og))), + ); + } + } + } + let len: i64 = comps + .iter() + .map(|c| { + let l = c.i64(pid::LENGTH).unwrap_or(0); + if c.class == cls::TRANSITION { -l } else { l } + }) + .sum(); + let seq = Obj::new(cls::SEQUENCE) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, len.to_le_bytes().to_vec()) + .with(pid::COMPONENTS, Value::StrongVec(comps)); + slots.push(timeline_slot(slot_id, &t.name, t.number, rate, seq)); + slot_id += 1; + } + if !comp.markers.is_empty() { + slots.push(event_slot(w, slot_id, crate_rate, &comp.markers)); + } + let mut mob = Obj::new(cls::COMPOSITION_MOB) + .data_prop(pid::MOB_ID, id.to_vec()) + .data_prop(pid::MOB_NAME, utf16z(&comp.name)) + .data_prop(pid::MOB_LAST_MODIFIED, timestamp()) + .data_prop(pid::MOB_CREATION_TIME, timestamp()); + // only the exported sequence is a top-level composition; a nested sequence is found through + // the clips that use it + if top { + mob.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL.to_vec())); + } + mob.with(pid::SLOTS, Value::StrongVec(slots)).with( + pid::MOB_USER_COMMENTS, + Value::StrongVec(vec![ + tagged("FilmCraft Frame Size", &format!("{}x{}", comp.width, comp.height)), + tagged("FilmCraft Audio Sample Rate", &comp.sample_rate.to_string()), + ]), + ) + } +} + +fn slot_name(kind: CKind, n: u32) -> String { + match kind { + CKind::Picture => format!("V{n}"), + CKind::Sound => format!("A{n}"), + } +} + +fn timeline_slot(id: u32, name: &str, number: u32, rate: (i64, i64), segment: Obj) -> Obj { + let mut o = Obj::new(cls::TIMELINE_MOB_SLOT) + .data_prop(pid::SLOT_ID, id.to_le_bytes().to_vec()) + .data_prop(pid::SLOT_NAME, utf16z(name)) + .data_prop(pid::EDIT_RATE, rational(rate.0, rate.1)) + .data_prop(pid::ORIGIN, 0i64.to_le_bytes().to_vec()) + .with(pid::SEGMENT, Value::Strong(Box::new(segment))); + if number > 0 { + o.set(pid::PHYSICAL_TRACK_NUMBER, Value::Data(number.to_le_bytes().to_vec())); + } + o +} + +fn source_clip(kind: CKind, len: i64, source: [u8; 32], slot: u32, start: i64) -> Obj { + Obj::new(cls::SOURCE_CLIP) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, data_def(kind))) + .data_prop(pid::LENGTH, len.to_le_bytes().to_vec()) + .data_prop(pid::SOURCE_ID, source.to_vec()) + .data_prop(pid::SOURCE_MOB_SLOT_ID, slot.to_le_bytes().to_vec()) + .data_prop(pid::START_TIME, start.to_le_bytes().to_vec()) +} + +fn event_slot(w: &mut W, id: u32, rate: (i64, i64), markers: &[CMarker]) -> Obj { + let comps = markers + .iter() + .map(|m| { + let pos = w.u(m.start, rate); + let len = w.u(m.start + m.duration, rate) - pos; + let mut tags = vec![tagged("Name", &m.name), tagged("Comment", &m.comment)]; + if let Some(c) = &m.color { + tags.push(tagged("Color", c)); + } + Obj::new(cls::COMMENT_MARKER) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::DESCRIPTIVE_METADATA)) + .data_prop(pid::LENGTH, len.to_le_bytes().to_vec()) + .data_prop(pid::POSITION, pos.to_le_bytes().to_vec()) + .data_prop(pid::COMMENT, utf16z(if m.comment.is_empty() { &m.name } else { &m.comment })) + .with(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(tags)) + }) + .collect(); + Obj::new(cls::EVENT_MOB_SLOT) + .data_prop(pid::SLOT_ID, id.to_le_bytes().to_vec()) + .data_prop(pid::SLOT_NAME, utf16z("Markers")) + .data_prop(pid::EVENT_EDIT_RATE, rational(rate.0, rate.1)) + .with( + pid::SEGMENT, + Value::Strong(Box::new( + Obj::new(cls::SEQUENCE) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::DESCRIPTIVE_METADATA)) + .with(pid::COMPONENTS, Value::StrongVec(comps)), + )), + ) +} + +fn transition_op(kind: CKind, effect: &str) -> Auid { + match kind { + CKind::Sound => def::MONO_AUDIO_DISSOLVE, + CKind::Picture => match effect { + "dip_to_black" => def::VIDEO_FADE_TO_BLACK, + e if e.contains("wipe") => def::SMPTE_VIDEO_WIPE, + _ => def::VIDEO_DISSOLVE, + }, + } +} + +fn descriptor(w: &mut W, s: &Source) -> Obj { + let rate = source_rate(s); + let len = w.u(s.length, rate); + let container = if s.embedded.is_some() { def::CONTAINER_AAF } else { def::CONTAINER_EXTERNAL }; + let mut d = match s.kind { + CKind::Picture => Obj::new(cls::CDCI_DESCRIPTOR) + .data_prop(pid::STORED_WIDTH, s.width.to_le_bytes().to_vec()) + .data_prop(pid::STORED_HEIGHT, s.height.to_le_bytes().to_vec()) + .data_prop(pid::FRAME_LAYOUT, vec![0]) + .data_prop(pid::IMAGE_ASPECT_RATIO, rational(s.width.max(1) as i64, s.height.max(1) as i64)) + .data_prop(pid::VIDEO_LINE_MAP, { + let mut v = 2u32.to_le_bytes().to_vec(); + v.extend_from_slice(&4u32.to_le_bytes()); + v.extend_from_slice(&0i32.to_le_bytes()); + v.extend_from_slice(&0i32.to_le_bytes()); + v + }) + .data_prop(pid::COMPONENT_WIDTH, 8u32.to_le_bytes().to_vec()) + .data_prop(pid::HORIZONTAL_SUBSAMPLING, 2u32.to_le_bytes().to_vec()), + CKind::Sound => { + // Channel counts and rates come from the project: saturate, as these fields can't + // hold more anyway. + let block = s.file_channels.max(1).saturating_mul((s.bits as u32).div_ceil(8)); + Obj::new(cls::PCM_DESCRIPTOR) + .data_prop(pid::AUDIO_SAMPLING_RATE, rational(s.sample_rate as i64, 1)) + .data_prop(pid::LOCKED, vec![1]) + .data_prop(pid::CHANNELS, s.file_channels.max(1).to_le_bytes().to_vec()) + .data_prop(pid::QUANTIZATION_BITS, (s.bits as u32).to_le_bytes().to_vec()) + .data_prop(pid::BLOCK_ALIGN, u16::try_from(block).unwrap_or(u16::MAX).to_le_bytes().to_vec()) + .data_prop(pid::AVERAGE_BPS, block.saturating_mul(s.sample_rate).to_le_bytes().to_vec()) + } + }; + d.set(pid::SAMPLE_RATE, Value::Data(rational(rate.0, rate.1))); + d.set(pid::FILE_LENGTH, Value::Data(len.to_le_bytes().to_vec())); + d.set(pid::CONTAINER_FORMAT, weak(path::CONTAINER_DEFS, container)); + if let Some(p) = &s.path { + let url = if craft_timeline::path::is_absolute(p) { craft_timeline::path::path_to_file_url(p, false) } else { p.clone() }; + d.set(pid::LOCATOR, Value::StrongVec(vec![Obj::new(cls::NETWORK_LOCATOR).data_prop(pid::URL_STRING, utf16z(&url))])); + } + d +} diff --git a/crates/aaf/src/lib.rs b/crates/aaf/src/lib.rs new file mode 100644 index 000000000..ee7448bc0 --- /dev/null +++ b/crates/aaf/src/lib.rs @@ -0,0 +1,60 @@ +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] +//! AAF and OMF: the two mob-based editorial interchange formats, read and written through one +//! composition model. +//! +//! - [`model`]: a [`model::Document`] of compositions (tracks of fillers, source clips and +//! overlapping transitions, with clip gain and markers) and the media sources they reference, +//! with exact times ([`craft_timeline::time::Tick`]). +//! - [`aaf`]: Advanced Authoring Format, Edit Protocol, in structured storage (`craft-cfb`). +//! - [`omf`]: OMF Interchange 2.0 in a Bento container; sound only. +//! +//! Both read into and write from the same model, so an application maps its timeline onto the +//! model once. Audio essence can be embedded: the model carries it as PCM, and the WAVE / AIFF +//! wrappers the formats use are craft-audio's. +//! +//! Clean-room: written from the public specifications only (AMWA *AAF Object Specification* v1.1, +//! *AAF Low-Level Container Specification* v1.0.1, *AAF Edit Protocol* v1.0, SMPTE RP 224 / RP 210 +//! labels; Avid *OMF Interchange Specification* 2.0, Apple *Bento Specification* 1.0d5). No file +//! I/O: documents are bytes and media references are strings. +//! +//! Input is untrusted: a damaged or crafted file gives an [`Error`] or a [`Report`] entry, never +//! a panic, a hang or an allocation sized by a count in the file. + +pub mod aaf; +pub mod model; +pub mod omf; +mod pcm; +#[cfg(test)] +mod roundtrip_tests; +#[cfg(test)] +mod testdoc; + +pub use craft_timeline::report::Report; + +/// Error from a reader or writer. Unsupported *features* never error; they go in the [`Report`]. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The bytes are not a readable document of the format. + #[error("{format} parse error: {message}")] + Parse { format: &'static str, message: String }, + /// The document has no composition. + #[error("the document contains no timeline")] + Empty, + /// The document could not be written. + #[error("{0}")] + Other(String), +} + +pub type Result = std::result::Result; + +/// Who a written file says made it (the AAF `Identification` object, the OMF `IDNT` object). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Identity<'a> { + pub company: &'a str, + pub product: &'a str, + /// The product's version, as text. + pub version: &'a str, + pub platform: &'a str, + /// AAF `ProductID`: an AUID naming the product. + pub product_id: [u8; 16], +} diff --git a/crates/aaf/src/model.rs b/crates/aaf/src/model.rs new file mode 100644 index 000000000..3dff507be --- /dev/null +++ b/crates/aaf/src/model.rs @@ -0,0 +1,185 @@ +//! A format-neutral mob-style composition model shared by AAF and OMF. +//! +//! Both formats describe a timeline as a composition of slots (tracks) whose segments are +//! sequences of fillers, source clips and transitions, where a transition *overlaps* the end of +//! the segment before it and the start of the segment after it (the sequence's length is the sum of +//! its segment lengths minus its transition lengths). Source clips reference media through master +//! mobs and file source mobs: here, a [`Source`] per essence, grouped into one media item by its +//! key. All times are ticks; the format serialisers convert to and from edit units. + +use craft_timeline::time::{FrameRate, TICKS_PER_SECOND, Tick}; + +/// Picture or sound. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CKind { + Picture, + Sound, +} + +/// A whole document: compositions and the media they reference. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Document { + /// The top-level compositions. + pub compositions: Vec, + pub sources: Vec, + /// Compositions that are only used inside others (nested sequences); a [`Source`] refers to + /// one by its index here. They may nest further. + pub nested: Vec, +} + +/// How a nested sequence is written. Premiere Pro writes one as a composition of its own in AAF +/// (clips refer to it the way they refer to media) and renders its sound in OMF, which has no +#[derive(Clone, Debug, PartialEq)] +pub struct Composition { + pub name: String, + pub rate: FrameRate, + pub sample_rate: u32, + pub width: u32, + pub height: u32, + pub start_tc: i64, + pub drop: bool, + pub tracks: Vec, + pub markers: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CTrack { + pub kind: CKind, + pub name: String, + /// Physical track number (1-based, per kind). + pub number: u32, + /// Sound: channels of the track (1 mono, 2 stereo, 6 5.1). + pub channels: u32, + pub items: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum CItem { + Filler(Tick), + Clip(CClip), + Transition(CTransition), +} + +impl CItem { + /// The item's length on the track. + pub fn len(&self) -> Tick { + match self { + CItem::Filler(l) => *l, + CItem::Clip(c) => c.len, + CItem::Transition(t) => t.len, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CClip { + pub len: Tick, + /// Index into [`Document::sources`]. + pub source: usize, + /// Source (file) time of the segment's first frame. + pub start: Tick, + pub gain: Option, + pub name: String, +} + +/// Clip gain (linear amplitude). +#[derive(Clone, Debug, PartialEq)] +pub enum Gain { + Constant(f64), + /// Points at offsets from the segment start; `linear` false = hold (step) interpolation. + Varying { + linear: bool, + points: Vec<(Tick, f64)>, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CTransition { + pub len: Tick, + /// Where the cut lies, from the transition start. + pub cut: Tick, + /// The transition, by a name of the writing application's choosing; it is kept in a private tag + /// and comes back unchanged. Names the formats themselves can say: `cross_dissolve` and + /// `dip_to_black` (picture), any name containing `wipe` (a SMPTE wipe), `constant_power` (sound). + /// A file without the tag reads as one of these. + pub effect: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CMarker { + pub start: Tick, + pub duration: Tick, + pub name: String, + pub comment: String, + pub color: Option, +} + +/// One essence: a file (or embedded data) carrying the picture, or some channels of sound, of a +/// media item. +#[derive(Clone, Debug, PartialEq)] +pub struct Source { + /// Groups the sources of one media item (one master mob). + pub key: String, + pub name: String, + pub kind: CKind, + pub path: Option, + /// Sound: the (0-based) channel of the file this source exposes (broken out to mono), or + /// `None` for all of them. + pub channel: Option, + /// Sound: channels this source exposes (1 when `channel` is set, else `file_channels`). + pub channels: u32, + /// Sound: channels of the file / embedded data. + pub file_channels: u32, + pub width: u32, + pub height: u32, + /// Picture: the frame rate of the media. + pub frame_rate: FrameRate, + pub sample_rate: u32, + pub bits: u16, + pub length: Tick, + /// Media time of the essence's time 0 (trimmed / consolidated essence). + pub offset: Tick, + /// Start timecode in frames at `tc_rate`. + pub start_tc: Option, + pub tc_rate: FrameRate, + pub embedded: Option>, + pub markers: Vec, + /// Not media but a nested composition: its index in [`Document::nested`]. `start` of a clip + /// that uses it is a time in that composition. + pub nested: Option, +} + +impl Source { + /// A picture source with no length: a still image. + pub fn is_still(&self) -> bool { + self.kind == CKind::Picture && self.length == Tick::ZERO + } +} + +/// The largest time read from a document (about 3.3 days). +pub const MAX_TIME: Tick = Tick(1 << 56); + +/// Ticks of `n` edit units at rate `num/den` (rounded to the nearest tick). +pub fn units_to_ticks(n: i64, num: i64, den: i64) -> Tick { + if num <= 0 || den <= 0 { + return Tick::ZERO; + } + let t = n as i128 * den as i128 * TICKS_PER_SECOND as i128; + let q = t.div_euclid(num as i128); + let r = t.rem_euclid(num as i128); + // documents are untrusted: keep every time far from overflow (±3 days) + Tick((q + if r * 2 >= num as i128 { 1 } else { 0 }).clamp(-MAX_TIME.0 as i128, MAX_TIME.0 as i128) as i64) +} + +/// Edit units at rate `num/den` nearest to `t`; the flag is false when `t` is not on a unit. +pub fn ticks_to_units(t: Tick, num: i64, den: i64) -> (i64, bool) { + if num <= 0 || den <= 0 { + return (0, false); + } + let x = t.0 as i128 * num as i128; + let d = den as i128 * TICKS_PER_SECOND as i128; + let q = x.div_euclid(d); + let r = x.rem_euclid(d); + let n = q + if r * 2 >= d { 1 } else { 0 }; + (n.clamp(i64::MIN as i128, i64::MAX as i128) as i64, r == 0) +} diff --git a/crates/aaf/src/omf.rs b/crates/aaf/src/omf.rs new file mode 100644 index 000000000..57e0f756c --- /dev/null +++ b/crates/aaf/src/omf.rs @@ -0,0 +1,47 @@ +//! OMF Interchange 2.0 for audio post: written, and the same structures read. +//! +//! Written from the public *OMF Interchange Specification Version 2.0* (Avid Technology, 1995/97) +//! and Apple's *Bento Specification* revision 1.0d5 for the container ([`bento`]). +//! +//! The file holds a composition mob (`CMOB`) with a timecode slot and one sound slot per audio +//! track (one per channel when broken out to mono): sequences (`SEQU`) of fillers (`FILL`), source +//! clips (`SCLP`) and transitions (`TRAN` with a `SimpleMonoAudioDissolve` effect); clip volume is a +//! `MonoAudioGain` effect (`EFFE`) whose slot −1 is the clip and slot 1 the amplitude +//! (`CVAL` constant or `VVAL` keyframes). Every media item has a master mob (`MMOB`), a file source +//! mob (`SMOB` with a `WAVD` / `AIFD` descriptor: embedded essence in a `WAVE` media data object, +//! or a locator to a separate file) and a tape source mob carrying its timecode. Times are in +//! samples (sound slots use the sample rate as edit rate) so edits are sample-exact. +//! +//! Only sound is written: picture tracks and markers of the model are left out, and a nested +//! composition is not written as one (readers of OMF do not follow compositions). A caller with +//! nested sequences mixes their sound and passes it as media like any other; Premiere Pro's OMF +//! export does the same. +//! +//! Private properties. `FilmCraft:SCLP:ClipName` (a clip's name) and `FilmCraft:EFFE:EffectID` (a +//! transition's name) are not in the specification; they were first written by FilmCraft and keep +//! their names so that existing files read back. + +pub(crate) mod bento; +mod read; +mod write; + +use crate::model::Document; +use crate::{Identity, Report, Result}; + +/// Write the sound of `doc`'s first composition as an OMF 2.0 file. +pub fn write(doc: &Document, identity: &Identity<'_>, report: &mut Report) -> Result> { + write::write(doc, identity, report) +} + +/// Read an OMF 2.0 file (as written by [`write`] and by applications using the same structures). +pub fn read(bytes: &[u8], report: &mut Report) -> Result { + read::read(bytes, report) +} + +/// Whether `bytes` end with a Bento container label (OMF files do). +pub fn sniff(bytes: &[u8]) -> bool { + bento::sniff(bytes) +} + +#[cfg(test)] +mod tests; diff --git a/crates/aaf/src/omf/bento.rs b/crates/aaf/src/omf/bento.rs new file mode 100644 index 000000000..00a7e2a26 --- /dev/null +++ b/crates/aaf/src/omf/bento.rs @@ -0,0 +1,407 @@ +//! The Bento container (Apple, *Bento Specification* revision 1.0d5), the storage layer of OMF +//! Interchange 2.0 files. +//! +//! A Bento container is a heap of value bytes, a table of contents (TOC) describing every value of +//! every object, and a fixed-size label at the very end of the file that locates the TOC: +//! +//! ```text +//! label (24 bytes, big-endian): magic A4 'C' 'M' A5 'H' 'd' 'r' D7, u16 flags, u16 buffer size +//! (KiB), u16 major version (1), u16 minor version (0), +//! u32 TOC offset, u32 TOC size +//! ``` +//! +//! Every value belongs to an (object id, property id, type id) triple. Properties and types are +//! themselves objects carrying a global name (`"OMFI:CPNT:Length"`, `"omfi:Length32"`). The TOC +//! is a stream of one-byte operations, each followed by its operands (big-endian): +//! +//! | op | operands | meaning | +//! |---|---|---| +//! | 1 NewObject | u32 id | following entries belong to this object | +//! | 2 NewProperty | u32 id | … to this property | +//! | 3 NewType | u32 id | starts a new value of this type | +//! | 4 ExplicitGen | u32 | generation of the value | +//! | 5 Offset4Len4 | u32 offset, u32 length | a value segment in the file | +//! | 6 ContdOffset4Len4 | u32 offset, u32 length | a continuation segment | +//! | 7 Offset8Len4 / 8 Contd… | u64 offset, u32 length | segments beyond 4 GiB | +//! | 9–13 Immediate0–4 | 4 bytes | a value of 0–4 bytes stored in the TOC | +//! | 14 ContdImmediate4 | 4 bytes | continuation | +//! | 15 ReferenceListID | u32 id | the object holding this value's reference list | +//! | 24 EndOfBufr | — | skip to the end of the current TOC buffer | +//! | 0xFF Padding | — | ignored | +//! +//! Object references (OMF's `omfi:ObjRef`) are 4-byte keys resolved through the referencing +//! object's reference list (standard property 22: pairs of u32 key, u32 object id). FilmCraft +//! uses the referenced object's id as the key. + +use std::collections::{BTreeMap, HashMap}; + +pub(crate) const MAGIC: [u8; 8] = [0xA4, b'C', b'M', 0xA5, b'H', b'd', b'r', 0xD7]; +pub(crate) const LABEL_SIZE: usize = 24; + +// standard object ids +const TOC_OBJECT: u32 = 1; +const TOC_SEED: u32 = 2; +const TOC_MIN_SEED: u32 = 3; +const TOC_TYPE: u32 = 19; +const TYPE_7BIT_ASCII: u32 = 21; +pub(crate) const OBJ_REFERENCES: u32 = 22; +const GLOBAL_TYPE_NAME: u32 = 23; +const GLOBAL_PROP_NAME: u32 = 24; +const MIN_USER_ID: u32 = 100; + +const OP_NEW_OBJECT: u8 = 1; +const OP_NEW_PROPERTY: u8 = 2; +const OP_NEW_TYPE: u8 = 3; +const OP_EXPLICIT_GEN: u8 = 4; +const OP_OFFSET4_LEN4: u8 = 5; +const OP_CONTD_OFFSET4_LEN4: u8 = 6; +const OP_OFFSET8_LEN4: u8 = 7; +const OP_CONTD_OFFSET8_LEN4: u8 = 8; +const OP_IMMEDIATE0: u8 = 9; +const OP_IMMEDIATE4: u8 = 13; +const OP_CONTD_IMMEDIATE4: u8 = 14; +const OP_REFERENCE_LIST_ID: u8 = 15; +const OP_END_OF_BUFFER: u8 = 24; +const OP_PADDING: u8 = 0xFF; + +const TOC_BUFFER_KIB: u16 = 8; + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Seg { + Imm(Vec), + At(u64, u32), +} + +/// Bento values are metadata, not essence payloads. Limit reassembled segments so repeated +/// references cannot amplify a small OMF into an enormous allocation. +const MAX_VALUE_BYTES: usize = 16 << 20; + +/// Most bytes of global names (property and type names) kept for one container. Real files name a +/// few hundred short strings; without a cap, many objects naming one large shared range would each +/// retain their own copy. +const MAX_NAME_BYTES: usize = 4 << 20; + +/// Builds a Bento container. +pub(crate) struct Writer { + data: Vec, + names: HashMap<(u32, String), u32>, + next: u32, + /// (object, property, type, segments) + entries: Vec<(u32, u32, u32, Vec)>, +} + +impl Writer { + pub fn new() -> Writer { + Writer { data: Vec::new(), names: HashMap::new(), next: MIN_USER_ID, entries: Vec::new() } + } + + fn named(&mut self, kind: u32, name: &str) -> u32 { + if let Some(&id) = self.names.get(&(kind, name.to_string())) { + return id; + } + let id = self.new_object(); + let mut v = name.as_bytes().to_vec(); + v.push(0); + let seg = self.store(&v); + self.entries.push((id, kind, TYPE_7BIT_ASCII, vec![seg])); + self.names.insert((kind, name.to_string()), id); + id + } + + pub fn property(&mut self, name: &str) -> u32 { + self.named(GLOBAL_PROP_NAME, name) + } + + pub fn type_id(&mut self, name: &str) -> u32 { + self.named(GLOBAL_TYPE_NAME, name) + } + + pub fn new_object(&mut self) -> u32 { + let id = self.next; + self.next += 1; + id + } + + fn store(&mut self, v: &[u8]) -> Seg { + if v.len() <= 4 { + return Seg::Imm(v.to_vec()); + } + let at = self.data.len() as u64; + self.data.extend_from_slice(v); + Seg::At(at, v.len() as u32) + } + + /// Set a value of `obj` (values of more than 4 GiB are not supported by OMF). + pub fn set(&mut self, obj: u32, property: &str, ty: &str, value: &[u8]) { + let p = self.property(property); + let t = self.type_id(ty); + let seg = self.store(value); + self.entries.push((obj, p, t, vec![seg])); + } + + /// The reference list of `obj` (keys are object ids). + pub fn set_references(&mut self, obj: u32, targets: &[u32]) { + let mut v = Vec::with_capacity(targets.len() * 8); + for t in targets { + v.extend_from_slice(&t.to_be_bytes()); + v.extend_from_slice(&t.to_be_bytes()); + } + let seg = self.store(&v); + self.entries.push((obj, OBJ_REFERENCES, TYPE_7BIT_ASCII, vec![seg])); + } + + pub fn finish(mut self) -> Vec { + let seed = self.next; + self.entries.push((TOC_OBJECT, TOC_SEED, TOC_TYPE, vec![Seg::Imm(seed.to_be_bytes().to_vec())])); + self.entries.push((TOC_OBJECT, TOC_MIN_SEED, TOC_TYPE, vec![Seg::Imm(MIN_USER_ID.to_be_bytes().to_vec())])); + self.entries.sort_by_key(|e| (e.0, e.1, e.2)); + let mut toc = Vec::new(); + let (mut cur_obj, mut cur_prop) = (u32::MAX, u32::MAX); + for (obj, prop, ty, segs) in &self.entries { + if *obj != cur_obj { + toc.push(OP_NEW_OBJECT); + toc.extend_from_slice(&obj.to_be_bytes()); + cur_obj = *obj; + cur_prop = u32::MAX; + } + if *prop != cur_prop { + toc.push(OP_NEW_PROPERTY); + toc.extend_from_slice(&prop.to_be_bytes()); + cur_prop = *prop; + } + toc.push(OP_NEW_TYPE); + toc.extend_from_slice(&ty.to_be_bytes()); + for (i, s) in segs.iter().enumerate() { + match s { + Seg::Imm(b) => { + toc.push(if i > 0 { OP_CONTD_IMMEDIATE4 } else { OP_IMMEDIATE0 + b.len() as u8 }); + let mut w = [0u8; 4]; + w[..b.len()].copy_from_slice(b); + toc.extend_from_slice(&w); + } + Seg::At(off, len) if *off <= u32::MAX as u64 => { + toc.push(if i > 0 { OP_CONTD_OFFSET4_LEN4 } else { OP_OFFSET4_LEN4 }); + toc.extend_from_slice(&(*off as u32).to_be_bytes()); + toc.extend_from_slice(&len.to_be_bytes()); + } + Seg::At(off, len) => { + toc.push(if i > 0 { OP_CONTD_OFFSET8_LEN4 } else { OP_OFFSET8_LEN4 }); + toc.extend_from_slice(&off.to_be_bytes()); + toc.extend_from_slice(&len.to_be_bytes()); + } + } + } + } + let mut out = self.data; + let toc_at = out.len() as u64; + out.extend_from_slice(&toc); + let mut label = MAGIC.to_vec(); + label.extend_from_slice(&0u16.to_be_bytes()); // flags + label.extend_from_slice(&TOC_BUFFER_KIB.to_be_bytes()); + label.extend_from_slice(&1u16.to_be_bytes()); + label.extend_from_slice(&0u16.to_be_bytes()); + label.extend_from_slice(&(toc_at.min(u32::MAX as u64) as u32).to_be_bytes()); + label.extend_from_slice(&(toc.len() as u32).to_be_bytes()); + out.extend_from_slice(&label); + out + } +} + +/// One value of a parsed object. +#[derive(Clone, Debug)] +pub(crate) struct Prop { + pub prop: u32, + #[allow(dead_code)] + pub ty: u32, + segs: Vec, +} + +/// A parsed Bento container. +pub(crate) struct Container<'a> { + data: &'a [u8], + pub objects: BTreeMap>, + names: HashMap, + by_name: HashMap, +} + +fn be32(b: &[u8], at: usize) -> Option { + b.get(at..at + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])) +} + +/// Whether `b` ends with a Bento label. +pub(crate) fn sniff(b: &[u8]) -> bool { + b.len() >= LABEL_SIZE && b[b.len() - LABEL_SIZE..b.len() - LABEL_SIZE + 8] == MAGIC +} + +impl<'a> Container<'a> { + pub fn open(data: &'a [u8]) -> Result, String> { + if !sniff(data) { + return Err("no Bento label at the end of the file".into()); + } + let l = &data[data.len() - LABEL_SIZE..]; + let buf = (u16::from_be_bytes([l[10], l[11]]) as usize).max(1) * 1024; + let toc_at = be32(l, 16).unwrap_or(0) as usize; + let toc_len = be32(l, 20).unwrap_or(0) as usize; + let toc = data.get(toc_at..toc_at.checked_add(toc_len).ok_or("bad TOC size")?).ok_or("the TOC lies outside the file")?; + let mut c = Container { data, objects: BTreeMap::new(), names: HashMap::new(), by_name: HashMap::new() }; + let (mut obj, mut prop) = (0u32, 0u32); + let mut i = 0; + while i < toc.len() { + let op = toc[i]; + i += 1; + let need = |n: usize| -> Result<&[u8], String> { toc.get(i..i + n).ok_or_else(|| "truncated TOC".to_string()) }; + match op { + OP_NEW_OBJECT => { + obj = be32(need(4)?, 0).unwrap_or(0); + i += 4; + } + OP_NEW_PROPERTY => { + prop = be32(need(4)?, 0).unwrap_or(0); + i += 4; + } + OP_NEW_TYPE => { + let ty = be32(need(4)?, 0).unwrap_or(0); + i += 4; + c.objects.entry(obj).or_default().push(Prop { prop, ty, segs: Vec::new() }); + } + OP_EXPLICIT_GEN | OP_REFERENCE_LIST_ID => { + need(4)?; + i += 4; + } + OP_OFFSET4_LEN4 | OP_CONTD_OFFSET4_LEN4 => { + let b = need(8)?; + let seg = Seg::At(be32(b, 0).unwrap_or(0) as u64, be32(b, 4).unwrap_or(0)); + i += 8; + c.push_seg(obj, seg)?; + } + OP_OFFSET8_LEN4 | OP_CONTD_OFFSET8_LEN4 => { + let b = need(12)?; + let off = u64::from_be_bytes(b[..8].try_into().map_err(|_| "truncated TOC")?); + let seg = Seg::At(off, be32(b, 8).unwrap_or(0)); + i += 12; + c.push_seg(obj, seg)?; + } + x @ (OP_IMMEDIATE0..=OP_IMMEDIATE4 | OP_CONTD_IMMEDIATE4) => { + let b = need(4)?; + let n = if x == OP_CONTD_IMMEDIATE4 { 4 } else { (x - OP_IMMEDIATE0) as usize }; + let seg = Seg::Imm(b[..n].to_vec()); + i += 4; + c.push_seg(obj, seg)?; + } + OP_END_OF_BUFFER => { + // the rest of this TOC buffer is unused + i = (i - 1) / buf * buf + buf; + } + OP_PADDING | 0 => {} + other => return Err(format!("unknown TOC operation {other}")), + } + } + // global names + let ids: Vec = c.objects.keys().copied().collect(); + let mut name_bytes = 0usize; + for id in ids { + let name = c.objects[&id].iter().find(|p| p.prop == GLOBAL_PROP_NAME || p.prop == GLOBAL_TYPE_NAME).and_then(|p| c.value(p).ok()); + if let Some(n) = name { + name_bytes = name_bytes.saturating_add(n.len()); + if name_bytes > MAX_NAME_BYTES { + return Err("Bento global names exceed the name budget".into()); + } + let s = String::from_utf8_lossy(&n).trim_end_matches('\0').to_string(); + c.by_name.insert(s.clone(), id); + c.names.insert(id, s); + } + } + Ok(c) + } + + fn push_seg(&mut self, obj: u32, seg: Seg) -> Result<(), String> { + let p = self.objects.get_mut(&obj).and_then(|v| v.last_mut()).ok_or("a value without a type in the TOC")?; + if p.segs.len() > 1 << 20 { + return Err("too many value segments".into()); + } + p.segs.push(seg); + Ok(()) + } + + /// The bytes of a value. + pub fn value(&self, p: &Prop) -> Result, String> { + let total = p.segs.iter().try_fold(0usize, |total, s| { + let len = match s { + Seg::Imm(b) => b.len(), + Seg::At(_, len) => *len as usize, + }; + total.checked_add(len).ok_or_else(|| "Bento value length overflows".to_string()) + })?; + if total > MAX_VALUE_BYTES { + return Err("Bento value exceeds the decoded-value budget".into()); + } + let mut out = Vec::new(); + out.try_reserve_exact(total).map_err(|_| "cannot allocate Bento value")?; + for s in &p.segs { + match s { + Seg::Imm(b) => out.extend_from_slice(b), + Seg::At(off, len) => { + let start = usize::try_from(*off).map_err(|_| "value offset too large")?; + let b = + self.data.get(start..start.checked_add(*len as usize).ok_or("bad value length")?).ok_or("a value lies outside the file")?; + out.extend_from_slice(b); + } + } + } + Ok(out) + } + + pub fn id_of(&self, name: &str) -> Option { + self.by_name.get(name).copied() + } + + #[allow(dead_code)] + pub fn name_of(&self, id: u32) -> Option<&str> { + self.names.get(&id).map(String::as_str) + } + + /// The first value of property `name` of `obj`. + pub fn get(&self, obj: u32, name: &str) -> Option> { + let pid = self.id_of(name)?; + let p = self.objects.get(&obj)?.iter().find(|p| p.prop == pid)?; + self.value(p).ok() + } + + /// Resolve an object reference key of `obj` through its reference list. + pub fn resolve(&self, obj: u32, key: u32) -> u32 { + if let Some(p) = self.objects.get(&obj).and_then(|v| v.iter().find(|p| p.prop == OBJ_REFERENCES)) + && let Ok(v) = self.value(p) + { + for pair in v.as_chunks::<8>().0 { + if be32(pair, 0) == Some(key) { + return be32(pair, 4).unwrap_or(key); + } + } + } + key + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn many_objects_cannot_name_themselves_with_one_shared_range() { + let mut w = Writer::new(); + w.data = vec![b'a'; 1 << 20]; + let ids: Vec = (0..8).map(|_| w.new_object()).collect(); + for id in ids { + w.entries.push((id, GLOBAL_PROP_NAME, TYPE_7BIT_ASCII, vec![Seg::At(0, 1 << 20)])); + } + let file = w.finish(); + assert!(Container::open(&file).err().is_some_and(|e| e.contains("name budget"))); + } + + #[test] + fn repeated_segments_cannot_expand_a_value_past_its_budget() { + let p = Prop { prop: 1, ty: 1, segs: vec![Seg::At(0, MAX_VALUE_BYTES as u32), Seg::Imm(vec![0])] }; + let c = Container { data: &[], objects: BTreeMap::new(), names: HashMap::new(), by_name: HashMap::new() }; + assert!(c.value(&p).unwrap_err().contains("budget")); + } +} diff --git a/crates/aaf/src/omf/read.rs b/crates/aaf/src/omf/read.rs new file mode 100644 index 000000000..50e4b270c --- /dev/null +++ b/crates/aaf/src/omf/read.rs @@ -0,0 +1,438 @@ +//! OMF 2.0 objects (Bento) → composition model. + +use std::collections::{HashMap, HashSet}; + +use craft_timeline::time::{FrameRate, Tick}; + +use super::bento::Container; +use crate::model::{CClip, CItem, CKind, CTrack, CTransition, Composition, Document, Gain, Source, units_to_ticks}; +use crate::{Error, Report, Result}; + +type Uid = [u8; 12]; + +const MAX_REFERENCE_VISITS: usize = 65_536; + +struct R<'a, 'b> { + c: &'b Container<'a>, + report: &'b mut Report, + /// big-endian values ("MM"); "II" files are little-endian + be: bool, + mobs: HashMap, + media: HashMap>, + doc: Document, + sources: HashMap<(Uid, u32, String), usize>, +} + +pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { + let perr = |m: String| Error::Parse { format: "OMF", message: m }; + let c = Container::open(bytes).map_err(perr)?; + let class_of = |o: u32| c.get(o, "OMFI:OOBJ:ObjClass").and_then(|v| v.get(..4).map(|b| [b[0], b[1], b[2], b[3]])); + let head = c.objects.keys().copied().find(|&o| class_of(o) == Some(*b"HEAD")).ok_or_else(|| perr("no OMF header object".into()))?; + let be = c.get(head, "OMFI:HEAD:ByteOrder").is_none_or(|v| v.first() != Some(&0x49)); + let mut r = R { c: &c, report, be, mobs: HashMap::new(), media: HashMap::new(), doc: Document::default(), sources: HashMap::new() }; + let mob_list = r.refs(head, "OMFI:HEAD:Mobs"); + let mob_list = if mob_list.is_empty() { + c.objects.keys().copied().filter(|&o| matches!(class_of(o).as_ref(), Some(b"CMOB" | b"MMOB" | b"SMOB"))).collect() + } else { + mob_list + }; + for &m in &mob_list { + if let Some(id) = r.uid(m, "OMFI:MOBJ:MobID") { + r.mobs.insert(id, m); + } + } + let md = r.refs(head, "OMFI:HEAD:MediaData"); + let md = + if md.is_empty() { c.objects.keys().copied().filter(|&o| matches!(class_of(o).as_ref(), Some(b"WAVE" | b"AIFC"))).collect() } else { md }; + for m in md { + let Some(id) = r.uid(m, "OMFI:MDAT:MobID") else { continue }; + if let Some(d) = c.get(m, "OMFI:WAVE:Data") { + r.media.insert(id, d); + } else if let Some(d) = c.get(m, "OMFI:AIFC:Data") { + r.media.insert(id, d); + } + } + let cmobs: Vec = mob_list.iter().copied().filter(|&m| class_of(m) == Some(*b"CMOB")).collect(); + let mut referenced = HashSet::new(); + let mut visited = HashSet::new(); + let mut visits = 0; + for &m in &cmobs { + r.collect_refs(m, &mut referenced, &mut visited, &mut visits, 0); + } + let primary: Vec = r.refs(head, "OMFI:HEAD:PrimaryMobs").into_iter().filter(|m| cmobs.contains(m)).collect(); + let top: Vec = if !primary.is_empty() { + primary + } else { + cmobs.iter().copied().filter(|m| r.uid(*m, "OMFI:MOBJ:MobID").is_none_or(|id| !referenced.contains(&id))).collect() + }; + for m in top { + let comp = r.composition(m); + r.doc.compositions.push(comp); + } + if r.doc.compositions.is_empty() { + return Err(Error::Empty); + } + Ok(r.doc) +} + +impl R<'_, '_> { + fn class(&self, o: u32) -> [u8; 4] { + self.c.get(o, "OMFI:OOBJ:ObjClass").and_then(|v| v.get(..4).map(|b| [b[0], b[1], b[2], b[3]])).unwrap_or(*b"????") + } + fn u32_of(&self, b: &[u8]) -> Option { + let a: [u8; 4] = b.get(..4)?.try_into().ok()?; + Some(if self.be { u32::from_be_bytes(a) } else { u32::from_le_bytes(a) }) + } + fn i32(&self, o: u32, p: &str) -> Option { + self.c.get(o, p).and_then(|v| self.u32_of(&v)).map(|x| x as i32 as i64) + } + fn u32(&self, o: u32, p: &str) -> Option { + self.c.get(o, p).and_then(|v| self.u32_of(&v)) + } + fn u16(&self, o: u32, p: &str) -> Option { + let v = self.c.get(o, p)?; + let a: [u8; 2] = v.get(..2)?.try_into().ok()?; + Some(if self.be { u16::from_be_bytes(a) } else { u16::from_le_bytes(a) }) + } + fn rational(&self, o: u32, p: &str) -> Option<(i64, i64)> { + let v = self.c.get(o, p)?; + self.rational_of(&v) + } + fn rational_of(&self, v: &[u8]) -> Option<(i64, i64)> { + Some((self.u32_of(v)? as i32 as i64, self.u32_of(v.get(4..)?)? as i32 as i64)) + } + fn string(&self, o: u32, p: &str) -> Option { + self.c.get(o, p).map(|v| String::from_utf8_lossy(&v).trim_end_matches('\0').to_string()) + } + fn uid(&self, o: u32, p: &str) -> Option { + self.c.get(o, p).and_then(|v| v.get(..12).and_then(|b| b.try_into().ok())) + } + fn r#ref(&self, o: u32, p: &str) -> Option { + let v = self.c.get(o, p)?; + let key = u32::from_be_bytes(v.get(..4)?.try_into().ok()?); + Some(self.c.resolve(o, key)) + } + fn refs(&self, o: u32, p: &str) -> Vec { + let Some(v) = self.c.get(o, p) else { return Vec::new() }; + if v.len() < 2 { + return Vec::new(); + } + let n = u16::from_be_bytes([v[0], v[1]]) as usize; + v[2..].as_chunks::<4>().0.iter().take(n).map(|k| self.c.resolve(o, u32::from_be_bytes([k[0], k[1], k[2], k[3]]))).collect() + } + fn data_kind(&self, o: u32) -> String { + self.r#ref(o, "OMFI:CPNT:DataKind").and_then(|d| self.string(d, "OMFI:DDEF:DataKindID")).unwrap_or_default() + } + fn len(&self, o: u32) -> i64 { + self.i32(o, "OMFI:CPNT:Length").unwrap_or(0).max(0) + } + + fn collect_refs(&self, o: u32, out: &mut HashSet, visited: &mut HashSet, visits: &mut usize, depth: usize) { + if depth > 64 || !visited.insert(o) || *visits >= MAX_REFERENCE_VISITS { + return; + } + *visits += 1; + if self.class(o) == *b"SCLP" + && let Some(id) = self.uid(o, "OMFI:SCLP:SourceID") + { + out.insert(id); + } + for p in ["OMFI:MOBJ:Slots", "OMFI:SEQU:Components", "OMFI:EFFE:EffectSlots"] { + for c in self.refs(o, p) { + self.collect_refs(c, out, visited, visits, depth + 1); + } + } + for p in ["OMFI:MSLT:Segment", "OMFI:ESLT:ArgValue"] { + if let Some(c) = self.r#ref(o, p) { + self.collect_refs(c, out, visited, visits, depth + 1); + } + } + } + + fn composition(&mut self, m: u32) -> Composition { + let name = self.string(m, "OMFI:MOBJ:Name").unwrap_or_else(|| "Sequence".into()); + let mut comp = Composition { + name, + rate: FrameRate::FPS_25, + sample_rate: 48_000, + width: 1920, + height: 1080, + start_tc: 0, + drop: false, + tracks: Vec::new(), + markers: Vec::new(), + }; + let slots = self.refs(m, "OMFI:MOBJ:Slots"); + let mut na = 0; + for s in slots { + let Some(seg) = self.r#ref(s, "OMFI:MSLT:Segment") else { continue }; + let rate = self.rational(s, "OMFI:MSLT:EditRate").filter(|r| r.0 > 0 && r.1 > 0).unwrap_or((25, 1)); + let kind = self.data_kind(seg); + if self.class(seg) == *b"TCCP" || kind == "omfi:data:Timecode" { + comp.rate = FrameRate::new(rate.0, rate.1); + if self.class(seg) == *b"TCCP" { + comp.start_tc = self.i32(seg, "OMFI:TCCP:Start").unwrap_or(0); + comp.drop = self.c.get(seg, "OMFI:TCCP:Drop").and_then(|v| v.first().copied()).unwrap_or(0) != 0; + } + continue; + } + let ckind = match kind.as_str() { + "omfi:data:Sound" => CKind::Sound, + "omfi:data:Picture" | "omfi:data:PictureWithMatte" => CKind::Picture, + _ => { + self.report.info("an OMF slot of an unsupported data kind was skipped"); + continue; + } + }; + if ckind == CKind::Picture { + self.report.info("OMF picture slots are not imported (audio only)"); + continue; + } + if rate.1 == 1 && rate.0 >= 8000 { + comp.sample_rate = rate.0 as u32; + } + let items = self.segment(seg, rate, 0); + na += 1; + let td = self.r#ref(s, "OMFI:MSLT:TrackDesc"); + let tname = td.and_then(|t| self.string(t, "OMFI:TRKD:TrackName")).unwrap_or_else(|| format!("A{na}")); + let number = td.and_then(|t| self.u32(t, "OMFI:TRKD:PhysicalTrack")).unwrap_or(na); + let channels = items + .iter() + .filter_map(|i| match i { + CItem::Clip(c) => Some(self.doc.sources[c.source].channels), + _ => None, + }) + .max() + .unwrap_or(1) + .min(6); + comp.tracks.push(CTrack { kind: CKind::Sound, name: tname, number, channels, items }); + } + comp + } + + fn segment(&mut self, seg: u32, rate: (i64, i64), depth: usize) -> Vec { + let len = units_to_ticks(self.len(seg), rate.0, rate.1); + if depth > 32 { + return vec![CItem::Filler(len)]; + } + match &self.class(seg) { + b"SEQU" => { + let mut out = Vec::new(); + for c in self.refs(seg, "OMFI:SEQU:Components") { + out.extend(self.segment(c, rate, depth + 1)); + } + out + } + b"FILL" => vec![CItem::Filler(len)], + b"SCLP" => vec![self.clip(seg, rate)], + b"TRAN" => { + let cut = units_to_ticks(self.i32(seg, "OMFI:TRAN:CutPoint").unwrap_or(0), rate.0, rate.1); + let effect = self + .r#ref(seg, "OMFI:TRAN:Effect") + .and_then(|e| self.string(e, "FilmCraft:EFFE:EffectID")) + .unwrap_or_else(|| "constant_power".into()); + vec![CItem::Transition(CTransition { len, cut: cut.clamp(Tick::ZERO, len), effect })] + } + b"EFFE" => { + let kind = self.r#ref(seg, "OMFI:EFFE:EffectKind").and_then(|k| self.string(k, "OMFI:EDEF:EffectID")).unwrap_or_default(); + let slots = self.refs(seg, "OMFI:EFFE:EffectSlots"); + let arg = |r: &Self, id: i64| { + slots.iter().copied().find(|&s| r.i32(s, "OMFI:ESLT:ArgID") == Some(id)).and_then(|s| r.r#ref(s, "OMFI:ESLT:ArgValue")) + }; + let Some(input) = arg(self, -1).or_else(|| arg(self, 1).filter(|_| kind != "omfi:effect:MonoAudioGain")) else { + return vec![CItem::Filler(len)]; + }; + let gain = if kind == "omfi:effect:MonoAudioGain" { + arg(self, 1).and_then(|v| self.gain(v, len)) + } else { + self.report.warn("OMF effects other than audio gain are not imported (their input is used)"); + None + }; + let mut items = self.segment(input, rate, depth + 1); + if let (Some(g), [CItem::Clip(c)]) = (gain, items.as_mut_slice()) { + c.gain = Some(g); + } + items + } + _ => { + self.report.info("an unsupported OMF component was imported as a gap"); + vec![CItem::Filler(len)] + } + } + } + + fn amp(&self, v: &[u8]) -> Option { + self.rational_of(v).filter(|r| r.1 != 0).map(|(n, d)| n as f64 / d as f64) + } + + fn gain(&mut self, v: u32, len: Tick) -> Option { + match &self.class(v) { + b"CVAL" => self.c.get(v, "OMFI:CVAL:Value").and_then(|d| self.amp(&d)).map(Gain::Constant), + b"VVAL" => { + let linear = self.u16(v, "OMFI:VVAL:Interpolation") != Some(1); + let points: Vec<(Tick, f64)> = self + .refs(v, "OMFI:VVAL:PointList") + .into_iter() + .filter_map(|p| { + let (n, d) = self.rational(p, "OMFI:CTLP:Time").filter(|r| r.1 != 0)?; + let a = self.c.get(p, "OMFI:CTLP:Value").and_then(|d| self.amp(&d))?; + Some((Tick((len.0 as i128 * n as i128 / d as i128).clamp(-(1i128 << 56), 1i128 << 56) as i64), a)) + }) + .collect(); + (!points.is_empty()).then_some(Gain::Varying { linear, points }) + } + _ => None, + } + } + + fn clip(&mut self, c: u32, rate: (i64, i64)) -> CItem { + let len = units_to_ticks(self.len(c), rate.0, rate.1); + let start = units_to_ticks(self.i32(c, "OMFI:SCLP:StartTime").unwrap_or(0), rate.0, rate.1); + let name = self.string(c, "FilmCraft:SCLP:ClipName").unwrap_or_default(); + let (Some(id), Some(track)) = (self.uid(c, "OMFI:SCLP:SourceID"), self.u32(c, "OMFI:SCLP:SourceTrackID")) else { return CItem::Filler(len) }; + if id == [0; 12] { + return CItem::Filler(len); + } + match self.resolve(id, track, start, None, 0) { + Some((source, t)) => CItem::Clip(CClip { len, source, start: t, gain: None, name }), + None => CItem::Filler(len), + } + } + + fn slot_of(&self, mob: u32, track: u32) -> Option { + self.refs(mob, "OMFI:MOBJ:Slots") + .into_iter() + .find(|&s| self.r#ref(s, "OMFI:MSLT:TrackDesc").and_then(|t| self.u32(t, "OMFI:TRKD:TrackID")) == Some(track)) + } + + fn first_clip(&self, seg: u32) -> Option { + match &self.class(seg) { + b"SCLP" => Some(seg), + b"SEQU" => self.refs(seg, "OMFI:SEQU:Components").into_iter().find_map(|c| self.first_clip(c)), + _ => None, + } + } + + fn resolve(&mut self, id: Uid, track: u32, start: Tick, master: Option, depth: usize) -> Option<(usize, Tick)> { + if depth > 16 { + return None; + } + let Some(&mob) = self.mobs.get(&id) else { + self.report.warn("a clip references a mob that is not in the file (imported as a gap)"); + return None; + }; + let slot = self.slot_of(mob, track)?; + let rate = self.rational(slot, "OMFI:MSLT:EditRate").filter(|r| r.0 > 0 && r.1 > 0).unwrap_or((48_000, 1)); + let seg = self.r#ref(slot, "OMFI:MSLT:Segment")?; + match &self.class(mob) { + b"MMOB" => { + let key = master.unwrap_or_else(|| id.iter().map(|b| format!("{b:02x}")).collect()); + let clip = self.first_clip(seg)?; + let inner = units_to_ticks(self.i32(clip, "OMFI:SCLP:StartTime").unwrap_or(0), rate.0, rate.1); + let next = self.uid(clip, "OMFI:SCLP:SourceID")?; + let next_track = self.u32(clip, "OMFI:SCLP:SourceTrackID")?; + let name = self.string(mob, "OMFI:MOBJ:Name"); + let r = self.resolve(next, next_track, start + inner, Some(key), depth + 1)?; + if let Some(n) = name { + self.doc.sources[r.0].name = n; + } + Some(r) + } + b"SMOB" => { + let desc = self.r#ref(mob, "OMFI:SMOB:MediaDescription")?; + let sr = self.rational(desc, "OMFI:MDFL:SampleRate"); + if sr.is_none() && !self.media.contains_key(&id) { + return None; // a tape / physical source + } + let key = master.unwrap_or_else(|| id.iter().map(|b| format!("{b:02x}")).collect()); + let skey = (id, track, key.clone()); + if let Some(&i) = self.sources.get(&skey) { + return Some((i, start)); + } + let file_rate = sr.filter(|r| r.0 > 0 && r.1 > 0).unwrap_or(rate); + let length = units_to_ticks(self.i32(desc, "OMFI:MDFL:Length").unwrap_or(0), file_rate.0, file_rate.1); + let summary = self.c.get(desc, "OMFI:WAVD:Summary").or_else(|| self.c.get(desc, "OMFI:AIFD:Summary")).unwrap_or_default(); + let fmt = crate::pcm::parse_wav(&summary).or_else(|| crate::pcm::parse_aiff(&summary)).map(|(_, ch, sr, bits)| (ch as u32, sr, bits)); + let mut path = None; + for l in self.refs(desc, "OMFI:MDES:Locator") { + let p = match &self.class(l) { + b"UNXL" => self.string(l, "OMFI:UNXL:PathName"), + b"DOSL" => self.string(l, "OMFI:DOSL:PathName"), + b"MACL" => self.string(l, "OMFI:MACL:PathName"), + b"TXTL" => self.string(l, "OMFI:TXTL:Name"), + b"NETL" => self.string(l, "OMFI:NETL:URLString").map(|u| craft_timeline::path::file_url_to_path(&u)), + _ => None, + }; + if p.is_some() { + path = p; + break; + } + } + let sound_slots = self.refs(mob, "OMFI:MOBJ:Slots").len(); + let (file_channels, sample_rate, bits) = fmt.unwrap_or((1, file_rate.0 as u32, 16)); + let channel = (file_channels > 1 && sound_slots > 1).then(|| track.saturating_sub(1).min(file_channels - 1)); + // timecode of the physical source + let tc = self.first_clip(seg).and_then(|clip| { + let tid = self.uid(clip, "OMFI:SCLP:SourceID")?; + let tape = *self.mobs.get(&tid)?; + let (start_tc, fps, trate) = self.refs(tape, "OMFI:MOBJ:Slots").into_iter().find_map(|s| { + let g = self.r#ref(s, "OMFI:MSLT:Segment")?; + (self.class(g) == *b"TCCP").then(|| { + ( + self.i32(g, "OMFI:TCCP:Start").unwrap_or(0), + self.u16(g, "OMFI:TCCP:FPS").unwrap_or(25), + self.rational(s, "OMFI:MSLT:EditRate"), + ) + }) + })?; + let tcr = trate + .filter(|r| r.0 > 0 && r.1 > 0) + .map(|r| FrameRate::new(r.0, r.1)) + .unwrap_or_else(|| FrameRate::new(fps.max(1) as i64, 1)); + let off = units_to_ticks(self.i32(clip, "OMFI:SCLP:StartTime").unwrap_or(0), rate.0, rate.1); + Some((start_tc + tcr.frame_at(off), tcr)) + }); + let mut s = Source { + key, + name: self.string(mob, "OMFI:MOBJ:Name").unwrap_or_default(), + kind: CKind::Sound, + path, + channel, + channels: if channel.is_some() { 1 } else { file_channels }, + file_channels, + width: 0, + height: 0, + frame_rate: FrameRate::FPS_25, + sample_rate, + bits, + length, + offset: Tick::ZERO, + start_tc: tc.map(|t| t.0), + tc_rate: tc.map(|t| t.1).unwrap_or(FrameRate::FPS_25), + embedded: None, + markers: Vec::new(), + nested: None, + }; + if let Some(d) = self.media.get(&id) { + if let Some((pcm, ch, sr, b)) = crate::pcm::parse_wav(d).or_else(|| crate::pcm::parse_aiff(d)) { + s.embedded = Some(pcm); + s.file_channels = ch as u32; + s.channels = if s.channel.is_some() { 1 } else { ch as u32 }; + s.sample_rate = sr; + s.bits = b; + } else { + self.report.warn("embedded OMF audio in an unsupported format was skipped"); + } + } + let i = self.doc.sources.len(); + self.doc.sources.push(s); + self.sources.insert(skey, i); + Some((i, start)) + } + _ => { + self.report.warn("nested OMF compositions are not supported (imported as gaps)"); + None + } + } + } +} diff --git a/crates/aaf/src/omf/tests.rs b/crates/aaf/src/omf/tests.rs new file mode 100644 index 000000000..c6f4ef9f0 --- /dev/null +++ b/crates/aaf/src/omf/tests.rs @@ -0,0 +1,135 @@ +//! Structural checks of written OMF files: the Bento label and TOC, and the required properties of +//! the OMF Interchange 2.0 classes written. + +use std::collections::HashMap; + +use super::bento::{self, Container}; +use super::*; +use crate::testdoc::{IDENTITY, sound_only}; + +/// Every object of a class written has the properties the specification requires of it. +fn assert_required_properties(c: &Container<'_>, by_class: &HashMap>) { + let required: &[(&str, &[&str])] = &[ + ( + "HEAD", + &[ + "OMFI:HEAD:ByteOrder", + "OMFI:HEAD:LastModified", + "OMFI:HEAD:Version", + "OMFI:HEAD:Mobs", + "OMFI:HEAD:MediaData", + "OMFI:HEAD:DefinitionObjects", + ], + ), + ("CMOB", &["OMFI:MOBJ:MobID", "OMFI:MOBJ:Slots", "OMFI:MOBJ:LastModified", "OMFI:MOBJ:CreationTime"]), + ("MMOB", &["OMFI:MOBJ:MobID", "OMFI:MOBJ:Slots", "OMFI:MOBJ:LastModified", "OMFI:MOBJ:CreationTime"]), + ("SMOB", &["OMFI:MOBJ:MobID", "OMFI:MOBJ:Slots", "OMFI:SMOB:MediaDescription"]), + ("MSLT", &["OMFI:MSLT:Segment", "OMFI:MSLT:EditRate", "OMFI:MSLT:TrackDesc"]), + ("TRKD", &["OMFI:TRKD:Origin", "OMFI:TRKD:TrackID"]), + ("SEQU", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:SEQU:Components"]), + ("SCLP", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:SCLP:SourceID", "OMFI:SCLP:SourceTrackID", "OMFI:SCLP:StartTime"]), + ("FILL", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length"]), + ("TRAN", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:TRAN:CutPoint", "OMFI:TRAN:Effect"]), + ("EFFE", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:EFFE:EffectKind"]), + ("ESLT", &["OMFI:ESLT:ArgID", "OMFI:ESLT:ArgValue"]), + ("CVAL", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:CVAL:Value"]), + ("EDEF", &["OMFI:EDEF:EffectID"]), + ("DDEF", &["OMFI:DDEF:DataKindID"]), + ("TCCP", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:TCCP:Start", "OMFI:TCCP:FPS", "OMFI:TCCP:Drop"]), + ("WAVD", &["OMFI:MDFL:IsOMFI", "OMFI:MDFL:SampleRate", "OMFI:MDFL:Length", "OMFI:WAVD:Summary"]), + ("WAVE", &["OMFI:MDAT:MobID", "OMFI:WAVE:Data"]), + ("IDNT", &["OMFI:IDNT:CompanyName", "OMFI:IDNT:ProductName"]), + ]; + for (k, props) in required { + let Some(objs) = by_class.get(*k) else { + assert_eq!(*k, "FILL", "no {k} object"); + continue; + }; + for &o in objs { + for prop in *props { + assert!(c.get(o, prop).is_some(), "{k} {o} lacks {prop}"); + } + } + } +} + +#[test] +fn written_files_have_the_required_structure() { + let mut report = Report::default(); + let bytes = write(&sound_only(Some(vec![7; 480 * 4])), &IDENTITY, &mut report).unwrap(); + assert!(!report.has_warnings(), "{report}"); + // label + let l = &bytes[bytes.len() - bento::LABEL_SIZE..]; + assert_eq!(&l[..8], &bento::MAGIC); + assert_eq!(u16::from_be_bytes([l[12], l[13]]), 1, "Bento major version"); + let c = Container::open(&bytes).unwrap(); + let class = |o: u32| c.get(o, "OMFI:OOBJ:ObjClass").map(|v| String::from_utf8_lossy(&v).to_string()); + let mut by_class: HashMap> = HashMap::new(); + for &o in c.objects.keys() { + if let Some(k) = class(o) { + by_class.entry(k).or_default().push(o); + } + } + assert_required_properties(&c, &by_class); + assert_eq!(by_class["HEAD"].len(), 1); + assert_eq!(by_class["CMOB"].len(), 1); + let head = by_class["HEAD"][0]; + assert_eq!(c.get(head, "OMFI:HEAD:Version"), Some(vec![2, 0])); + assert_eq!(c.get(head, "OMFI:HEAD:ByteOrder"), Some(b"MM".to_vec())); + // object references resolve to objects of the right class + let refs = |o: u32, p: &str| -> Vec { + let v = c.get(o, p).unwrap(); + let n = u16::from_be_bytes([v[0], v[1]]) as usize; + v[2..].as_chunks::<4>().0.iter().take(n).map(|k| c.resolve(o, u32::from_be_bytes([k[0], k[1], k[2], k[3]]))).collect() + }; + let one = |o: u32, p: &str| -> u32 { c.resolve(o, u32::from_be_bytes(c.get(o, p).unwrap()[..4].try_into().unwrap())) }; + for m in refs(head, "OMFI:HEAD:Mobs") { + assert!(matches!(class(m).as_deref(), Some("CMOB" | "MMOB" | "SMOB"))); + for s in refs(m, "OMFI:MOBJ:Slots") { + assert_eq!(class(s).as_deref(), Some("MSLT")); + assert_eq!(class(one(s, "OMFI:MSLT:TrackDesc")).as_deref(), Some("TRKD")); + } + } + // embedded media: WAVE data is a WAVE file of the file mob it names + for w in &by_class["WAVE"] { + let data = c.get(*w, "OMFI:WAVE:Data").unwrap(); + let (pcm, ch, sr, bits) = crate::pcm::parse_wav(&data).unwrap(); + assert_eq!((pcm.len(), ch, sr, bits), (480 * 4, 2, 48_000, 16)); + let id = c.get(*w, "OMFI:MDAT:MobID").unwrap(); + assert!(by_class["SMOB"].iter().any(|s| c.get(*s, "OMFI:MOBJ:MobID") == Some(id.clone()))); + } + // the composition's sound sequence: clip, transition, gain effect around a clip + let cm = by_class["CMOB"][0]; + let slots = refs(cm, "OMFI:MOBJ:Slots"); + assert_eq!(class(one(slots[0], "OMFI:MSLT:Segment")).as_deref(), Some("TCCP")); + let seq = one(slots[1], "OMFI:MSLT:Segment"); + let comps = refs(seq, "OMFI:SEQU:Components"); + let classes: Vec = comps.iter().map(|&o| class(o).unwrap()).collect(); + assert_eq!(classes, vec!["EFFE", "TRAN", "SCLP"]); + let len = |o: u32| i32::from_be_bytes(c.get(o, "OMFI:CPNT:Length").unwrap()[..4].try_into().unwrap()) as i64; + let samples = |f: i64| f * 48_000 / 25; + assert_eq!(len(comps[0]), samples(55)); + assert_eq!(len(comps[1]), samples(10)); + assert_eq!(len(comps[2]), samples(55)); + assert_eq!(len(seq), samples(100)); + assert_eq!(c.get(one(comps[0], "OMFI:EFFE:EffectKind"), "OMFI:EDEF:EffectID"), Some(b"omfi:effect:MonoAudioGain\0".to_vec())); +} + +#[test] +fn bento_values_round_trip() { + let mut w = bento::Writer::new(); + let a = w.new_object(); + let b = w.new_object(); + w.set(a, "Test:Small", "test:Bytes", &[1, 2]); + w.set(a, "Test:Empty", "test:Bytes", &[]); + w.set(b, "Test:Big", "test:Bytes", &vec![9; 100_000]); + w.set_references(a, &[b]); + let bytes = w.finish(); + let c = Container::open(&bytes).unwrap(); + assert_eq!(c.get(a, "Test:Small"), Some(vec![1, 2])); + assert_eq!(c.get(a, "Test:Empty"), Some(vec![])); + assert_eq!(c.get(b, "Test:Big").map(|v| v.len()), Some(100_000)); + assert_eq!(c.resolve(a, b), b); + assert_eq!(c.name_of(c.id_of("Test:Big").unwrap()), Some("Test:Big")); + assert!(Container::open(&bytes[..bytes.len() - 1]).is_err()); +} diff --git a/crates/aaf/src/omf/write.rs b/crates/aaf/src/omf/write.rs new file mode 100644 index 000000000..755994804 --- /dev/null +++ b/crates/aaf/src/omf/write.rs @@ -0,0 +1,419 @@ +//! Composition model → OMF 2.0 objects in a Bento container. + +use std::collections::HashMap; + +use craft_timeline::time::Tick; + +use super::bento; +use crate::model::{CItem, CKind, Document, Gain, Source, ticks_to_units}; +use crate::{Error, Identity, Report, Result}; + +/// An OMF mob id (`omfi:UID`): prefix, major, minor. +pub(crate) type Uid = [u8; 12]; + +pub(crate) fn uid(prefix: u32, major: u32, minor: u32) -> Uid { + let mut u = [0u8; 12]; + u[..4].copy_from_slice(&prefix.to_be_bytes()); + u[4..8].copy_from_slice(&major.to_be_bytes()); + u[8..].copy_from_slice(&minor.to_be_bytes()); + u +} + +struct W<'a> { + b: bento::Writer, + refs: HashMap>, + ddefs: HashMap<&'static str, u32>, + edefs: HashMap<&'static str, u32>, + defs: Vec, + report: &'a mut Report, + inexact: bool, +} + +fn rational(n: i64, d: i64) -> Vec { + let mut v = (n.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_be_bytes().to_vec(); + v.extend_from_slice(&(d.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_be_bytes()); + v +} + +fn cstr(s: &str) -> Vec { + let mut v = s.as_bytes().to_vec(); + v.push(0); + v +} + +impl W<'_> { + fn obj(&mut self, class: &[u8; 4]) -> u32 { + let id = self.b.new_object(); + self.b.set(id, "OMFI:OOBJ:ObjClass", "omfi:ClassID", class); + id + } + fn str(&mut self, o: u32, p: &str, v: &str) { + self.b.set(o, p, "omfi:String", &cstr(v)); + } + fn i32(&mut self, o: u32, p: &str, ty: &str, v: i64) { + if v > i32::MAX as i64 || v < i32::MIN as i64 { + self.report.warn("a time does not fit OMF's 32-bit positions and was clamped"); + } + self.b.set(o, p, ty, &(v.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_be_bytes()); + } + fn r#ref(&mut self, o: u32, p: &str, target: u32) { + self.b.set(o, p, "omfi:ObjRef", &target.to_be_bytes()); + self.refs.entry(o).or_default().push(target); + } + fn refs(&mut self, o: u32, p: &str, targets: &[u32]) { + let mut v = (targets.len() as u16).to_be_bytes().to_vec(); + for t in targets { + v.extend_from_slice(&t.to_be_bytes()); + } + self.b.set(o, p, "omfi:ObjRefArray", &v); + self.refs.entry(o).or_default().extend_from_slice(targets); + } + fn u(&mut self, t: Tick, rate: (i64, i64)) -> i64 { + let (n, exact) = ticks_to_units(t, rate.0, rate.1); + if !exact { + self.inexact = true; + } + n + } + fn ddef(&mut self, kind: &'static str) -> u32 { + if let Some(&d) = self.ddefs.get(kind) { + return d; + } + let d = self.obj(b"DDEF"); + self.b.set(d, "OMFI:DDEF:DataKindID", "omfi:UniqueName", &cstr(kind)); + self.ddefs.insert(kind, d); + self.defs.push(d); + d + } + fn edef(&mut self, id: &'static str, name: &str) -> u32 { + if let Some(&d) = self.edefs.get(id) { + return d; + } + let d = self.obj(b"EDEF"); + self.b.set(d, "OMFI:EDEF:EffectID", "omfi:UniqueName", &cstr(id)); + self.str(d, "OMFI:EDEF:EffectName", name); + self.b.set(d, "OMFI:EDEF:Bypass", "omfi:ArgIDType", &(-1i32).to_be_bytes()); + self.edefs.insert(id, d); + self.defs.push(d); + d + } + fn cpnt(&mut self, o: u32, kind: &'static str, len: i64) { + let d = self.ddef(kind); + self.r#ref(o, "OMFI:CPNT:DataKind", d); + self.i32(o, "OMFI:CPNT:Length", "omfi:Length32", len); + } + fn mob(&mut self, class: &[u8; 4], id: Uid, name: &str, slots: &[u32]) -> u32 { + let m = self.obj(class); + self.b.set(m, "OMFI:MOBJ:MobID", "omfi:UID", &id); + self.str(m, "OMFI:MOBJ:Name", name); + self.refs(m, "OMFI:MOBJ:Slots", slots); + self.b.set(m, "OMFI:MOBJ:LastModified", "omfi:TimeStamp", &[0, 0, 0, 0, 1]); + self.b.set(m, "OMFI:MOBJ:CreationTime", "omfi:TimeStamp", &[0, 0, 0, 0, 1]); + m + } + fn slot(&mut self, rate: (i64, i64), segment: u32, track_id: u32, name: &str, physical: u32) -> u32 { + let t = self.obj(b"TRKD"); + self.i32(t, "OMFI:TRKD:Origin", "omfi:Position32", 0); + self.b.set(t, "OMFI:TRKD:TrackID", "omfi:UInt32", &track_id.to_be_bytes()); + self.str(t, "OMFI:TRKD:TrackName", name); + if physical > 0 { + self.b.set(t, "OMFI:TRKD:PhysicalTrack", "omfi:UInt32", &physical.to_be_bytes()); + } + let s = self.obj(b"MSLT"); + self.b.set(s, "OMFI:MSLT:EditRate", "omfi:Rational", &rational(rate.0, rate.1)); + self.r#ref(s, "OMFI:MSLT:Segment", segment); + self.r#ref(s, "OMFI:MSLT:TrackDesc", t); + s + } + fn sclp(&mut self, kind: &'static str, len: i64, source: Uid, track: u32, start: i64) -> u32 { + let c = self.obj(b"SCLP"); + self.cpnt(c, kind, len); + self.b.set(c, "OMFI:SCLP:SourceID", "omfi:UID", &source); + self.b.set(c, "OMFI:SCLP:SourceTrackID", "omfi:UInt32", &track.to_be_bytes()); + self.i32(c, "OMFI:SCLP:StartTime", "omfi:Position32", start); + c + } + fn tccp(&mut self, len: i64, start: i64, fps: i64, drop: bool) -> u32 { + let t = self.obj(b"TCCP"); + self.cpnt(t, "omfi:data:Timecode", len); + self.i32(t, "OMFI:TCCP:Start", "omfi:Position32", start); + self.b.set(t, "OMFI:TCCP:FPS", "omfi:UInt16", &(fps.clamp(1, u16::MAX as i64) as u16).to_be_bytes()); + self.b.set(t, "OMFI:TCCP:Drop", "omfi:Boolean", &[drop as u8]); + t + } + fn value(&mut self, len: i64, g: &Gain, seg_len: i64, rate: (i64, i64), base: Tick) -> u32 { + match g { + Gain::Constant(a) => { + let v = self.obj(b"CVAL"); + self.cpnt(v, "omfi:data:Rational", len); + self.b.set(v, "OMFI:CVAL:Value", "omfi:DataValue", &(*a)); + v + } + Gain::Varying { linear, points } => { + let mut pts = Vec::new(); + for (off, a) in points { + let o = self.u(base + *off, rate) - self.u(base, rate); + let p = self.obj(b"CTLP"); + self.b.set(p, "OMFI:CTLP:Time", "omfi:Rational", &rational(o, seg_len.max(1))); + self.b.set(p, "OMFI:CTLP:Value", "omfi:DataValue", &(*a)); + self.b.set(p, "OMFI:CTLP:EditHint", "omfi:EditHintType", &[0]); + pts.push(p); + } + let v = self.obj(b"VVAL"); + self.cpnt(v, "omfi:data:Rational", len); + self.b.set(v, "OMFI:VVAL:Interpolation", "omfi:InterpKind", &(if *linear { 2u16 } else { 1u16 }).to_be_bytes()); + self.refs(v, "OMFI:VVAL:PointList", &pts); + v + } + } + } +} + +fn fnv(s: &[u8], h: u64) -> u64 { + s.iter().fold(h, |h, &b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01B3)) +} + +fn amp(a: f64) -> Vec { + rational((a.max(0.0) * 65536.0).round().min(i32::MAX as f64) as i64, 65536) +} + +fn rate_of(s: &Source) -> (i64, i64) { + match s.kind { + CKind::Picture => (s.frame_rate.num, s.frame_rate.den), + CKind::Sound => (s.sample_rate.max(1) as i64, 1), + } +} + +pub(crate) fn write(doc: &Document, identity: &Identity<'_>, report: &mut Report) -> Result> { + let comp = doc.compositions.first().ok_or(Error::Empty)?; + let mut w = + W { b: bento::Writer::new(), refs: HashMap::new(), ddefs: HashMap::new(), edefs: HashMap::new(), defs: Vec::new(), report, inexact: false }; + let mut seed = fnv(comp.name.as_bytes(), 0xCBF2_9CE4_8422_2325); + for s in &doc.sources { + seed = fnv(s.path.as_deref().unwrap_or("").as_bytes(), fnv(s.key.as_bytes(), seed)); + } + let major = (seed >> 32) as u32 ^ seed as u32; + let mut minor = 0u32; + let mut new_uid = || { + minor += 1; + uid(0x464C_4D43, major, minor) + }; + let mut mobs = Vec::new(); + let mut media_data = Vec::new(); + let mut master_ref: HashMap = HashMap::new(); + // media + let mut groups: Vec<(String, Vec)> = Vec::new(); + for (i, s) in doc.sources.iter().enumerate() { + if s.kind != CKind::Sound { + continue; + } + match groups.iter_mut().find(|(k, _)| *k == s.key) { + Some((_, v)) => v.push(i), + None => groups.push((s.key.clone(), vec![i])), + } + } + for (_, members) in &groups { + let first = &doc.sources[members[0]]; + let master = new_uid(); + let tc = members.iter().find_map(|&i| doc.sources[i].start_tc.map(|t| (t, doc.sources[i].tc_rate))); + let tape = new_uid(); + let mut tape_slots = Vec::new(); + if let Some((start, r)) = tc { + let len = members.iter().map(|&i| doc.sources[i].length).max().unwrap_or(Tick::ZERO); + let l = w.u(len, (r.num, r.den)); + let t = w.tccp(l, start, r.timecode_base(), false); + tape_slots.push(w.slot((r.num, r.den), t, 1, "TC1", 0)); + } + let mut master_slots = Vec::new(); + for (k, &si) in members.iter().enumerate() { + let s = &doc.sources[si]; + let rate = rate_of(s); + let len = w.u(s.length, rate); + // file mob + let file = new_uid(); + let file_track = s.channel.map_or(1, |c| c + 1); + let tape_track = 2 + k as u32; + let to_tape = + if tc.is_some() { w.sclp("omfi:data:Sound", len, tape, tape_track, 0) } else { w.sclp("omfi:data:Sound", len, uid(0, 0, 0), 0, 0) }; + let fslot = w.slot(rate, to_tape, file_track, &format!("A{file_track}"), file_track); + let desc = descriptor(&mut w, s, len); + let fm = w.mob(b"SMOB", file, &s.name, &[fslot]); + w.r#ref(fm, "OMFI:SMOB:MediaDescription", desc); + mobs.push(fm); + if let Some(pcm) = &s.embedded { + let md = w.obj(b"WAVE"); + w.b.set(md, "OMFI:MDAT:MobID", "omfi:UID", &file); + w.b.set( + md, + "OMFI:WAVE:Data", + "omfi:DataValue", + &craft_audio::pcm_wav_file(pcm, u16::try_from(s.file_channels.max(1)).unwrap_or(u16::MAX), s.sample_rate, s.bits), + ); + media_data.push(md); + } + if tc.is_some() { + let c = w.sclp("omfi:data:Sound", len, uid(0, 0, 0), 0, 0); + tape_slots.push(w.slot(rate, c, tape_track, &format!("A{}", k + 1), k as u32 + 1)); + } + let mclip = w.sclp("omfi:data:Sound", len, file, file_track, 0); + master_slots.push(w.slot(rate, mclip, k as u32 + 1, &format!("A{}", k + 1), k as u32 + 1)); + master_ref.insert(si, (master, k as u32 + 1)); + } + mobs.push(w.mob(b"MMOB", master, &first.name, &master_slots)); + if tc.is_some() { + let d = w.obj(b"MDTP"); + let reel = first.path.as_deref().map(craft_timeline::path::file_stem).unwrap_or(&first.name).to_string(); + let tm = w.mob(b"SMOB", tape, &reel, &tape_slots); + w.r#ref(tm, "OMFI:SMOB:MediaDescription", d); + mobs.push(tm); + } + } + // composition + let crate_rate = (comp.rate.num, comp.rate.den); + let mut slots = Vec::new(); + let total = comp + .tracks + .iter() + .map(|t| t.items.iter().fold(Tick::ZERO, |a, i| if matches!(i, CItem::Transition(_)) { a - i.len() } else { a + i.len() })) + .max() + .unwrap_or(Tick::ZERO); + let tl = w.u(total, crate_rate); + let tcc = w.tccp(tl, comp.start_tc, comp.rate.timecode_base(), comp.drop); + slots.push(w.slot(crate_rate, tcc, 1, "TC1", 0)); + for (track_id, t) in (2..).zip(comp.tracks.iter().filter(|t| t.kind == CKind::Sound)) { + let rate = (comp.sample_rate.max(1) as i64, 1); + let mut comps = Vec::new(); + let mut cursor = Tick::ZERO; + for it in &t.items { + match it { + CItem::Filler(l) => { + let n = w.u(cursor + *l, rate) - w.u(cursor, rate); + cursor += *l; + let f = w.obj(b"FILL"); + w.cpnt(f, "omfi:data:Sound", n); + comps.push(f); + } + CItem::Clip(c) => { + let n = w.u(cursor + c.len, rate) - w.u(cursor, rate); + let (mid, mtrack) = master_ref.get(&c.source).copied().unwrap_or((uid(0, 0, 0), 0)); + let start = w.u(c.start, rate); + let sc = w.sclp("omfi:data:Sound", n, mid, mtrack, start); + if !c.name.is_empty() { + w.str(sc, "FilmCraft:SCLP:ClipName", &c.name); + } + let seg = match &c.gain { + Some(g) => { + let v = w.value(n, g, n, rate, cursor); + let input = w.obj(b"ESLT"); + w.b.set(input, "OMFI:ESLT:ArgID", "omfi:ArgIDType", &(-1i32).to_be_bytes()); + w.r#ref(input, "OMFI:ESLT:ArgValue", sc); + let level = w.obj(b"ESLT"); + w.b.set(level, "OMFI:ESLT:ArgID", "omfi:ArgIDType", &1i32.to_be_bytes()); + w.r#ref(level, "OMFI:ESLT:ArgValue", v); + let kind = w.edef("omfi:effect:MonoAudioGain", "Mono Audio Gain"); + let e = w.obj(b"EFFE"); + w.cpnt(e, "omfi:data:Sound", n); + w.r#ref(e, "OMFI:EFFE:EffectKind", kind); + w.refs(e, "OMFI:EFFE:EffectSlots", &[input, level]); + e + } + None => sc, + }; + comps.push(seg); + cursor += c.len; + } + CItem::Transition(x) => { + let ts = cursor - x.len; + let n = w.u(cursor, rate) - w.u(ts, rate); + let cut = w.u(ts + x.cut, rate) - w.u(ts, rate); + cursor = ts; + let kind = w.edef("omfi:effect:SimpleMonoAudioDissolve", "Simple Mono Audio Dissolve"); + let e = w.obj(b"EFFE"); + w.cpnt(e, "omfi:data:Sound", n); + w.r#ref(e, "OMFI:EFFE:EffectKind", kind); + w.refs(e, "OMFI:EFFE:EffectSlots", &[]); + w.str(e, "FilmCraft:EFFE:EffectID", &x.effect); + let tr = w.obj(b"TRAN"); + w.cpnt(tr, "omfi:data:Sound", n); + w.i32(tr, "OMFI:TRAN:CutPoint", "omfi:Position32", cut); + w.r#ref(tr, "OMFI:TRAN:Effect", e); + comps.push(tr); + } + } + } + let len = w.u(cursor.max(Tick::ZERO), rate); + let seq = w.obj(b"SEQU"); + w.cpnt(seq, "omfi:data:Sound", len); + w.refs(seq, "OMFI:SEQU:Components", &comps); + slots.push(w.slot(rate, seq, track_id, &t.name, t.number)); + } + let cmob = w.mob(b"CMOB", new_uid(), &comp.name, &slots); + mobs.insert(0, cmob); + if w.inexact { + w.report.info("some times are not on whole samples / frames and were rounded"); + } + let ident = w.obj(b"IDNT"); + w.str(ident, "OMFI:IDNT:CompanyName", identity.company); + w.str(ident, "OMFI:IDNT:ProductName", identity.product); + w.str(ident, "OMFI:IDNT:ProductVersionString", identity.version); + w.str(ident, "OMFI:IDNT:Platform", identity.platform); + w.b.set(ident, "OMFI:IDNT:Date", "omfi:TimeStamp", &[0, 0, 0, 0, 1]); + let head = w.obj(b"HEAD"); + w.b.set(head, "OMFI:HEAD:ByteOrder", "omfi:Int16", &0x4D4Di16.to_be_bytes()); + w.b.set(head, "OMFI:HEAD:LastModified", "omfi:TimeStamp", &[0, 0, 0, 0, 1]); + w.b.set(head, "OMFI:HEAD:Version", "omfi:VersionType", &[2, 0]); + w.refs(head, "OMFI:HEAD:Mobs", &mobs); + w.refs(head, "OMFI:HEAD:MediaData", &media_data); + w.refs(head, "OMFI:HEAD:PrimaryMobs", &[cmob]); + let defs = w.defs.clone(); + w.refs(head, "OMFI:HEAD:DefinitionObjects", &defs); + w.refs(head, "OMFI:HEAD:IdentificationList", &[ident]); + let refs = std::mem::take(&mut w.refs); + let mut keys: Vec<_> = refs.keys().copied().collect(); + keys.sort_unstable(); + for k in keys { + let mut t = refs[&k].clone(); + t.sort_unstable(); + t.dedup(); + w.b.set_references(k, &t); + } + Ok(w.b.finish()) +} + +fn descriptor(w: &mut W, s: &Source, len: i64) -> u32 { + let aiff = + s.embedded.is_none() && s.path.as_deref().is_some_and(|p| matches!(craft_timeline::path::extension(p).as_str(), "aif" | "aiff" | "aifc")); + let d = w.obj(if aiff { b"AIFD" } else { b"WAVD" }); + w.b.set(d, "OMFI:MDFL:IsOMFI", "omfi:Boolean", &[s.embedded.is_some() as u8]); + let r = rate_of(s); + w.b.set(d, "OMFI:MDFL:SampleRate", "omfi:Rational", &rational(r.0, r.1)); + w.i32(d, "OMFI:MDFL:Length", "omfi:Length32", len); + let frames = u32::try_from(len.max(0)).unwrap_or(u32::MAX); + // Channel counts come from the project: saturate, as the headers can't hold more anyway. + let bytes_per_frame = s.file_channels.max(1).saturating_mul((s.bits as u32).div_ceil(8)); + let channels = u16::try_from(s.file_channels.max(1)).unwrap_or(u16::MAX); + if aiff { + w.b.set(d, "OMFI:AIFD:Summary", "omfi:DataValue", &craft_audio::pcm_aiff_header(frames, channels, s.sample_rate, s.bits)); + } else { + w.b.set( + d, + "OMFI:WAVD:Summary", + "omfi:DataValue", + &craft_audio::pcm_wav_header(frames.saturating_mul(bytes_per_frame), channels, s.sample_rate, s.bits), + ); + } + if let Some(p) = &s.path { + let mut locs = Vec::new(); + let dos = p.len() > 2 && p.as_bytes()[1] == b':'; + let l = w.obj(if dos { b"DOSL" } else { b"UNXL" }); + w.str(l, if dos { "OMFI:DOSL:PathName" } else { "OMFI:UNXL:PathName" }, p); + locs.push(l); + if craft_timeline::path::is_absolute(p) { + let n = w.obj(b"NETL"); + w.str(n, "OMFI:NETL:URLString", &craft_timeline::path::path_to_file_url(p, false)); + locs.push(n); + } + w.refs(d, "OMFI:MDES:Locator", &locs); + } + d +} diff --git a/crates/aaf/src/pcm.rs b/crates/aaf/src/pcm.rs new file mode 100644 index 000000000..789c976a8 --- /dev/null +++ b/crates/aaf/src/pcm.rs @@ -0,0 +1,11 @@ +//! Embedded PCM essence in and out of WAVE and AIFF wrappers (craft-audio does the containers). + +/// PCM (little-endian, 8-bit unsigned), channels, sample rate and bits of a WAVE file. +pub(crate) fn parse_wav(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { + craft_audio::wav_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits)) +} + +/// The same for an AIFF / AIFF-C (`NONE`, `twos`, `sowt`) file. +pub(crate) fn parse_aiff(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { + craft_audio::aiff_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits)) +} diff --git a/crates/aaf/src/roundtrip_tests.rs b/crates/aaf/src/roundtrip_tests.rs new file mode 100644 index 000000000..5ae2a6d8f --- /dev/null +++ b/crates/aaf/src/roundtrip_tests.rs @@ -0,0 +1,217 @@ +//! Documents written and read back, in both formats; damaged files. + +use craft_timeline::time::{FrameRate, Tick}; + +use crate::model::{CItem, CKind, CMarker, Document, Gain}; +use crate::testdoc::{IDENTITY, pcm_ramp, picture_and_sound, sound_only}; +use crate::{Error, Report, aaf, omf}; + +fn aaf_bytes(doc: &Document, small_sectors: bool) -> Vec { + let mut report = Report::default(); + let bytes = aaf::write(doc, &aaf::WriteOptions { identity: IDENTITY, small_sectors }, &mut report).unwrap(); + assert!(report.is_empty(), "{report}"); + bytes +} + +fn omf_bytes(doc: &Document) -> Vec { + let mut report = Report::default(); + let bytes = omf::write(doc, &IDENTITY, &mut report).unwrap(); + assert!(!report.has_warnings(), "{report}"); + bytes +} + +fn read_clean(bytes: &[u8], is_aaf: bool) -> Document { + let mut report = Report::default(); + let doc = if is_aaf { aaf::read(bytes, &mut report) } else { omf::read(bytes, &mut report) }.unwrap(); + assert!(!report.has_warnings(), "{report}"); + doc +} + +/// What a track holds, with each clip's source by what it is rather than by index. Gain is stored +/// as a rational: four decimals survive. +fn shape(doc: &Document) -> Vec<(CKind, String, u32, Vec)> { + let comp = &doc.compositions[0]; + comp.tracks + .iter() + .map(|t| { + let items = t + .items + .iter() + .map(|i| match i { + CItem::Filler(l) => format!("gap {}", l.0), + CItem::Transition(x) => format!("{} {} cut {}", x.effect, x.len.0, x.cut.0), + CItem::Clip(c) => { + let s = &doc.sources[c.source]; + let gain = match &c.gain { + None => "unity".to_string(), + Some(Gain::Constant(g)) => format!("{g:.4}"), + Some(Gain::Varying { linear, points }) => { + format!("{linear} {:?}", points.iter().map(|(t, g)| (t.0, format!("{g:.4}"))).collect::>()) + } + }; + format!("clip {} from {} of {:?} {:?} gain {gain}", c.len.0, c.start.0, s.path, s.kind) + } + }) + .collect(); + (t.kind, t.name.clone(), t.number, items) + }) + .collect() +} + +#[test] +fn aaf_round_trips_the_edit_at_every_rate() { + for (rate, drop) in [(FrameRate::FPS_25, false), (FrameRate::FPS_29_97, true), (FrameRate::FPS_23_976, false), (FrameRate::FPS_59_94, true)] { + let mut doc = picture_and_sound(rate); + let comp = &mut doc.compositions[0]; + (comp.start_tc, comp.drop) = (rate.timecode_base() * 3600, drop); + comp.markers = vec![ + CMarker { start: rate.tick_of(10), duration: Tick::ZERO, name: "Slate".into(), comment: "take 2".into(), color: Some("Green".into()) }, + CMarker { start: rate.tick_of(40), duration: rate.tick_of(5), name: "Range".into(), comment: String::new(), color: None }, + ]; + // keyframed gain on the first sound clip, held gain steps on nothing else + if let Some(CItem::Clip(c)) = comp.tracks[1].items.first_mut() { + c.gain = Some(Gain::Varying { linear: true, points: vec![(Tick::ZERO, 1.0), (rate.tick_of(25), 0.5)] }); + } + doc.sources[0].markers = + vec![CMarker { start: rate.tick_of(30), duration: Tick::ZERO, name: "In media".into(), comment: String::new(), color: None }]; + for small in [false, true] { + let back = read_clean(&aaf_bytes(&doc, small), true); + let (want, got) = (&doc.compositions[0], &back.compositions[0]); + assert_eq!(shape(&back), shape(&doc), "{rate} small {small}"); + assert_eq!((&got.name, got.rate, got.start_tc, got.drop), (&want.name, want.rate, want.start_tc, want.drop), "{rate}"); + assert_eq!((got.width, got.height, got.sample_rate), (1920, 1080, 48_000), "{rate}"); + let markers = |m: &[CMarker]| m.iter().map(|m| (m.start, m.duration, m.name.clone(), m.comment.clone())).collect::>(); + assert_eq!(markers(&got.markers), markers(&want.markers), "{rate}"); + assert_eq!(back.nested, []); + let picture = back.sources.iter().find(|s| s.kind == CKind::Picture).unwrap(); + assert_eq!((picture.width, picture.height, picture.frame_rate, picture.length), (1280, 720, rate, doc.sources[0].length), "{rate}"); + assert_eq!((picture.start_tc, picture.tc_rate), (Some(86_400), rate), "{rate}"); + assert_eq!(markers(&picture.markers), markers(&doc.sources[0].markers), "{rate}"); + let sound = back.sources.iter().find(|s| s.kind == CKind::Sound).unwrap(); + assert_eq!((sound.channels, sound.file_channels, sound.sample_rate, sound.bits), (2, 2, 48_000, 24), "{rate}"); + assert_eq!(sound.key, picture.key, "one media item"); + // what was read, written again, reads as the same edit (mob ids, and so source keys, are new) + let again = read_clean(&aaf_bytes(&back, small), true); + assert_eq!((shape(&again), &again.compositions), (shape(&back), &back.compositions), "{rate}"); + } + } +} + +#[test] +fn embedded_audio_comes_back_bit_for_bit() { + let pcm = pcm_ramp(480, 2, 3); + let mut doc = sound_only(Some(pcm.clone())); + // trimmed essence: its first sample is media time 0.2 s + doc.sources[0].offset = Tick::from_units(9_600, 48_000); + for is_aaf in [true, false] { + let bytes = if is_aaf { aaf_bytes(&doc, false) } else { omf_bytes(&doc) }; + assert_eq!((aaf::sniff(&bytes), omf::sniff(&bytes)), (is_aaf, !is_aaf)); + let back = read_clean(&bytes, is_aaf); + let s = &back.sources[0]; + assert_eq!(s.embedded.as_deref(), Some(&pcm[..]), "aaf {is_aaf}"); + assert_eq!((s.path.as_deref(), s.file_channels, s.sample_rate, s.bits), (None, 2, 48_000, 16), "aaf {is_aaf}"); + assert_eq!(s.length, Tick::from_units(480, 48_000), "aaf {is_aaf}"); + assert_eq!(shape(&back), shape(&doc), "aaf {is_aaf}"); + } +} + +#[test] +fn omf_round_trips_sound_linked_to_wave_and_aiff_files() { + for path in ["/m/a.wav", "/m/a.aif"] { + let mut doc = sound_only(None); + doc.sources[0].path = Some(path.into()); + let back = read_clean(&omf_bytes(&doc), false); + assert_eq!(shape(&back), shape(&doc), "{path}"); + let s = &back.sources[0]; + assert_eq!((s.file_channels, s.sample_rate, s.bits, s.embedded.as_ref()), (2, 48_000, 16, None), "{path}"); + assert_eq!(back.compositions[0].rate, FrameRate::FPS_25); + } +} + +#[test] +fn omf_leaves_picture_out() { + let doc = picture_and_sound(FrameRate::FPS_25); + let back = read_clean(&omf_bytes(&doc), false); + assert!(back.compositions[0].tracks.iter().all(|t| t.kind == CKind::Sound)); + assert_eq!(shape(&back).len(), 1); +} + +#[test] +fn empty_and_foreign_documents() { + let none = Document::default(); + assert_eq!(aaf::write(&none, &aaf::WriteOptions { identity: IDENTITY, small_sectors: false }, &mut Report::default()), Err(Error::Empty)); + assert_eq!(omf::write(&none, &IDENTITY, &mut Report::default()), Err(Error::Empty)); + let mut empty = sound_only(None); + empty.compositions[0].tracks.clear(); + empty.sources.clear(); + for small in [false, true] { + assert_eq!(read_clean(&aaf_bytes(&empty, small), true).compositions.len(), 1); + } + assert_eq!(read_clean(&omf_bytes(&empty), false).compositions.len(), 1); + assert!(matches!(aaf::read(b"not an aaf", &mut Report::default()), Err(Error::Parse { format: "AAF", .. }))); + assert!(matches!(omf::read(b"not an omf", &mut Report::default()), Err(Error::Parse { format: "OMF", .. }))); + assert!(!aaf::sniff(b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1 but short")); + assert!(!omf::sniff(b"")); +} + +/// Truncation and random corruption: an error or a document, never a panic. +#[test] +fn damaged_documents_never_panic() { + let aaf_file = aaf_bytes(&picture_and_sound(FrameRate::FPS_25), true); + let omf_file = omf_bytes(&sound_only(Some(pcm_ramp(100, 2, 1)))); + for (bytes, is_aaf) in [(&aaf_file, true), (&omf_file, false)] { + let read = |b: &[u8]| { + let mut report = Report::default(); + let _ = if is_aaf { aaf::read(b, &mut report) } else { omf::read(b, &mut report) }; + }; + for cut in (0..bytes.len()).step_by(97) { + read(&bytes[..cut]); + } + let mut seed = 0xA5A5_1234_5678_9ABCu64; + for _ in 0..400 { + let mut g = bytes.clone(); + for _ in 0..8 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let at = (seed as usize) % g.len(); + g[at] = (seed >> 40) as u8; + } + read(&g); + } + } +} + +/// A time that is not on a whole edit unit is rounded, and the report says so. +#[test] +fn off_grid_times_are_rounded_and_reported() { + let mut doc = picture_and_sound(FrameRate::FPS_25); + if let Some(CItem::Clip(c)) = doc.compositions[0].tracks[0].items.first_mut() { + c.start += Tick(7); + } + let mut report = Report::default(); + aaf::write(&doc, &aaf::WriteOptions { identity: IDENTITY, small_sectors: false }, &mut report).unwrap(); + assert!(report.mentions("rounded"), "{report}"); +} + +/// A composition that uses itself (a damaged file) is a gap with a warning, not a recursion. +#[test] +fn a_composition_nested_in_itself_is_a_gap() { + let rate = FrameRate::FPS_25; + let mut doc = picture_and_sound(rate); + let mut inner = doc.compositions[0].clone(); + inner.name = "Inner".into(); + let mut nest = doc.sources[0].clone(); + (nest.key, nest.path, nest.nested, nest.start_tc) = ("seq:9".into(), None, Some(0), None); + doc.sources.push(nest); + let uses_inner = CItem::Clip(crate::model::CClip { len: rate.tick_of(20), source: 2, start: Tick::ZERO, gain: None, name: "Inner".into() }); + inner.tracks[0].items = vec![uses_inner.clone()]; + doc.nested.push(inner); + doc.compositions[0].tracks[0].items = vec![uses_inner]; + let bytes = aaf::write(&doc, &aaf::WriteOptions { identity: IDENTITY, small_sectors: false }, &mut Report::default()).unwrap(); + let mut report = Report::default(); + let back = aaf::read(&bytes, &mut report).unwrap(); + assert!(report.mentions("nested in itself"), "{report}"); + assert_eq!(back.nested.len(), 1); + assert!(matches!(back.nested[0].tracks[0].items[..], [CItem::Filler(_)]), "{:?}", back.nested[0].tracks[0].items); +} diff --git a/crates/aaf/src/testdoc.rs b/crates/aaf/src/testdoc.rs new file mode 100644 index 000000000..81db0a158 --- /dev/null +++ b/crates/aaf/src/testdoc.rs @@ -0,0 +1,106 @@ +//! Documents the tests write: what an editor's two-clip sequence with a dissolve looks like in +//! the model. + +use craft_timeline::time::{FrameRate, Tick}; + +use crate::Identity; +use crate::model::{CClip, CItem, CKind, CTrack, CTransition, Composition, Document, Gain, Source}; + +pub(crate) const IDENTITY: Identity<'static> = + Identity { company: "Craft", product: "craft-aaf tests", version: "1.2.3", platform: "test", product_id: *b"craft-aaf-tests." }; + +/// A source of `kind` for the media item `key` at `path`: 1280×720 picture at `rate`, or stereo +/// 48 kHz sound of `bits` bits; 100 seconds long. +pub(crate) fn source(key: &str, path: &str, kind: CKind, rate: FrameRate, bits: u16, start_tc: Option) -> Source { + let sound = kind == CKind::Sound; + Source { + key: key.into(), + name: path.rsplit('/').next().unwrap_or(path).into(), + kind, + path: Some(path.into()), + channel: None, + channels: if sound { 2 } else { 0 }, + file_channels: if sound { 2 } else { 0 }, + width: if sound { 0 } else { 1280 }, + height: if sound { 0 } else { 720 }, + frame_rate: rate, + sample_rate: 48_000, + bits, + length: rate.tick_of(100 * rate.timecode_base()), + offset: Tick::ZERO, + start_tc, + tc_rate: rate, + embedded: None, + markers: Vec::new(), + nested: None, + } +} + +pub(crate) fn clip(rate: FrameRate, source: usize, start: i64, len: i64, name: &str) -> CItem { + CItem::Clip(CClip { len: rate.tick_of(len), source, start: rate.tick_of(start), gain: None, name: name.into() }) +} + +/// Two clips of `source` cut at frame `cut`, each `cut` frames long on the timeline, joined by a +/// transition of `dur` frames centred on the cut: each clip runs half the transition past the cut. +pub(crate) fn two_clips(rate: FrameRate, source: usize, cut: i64, dur: i64, (in_a, in_b): (i64, i64), effect: &str) -> Vec { + let half = dur / 2; + vec![ + clip(rate, source, in_a, cut + half, "a"), + CItem::Transition(CTransition { len: rate.tick_of(dur), cut: rate.tick_of(half), effect: effect.into() }), + clip(rate, source, in_b - half, cut + half, "a"), + ] +} + +pub(crate) fn composition(name: &str, rate: FrameRate, tracks: Vec) -> Composition { + Composition { name: name.into(), rate, sample_rate: 48_000, width: 1920, height: 1080, start_tc: 0, drop: false, tracks, markers: Vec::new() } +} + +pub(crate) fn track(kind: CKind, name: &str, number: u32, items: Vec) -> CTrack { + CTrack { kind, name: name.into(), number, channels: if kind == CKind::Sound { 2 } else { 0 }, items } +} + +/// "S" at `rate`: V1 and A1 each hold two clips of `a.mov`, `cut` frames each on the timeline (from +/// source frames `ins`), with a transition of `dur` frames centred on the cut; the second sound +/// clip is 3 dB down. +pub(crate) fn picture_and_sound_cut(rate: FrameRate, cut: i64, dur: i64, ins: (i64, i64)) -> Document { + let sources = vec![ + source("item:1", "/m/a.mov", CKind::Picture, rate, 24, Some(86_400)), + source("item:1", "/m/a.mov", CKind::Sound, rate, 24, Some(86_400)), + ]; + let mut sound = two_clips(rate, 1, cut, dur, ins, "constant_power"); + if let Some(CItem::Clip(c)) = sound.last_mut() { + c.gain = Some(Gain::Constant(10f64.powf(-3.0 / 20.0))); + } + let tracks = vec![track(CKind::Picture, "V1", 1, two_clips(rate, 0, cut, dur, ins, "cross_dissolve")), track(CKind::Sound, "A1", 1, sound)]; + Document { compositions: vec![composition("S", rate, tracks)], sources, nested: Vec::new() } +} + +/// [`picture_and_sound_cut`] with 50-frame clips from source frames 10 and 205 and a 10-frame +/// transition: every time is a multiple of five frames, which is a whole number of 48 kHz samples +/// at the NTSC rates too. +pub(crate) fn picture_and_sound(rate: FrameRate) -> Document { + picture_and_sound_cut(rate, 50, 10, (10, 205)) +} + +/// 16-bit PCM: `frames` frames of `channels` channels, every sample different from its neighbours. +pub(crate) fn pcm_ramp(frames: usize, channels: usize, seed: i32) -> Vec { + (0..frames * channels).flat_map(|i| ((i as i32 * 37 + seed * 1000) as i16).to_le_bytes()).collect() +} + +/// "S" at 25 fps, sound only: A1 holds two 50-frame clips of `a.wav` (from source frames 10 and +/// 300) with a 10-frame crossfade centred on the cut; the first clip is 6 dB up. The sound is +/// embedded when `embedded` is given (480 frames of 16-bit stereo). +pub(crate) fn sound_only(embedded: Option>) -> Document { + let rate = FrameRate::FPS_25; + let mut s = source("item:1", "/m/a.wav", CKind::Sound, rate, 16, None); + if let Some(pcm) = embedded { + s.path = None; + s.length = Tick::from_units((pcm.len() / 4) as i64, 48_000); + s.embedded = Some(pcm); + } + let mut items = two_clips(rate, 0, 50, 10, (10, 300), "constant_power"); + if let Some(CItem::Clip(c)) = items.first_mut() { + c.gain = Some(Gain::Constant(10f64.powf(6.0 / 20.0))); + } + Document { compositions: vec![composition("S", rate, vec![track(CKind::Sound, "A1", 1, items)])], sources: vec![s], nested: Vec::new() } +} diff --git a/crates/aep/README.md b/crates/aep/README.md index 12ce8f9d6..95fcdd1a6 100644 --- a/crates/aep/README.md +++ b/crates/aep/README.md @@ -24,6 +24,13 @@ The XML form of a project (`.aepx`) is read into the same tree by `read_aepx` (a XML tokenizer of its own); `parse_any` picks the reader by content, so the typed view takes either form. The mapping is in [`docs/aep-format.md`](docs/aep-format.md), section 1. +A reader that only looks does not need the owned tree. `TreeIndex` is the same tree as one flat, +read-only array in depth-first order, borrowed from the input: `TreeIndex::parse` for an `.aep`, +`index_aepx` and `TreeIndex::from_drafts` for an `.aepx` (decoded into one buffer first). It +counts the same chunks against the same `Limits` and returns the same errors as `parse`, and the +typed view reads through either (`Project::new` for the owned tree, `Project::from_index` for the +index). An importer should use the index; it is about twice as fast and allocates far less. + Bodies that look like lists but are not chunk sequences (for example `LIST btdk`, raw text) stay opaque rather than failing the parse. Input is untrusted: sizes are checked against the remaining input, nesting and chunk count are bounded (`Limits`), nothing is allocated from a declared size, diff --git a/crates/aep/docs/aep-format.md b/crates/aep/docs/aep-format.md index a9269bc10..3582276d7 100644 --- a/crates/aep/docs/aep-format.md +++ b/crates/aep/docs/aep-format.md @@ -121,6 +121,11 @@ counterpart (a name that is not 1 to 4 characters) are skipped with their conten with the byte offset. It runs without recursion; the nesting depth (`Limits::max_depth`) and the element count (`Limits::max_chunks`) are bounded, and everything it allocates is bounded by the size of the input. +- There are two readers. `read_aepx` builds the owned tree element by element. The importer, which + only reads, uses a second reader that decodes every body (hex, text, the alias JSON, the + numbers) into one buffer and records the chunks as a flat depth-first list whose bodies are + ranges of that buffer; it indexes that buffer (`TreeIndex`) as it indexes an `.aep`. The tests + hold both readers to the same tree and the same errors. - Tests: `tests/aepx.rs` compares the five fixture pairs chunk by chunk and byte by byte, compares the typed view of both forms, and runs truncated, bit-flipped, deeply nested and oversized inputs; `crates/aep/tests/it/import/aepx.rs` imports both forms of each pair and expects the same @@ -139,8 +144,8 @@ write on their own. |---|---| | `svap` (4 bytes, the first top-level chunk) is the version of the After Effects that **wrote** the file: `0f 11 0e 02` in all 36 (a down-saved copy keeps the 2026 word) and in all 1 192 other `.aep` files of the local corpus folders. After Effects opens a file without `svap` (`t-nosvap`). | All 36; corpus scan. | | `head` bytes 4 to 7 are the version the file is **written for**: `0f 11 0e 02` (= `svap`) in the 2026 saves, `0f 0b 06 61` in the 25.x copies, `0f 03 06 41` in the 24.x copies, the same word in every family. After Effects refuses a file whose word is zero ("created with an older version [0.0x0]", `u-zhead`). | All 36; `u-zhead`. | -| The word is packed (bit 31 first): bits 25-24 and 21-19 the major, 18-15 the minor, 14-11 the bug-fix, 10-8 a stage (6 in all), 7-0 the build; bits 31-26 (`000011`) and 23-22 (`00`) are the same in all samples and not decoded. `0f110e02` = **26.2.1x2**, which is what the saving After Effects reports for itself (`app.version` recorded by the corpus scripts) - this one sample fixes minor, bug-fix and build. The copies read as **25.6.0x97** and **24.6.0x65** (major **V** from three consecutive majors; minor, bug-fix and build of the copies **E**: one other word decides their positions). `effectcraft_aep::AeVersion`, `AepFile::file_version`, `AepFile::saved_by_version`. | Tests `decodes_the_sampled_words`, `the_container_of_a_copy_states_its_version_in_head_and_the_writer_in_svap`. | -| `head` bytes 0 to 1 (a `u16`) step with the major: 97 (`0x61`) in the 2026 saves, 96 in 25.x, 95 in 24.x; bytes 2 to 3 are 5, 9 and 6 (**?**). Bytes 8 to 15 differ between families, not between versions; bytes 16 to 19 are the save counter (one higher in each copy). Nothing is derived from bytes 0 to 3 (`AepFile::head_revision` exposes the `u16`). | All 36. | +| The word is packed (bit 31 first): bits 25-24 and 21-19 the major, 18-15 the minor, 14-11 the bug-fix, 10-8 a stage (6 in all), 7-0 the build; bits 31-26 (`000011`) and 23-22 (`00`) are the same in all samples and not decoded. `0f110e02` = **26.2.1x2**, which is what the saving After Effects reports for itself (`app.version` recorded by the corpus scripts) - this one sample fixes minor, bug-fix and build. The copies read as **25.6.0x97** and **24.6.0x65** (major **V** from three consecutive majors; minor, bug-fix and build of the copies **E**: one other word decides their positions). `craft_aep::AeVersion`, `AepFile::file_version`, `AepFile::saved_by_version`. | Tests `decodes_the_sampled_words`, `the_container_of_a_copy_states_its_version_in_head_and_the_writer_in_svap`. | +| `head` bytes 0 to 1 (a `u16`) step with the major: 97 (`0x61`) in the 2026 saves, 96 in 25.x, 95 in 24.x; bytes 2 to 3 are 5, 9 and 6 (**?**). Bytes 8 to 15 differ between families, not between versions; bytes 16 to 19 are the save counter (one higher in each copy). Nothing is derived from bytes 0 to 3, and the reader does not expose them. | All 36. | | The XMP packet after the container is no guide: its `CreatorTool` is "Adobe After Effects 2026" in the copies too. | All 36. | | **26 against 25.x** (per family, chunk tree aligned by item and layer id): besides `head`, `nhed` / `nnhd` differ in 6 bytes (`nhed` 20-23 and 26-27: `827fa930` / `0015` in the 2026 save, `00000000` / `011b` in both copies; session state, see section 4). Every **solid's** `Pin /CLRS` changes: the 2026 save has `dcui` (1 byte, 1), `apid` all `0xff` and an empty `Utf8`; the copies drop `dcui`, set `apid` to a GUID (`601e9973...`, the same in all) and embed a 935-byte JSON with an ICC profile (`baseColorProfile/colorProfileData`). A **footage** item that the 2026 save stores with an assigned profile (`mcsp` = 1 and a profile JSON) loses `mcsp` and that JSON in the copies, and its `epid` becomes all `0xff`. The rest is save noise: the footage alias `ascendcount_base` (the copies were saved in another folder), `sspc` byte 112 of a footage item (a modification time), the `oEXR` `opti` of an EXR item (the copies hold the display device name `\.\DISPLAY1` as UTF-16 at byte 126 and, in the 24.x copy, a few non-zero bytes from byte 2 102 that look like uninitialised memory; the 2026 save has zeros), the plug-ins' sequence data `sdat` of Lumetri Color (16 instances and the project's `EfdG`), the mask counter `mkif` byte 8. No chunk is added or reordered, and no `pard`, `cdat`, `ldta`, `cdta`, `tdb4`, keyframe, text or shape chunk differs. | All 12 families. | | **25.x against 24.x**: only `head` (bytes 1, 3, 5 and 7), and the session noise in `opti` and `sdat` above. | All 12 families. | @@ -218,12 +223,12 @@ the value from the corpus manifest (test file in parentheses at the end of each API: `LayerHeader` (`is_video_enabled`/`is_enabled`, `is_audio_enabled`, `is_effects_enabled`, `is_auto_oriented`, `light_type`, `blend_mode`, `stretch` / `stretch_den`, `stretch_ratio`, -`stretch_percent`, `in_point`, `out_point`); the same switches on `Layer`; `Layer::track_matte` +`in_point`, `out_point`); the same switches on `Layer`; `Layer::track_matte` (`TrackMatte`, `MatteMode`; test `tests/matte.rs`). `stretch` is now the numerator of the ratio (it was the whole multiplier before 50 % and 150 % were sampled). Tests: `tests/header.rs`, `tests/layer_switches.rs`. The layer name itself is the `Utf8` child of the `Layr` (empty while the name is the source's); the layer then shows the name of its source item -(`Project::layer_display_name`). +(`Project::layer_source(...)` then `Item::display_name`, the rule the importer uses). ### 3.2 Composition header (`Item/cdta`, 204 bytes; the decoder needs the first 176) and renderer @@ -248,9 +253,9 @@ numerator of the ratio (it was the whole multiplier before 50 % and 150 % were s The inert `ADBE Time Remapping` record of every AV layer has `tduM` = the source's duration in seconds: 5 for 5 s compositions (124, 257, 258), 3 and 2 for a 3 s and a 2 s composition (600, 601), 1 for the 1 s WAV (351), 0.1 for the three-frame sequence (353), 0 on solids and stills (000, 126). Every property's keyframe time scale (`tdb4` bytes 12 to 15) follows the composition (23 976 in every property of `L` after 229 and 230). The corpus manifest calls the classic renderer -`ADBE Advanced 3d`; the file stores `ADBE Escher` / `Classic 3D`. API: `CompHeader::frame_rate_exact` -(exact fraction), `duration_frames`, `shutter_phase`, `display_start`, `display_start_seconds`, -`display_start_frame`. Tests: `tests/header.rs`, `tests/layer_switches.rs`. +`ADBE Advanced 3d`; the file stores `ADBE Escher` / `Classic 3D`. API: `CompHeader::{time_base, +frame_rate_fixed, duration_units, shutter_phase, display_start}` (`display_start` is the exact +fraction). Tests: `tests/header.rs`, `tests/layer_switches.rs`. ### 3.3 Items, footage and precomps @@ -295,7 +300,8 @@ name. A footage layer shows the item's name while it has no name of its own (351 Test: `tests/header.rs` (precomp), `tests/text_markers_footage.rs` and `tests/batch3_objects.rs` (footage), `tests/layer_switches.rs` (solid colour). API: `Footage::{duration, native_frame_rate, -bits_per_pixel, file_size, audio_sample_rate, is_sequence, sequence_frame_count}`. +bits_per_pixel, file_size, audio_sample_rate, is_sequence}`; `Item::sequence_info` (with +`SequenceInfo::frame_count`). ### 3.4 Properties: sparse storage, static values and units @@ -404,8 +410,8 @@ out speed, at 40 out influence**). Scale key 1 of 305 (`n = 3`, in 0 / 33 %, out 15 / 66) is `0,0, .33,.33, 15,15, .66,.66`. Component `i` uses slot `i` of each block (**V** for the block layout and the units, Scale speed in fractions per second and Mask Feather speed in pixels per second; **E** that different values per dimension sit in the slot of their dimension, because -the tool that made the corpus applies one ease to all dimensions; **V** since the exporter wrote three different eases for the three Scale dimensions and After Effects read the same three back, aep-export.md R13). `Keyframe::plain_ease_slots` -returns the doubles as stored, `Keyframe::ease_component(i)` one component's `KeyEase`. Layout of +the tool that made the corpus applies one ease to all dimensions; **V** since the exporter wrote three different eases for the three Scale dimensions and After Effects read the same three back, aep-export.md R13). `Keyframe::ease_component(i)` +returns one component's `KeyEase`, `Keyframe::ease_components` all of them. Layout of the spatial template: `u32` at 8 (1 normally, 0 after the spatial auto-bezier and continuous switches were turned off together, 054), `f64` arc length of the segment to the next key at 16 (100 in 204 key 1, 0 on the last key and right after creation; safe to ignore), **ease at 24 in @@ -430,7 +436,7 @@ in tangent (`n` x `f64`, relative offset from the value) at `56 + 8 n`, out tang | **ease, colour switched to bezier** | spatial n=4 @24..55 | keyframe.set_interpolation bezier on two colour keys stores speed 0 and influence 0 on both sides, and After Effects interpolates them linearly (598 Start Color red to blue: 0.75 / 0.5 / 0.25 red at 0.5 / 1 / 1.5 s); a custom colour ease cannot be set by script | 598 | V | | **ease, mask path** | 64-byte record @24..55 | in speed, in influence, out speed, out influence as in the spatial template: 599 out / in influence 0.75, 700 0.2 / 0.5, speeds 0 (the path at 0.5 s is 5.42 % / 28.0 % of the way). The `f64` at 16 is 1 (093) or 2 (599, 700) on the first key and 0 on the last (not decoded) | 093, 599, 700 | V (influence), ? (speed unit) | -API: `Keyframe::{interpolation_in, interpolation_out, kind, value, ease, ease_component, ease_components, plain_ease_slots, color_distance, spatial}`; +API: `Keyframe::{interpolation_in, interpolation_out, kind, value, ease, ease_component, ease_components, spatial}` (the `f64` at byte 16 of a colour key is `SpatialKey::segment_length`); `Property::keys()` hands the property's template to its records. Marker record (16 bytes): time, `03 03` hold bytes, 8 stale bytes. Mask path record (64 bytes): the common fields and the ease at byte 24 (599, 700). Test: `tests/values.rs`, `tests/keyframes.rs`. @@ -767,7 +773,7 @@ pins are placed by hand or by a preset. 328), so mode and inverted are reported per mask. `mkif` byte 8 is the running mask id counter of the **layer** in the session (1, 2 for the two masks of 328; 329 then gets 3; undo does not reset it; a new layer starts at 1 again): exposed as `Mask::counter`, a session counter and not a stable id. API: -`Mask::{mode, inverted, counter}`, `Project::mask_vertices_px` (vertices in layer pixels), `Layer::mask_atoms` (`MaskAtom`: the mask with its atom group, its path property and its shapes by position, for the keys and expressions of the mask properties). Tests: +`Mask::{mode, inverted, counter}`, `ShapePath::vertices(size)` (vertices in layer pixels: `size` is the size of the layer's source, `Project::layer_source_size`; a text or shape layer has no source size and its mask boxes are already pixels, so the importer passes 1 x 1), `Layer::mask_atoms` (`MaskAtom`: the mask with its atom group, its path property and its shapes by position, for the keys and expressions of the mask properties). Tests: `tests/masks.rs` (with a synthetic check of the handle order), `tests/batch3_objects.rs`. ### 3.9 Shape layers (`tdgp[ADBE Root Vectors Group]`) @@ -895,7 +901,7 @@ groups as on other layers, with these conventions: | What | Path | Stored | Evidence | Conf. | |---|---|---|---|---| -| camera Position, default (auto state) | `ADBE Transform Group/ADBE Position`, `tdb4` 76 and 77 = 1 although no expression exists | `[0, 0, -2666.67]` (x and y are 0 whatever the composition size; z = -zoom). A **one-node** camera reports `[0, 0, -2666.67]` (251). **Correction (S16): a reopened two-node camera reports `[0, 0, -2666.67]` too (256 read back), and After Effects renders it there**: the default two-node camera of 537 above the 3D solid of 486 renders from `[0, 0, -2666.67]` towards the point of interest, not like the composition's default view (537 differs from 486 in 24 % of the grid points, and EffectCraft's import with the stored position matches 537 but for 4 edge points). The `[960, 540, ...]` of the batch-3 notes was not reproduced (535 and 537, created by script, read back the stored value too); `CameraPosition::reported` keeps the old rule and is marked as contradicted | 256, 251, 537 | V | +| camera Position, default (auto state) | `ADBE Transform Group/ADBE Position`, `tdb4` 76 and 77 = 1 although no expression exists | `[0, 0, -2666.67]` (x and y are 0 whatever the composition size; z = -zoom). A **one-node** camera reports `[0, 0, -2666.67]` (251). **Correction (S16): a reopened two-node camera reports `[0, 0, -2666.67]` too (256 read back), and After Effects renders it there**: the default two-node camera of 537 above the 3D solid of 486 renders from `[0, 0, -2666.67]` towards the point of interest, not like the composition's default view (537 differs from 486 in 24 % of the grid points, and EffectCraft's import with the stored position matches 537 but for 4 edge points). The `[960, 540, ...]` of the batch-3 notes was not reproduced (535 and 537, created by script, read back the stored value too); the reader keeps only the stored value (`CameraPosition::stored`) | 256, 251, 537 | V | | camera Position, set by the user | same, `tdb4` 76 and 77 = 0 | the absolute value `[100, 200, -1000]` | 253 | V | | camera point of interest | `ADBE Anchor Point` | `[960, 540, 0]` in **pixels** (not a fraction); the record's `tdsb` is 1 on a two-node and 3 on the one-node camera (not asserted) | 251, 253, 256 | V (value), E (`tdsb`) | | light Position, default | same as the camera | `[0, 0, -1333.33]`, as After Effects reports it (255 read back); the point of interest `[960, 540, 0]` | 254, 255 | V | @@ -911,10 +917,8 @@ groups as on other layers, with these conventions: A point light made by converting a spot light has a different property set (`Orientation`, `Rotate X/Y/Z`, `Cone Angle`, `Cone Feather 2` in the default state) that a spot light lacks (252); whether that -is an artefact of the conversion is untested. API: `Layer::camera_position`, -`CameraPosition::reported`, `Layer::camera_point_of_interest`, `Layer::light_intensity`, -`Layer::{camera_zoom, camera_depth_of_field, camera_focus_distance, camera_aperture, light_color, -light_cone_angle, light_cone_feather}`, `DEFAULT_CAMERA_ZOOM` (2 666.67 is verified for the 1920 px +is an artefact of the conversion is untested. API: `Layer::camera_position`; the camera and light +options are read by the importer's table (`import/camera.rs`); `DEFAULT_CAMERA_ZOOM` (2 666.67 is verified for the 1920 px composition only), `Layer::orientation` (`Orientation`; test `orientation_is_otst_otda` in `tests/batch5.rs`). Render checks against After Effects (20 px grid, 5 184 points): 486 1 point off, 535 2, 536 0, 537 4 (anti-aliased edges); **488 (Orientation `[10, 20, 30]`): 272 points diff --git a/crates/aep/src/aepx.rs b/crates/aep/src/aepx.rs index 9fad696ce..5267080fb 100644 --- a/crates/aep/src/aepx.rs +++ b/crates/aep/src/aepx.rs @@ -12,13 +12,23 @@ //! instructions. A document type declaration is refused (no entity expansion). It runs without //! recursion; the nesting depth and the element count are bounded by [`Limits`], and everything //! it allocates is bounded by the size of the input. +//! +//! There are two readers. [`read_aepx`] builds the owned tree element by element +//! (`aepx/tree.rs`). The importer, which only reads, uses `index_aepx`: it decodes every body +//! (hex, text, the alias JSON, the numbers) into one buffer and records the chunks as entries of +//! the flat index ([`Draft`]s, in depth-first order, bodies as ranges of the buffer), which +//! [`crate::TreeIndex::from_drafts`] turns into an index that borrows the buffer. +//! The tests hold both to the same tree and the same errors. use std::borrow::Cow; -use crate::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; +use crate::chunk::{AepFile, LIST, NESTED_IDS}; use crate::error::AepError; +use crate::index::{Draft, Kind as EntryKind}; use crate::read::{Limits, parse}; +mod tree; + /// The root element of an `.aepx`. const ROOT: &[u8] = b"AfterEffectsProject"; /// The element that holds the XMP packet (the trailer of an `.aep`). @@ -68,17 +78,71 @@ pub fn read_aepx(data: &[u8]) -> Result, AepError> { /// # Errors /// See [`read_aepx`]. pub fn read_aepx_with_limits(data: &[u8], limits: Limits) -> Result, AepError> { + tree::read(data, limits) +} + +/// An `.aepx` read for the flat index: every body decoded into one buffer, and the chunks as +/// [`Draft`]s in depth-first order with their bodies as ranges of that buffer. +/// [`crate::TreeIndex::from_drafts`] makes the index, which borrows the buffer. +pub struct AepxDrafts { + /// The decoded bodies (hex, text, alias JSON, numbers) and the XMP packet. + pub buffer: Vec, + pub nodes: Vec, + /// The XMP packet: a range of `buffer` (empty without one). + pub trailer: (usize, usize), +} + +/// Reads an `.aepx` into [`AepxDrafts`]: the tree [`read_aepx_with_limits`] gives, with the same +/// errors, without one allocation per chunk. +/// +/// # Errors +/// See [`read_aepx_with_limits`]. When memory runs out, two errors come up in more cases than +/// there: [`AepError::TooLarge`] when the chunk list cannot grow (the owned-tree reader would +/// abort), and [`AepError::Xml`] "bdata is too large to hold in memory" also when the shared body +/// buffer cannot grow (the owned-tree reader reserves each value on its own). +pub fn index_aepx(data: &[u8], limits: Limits) -> Result { let text = match std::str::from_utf8(data) { Ok(t) => t.as_bytes(), Err(e) => return Err(xml(e.valid_up_to(), "the file is not valid UTF-8")), }; - Reader { data: text, pos: 0, limits, count: 0, stack: Vec::new(), top: None, trailer: None }.run() + // Every counted element takes at least 3 bytes (`` in a document cut short), so there are + // never more chunks than this. + let bound = (text.len() / 3).min(limits.max_chunks); + let mut nodes = Vec::new(); + let _ = nodes.try_reserve_exact(bound.min(INITIAL_SLOTS)); + // Hex is most of an `.aepx` and decodes to half its length: one buffer of that size usually + // holds everything. A failed reservation is not an error here; the buffer grows as it goes. + let mut buffer = Vec::new(); + let _ = buffer.try_reserve_exact(text.len() / 2); + let reader = Reader { + data: text, + pos: 0, + limits, + count: 0, + stack: Vec::new(), + root_closed: false, + trailer: None, + buffer, + nodes, + bound, + attrs: Vec::new(), + }; + reader.run() } +/// The slots the chunk list starts with; it doubles from there (as the array of +/// [`crate::TreeIndex`] does). +const INITIAL_SLOTS: usize = 1024; + fn xml(offset: usize, what: &'static str) -> AepError { AepError::Xml { offset, what } } +/// The pad byte of a body of `len` bytes, as [`crate::Chunk::data`] sets it. +fn pad_of(len: usize) -> Option { + if len % 2 == 1 { Some(0) } else { None } +} + /// What an open element becomes when it closes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Kind { @@ -102,13 +166,14 @@ struct Frame { at: usize, /// The name as written, to match the end tag. name: (usize, usize), - /// The decoded `bdata` attribute. - bdata: Option>, + /// The chunk's entry in the list (for `Chunk`, `Utf8` and `Alias`). + entry: Option, + /// The buffer length when the element opened: its body starts here. + mark: usize, + /// The end of the decoded `bdata` attribute in the buffer. + bdata_end: Option, /// The attributes of a `fileReference`, in document order. attrs: Vec<(String, String)>, - /// Collected text (only for `string` and the XMP packet). - text: Vec, - children: Vec>, } struct Reader<'d> { @@ -117,13 +182,19 @@ struct Reader<'d> { limits: Limits, count: usize, stack: Vec, - /// The top-level chunks once the root element has closed. - top: Option>>, - trailer: Option>, + /// True once the root element has closed. + root_closed: bool, + trailer: Option<(usize, usize)>, + buffer: Vec, + nodes: Vec, + /// The most chunks the input can hold under the limits: `nodes` never reserves past it. + bound: usize, + /// The attributes of the current start tag; kept to reuse its allocation. + attrs: Vec<((usize, usize), Cow<'d, [u8]>)>, } -impl Reader<'_> { - fn run(mut self) -> Result, AepError> { +impl<'d> Reader<'d> { + fn run(mut self) -> Result { if self.data.starts_with(&[0xef, 0xbb, 0xbf]) { self.pos = 3; } @@ -137,11 +208,13 @@ impl Reader<'_> { if let Some(open) = self.stack.last() { return Err(xml(open.at, "an element is not closed before the end of the file")); } - let chunks = self.top.ok_or_else(|| xml(self.data.len(), "no AfterEffectsProject root element"))?; - Ok(AepFile { chunks, trailer: Cow::Owned(self.trailer.unwrap_or_default()) }) + if !self.root_closed { + return Err(xml(self.data.len(), "no AfterEffectsProject root element")); + } + Ok(AepxDrafts { buffer: self.buffer, nodes: self.nodes, trailer: self.trailer.unwrap_or((0, 0)) }) } - fn rest(&self) -> &[u8] { + fn rest(&self) -> &'d [u8] { self.data.get(self.pos..).unwrap_or(&[]) } @@ -181,14 +254,13 @@ impl Reader<'_> { self.pos = start; let end = self.skip_past(b"]]>", "a CDATA section is not closed")?; let content = self.data.get(start..end).unwrap_or(&[]); - let at = start; - match self.stack.last_mut() { + match self.stack.last() { Some(frame) => { if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) { - frame.text.extend_from_slice(content); + self.buffer.extend_from_slice(content); } } - None => return Err(xml(at, "CDATA outside the root element")), + None => return Err(xml(start, "CDATA outside the root element")), } } else if rest.starts_with(b" { self.pos = self.pos.saturating_add(n); } - fn slice(&self, (a, b): (usize, usize)) -> &[u8] { + fn slice(&self, (a, b): (usize, usize)) -> &'d [u8] { self.data.get(a..b).unwrap_or(&[]) } - fn start_tag(&mut self) -> Result<(), AepError> { - let at = self.pos; - self.pos = self.pos.saturating_add(1); - let name = self.name()?; - let mut attrs: Vec<((usize, usize), Vec)> = Vec::new(); - let self_closing = loop { + /// Reads the attributes of a start tag into `attrs`; true when the tag closes itself. + fn attributes(&mut self, at: usize, attrs: &mut Vec<((usize, usize), Cow<'d, [u8]>)>) -> Result { + loop { self.skip_ws(); let rest = self.rest(); if rest.starts_with(b"/>") { self.pos = self.pos.saturating_add(2); - break true; + return Ok(true); } if rest.starts_with(b">") { self.pos = self.pos.saturating_add(1); - break false; + return Ok(false); } if rest.is_empty() { return Err(xml(at, "a start tag is not closed")); @@ -259,11 +328,27 @@ impl Reader<'_> { if raw.contains(&b'<') { return Err(xml(vstart, "`<` inside an attribute value")); } - let mut value = Vec::new(); - decode_entities(raw, vstart, &mut value)?; + // A value without `&` is its own decoding (most of them, every `bdata` After Effects + // writes): borrow it instead of copying it. + let value = if raw.contains(&b'&') { + let mut value = Vec::new(); + decode_entities(raw, vstart, &mut value)?; + Cow::Owned(value) + } else { + Cow::Borrowed(raw) + }; self.pos = vend.saturating_add(1); attrs.push((key, value)); - }; + } + } + + fn start_tag(&mut self) -> Result<(), AepError> { + let at = self.pos; + self.pos = self.pos.saturating_add(1); + let name = self.name()?; + let mut attrs = std::mem::take(&mut self.attrs); + attrs.clear(); + let self_closing = self.attributes(at, &mut attrs)?; let kind = self.kind_of(name, at)?; if kind != Kind::Root { self.count = self.count.saturating_add(1); @@ -275,15 +360,27 @@ impl Reader<'_> { return Err(AepError::TooDeep); } } - let mut frame = Frame { kind, at, name, bdata: None, attrs: Vec::new(), text: Vec::new(), children: Vec::new() }; - if matches!(kind, Kind::Chunk(_)) { - if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { - frame.bdata = Some(decode_hex(value, key.1)?); + let mark = self.buffer.len(); + let mut frame = Frame { kind, at, name, entry: None, mark, bdata_end: None, attrs: Vec::new() }; + match kind { + Kind::Chunk(id) => { + if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { + decode_hex_into(value, key.1, MAX_BDATA, &mut self.buffer)?; + frame.bdata_end = Some(self.buffer.len()); + } + frame.entry = Some(self.open_entry(id)?); } - } else if kind == Kind::Alias { - frame.attrs = - attrs.iter().map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())).collect(); + Kind::Utf8 => frame.entry = Some(self.open_entry(*b"Utf8")?), + Kind::Alias => { + frame.attrs = attrs + .iter() + .map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())) + .collect(); + frame.entry = Some(self.open_entry(*b"alas")?); + } + Kind::Root | Kind::Xmp | Kind::Skip => {} } + self.attrs = attrs; self.stack.push(frame); if self_closing { self.close()?; @@ -291,12 +388,38 @@ impl Reader<'_> { Ok(()) } + /// Appends the entry of a chunk whose element just opened; its body is filled in when it + /// closes. The list grows by its length (at least 16) but never past [`Self::bound`]; an + /// allocation the target cannot make is an error, not an abort. + fn open_entry(&mut self, id: [u8; 4]) -> Result { + let at = self.nodes.len(); + // This entry and the one after it must have `u32` indices. + u32::try_from(at.checked_add(1).ok_or(AepError::TooManyChunks)?).map_err(|_| AepError::TooManyChunks)?; + if at == self.nodes.capacity() { + // Past the bound (which only a wrong guess could reach) it keeps doubling. + let room = self.bound.saturating_sub(at); + let more = if room == 0 { at.max(16) } else { at.max(16).min(room) }; + self.nodes.try_reserve_exact(more).map_err(|_| AepError::TooLarge)?; + } + self.nodes.push(Draft::placeholder(id)); + Ok(at) + } + + /// Fills in the entry at `at` once its element has closed; its subtree is what follows it. + fn finish(&mut self, at: usize, id: [u8; 4], kind: EntryKind, list_type: [u8; 4], body: (usize, usize), pad: Option) -> Result<(), AepError> { + let end = u32::try_from(self.nodes.len()).map_err(|_| AepError::TooManyChunks)?; + if let Some(d) = self.nodes.get_mut(at) { + *d = Draft { start: body.0, len: body.1.saturating_sub(body.0), id, list_type, end, kind, pad }; + } + Ok(()) + } + /// Classifies an element by its name and where it is. fn kind_of(&self, name: (usize, usize), at: usize) -> Result { let n = self.slice(name); let parent = match self.stack.last() { None => { - if self.top.is_some() { + if self.root_closed { return Err(xml(at, "a second root element")); } if n != ROOT { @@ -340,39 +463,104 @@ impl Reader<'_> { self.close() } - /// Closes the innermost element and hands its chunk to the parent. + /// Closes the innermost element and fills in its chunk's entry. fn close(&mut self) -> Result<(), AepError> { let frame = self.stack.pop().ok_or(xml(self.pos, "an end tag without a start tag"))?; - let chunk = match frame.kind { - Kind::Root => { - self.top = Some(frame.children); - return Ok(()); - } - Kind::Skip => return Ok(()), + match frame.kind { + Kind::Root => self.root_closed = true, + Kind::Skip => {} Kind::Xmp => { + // Only the first packet is kept; a later one is dropped from the buffer (its + // children are skipped, so nothing else was written after it opened). if self.trailer.is_none() { - self.trailer = Some(frame.text); + self.trailer = Some((frame.mark, self.buffer.len())); + } else { + self.buffer.truncate(frame.mark); } - return Ok(()); } - Kind::Utf8 => Chunk::data(*b"Utf8", frame.text), - Kind::Alias => Chunk::data(*b"alas", alias_json(&frame.attrs).into_bytes()), - Kind::Chunk(id) => chunk_of(id, frame)?, - }; - if let Some(parent) = self.stack.last_mut() { - parent.children.push(chunk); + Kind::Utf8 => { + let at = frame.entry.ok_or(xml(frame.at, "an element lost its chunk"))?; + let end = self.buffer.len(); + self.finish(at, *b"Utf8", EntryKind::Data, [0; 4], (frame.mark, end), pad_of(end.saturating_sub(frame.mark)))?; + } + Kind::Alias => { + let at = frame.entry.ok_or(xml(frame.at, "an element lost its chunk"))?; + self.buffer.extend_from_slice(alias_json(&frame.attrs).as_bytes()); + let end = self.buffer.len(); + self.finish(at, *b"alas", EntryKind::Data, [0; 4], (frame.mark, end), pad_of(end.saturating_sub(frame.mark)))?; + } + Kind::Chunk(id) => self.close_chunk(id, &frame)?, } Ok(()) } + /// The chunk of a closed element named by a chunk id (what the owned reader's `chunk_of` + /// built): `bdata` wins over children, `numS` / `ppSn` hold their number, a nested id holds its + /// children (or nothing), any other name is a `LIST` of that type. + fn close_chunk(&mut self, id: [u8; 4], frame: &Frame) -> Result<(), AepError> { + let at = frame.entry.ok_or(xml(frame.at, "an element lost its chunk"))?; + let after = at.checked_add(1).ok_or(AepError::TooManyChunks)?; + if let Some(bdata_end) = frame.bdata_end { + // The children were read (and counted, and checked) but are not part of the chunk. + self.nodes.truncate(after); + self.buffer.truncate(bdata_end); + let body = (frame.mark, bdata_end); + let pad = pad_of(bdata_end.saturating_sub(frame.mark)); + if OPAQUE_LIST_TYPES.contains(&id) { + return self.finish(at, LIST, EntryKind::OpaqueList, id, body, pad); + } + return self.finish(at, id, EntryKind::Data, [0; 4], body, pad); + } + // Numbers written as text: `0` and `150.000000000`. + if &id == b"numS" || &id == b"ppSn" { + let missing = || xml(frame.at, "a numS or ppSn element without its number"); + // Exactly one child chunk, a `Utf8`: the entry after this one, whose subtree runs to the end. + let only = self.nodes.get(after).copied().filter(|c| usize::try_from(c.end).ok() == Some(self.nodes.len())).ok_or_else(missing)?; + if only.id != *b"Utf8" { + return Err(missing()); + } + let text = match only.kind { + EntryKind::Data | EntryKind::OpaqueList => { + only.start.checked_add(only.len).and_then(|end| self.buffer.get(only.start..end)).unwrap_or(&[]) + } + EntryKind::List | EntryKind::Nested => &[], + }; + let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); + let body: [u8; 8]; + let bytes: &[u8] = if &id == b"numS" { + // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. + let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); + let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; + body = u64::from(n as u32).to_be_bytes(); + body.get(4..).unwrap_or(&[]) + } else { + body = text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes(); + &body + }; + self.nodes.truncate(after); + self.buffer.truncate(frame.mark); + self.buffer.extend_from_slice(bytes); + let end = self.buffer.len(); + return self.finish(at, id, EntryKind::Data, [0; 4], (frame.mark, end), pad_of(bytes.len())); + } + let empty = (frame.mark, frame.mark); + if NESTED_IDS.contains(&id) { + if self.nodes.len() == after { + return self.finish(at, id, EntryKind::Data, [0; 4], empty, None); + } + return self.finish(at, id, EntryKind::Nested, [0; 4], empty, None); + } + self.finish(at, LIST, EntryKind::List, id, empty, None) + } + fn text(&mut self) -> Result<(), AepError> { let start = self.pos; let len = self.rest().iter().position(|b| *b == b'<').unwrap_or(self.rest().len()); let end = start.saturating_add(len); self.pos = end; let raw = self.data.get(start..end).unwrap_or(&[]); - match self.stack.last_mut() { - Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut frame.text), + match self.stack.last() { + Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut self.buffer), Some(_) => Ok(()), None if raw.iter().all(u8::is_ascii_whitespace) => Ok(()), None => Err(xml(start, "text outside the root element")), @@ -393,41 +581,6 @@ fn chunk_id(name: &[u8]) -> Option<[u8; 4]> { Some(id) } -/// The chunk of a closed element named by a chunk id. -fn chunk_of(id: [u8; 4], frame: Frame) -> Result, AepError> { - if let Some(bytes) = frame.bdata { - if OPAQUE_LIST_TYPES.contains(&id) { - let pad = if bytes.len() % 2 == 1 { Some(0) } else { None }; - return Ok(Chunk { id: LIST, body: Body::OpaqueList { list_type: id, data: Cow::Owned(bytes) }, pad }); - } - return Ok(Chunk::data(id, bytes)); - } - // Numbers written as text: `0` and `150.000000000`. - if &id == b"numS" || &id == b"ppSn" { - let text = match frame.children.as_slice() { - [only] if only.is(b"Utf8") => only.bytes().unwrap_or(&[]), - _ => return Err(xml(frame.at, "a numS or ppSn element without its number")), - }; - let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); - let body = if &id == b"numS" { - // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. - let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); - let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; - (n as u32).to_be_bytes().to_vec() - } else { - text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes().to_vec() - }; - return Ok(Chunk::data(id, body)); - } - if NESTED_IDS.contains(&id) { - if frame.children.is_empty() { - return Ok(Chunk::data(id, Vec::new())); - } - return Ok(Chunk { id, body: Body::Chunks(frame.children), pad: None }); - } - Ok(Chunk::list(id, frame.children)) -} - /// Appends `raw` with the predefined entities and character references decoded. fn decode_entities(raw: &[u8], offset: usize, out: &mut Vec) -> Result<(), AepError> { let mut i = 0; @@ -465,23 +618,74 @@ fn decode_entities(raw: &[u8], offset: usize, out: &mut Vec) -> Result<(), A Ok(()) } -/// Decodes a `bdata` value (hex digits, two per byte). +/// Decodes a `bdata` value (hex digits, two per byte) into a new `Vec` of exactly its size. fn decode_hex(text: &[u8], offset: usize) -> Result, AepError> { - if text.len() % 2 == 1 { - return Err(xml(offset, "bdata has an odd number of hex digits")); - } + decode_hex_at_most(text, offset, MAX_BDATA) +} + +/// The most bytes one `bdata` may decode to: what the 32-bit size field of a chunk can hold (a +/// larger body could not be written back as an `.aep` either). +const MAX_BDATA: usize = u32::MAX as usize; + +/// [`decode_hex`] with the decoded-size limit as a parameter (so tests can reach it). +fn decode_hex_at_most(text: &[u8], offset: usize, max: usize) -> Result, AepError> { + // Checked before anything is reserved, then sized once (collecting into `Option` has no + // size hint and regrows step by step), and without aborting when the memory is not there. + let pairs = check_hex(text, offset, max)?; + let mut out = Vec::new(); + out.try_reserve_exact(pairs).map_err(|_| xml(offset, "bdata is too large to hold in memory"))?; + decode_checked(text, offset, &mut out)?; + Ok(out) +} + +/// Appends the bytes of a `bdata` value (hex digits, two per byte, at most `max` bytes) to `out`. +/// On an error `out` is unchanged. +fn decode_hex_into(text: &[u8], offset: usize, max: usize, out: &mut Vec) -> Result<(), AepError> { + let pairs = check_hex(text, offset, max)?; + // Grown at most once per value (amortised over a shared buffer), and without aborting when the + // memory is not there. + out.try_reserve(pairs).map_err(|_| xml(offset, "bdata is too large to hold in memory"))?; + decode_checked(text, offset, out) +} + +/// Appends the bytes of a `bdata` value that [`check_hex`] accepted. On an error (a digit the +/// check let through, which it does not) `out` is unchanged. +fn decode_checked(text: &[u8], offset: usize, out: &mut Vec) -> Result<(), AepError> { let digit = |b: u8| match b { b'0'..=b'9' => Some(b - b'0'), b'a'..=b'f' => Some(b - b'a' + 10), b'A'..=b'F' => Some(b - b'A' + 10), _ => None, }; - let (pairs, _) = text.as_chunks::<2>(); - pairs - .iter() - .map(|[hi, lo]| digit(*hi).zip(digit(*lo)).map(|(h, l)| (h << 4) | l)) - .collect::>>() - .ok_or(xml(offset, "bdata holds a character that is not a hex digit")) + let mark = out.len(); + for [hi, lo] in text.as_chunks::<2>().0 { + match (digit(*hi), digit(*lo)) { + (Some(h), Some(l)) => out.push((h << 4) | l), + _ => { + out.truncate(mark); + return Err(xml(offset, "bdata holds a character that is not a hex digit")); + } + } + } + Ok(()) +} + +/// Checks a `bdata` value before anything is reserved for it: an even number of hex digits, at +/// most `max` bytes. Returns the number of bytes it decodes to. +fn check_hex(text: &[u8], offset: usize, max: usize) -> Result { + if text.len() % 2 == 1 { + return Err(xml(offset, "bdata has an odd number of hex digits")); + } + let pairs = text.len() / 2; + if pairs > max { + return Err(AepError::TooLarge); + } + // One cheap pass checks every digit first. Blocks without an early exit inside, so the check + // vectorises; it stops at the first bad block. + if !text.chunks(4096).all(|block| block.iter().fold(true, |ok, b| ok & b.is_ascii_hexdigit())) { + return Err(xml(offset, "bdata holds a character that is not a hex digit")); + } + Ok(pairs) } /// The JSON body of an `alas` chunk from the attributes of a `fileReference`, keys in document @@ -529,6 +733,7 @@ fn json_str(out: &mut String, s: &str) { #[cfg(test)] mod tests { use super::*; + use crate::index::TreeIndex; fn doc(body: &str) -> String { format!("\n{body}\n") @@ -629,6 +834,92 @@ mod tests { assert!(matches!(read_aepx(b"\xff"), Err(AepError::Xml { .. }))); } + /// Attribute values decode entities only where they have them. + #[test] + fn attribute_values_decode_entities_only_where_they_have_them() { + // An entity inside `bdata` still decodes before the hex does. + let f = read_aepx(doc("").as_bytes()).unwrap(); + assert_eq!(f.chunks[0].bytes(), Some(&[0x01, 0xab][..])); + // A bad entity in any attribute, even of an element that is skipped, is still an error. + for bad in ["", "", ""] { + assert!(matches!(read_aepx(doc(bad).as_bytes()), Err(AepError::Xml { .. })), "{bad}"); + } + // Without `&` the value is taken as written. + let f = read_aepx(doc("").as_bytes()).unwrap(); + assert_eq!(f.chunks[0].bytes(), Some(&[0x0a, 0xff][..])); + } + + /// A large bdata with a bad digit is refused before it is sized. + #[test] + fn a_large_bdata_with_a_bad_digit_is_refused_before_it_is_sized() { + // 10 MB of hex that is bad from the first pair (and once more at the very end). + let mut text = b"zz".to_vec(); + text.extend(std::iter::repeat_n(*b"00", 5_000_000).flatten()); + assert_eq!(decode_hex(&text, 3), Err(xml(3, "bdata holds a character that is not a hex digit"))); + let mut late = vec![b'0'; 10_000_000]; + late.extend_from_slice(b"0g"); + assert_eq!(decode_hex(&late, 3), Err(xml(3, "bdata holds a character that is not a hex digit"))); + let x = doc(&format!("", std::str::from_utf8(&text).unwrap())); + assert!(matches!(read_aepx(x.as_bytes()), Err(AepError::Xml { .. }))); + } + + /// Bdata decodes up to the size limit and not past it. + #[test] + fn bdata_decodes_up_to_the_size_limit_and_not_past_it() { + assert_eq!(decode_hex_at_most(b"00ff10", 0, 3), Ok(vec![0x00, 0xff, 0x10])); + assert_eq!(decode_hex_at_most(b"00ff10", 0, 2), Err(AepError::TooLarge)); + assert_eq!(decode_hex_at_most(b"", 0, 0), Ok(Vec::new())); + assert_eq!(decode_hex_at_most(b"00", 0, 0), Err(AepError::TooLarge)); + // The odd-length error still comes first. + assert_eq!(decode_hex_at_most(b"001", 0, 0), Err(xml(0, "bdata has an odd number of hex digits"))); + // The real limit is what a chunk's 32-bit size field holds. + assert_eq!(MAX_BDATA as u64, u64::from(u32::MAX)); + } + + /// Decode hex matches the collecting version. + #[test] + fn decode_hex_matches_the_collecting_version() { + /// The collecting decoder this one replaced, as the reference. + fn old(text: &[u8], offset: usize) -> Result, AepError> { + if text.len() % 2 == 1 { + return Err(xml(offset, "bdata has an odd number of hex digits")); + } + let digit = |b: u8| match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + b'A'..=b'F' => Some(b - b'A' + 10), + _ => None, + }; + let (pairs, _) = text.as_chunks::<2>(); + pairs + .iter() + .map(|[hi, lo]| digit(*hi).zip(digit(*lo)).map(|(h, l)| (h << 4) | l)) + .collect::>>() + .ok_or(xml(offset, "bdata holds a character that is not a hex digit")) + } + let alphabet = b"0123456789abcdefABCDEFgG \0"; + let mut seed = 0x2545_f491_4f6c_dd1du64; + for len in 0..200usize { + for _ in 0..20 { + let text: Vec = (0..len) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + // Mostly hex digits, now and then a byte that is not one. + let i = (seed % 1000) as usize; + alphabet[if i < 990 { i % 22 } else { 22 + i % 4 }] + }) + .collect(); + let new = decode_hex(&text, 7); + assert_eq!(new, old(&text, 7)); + if let Ok(v) = new { + assert_eq!(v.capacity(), v.len()); + } + } + } + } + #[test] fn limits_hold() { let deep = format!("{}{}", "".repeat(100_000), "".repeat(100_000)); @@ -638,4 +929,293 @@ mod tests { let many = format!("{}", "".repeat(10)); assert_eq!(read_aepx_with_limits(many.as_bytes(), Limits { max_depth: 64, max_chunks: 9 }), Err(AepError::TooManyChunks)); } + + /// A tiny deterministic generator (xorshift64*), so the tests need no extra crate. + struct Rng(u64); + + impl Rng { + /// The next pseudo-random number. + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + + /// A number below `n` (0 for `n == 0`). + fn below(&mut self, n: usize) -> usize { + if n == 0 { 0 } else { usize::try_from(self.next() % n as u64).unwrap() } + } + + /// One of `items`. + fn pick<'s>(&mut self, items: &[&'s str]) -> &'s str { + items[self.below(items.len())] + } + } + + /// `n` random bytes as hex, upper or lower case. + fn hex(rng: &mut Rng, n: usize) -> String { + let upper = rng.below(4) == 0; + (0..n).map(|_| if upper { format!("{:02X}", rng.below(256)) } else { format!("{:02x}", rng.below(256)) }).collect() + } + + /// Random `.aepx` content: every element form the reader knows (data, lists, nested ids, + /// strings, numbers, `btdk`, file references, skipped elements, XMP packets), `bdata` next to + /// children, bodies that read as chunk sequences, entities, CDATA, comments and stray text. + fn content(rng: &mut Rng, depth: usize, budget: &mut usize, out: &mut String) { + for _ in 0..rng.below(6) { + if *budget == 0 { + return; + } + *budget -= 1; + match rng.below(20) { + 0..=3 => { + let id = rng.pick(&["cdat", "tdmn", "head", "Utf8", "idta", "LIST", "a"]); + let n = rng.below(9); + out.push_str(&format!("<{id} bdata=\"{}\"/>", hex(rng, n))); + } + 4..=6 if depth < 10 => { + let id = rng.pick(&["Fold", "tdgp", "Layr", "Pin", "LIST", "btdk", "sspc"]); + let attr = if rng.below(5) == 0 { format!(" bdata=\"{}\"", hex(rng, 3)) } else { String::new() }; + out.push_str(&format!("<{id}{attr}>")); + content(rng, depth + 1, budget, out); + out.push_str(&format!("")); + } + 7 => { + let id = rng.pick(&["tdsn", "pdnm", "fnam"]); + match rng.below(4) { + 0 => out.push_str(&format!("<{id}/>")), + 1 => out.push_str(&format!("<{id}>name & A")), + // A body that is itself a chunk sequence (`Utf8`, 1 byte, pad): still data. + 2 => out.push_str(&format!("<{id} bdata=\"557466380000000161{}\"/>", if rng.below(2) == 0 { "00" } else { "" })), + _ => out.push_str(&format!("<{id}>ab")), + } + } + 8 => { + let text = + rng.pick(&["plain", "A < B", "", "ab", "", "été", "xgoney", "\r\n"]); + out.push_str(&format!("{text}")); + } + 9 => { + let id = rng.pick(&["numS", "ppSn"]); + let inner = rng.pick(&[ + "0", + " 7 ", + "-2147483648", + "150.000000000", + "x", + "", + "12", + "", + "", + "34", + ]); + let attr = if rng.below(6) == 0 { " bdata=\"00000002\"" } else { "" }; + out.push_str(&format!("<{id}{attr}>{inner}")); + } + 10 => { + let n = rng.pick(&["", "41", "414243", "4c495354000000000000"]); + out.push_str(&format!("")); + } + 11 => { + let platform = rng.pick(&["Win", "1", "Mac"]); + out.push_str(&format!( + "", + rng.below(3) + )); + } + 12 if depth < 10 => { + out.push_str("text"); + content(rng, depth + 1, budget, out); + out.push_str(""); + } + 13 => { + let packet = rng.pick(&["x]]>", "plain & text", ""]); + out.push_str(&format!("{packet}")); + } + 14 => out.push_str(rng.pick(&["", "", "\n ", "stray"])), + _ => { + let n = rng.below(5); + out.push_str(&format!("", hex(rng, n))); + } + } + } + } + + /// The default limits and six tight ones (depth 0, 1 and 3; 0, 7 and 40 chunks). + fn limit_sets() -> [Limits; 7] { + [ + Limits { max_depth: 0, max_chunks: 10_000_000 }, + Limits { max_depth: 64, max_chunks: 0 }, + Limits::default(), + Limits { max_depth: 1, max_chunks: 10_000_000 }, + Limits { max_depth: 3, max_chunks: 10_000_000 }, + Limits { max_depth: 64, max_chunks: 7 }, + Limits { max_depth: 64, max_chunks: 40 }, + ] + } + + /// The index reader and the owned-tree reader give the same `Result` (the tree, or the error), + /// and the index walks like the index of the owned tree. + fn same(bytes: &[u8], limits: Limits) { + let old = read_aepx_with_limits(bytes, limits); + let new = index_aepx(bytes, limits).map(|d| TreeIndex::from_drafts(&d.buffer, d.nodes, d.trailer).to_file().into_owned()); + assert_eq!(new, old, "{}", String::from_utf8_lossy(bytes)); + if let Ok(file) = &old { + let AepxDrafts { buffer, nodes, trailer } = index_aepx(bytes, limits).unwrap(); + let index = TreeIndex::from_drafts(&buffer, nodes, trailer); + let expected = TreeIndex::from_file(file).unwrap(); + assert_eq!(index.len(), expected.len()); + assert_eq!(index.trailer(), expected.trailer()); + let a: Vec = index.walk().map(|(d, n)| format!("{d} {n:?}")).collect(); + let b: Vec = expected.walk().map(|(d, n)| format!("{d} {n:?}")).collect(); + assert_eq!(a, b); + } + } + + /// The two readers give the same tree and errors on generated and damaged documents. + #[test] + fn the_two_readers_agree_on_generated_and_damaged_documents() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let noise = b"<>/=\"'&;#x0aZ \n![]-?"; + for _ in 0..600 { + let mut budget = 80; + let mut body = String::new(); + content(&mut rng, 0, &mut budget, &mut body); + let x = doc(&body); + for l in limit_sets() { + same(x.as_bytes(), l); + } + for _ in 0..4 { + let mut bad = x.clone().into_bytes(); + for _ in 0..1 + rng.below(3) { + let at = rng.below(bad.len()); + bad[at] = noise[rng.below(noise.len())]; + } + for l in limit_sets() { + same(&bad, l); + } + } + let cut = rng.below(x.len()); + same(&x.as_bytes()[..cut], Limits::default()); + // Bytes that are not UTF-8, and a multi-byte character cut in half. + let mut bad = x.clone().into_bytes(); + let at = rng.below(bad.len()); + bad.insert(at, 0xff); + same(&bad, Limits::default()); + let open = format!("{}é", x.trim_end().trim_end_matches("")).into_bytes(); + same(&open[..open.len() - 1], Limits::default()); + } + } + + /// The flat chunk list never reserves more slots than the input or the chunk limit allows. + #[test] + fn the_chunk_list_is_bounded_by_the_input_and_the_limit() { + let many = format!("{}", "".repeat(10_000)); + let d = index_aepx(many.as_bytes(), Limits::default()).unwrap(); + assert_eq!(d.nodes.len(), 10_000); + assert!(d.nodes.capacity() <= 2 * 10_000, "{} slots for 10 000 chunks", d.nodes.capacity()); + // The buffer is reserved once, at half the input, and holds nothing here. + assert!(d.buffer.is_empty() && d.buffer.capacity() <= many.len() / 2); + // At the limit the list never holds more slots than the limit. + let d = index_aepx(many.as_bytes(), Limits { max_depth: 64, max_chunks: 10_000 }).unwrap(); + assert!(d.nodes.capacity() <= 10_000); + let few = format!("{}", "".repeat(100)); + let d = index_aepx(few.as_bytes(), Limits { max_depth: 64, max_chunks: 100 }).unwrap(); + assert!(d.nodes.capacity() <= 100, "{} slots for at most 100 chunks", d.nodes.capacity()); + assert_eq!(index_aepx(few.as_bytes(), Limits { max_depth: 64, max_chunks: 99 }).err(), Some(AepError::TooManyChunks)); + // A tiny input cannot hold more than a third of its bytes in elements. + let tiny = doc(""); + assert!(index_aepx(tiny.as_bytes(), Limits::default()).unwrap().nodes.capacity() <= tiny.len() / 3); + } + + /// What a closed element drops is gone from the buffer and the chunk list, but was counted. + #[test] + fn dropped_content_leaves_nothing_behind_but_still_counts() { + // `bdata` wins over the children: they are read, counted and dropped. + let x = doc("xyzq"); + let d = index_aepx(x.as_bytes(), Limits::default()).unwrap(); + assert_eq!((d.buffer.as_slice(), d.nodes.len()), (&[1u8][..], 1)); + assert_eq!(index_aepx(x.as_bytes(), Limits { max_depth: 64, max_chunks: 4 }).err(), Some(AepError::TooManyChunks)); + assert!(index_aepx(x.as_bytes(), Limits { max_depth: 64, max_chunks: 5 }).is_ok()); + // A child's error is raised although the child would be dropped. + assert!(matches!(index_aepx(doc("").as_bytes(), Limits::default()), Err(AepError::Xml { .. }))); + // Only the first XMP packet stays in the buffer. + let packets = doc(&"packet".repeat(1000)); + let d = index_aepx(packets.as_bytes(), Limits::default()).unwrap(); + assert_eq!((d.buffer.as_slice(), d.trailer), (&b"packet"[..], (0, 6))); + // A number keeps its 4 or 8 bytes, not its text. + let d = index_aepx(doc(" 7 1.5").as_bytes(), Limits::default()).unwrap(); + assert_eq!(d.buffer, [&[0, 0, 0, 7][..], &1.5f64.to_be_bytes()[..]].concat()); + assert_eq!(d.nodes.len(), 2); + } + + /// Bodies keep what the element says they are, even where reading the same bytes as an `.aep` + /// would decide otherwise: a nested id whose `bdata` is a chunk sequence stays data, an empty + /// `btdk` stays an opaque list, an empty list at the deepest level stays a list. + #[test] + fn bodies_keep_the_kind_the_element_gives_them() { + let x = doc(""); + let AepxDrafts { buffer, nodes, trailer } = index_aepx(x.as_bytes(), Limits::default()).unwrap(); + let index = TreeIndex::from_drafts(&buffer, nodes, trailer); + let top: Vec<_> = index.chunks().collect(); + assert_eq!(top.len(), 3); + assert_eq!(top[0].bytes().map(<[u8]>::len), Some(11)); + assert!(top[0].children().next().is_none()); + assert!(top[1].is_opaque_list() && top[1].bytes() == Some(&[][..])); + assert!(top[2].is_opaque_list() && top[2].bytes().map(<[u8]>::len) == Some(12)); + // 64 levels: the innermost (empty) list is a list, not opaque. + let deep = format!("{}{}", "".repeat(64), "".repeat(64)); + let AepxDrafts { buffer, nodes, trailer } = index_aepx(deep.as_bytes(), Limits::default()).unwrap(); + let index = TreeIndex::from_drafts(&buffer, nodes, trailer); + assert_eq!(index.walk().map(|(d, _)| d).max(), Some(64)); + assert!(index.walk().all(|(_, n)| n.is_list(b"Fold") && !n.is_opaque_list())); + same(x.as_bytes(), Limits::default()); + same(deep.as_bytes(), Limits::default()); + } + + /// Hostile input is refused by both readers with the same errors. + #[test] + fn hostile_input_is_refused_alike_by_both_readers() { + let hostile = [ + format!("{}{}", "".repeat(100_000), "".repeat(100_000)), + format!("{}", "".repeat(1000)), + doc(&format!("", "00".repeat(100_000))), + doc(&format!("", "00".repeat(100_000))), + doc("4294967296"), + doc("1e400x"), + doc("�"), + doc("�"), + doc(&format!("{}", "".repeat(1000))), + format!("{}", "".repeat(10)), + " = + entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "aepx")).collect(); + paths.sort(); + for path in paths { + let bytes = std::fs::read(&path).unwrap(); + for l in limit_sets() { + let index = index_aepx(&bytes, l).map(|d| TreeIndex::from_drafts(&d.buffer, d.nodes, d.trailer).to_file().into_owned()); + assert_eq!(index, read_aepx_with_limits(&bytes, l), "{}", path.display()); + } + } + } } diff --git a/crates/aep/src/aepx/tree.rs b/crates/aep/src/aepx/tree.rs new file mode 100644 index 000000000..6c0bc8435 --- /dev/null +++ b/crates/aep/src/aepx/tree.rs @@ -0,0 +1,362 @@ +//! The `.aepx` reader of the owned chunk tree ([`super::read_aepx`]): it builds the tree element by +//! element. The importer uses the index reader in `aepx.rs` instead; the tests compare the two on +//! generated, damaged and corpus input (the same tree and the same errors). + +use std::borrow::Cow; + +use super::{FILE_REFERENCE, OPAQUE_LIST_TYPES, ROOT, STRING, XMP, alias_json, chunk_id, decode_entities, decode_hex, xml}; +use crate::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; +use crate::error::AepError; +use crate::read::Limits; + +/// [`super::read_aepx_with_limits`]. +pub(super) fn read(data: &[u8], limits: Limits) -> Result, AepError> { + let text = match std::str::from_utf8(data) { + Ok(t) => t.as_bytes(), + Err(e) => return Err(xml(e.valid_up_to(), "the file is not valid UTF-8")), + }; + Reader { data: text, pos: 0, limits, count: 0, stack: Vec::new(), top: None, trailer: None }.run() +} + +/// What an open element becomes when it closes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + /// The root element: its children are the top-level chunks. + Root, + /// A chunk with this id (or a `LIST` with this list type). + Chunk([u8; 4]), + /// A `Utf8` chunk. + Utf8, + /// An `alas` chunk built from the attributes. + Alias, + /// The XMP packet (only directly below the root). + Xmp, + /// An element without a chunk counterpart (a name that is no chunk id); skipped with its content. + Skip, +} + +struct Frame { + kind: Kind, + /// Offset of the start tag (for errors). + at: usize, + /// The name as written, to match the end tag. + name: (usize, usize), + /// The decoded `bdata` attribute. + bdata: Option>, + /// The attributes of a `fileReference`, in document order. + attrs: Vec<(String, String)>, + /// Collected text (only for `string` and the XMP packet). + text: Vec, + children: Vec>, +} + +struct Reader<'d> { + data: &'d [u8], + pos: usize, + limits: Limits, + count: usize, + stack: Vec, + /// The top-level chunks once the root element has closed. + top: Option>>, + trailer: Option>, +} + +impl Reader<'_> { + fn run(mut self) -> Result, AepError> { + if self.data.starts_with(&[0xef, 0xbb, 0xbf]) { + self.pos = 3; + } + while self.pos < self.data.len() { + if self.rest().starts_with(b"<") { + self.markup()?; + } else { + self.text()?; + } + } + if let Some(open) = self.stack.last() { + return Err(xml(open.at, "an element is not closed before the end of the file")); + } + let chunks = self.top.ok_or_else(|| xml(self.data.len(), "no AfterEffectsProject root element"))?; + Ok(AepFile { chunks, trailer: Cow::Owned(self.trailer.unwrap_or_default()) }) + } + + fn rest(&self) -> &[u8] { + self.data.get(self.pos..).unwrap_or(&[]) + } + + /// The offset of `needle` at or after `from`. + fn find(&self, from: usize, needle: &[u8]) -> Option { + let hay = self.data.get(from..)?; + if needle.is_empty() || hay.len() < needle.len() { + return None; + } + let first = *needle.first()?; + let mut i = 0; + while let Some(p) = hay.get(i..)?.iter().position(|b| *b == first) { + let at = i.checked_add(p)?; + if hay.get(at..)?.starts_with(needle) { + return from.checked_add(at); + } + i = at.checked_add(1)?; + } + None + } + + /// Skips to just after `close`, which must follow. + fn skip_past(&mut self, close: &[u8], what: &'static str) -> Result { + let at = self.find(self.pos, close).ok_or(xml(self.pos, what))?; + self.pos = at.saturating_add(close.len()); + Ok(at) + } + + fn markup(&mut self) -> Result<(), AepError> { + let rest = self.rest(); + if rest.starts_with(b"", "a processing instruction is not closed")?; + } else if rest.starts_with(b"", "a comment is not closed")?; + } else if rest.starts_with(b"", "a CDATA section is not closed")?; + let content = self.data.get(start..end).unwrap_or(&[]); + let at = start; + match self.stack.last_mut() { + Some(frame) => { + if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) { + frame.text.extend_from_slice(content); + } + } + None => return Err(xml(at, "CDATA outside the root element")), + } + } else if rest.starts_with(b" bool { + !(b.is_ascii_whitespace() || matches!(b, b'<' | b'>' | b'/' | b'=' | b'"' | b'\'' | b'&')) + } + + fn name(&mut self) -> Result<(usize, usize), AepError> { + let start = self.pos; + let len = self.rest().iter().position(|b| !Self::is_name_byte(*b)).unwrap_or(self.rest().len()); + if len == 0 { + return Err(xml(start, "a tag or attribute has no name")); + } + self.pos = start.saturating_add(len); + Ok((start, self.pos)) + } + + fn skip_ws(&mut self) { + let n = self.rest().iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(self.rest().len()); + self.pos = self.pos.saturating_add(n); + } + + fn slice(&self, (a, b): (usize, usize)) -> &[u8] { + self.data.get(a..b).unwrap_or(&[]) + } + + fn start_tag(&mut self) -> Result<(), AepError> { + let at = self.pos; + self.pos = self.pos.saturating_add(1); + let name = self.name()?; + let mut attrs = Vec::new(); + let self_closing = loop { + self.skip_ws(); + let rest = self.rest(); + if rest.starts_with(b"/>") { + self.pos = self.pos.saturating_add(2); + break true; + } + if rest.starts_with(b">") { + self.pos = self.pos.saturating_add(1); + break false; + } + if rest.is_empty() { + return Err(xml(at, "a start tag is not closed")); + } + let key = self.name()?; + self.skip_ws(); + if !self.rest().starts_with(b"=") { + return Err(xml(self.pos, "an attribute has no value")); + } + self.pos = self.pos.saturating_add(1); + self.skip_ws(); + let quote = *self.rest().first().ok_or(xml(self.pos, "a start tag is not closed"))?; + if quote != b'"' && quote != b'\'' { + return Err(xml(self.pos, "an attribute value is not quoted")); + } + let vstart = self.pos.saturating_add(1); + let vend = self.find(vstart, &[quote]).ok_or(xml(vstart, "an attribute value is not closed"))?; + let raw = self.data.get(vstart..vend).unwrap_or(&[]); + if raw.contains(&b'<') { + return Err(xml(vstart, "`<` inside an attribute value")); + } + // A value without `&` is its own decoding (most of them, every `bdata` After Effects + // writes): borrow it instead of copying it. + let value = if raw.contains(&b'&') { + let mut value = Vec::new(); + decode_entities(raw, vstart, &mut value)?; + Cow::Owned(value) + } else { + Cow::Borrowed(raw) + }; + self.pos = vend.saturating_add(1); + attrs.push((key, value)); + }; + let kind = self.kind_of(name, at)?; + if kind != Kind::Root { + self.count = self.count.saturating_add(1); + if self.count > self.limits.max_chunks { + return Err(AepError::TooManyChunks); + } + // The root's children are depth 1, like the top-level chunks of an `.aep`. + if self.stack.len() > self.limits.max_depth { + return Err(AepError::TooDeep); + } + } + let mut frame = Frame { kind, at, name, bdata: None, attrs: Vec::new(), text: Vec::new(), children: Vec::new() }; + if matches!(kind, Kind::Chunk(_)) { + if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { + frame.bdata = Some(decode_hex(value, key.1)?); + } + } else if kind == Kind::Alias { + frame.attrs = + attrs.iter().map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())).collect(); + } + self.stack.push(frame); + if self_closing { + self.close()?; + } + Ok(()) + } + + /// Classifies an element by its name and where it is. + fn kind_of(&self, name: (usize, usize), at: usize) -> Result { + let n = self.slice(name); + let parent = match self.stack.last() { + None => { + if self.top.is_some() { + return Err(xml(at, "a second root element")); + } + if n != ROOT { + return Err(xml(at, "the root element is not AfterEffectsProject")); + } + return Ok(Kind::Root); + } + Some(p) => p.kind, + }; + Ok(match parent { + Kind::Skip | Kind::Utf8 | Kind::Xmp | Kind::Alias => Kind::Skip, + Kind::Root | Kind::Chunk(_) => { + if n == STRING { + Kind::Utf8 + } else if n == FILE_REFERENCE { + Kind::Alias + } else if n == XMP && parent == Kind::Root { + Kind::Xmp + } else if let Some(id) = chunk_id(n) { + Kind::Chunk(id) + } else { + Kind::Skip + } + } + }) + } + + fn end_tag(&mut self) -> Result<(), AepError> { + let at = self.pos; + self.pos = self.pos.saturating_add(2); + let name = self.name()?; + self.skip_ws(); + if !self.rest().starts_with(b">") { + return Err(xml(at, "an end tag is not closed")); + } + self.pos = self.pos.saturating_add(1); + let open = self.stack.last().ok_or(xml(at, "an end tag without a start tag"))?; + if self.slice(open.name) != self.slice(name) { + return Err(xml(at, "an end tag does not match its start tag")); + } + self.close() + } + + /// Closes the innermost element and hands its chunk to the parent. + fn close(&mut self) -> Result<(), AepError> { + let frame = self.stack.pop().ok_or(xml(self.pos, "an end tag without a start tag"))?; + let chunk = match frame.kind { + Kind::Root => { + self.top = Some(frame.children); + return Ok(()); + } + Kind::Skip => return Ok(()), + Kind::Xmp => { + if self.trailer.is_none() { + self.trailer = Some(frame.text); + } + return Ok(()); + } + Kind::Utf8 => Chunk::data(*b"Utf8", frame.text), + Kind::Alias => Chunk::data(*b"alas", alias_json(&frame.attrs).into_bytes()), + Kind::Chunk(id) => chunk_of(id, frame)?, + }; + if let Some(parent) = self.stack.last_mut() { + parent.children.push(chunk); + } + Ok(()) + } + + fn text(&mut self) -> Result<(), AepError> { + let start = self.pos; + let len = self.rest().iter().position(|b| *b == b'<').unwrap_or(self.rest().len()); + let end = start.saturating_add(len); + self.pos = end; + let raw = self.data.get(start..end).unwrap_or(&[]); + match self.stack.last_mut() { + Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut frame.text), + Some(_) => Ok(()), + None if raw.iter().all(u8::is_ascii_whitespace) => Ok(()), + None => Err(xml(start, "text outside the root element")), + } + } +} + +/// The chunk of a closed element named by a chunk id. +fn chunk_of(id: [u8; 4], frame: Frame) -> Result, AepError> { + if let Some(bytes) = frame.bdata { + if OPAQUE_LIST_TYPES.contains(&id) { + let pad = if bytes.len() % 2 == 1 { Some(0) } else { None }; + return Ok(Chunk { id: LIST, body: Body::OpaqueList { list_type: id, data: Cow::Owned(bytes) }, pad }); + } + return Ok(Chunk::data(id, bytes)); + } + // Numbers written as text: `0` and `150.000000000`. + if &id == b"numS" || &id == b"ppSn" { + let text = match frame.children.as_slice() { + [only] if only.is(b"Utf8") => only.bytes().unwrap_or(&[]), + _ => return Err(xml(frame.at, "a numS or ppSn element without its number")), + }; + let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); + let body = if &id == b"numS" { + // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. + let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); + let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; + (n as u32).to_be_bytes().to_vec() + } else { + text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes().to_vec() + }; + return Ok(Chunk::data(id, body)); + } + if NESTED_IDS.contains(&id) { + if frame.children.is_empty() { + return Ok(Chunk::data(id, Vec::new())); + } + return Ok(Chunk { id, body: Body::Chunks(frame.children), pad: None }); + } + Ok(Chunk::list(id, frame.children)) +} diff --git a/crates/aep/src/arbitrary.rs b/crates/aep/src/arbitrary.rs index 45768ae44..70627139b 100644 --- a/crates/aep/src/arbitrary.rs +++ b/crates/aep/src/arbitrary.rs @@ -7,9 +7,9 @@ //! Hue/Saturation (444-446) or a Levels value (512-516) changes only bytes of this `aRbp` (and stale //! UI bytes of `pard`); the visible parameters of the same names keep no record. -use crate::Chunk; use crate::bytes::{be_f32, be_i32, be_u16, be_u32}; use crate::effects::Effect; +use crate::index::Node; impl<'f, 'a> Effect<'f, 'a> { /// The arbitrary data stored for the parameter with this match name (`-NNNN`): the @@ -17,13 +17,13 @@ impl<'f, 'a> Effect<'f, 'a> { /// none. pub fn arbitrary_data(&self, match_name: &str) -> Option<&'f [u8]> { let values = self.chunk().child_list(b"tdgp")?; - let kids = values.children(); - let at = kids.iter().position(|c| c.is(b"tdmn") && c.bytes().is_some_and(|b| name_is(b, match_name)))?; - // The value record, then the data list (no match name of its own). - let rest = kids.get(at.checked_add(1)?..)?; - let mut it = rest.iter().take(3); + let mut kids = values.children(); + // Up to the parameter's match name, then the value record, then the data list (no match + // name of its own). + kids.find(|c| c.is(b"tdmn") && c.bytes().is_some_and(|b| name_is(b, match_name)))?; + let mut it = kids.take(3); let _record = it.next().filter(|c| c.is_list(b"tdbs"))?; - it.find(|c| c.is_list(b"aRbs")).and_then(|l| l.child(b"aRbp")).and_then(Chunk::bytes) + it.find(|c| c.is_list(b"aRbs")).and_then(|l| l.child(b"aRbp")).and_then(Node::bytes) } } diff --git a/crates/aep/src/camera.rs b/crates/aep/src/camera.rs index 69cd8c2c8..934f36bd6 100644 --- a/crates/aep/src/camera.rs +++ b/crates/aep/src/camera.rs @@ -16,7 +16,6 @@ //! only when it is not the default 100. use crate::typed::{Layer, PropNode}; -use crate::values::{Tracked, ValueSource, read, read_opt}; /// The Position of a camera or light layer as stored. #[derive(Debug, Clone, Copy, PartialEq)] @@ -28,16 +27,6 @@ pub struct CameraPosition { pub auto_state: bool, } -impl CameraPosition { - /// The position as the batch-3 notes had After Effects report it: in the auto state of a - /// two-node camera (`two_node`) x and y are the composition centre; otherwise the stored - /// value. **Contradicted by 256 and 537 (session S16): After Effects reports and renders the - /// stored value**; use `stored` for what After Effects shows. - pub fn reported(&self, comp_width: u32, comp_height: u32, two_node: bool) -> [f64; 3] { - if self.auto_state && two_node { [f64::from(comp_width) / 2.0, f64::from(comp_height) / 2.0, self.stored[2]] } else { self.stored } - } -} - impl<'f, 'a> Layer<'f, 'a> { /// The Position record of a camera or light layer. pub fn camera_position(&self) -> Option { @@ -49,87 +38,9 @@ impl<'f, 'a> Layer<'f, 'a> { let derived = h.get(76) == Some(&1) && h.get(77) == Some(&1) && position.expression().is_none(); Some(CameraPosition { stored, auto_state: derived }) } - - /// The point of interest of a camera in pixels (its Anchor Point record); `None` when absent. - pub fn camera_point_of_interest(&self) -> Option<[f64; 3]> { - let Some(PropNode::Group(transform)) = self.properties()?.get("ADBE Transform Group") else { return None }; - let tracked = read(&transform, "ADBE Anchor Point", [0.0; 3], 1.0); - matches!(tracked.source, ValueSource::Stored | ValueSource::Keyframed).then_some(tracked.value) - } - - /// A light's intensity in percent; the default 100 when the property is absent. - pub fn light_intensity(&self) -> Option> { - let root = self.properties()?; - let Some(PropNode::Group(options)) = root.get("ADBE Light Options Group") else { return None }; - let t = read(&options, "ADBE Light Intensity", [100.0], 1.0); - Some(Tracked { value: t.value[0], source: t.source }) - } } /// The camera zoom After Effects uses when `ADBE Camera Zoom` is absent: 2666.67 px for the 50 mm /// default camera in the 1920 px wide corpus composition. Whether it follows other composition /// widths was not sampled. pub const DEFAULT_CAMERA_ZOOM: f64 = 2_666.666_666_666_666_5; - -impl<'f, 'a> Layer<'f, 'a> { - fn camera_options(&self) -> Option> { - match self.properties()?.get("ADBE Camera Options Group") { - Some(PropNode::Group(g)) => Some(g), - _ => None, - } - } - - fn light_options(&self) -> Option> { - match self.properties()?.get("ADBE Light Options Group") { - Some(PropNode::Group(g)) => Some(g), - _ => None, - } - } - - /// A camera's zoom in pixels (`ADBE Camera Options Group/ADBE Camera Zoom`); absent = the - /// default, [`DEFAULT_CAMERA_ZOOM`] (341: 2000 is stored). The auto Position keeps `-2666.67` and - /// is not recomputed from the zoom. - pub fn camera_zoom(&self) -> Option> { - let t = read(&self.camera_options()?, "ADBE Camera Zoom", [DEFAULT_CAMERA_ZOOM], 1.0); - Some(Tracked { value: t.value[0], source: t.source }) - } - - /// The depth of field switch (`ADBE Camera Depth of Field`, a checkbox; off by default, 342). - pub fn camera_depth_of_field(&self) -> Option> { - let t = read(&self.camera_options()?, "ADBE Camera Depth of Field", [0.0], 1.0); - Some(Tracked { value: t.value[0] != 0.0, source: t.source }) - } - - /// A camera's focus distance in pixels (`ADBE Camera Focus Distance`); `None` while absent (its - /// default is not known). - pub fn camera_focus_distance(&self) -> Option> { - let t = read_opt::<1>(&self.camera_options()?, "ADBE Camera Focus Distance", 1.0)?; - Some(Tracked { value: t.value[0], source: t.source }) - } - - /// A camera's aperture (`ADBE Camera Aperture`); `None` while absent (its default is not known). - pub fn camera_aperture(&self) -> Option> { - let t = read_opt::<1>(&self.camera_options()?, "ADBE Camera Aperture", 1.0)?; - Some(Tracked { value: t.value[0], source: t.source }) - } - - /// A light's colour as `[A, R, G, B]` fractions (`ADBE Light Options Group/ADBE Light Color`, - /// stored as doubles 0..255); white when absent (343 stores red). - pub fn light_color(&self) -> Option> { - Some(read(&self.light_options()?, "ADBE Light Color", [1.0; 4], 1.0 / 255.0)) - } - - /// A spot light's cone angle in degrees (`ADBE Light Cone Angle`); 90 when absent (344 stores 60). - /// A point light stores 90 with `tdsb` 3. - pub fn light_cone_angle(&self) -> Option> { - let t = read(&self.light_options()?, "ADBE Light Cone Angle", [90.0], 1.0); - Some(Tracked { value: t.value[0], source: t.source }) - } - - /// A spot light's cone feather in percent (`ADBE Light Cone Feather 2`); 50 when absent (345 - /// stores 30). - pub fn light_cone_feather(&self) -> Option> { - let t = read(&self.light_options()?, "ADBE Light Cone Feather 2", [50.0], 1.0); - Some(Tracked { value: t.value[0], source: t.source }) - } -} diff --git a/crates/aep/src/effects.rs b/crates/aep/src/effects.rs index 25b7051ab..65f3c6125 100644 --- a/crates/aep/src/effects.rs +++ b/crates/aep/src/effects.rs @@ -20,8 +20,8 @@ use std::collections::{HashMap, HashSet}; -use crate::Chunk; use crate::bytes::{array, be_f32, be_f64, be_i32, be_u16, be_u32, cstr, text, until_nul}; +use crate::index::Node; use crate::typed::{KeyList, Layer, Project, PropGroup, PropNode, Property}; /// The parameter type, the `u32` at byte 12 of `pard`. The numbering matches the plug-in @@ -132,7 +132,7 @@ pub enum LayerRef { #[derive(Debug, Clone)] pub struct Effect<'f, 'a> { match_name: String, - chunk: &'f Chunk<'a>, + chunk: Node<'f, 'a>, } /// Where the parameter definitions of an effect instance come from. @@ -178,13 +178,13 @@ impl<'f, 'a> Effect<'f, 'a> { } /// The underlying `LIST sspc` chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } /// The instance name shown in the effect controls (`fnam`). pub fn name(&self) -> Option { - self.chunk.child(b"fnam")?.children().iter().find(|c| c.is(b"Utf8"))?.bytes().map(text) + self.chunk.child(b"fnam")?.child(b"Utf8")?.bytes().map(text) } /// The name the user gave the instance: the `tdsn` of the instance's value group when it is @@ -192,7 +192,7 @@ impl<'f, 'a> Effect<'f, 'a> { /// `None` while the instance shows the effect's name. pub fn user_name(&self) -> Option { let values = self.chunk.child_list(b"tdgp")?; - let name = values.child(b"tdsn")?.children().iter().find(|c| c.is(b"Utf8"))?.bytes().map(text)?; + let name = values.child(b"tdsn")?.child(b"Utf8")?.bytes().map(text)?; (name != "-_0_/-" && !name.is_empty()).then_some(name) } @@ -250,7 +250,7 @@ impl<'f, 'a> Effect<'f, 'a> { } /// The parameters described by `part` (a `LIST parT`) with the values of this instance. - fn params_from(&self, part: &'f Chunk<'a>, borrowed: bool) -> Vec> { + fn params_from(&self, part: Node<'f, 'a>, borrowed: bool) -> Vec> { let mut out: Vec> = Vec::new(); // The stored values by match name: the first entry of a name, as `PropGroup::get` finds it // (a group of that name means no stored value). Indexed once: a lookup per parameter @@ -271,8 +271,8 @@ impl<'f, 'a> Effect<'f, 'a> { out.push(EffectParam { index: out.len(), match_name, - kind: ParamKind::from_u32(be_u32(pard, 12).unwrap_or(u32::MAX)), - name: cstr(pard, 16, 32).unwrap_or_default(), + kind: Pard(pard).kind(), + name: Pard(pard).name().unwrap_or_default(), items: None, borrowed_definition: borrowed, pard, @@ -280,7 +280,7 @@ impl<'f, 'a> Effect<'f, 'a> { }); } else if c.is(b"pdnm") && let Some(last) = out.last_mut() - && let Some(u) = c.children().iter().find(|u| u.is(b"Utf8")) + && let Some(u) = c.child(b"Utf8") && let Some(b) = u.bytes() // An empty `pdnm` names nothing (some writers store one: the effect // supplies its items). @@ -293,8 +293,9 @@ impl<'f, 'a> Effect<'f, 'a> { } } -fn has_pard(part: &Chunk<'_>) -> bool { - part.children().iter().any(|c| c.is(b"pard")) +/// True when a `LIST parT` holds parameter definitions (a `pard`). +fn has_pard(part: Node<'_, '_>) -> bool { + part.children().any(|c| c.is(b"pard")) } impl<'f, 'a> Project<'f, 'a> { @@ -302,18 +303,18 @@ impl<'f, 'a> Project<'f, 'a> { /// name and the `LIST parT` of the copied instance, in file order (the stack order of the /// types, 365/366). The `EfDC` count before them is little-endian and is not needed to read /// them. A type whose copy has no definitions is left out. - pub fn effect_definitions(&self) -> Vec<(String, &'f Chunk<'a>)> { - let mut out: Vec<(String, &'f Chunk<'a>)> = Vec::new(); + pub fn effect_definitions(&self) -> Vec<(String, Node<'f, 'a>)> { + let mut out: Vec<(String, Node<'f, 'a>)> = Vec::new(); let Some(defs) = self.effect_defs else { return out }; let mut seen: HashSet = HashSet::new(); - for df in defs.children().iter().filter(|c| c.is_list(b"EfDf")) { + for df in defs.children().filter(|c| c.is_list(b"EfDf")) { let mut name: Option = None; for c in df.children() { if c.is(b"tdmn") { name = c.bytes().map(|b| text(until_nul(b))); } else if c.is_list(b"sspc") && let Some(n) = name.take() - && let Some(part) = c.child_list(b"parT").filter(|p| has_pard(p)) + && let Some(part) = c.child_list(b"parT").filter(|p| has_pard(*p)) && seen.insert(n.clone()) { out.push((n, part)); @@ -328,8 +329,8 @@ impl<'f, 'a> Project<'f, 'a> { /// For a type without a project-level copy it also keeps the own `parT` of the first instance /// in the file (items, layers and effects in file order) that has one. pub fn effect_definition_index(&self) -> EffectDefinitions<'f, 'a> { - let by_name: HashMap> = self.effect_definitions().into_iter().collect(); - let mut instances: HashMap> = HashMap::new(); + let by_name: HashMap> = self.effect_definitions().into_iter().collect(); + let mut instances: HashMap> = HashMap::new(); for item in self.all_items() { let Some(comp) = item.comp() else { continue }; for layer in comp.layers() { @@ -337,7 +338,7 @@ impl<'f, 'a> Project<'f, 'a> { if by_name.contains_key(&fx.match_name) || instances.contains_key(&fx.match_name) { continue; } - if let Some(part) = fx.chunk.child_list(b"parT").filter(|p| has_pard(p)) { + if let Some(part) = fx.chunk.child_list(b"parT").filter(|p| has_pard(*p)) { instances.insert(fx.match_name, part); } } @@ -363,9 +364,9 @@ impl<'f, 'a> Project<'f, 'a> { #[derive(Debug, Clone, Default)] pub struct EffectDefinitions<'f, 'a> { /// The project-level copies (`EfdG`). - by_name: HashMap>, + by_name: HashMap>, /// For a type without a project-level copy: the own `parT` of the first instance that has one. - instances: HashMap>, + instances: HashMap>, } impl<'f, 'a> EffectDefinitions<'f, 'a> { @@ -392,7 +393,7 @@ impl<'f, 'a> EffectDefinitions<'f, 'a> { return effect.params(); } match self.by_name.get(effect.match_name()).or_else(|| self.instances.get(effect.match_name())) { - Some(part) => effect.params_from(part, true), + Some(part) => effect.params_from(*part, true), None => Vec::new(), } } @@ -484,26 +485,7 @@ impl<'f, 'a> EffectParam<'f, 'a> { pub fn pard_default(&self) -> Option { match self.kind { ParamKind::Popup if self.borrowed_definition => None, - ParamKind::FloatSlider => be_f64(self.pard, 56).map(ParamValue::Number), - ParamKind::FixedSlider | ParamKind::Angle => be_i32(self.pard, 56).map(|v| ParamValue::Number(f64::from(v) / 65536.0)), - ParamKind::IntSlider => be_i32(self.pard, 56).map(|v| ParamValue::Number(f64::from(v))), - ParamKind::Checkbox => be_u32(self.pard, 56).map(|v| ParamValue::Bool(v != 0)), - ParamKind::Popup => be_u32(self.pard, 56).map(ParamValue::Index), - ParamKind::Point => { - let p = [f64::from(be_i32(self.pard, 56)?) / 65536.0, f64::from(be_i32(self.pard, 60)?) / 65536.0]; - // A fresh instance stores fractions of the layer (0.5, 0.5); After Effects' save of - // a project it opened stores percent (50, 50: the re-saves of read-back tests e1 and - // e2, where Gradient Ramp's Start and End and every other point default came back - // as 50 / 0 and 50 / 100). Point - // defaults lie inside the layer, so a component beyond 1 tells percent. - let percent = p.iter().any(|c| c.abs() > 1.0 + 1e-9); - Some(ParamValue::Point(if percent { p.map(|c| c / 100.0) } else { p })) - } - ParamKind::Color => { - let [a, r, g, b] = array::<4>(self.pard, 56)?.map(|c| f64::from(c) / 255.0); - Some(ParamValue::Argb([a, r, g, b])) - } - _ => None, + kind => Pard(self.pard).default(kind), } } @@ -557,22 +539,14 @@ impl<'f, 'a> EffectParam<'f, 'a> { /// slider differs per parameter (Amount 37.5 % is stored 37.5, Blend 25 % is stored 0.25), so /// this is what tells a reader the scale. `None` for other types. pub fn valid_max(&self) -> Option { - match self.kind { - ParamKind::FixedSlider => be_i32(self.pard, 128).map(|v| f64::from(v) / 65536.0), - ParamKind::FloatSlider => be_f32(self.pard, 108).map(f64::from), - ParamKind::IntSlider => be_i32(self.pard, 128).map(f64::from), - _ => None, - } + Pard(self.pard).valid_max(self.kind) } /// The smallest valid value of a float slider, the `f32` at byte 104 of `pard` (Exposure /// -100, Offset -2, Gamma Correction 0.1: 389). `None` for other types (a fixed slider's /// minimum is not decoded). pub fn valid_min(&self) -> Option { - match self.kind { - ParamKind::FloatSlider => be_f32(self.pard, 104).map(f64::from), - _ => None, - } + Pard(self.pard).valid_min(self.kind) } /// The range of a float slider's slider (what the control's drag covers, inside the valid @@ -581,7 +555,7 @@ impl<'f, 'a> EffectParam<'f, 'a> { /// for other types. pub fn slider_range(&self) -> Option<(f64, f64)> { match self.kind { - ParamKind::FloatSlider => Some((f64::from(be_f32(self.pard, 112)?), f64::from(be_f32(self.pard, 116)?))), + ParamKind::FloatSlider => Pard(self.pard).slider_range(self.kind), _ => None, } } @@ -591,7 +565,7 @@ impl<'f, 'a> EffectParam<'f, 'a> { if self.kind != ParamKind::Popup { return None; } - be_u16(self.pard, 60) + Pard(self.pard).popup_item_count() } /// For a popup: the selected item index (1-based): the stored selection, else the default. @@ -619,6 +593,93 @@ impl<'f, 'a> EffectParam<'f, 'a> { } } +/// A parameter definition (`pard`, 148 bytes; aep-format.md 3.7): the one decoder of its fields. +/// The import reads them through [`EffectParam`]; the export writes them from its effect table and +/// its tests read them back through this. +#[derive(Clone, Copy, Debug)] +pub struct Pard<'f>(pub &'f [u8]); + +impl Pard<'_> { + /// The type code, the `u32` at byte 12. + pub fn code(self) -> Option { + be_u32(self.0, 12) + } + + /// The parameter type (an unreadable code is [`ParamKind::Other`]). + pub fn kind(self) -> ParamKind { + ParamKind::from_u32(self.code().unwrap_or(u32::MAX)) + } + + /// The parameter name at byte 16 (32 bytes). + pub fn name(self) -> Option { + cstr(self.0, 16, 32) + } + + /// The default at byte 56 as a parameter of type `kind` reads it (see + /// [`EffectParam::pard_default`]). + pub fn default(self, kind: ParamKind) -> Option { + let p = self.0; + match kind { + ParamKind::FloatSlider => be_f64(p, 56).map(ParamValue::Number), + ParamKind::FixedSlider | ParamKind::Angle => be_i32(p, 56).map(|v| ParamValue::Number(f64::from(v) / 65536.0)), + ParamKind::IntSlider => be_i32(p, 56).map(|v| ParamValue::Number(f64::from(v))), + ParamKind::Checkbox => be_u32(p, 56).map(|v| ParamValue::Bool(v != 0)), + ParamKind::Popup => be_u32(p, 56).map(ParamValue::Index), + ParamKind::Point => { + let pt = [f64::from(be_i32(p, 56)?) / 65536.0, f64::from(be_i32(p, 60)?) / 65536.0]; + // A fresh instance stores fractions of the layer (0.5, 0.5); After Effects' save of + // a project it opened stores percent (50, 50: the re-saves of read-back tests e1 and + // e2, where Gradient Ramp's Start and End and every other point default came back + // as 50 / 0 and 50 / 100). Point + // defaults lie inside the layer, so a component beyond 1 tells percent. + let percent = pt.iter().any(|c| c.abs() > 1.0 + 1e-9); + Some(ParamValue::Point(if percent { pt.map(|c| c / 100.0) } else { pt })) + } + ParamKind::Color => { + let [a, r, g, b] = array::<4>(p, 56)?.map(|c| f64::from(c) / 255.0); + Some(ParamValue::Argb([a, r, g, b])) + } + _ => None, + } + } + + /// The valid maximum of a slider (see [`EffectParam::valid_max`]). + pub fn valid_max(self, kind: ParamKind) -> Option { + match kind { + ParamKind::FixedSlider => be_i32(self.0, 128).map(|v| f64::from(v) / 65536.0), + ParamKind::FloatSlider => be_f32(self.0, 108).map(f64::from), + ParamKind::IntSlider => be_i32(self.0, 128).map(f64::from), + _ => None, + } + } + + /// The valid minimum of a float slider (see [`EffectParam::valid_min`]). + pub fn valid_min(self, kind: ParamKind) -> Option { + match kind { + ParamKind::FloatSlider => be_f32(self.0, 104).map(f64::from), + _ => None, + } + } + + /// A slider's range, the one its value records repeat as `tdum` / `tduM`: a float slider's + /// `f32` pair at 112 / 116, a fixed slider's 16.16 pair and an integer slider's `i32` pair at + /// 132 / 136. + pub fn slider_range(self, kind: ParamKind) -> Option<(f64, f64)> { + let p = self.0; + match kind { + ParamKind::FloatSlider => Some((f64::from(be_f32(p, 112)?), f64::from(be_f32(p, 116)?))), + ParamKind::FixedSlider => Some((f64::from(be_i32(p, 132)?) / 65536.0, f64::from(be_i32(p, 136)?) / 65536.0)), + ParamKind::IntSlider => Some((f64::from(be_i32(p, 132)?), f64::from(be_i32(p, 136)?))), + _ => None, + } + } + + /// A popup's item count, the `u16` at byte 60. + pub fn popup_item_count(self) -> Option { + be_u16(self.0, 60) + } +} + impl<'f, 'a> Layer<'f, 'a> { /// The effects on the layer, in stack order (`ADBE Effect Parade`). pub fn effects(&self) -> Vec> { @@ -638,6 +699,30 @@ impl<'f, 'a> Layer<'f, 'a> { #[cfg(test)] mod tests { use super::*; + use crate::Chunk; + + #[test] + fn a_parameter_definition_reads_its_fields_and_nothing_from_a_cut_record() { + let mut b = vec![0u8; 148]; + b[12..16].copy_from_slice(&7u32.to_be_bytes()); + b[16..22].copy_from_slice(b"Amount"); + b[56..64].copy_from_slice(&2.5f64.to_be_bytes()); + let p = Pard(&b); + assert_eq!((p.code(), p.name().as_deref()), (Some(7), Some("Amount"))); + assert_eq!(p.default(ParamKind::FloatSlider), Some(ParamValue::Number(2.5))); + // The same bytes as a checkbox and as a popup: the `u32` at 56, and the `u16` at 60. + b[56..60].copy_from_slice(&1u32.to_be_bytes()); + b[60..62].copy_from_slice(&3u16.to_be_bytes()); + let p = Pard(&b); + assert_eq!(p.default(ParamKind::Checkbox), Some(ParamValue::Bool(true))); + assert_eq!((p.default(ParamKind::Popup), p.popup_item_count()), (Some(ParamValue::Index(1)), Some(3))); + assert_eq!(p.default(ParamKind::IntSlider), Some(ParamValue::Number(1.0))); + // A record cut before a field has no value for it, and an unreadable code is `Other`. + let cut = Pard(&b[..12]); + assert_eq!((cut.code(), cut.kind(), cut.name(), cut.popup_item_count()), (None, ParamKind::Other(u32::MAX), None, None)); + assert_eq!(cut.default(ParamKind::FloatSlider), None); + assert_eq!(Pard(&b[..58]).default(ParamKind::Checkbox), None); + } fn tdmn(name: &str) -> Chunk<'static> { let mut b = name.as_bytes().to_vec(); @@ -670,11 +755,11 @@ mod tests { ("A".to_string(), Chunk::list(*b"tdbs", vec![Chunk::data(*b"cdat", vec![0u8; 8])])), ]; let chunk = instance(&names, &stored); - let fx = Effect { match_name: "X".into(), chunk: &chunk }; + let fx = Effect { match_name: "X".into(), chunk: Node::from(&chunk) }; let params = fx.params(); assert_eq!(params.iter().map(|p| p.match_name.as_str()).collect::>(), ["A", "B", "C"]); let first = params.first().and_then(|p| p.stored).expect("A stored"); - assert!(first.chunk.children().is_empty(), "the first A (the second has a cdat)"); + assert!(first.chunk.children().next().is_none(), "the first A (the second has a cdat)"); assert!(params.get(1).is_some_and(|p| p.stored.is_none()), "a group of that name is no stored value"); assert!(params.get(2).is_some_and(|p| p.stored.is_none())); } @@ -687,7 +772,7 @@ mod tests { let names: Vec = (0..n).map(|i| format!("P{i}")).collect(); let stored: Vec<(String, Chunk<'static>)> = names.iter().map(|m| (m.clone(), tdbs())).collect(); let chunk = instance(&names, &stored); - let fx = Effect { match_name: "X".into(), chunk: &chunk }; + let fx = Effect { match_name: "X".into(), chunk: Node::from(&chunk) }; let params = fx.params(); assert_eq!(params.len(), n); assert!(params.iter().all(|p| p.stored.is_some())); @@ -707,19 +792,19 @@ mod tests { } let efdg = Chunk::list(*b"EfdG", defs); let fold = Chunk::list(*b"Fold", Vec::new()); - let project = Project { fold: &fold, effect_defs: Some(&efdg) }; + let project = Project { fold: Node::from(&fold), effect_defs: Some(Node::from(&efdg)) }; let all = project.effect_definitions(); assert_eq!(all.len(), n); let index = project.effect_definition_index(); let bare = Chunk::list(*b"sspc", vec![Chunk::list(*b"parT", Vec::new())]); for i in (0..n).step_by(50) { - let fx = Effect { match_name: format!("FX{i}"), chunk: &bare }; + let fx = Effect { match_name: format!("FX{i}"), chunk: Node::from(&bare) }; assert_eq!(index.source(&fx), DefinitionSource::Project); let params = index.params(&fx); assert_eq!(params.iter().map(|p| p.match_name.as_str()).collect::>(), ["R0"], "the first copy's definitions"); assert!(params.iter().all(|p| p.borrowed_definition)); } - let unknown = Effect { match_name: "nope".into(), chunk: &bare }; + let unknown = Effect { match_name: "nope".into(), chunk: Node::from(&bare) }; assert_eq!(index.source(&unknown), DefinitionSource::Missing); assert!(index.params(&unknown).is_empty()); assert_eq!(project.definition_source(&unknown), DefinitionSource::Missing); diff --git a/crates/aep/src/footage.rs b/crates/aep/src/footage.rs index 58a653a4a..e8c89b924 100644 --- a/crates/aep/src/footage.rs +++ b/crates/aep/src/footage.rs @@ -2,8 +2,8 @@ //! of a layer's source. use crate::bytes::{be_f32, be_f64, be_i32, be_u32, cstr, le_u32, text, until_nul}; -use crate::chunk::Chunk; use crate::header::Rational; +use crate::index::Node; use crate::typed::{Item, ItemKind, Layer, Project}; /// The footage data of an item (`LIST Pin ` with `sspc`, `opti` and, for files, `Als2/alas`). @@ -101,21 +101,6 @@ impl PsdLayer { } impl Footage { - /// The number of frames of an image sequence (`duration * native_frame_rate`: 3/30 s at 30 fps is - /// 3); `None` for anything else. - pub fn sequence_frame_count(&self) -> Option { - if !self.is_sequence { - return None; - } - let d = self.duration?; - let frames = i128::from(d.num).checked_mul(i128::from(self.native_frame_rate))?; - let den = i128::from(d.den); - if den <= 0 || frames % den != 0 { - return None; - } - u32::try_from(frames / den).ok() - } - /// The solid's colour as fractions R, G, B. pub fn solid_rgb(&self) -> Option<[f32; 3]> { let [_, r, g, b] = self.solid_argb?; @@ -269,14 +254,14 @@ impl SequenceInfo { /// is unreadable (empty). A name that is not a plain file name (holding `/`, `\`, `:` or a control /// character such as NUL, or being `.` or `..`) makes the whole list unreadable (empty): the names /// are joined to the folder. -fn sequence_file_list(list: &Chunk<'_>) -> Vec { +fn sequence_file_list(list: Node<'_, '_>) -> Vec { // After Effects writes the count first (the one sample); a list without a readable count is // not read rather than guessed. let Some(count) = list.child(b"StVS").and_then(|c| c.bytes()).and_then(|b| le_u32(b, 0)).and_then(|n| usize::try_from(n).ok()) else { return Vec::new(); }; let names: Vec = - list.children().iter().filter(|c| c.is(b"Utf8")).filter_map(|c| c.bytes()).take(count).map(text).filter(|n| !n.is_empty()).collect(); + list.children().filter(|c| c.is(b"Utf8")).filter_map(Node::bytes).take(count).map(text).filter(|n| !n.is_empty()).collect(); if names.iter().any(|n| n.contains(|c: char| matches!(c, '/' | '\\' | ':') || c.is_control()) || n == "." || n == "..") { return Vec::new(); } @@ -308,9 +293,8 @@ impl<'f, 'a> Item<'f, 'a> { } let pin = self.chunk.child_list(b"Pin ")?; let sspc = pin.child(b"sspc")?.bytes()?; - let kids = pin.children(); - let after = kids.iter().position(|c| c.is_list(b"Als2"))?; - let naming = || kids.iter().skip(after.saturating_add(1)).take_while(|c| !c.is(b"opti")); + let after = pin.children().position(|c| c.is_list(b"Als2"))?; + let naming = || pin.children().skip(after.saturating_add(1)).take_while(|c| !c.is(b"opti")); let (start, end, digits) = (be_u32(sspc, 172)?, be_u32(sspc, 176)?, be_u32(sspc, 180)?); // Force alphabetical order: the file list replaces the numbering. if let Some(list) = naming().find(|c| c.is_list(b"StVc")) { @@ -320,7 +304,7 @@ impl<'f, 'a> Item<'f, 'a> { } return Some(SequenceInfo { prefix: String::new(), suffix: String::new(), start, end, digits, files }); } - let names: Vec = naming().filter(|c| c.is(b"Utf8")).filter_map(|c| c.bytes()).map(text).take(2).collect(); + let names: Vec = naming().filter(|c| c.is(b"Utf8")).filter_map(Node::bytes).map(text).take(2).collect(); let (prefix, suffix) = match names.as_slice() { [prefix, suffix] => (prefix.clone(), suffix.clone()), // An empty prefix is not stored (`0001.png` has only `.png`). @@ -350,12 +334,6 @@ impl<'f, 'a> Item<'f, 'a> { self.chunk.child(b"idta")?.bytes()?.get(58).copied() } - /// The ids of the compositions this item uses as precomp layers: the little-endian `u32` of - /// each `idpi` chunk. - pub fn used_item_ids(&self) -> Vec { - self.chunk.children().iter().filter(|c| c.is(b"idpi")).filter_map(|c| le_u32(c.bytes()?, 0)).collect() - } - /// The footage data of a footage item. pub fn footage(&self) -> Option { if self.kind()? != ItemKind::Footage { @@ -405,11 +383,6 @@ impl<'f, 'a> Project<'f, 'a> { self.item_by_id(layer.header()?.source_id?) } - /// The name a layer shows: its own name, or its source's name when it has none. - pub fn layer_display_name(&self, layer: &Layer<'f, 'a>) -> Option { - layer.name().or_else(|| self.layer_source(layer)?.display_name()) - } - /// The pixel size of a layer's source: a footage item's width and height, or a precomp's /// composition size. pub fn layer_source_size(&self, layer: &Layer<'f, 'a>) -> Option<(u32, u32)> { diff --git a/crates/aep/src/header.rs b/crates/aep/src/header.rs index 8593a5633..ac869095f 100644 --- a/crates/aep/src/header.rs +++ b/crates/aep/src/header.rs @@ -237,12 +237,6 @@ impl LayerHeader { self.flag_bytes.get(byte).is_some_and(|b| b & mask != 0) } - /// Byte 37 bit `0x01`: the layer has a name set by the user (clear on a default-named camera or - /// light and on a precomp layer, whose name is the source's). - pub fn name_is_user_set(&self) -> bool { - self.flag(0, 0x01) - } - /// Byte 37 bit `0x02`: guide layer. pub fn is_guide(&self) -> bool { self.flag(0, 0x02) @@ -333,17 +327,6 @@ impl LayerHeader { Rational::new(i64::from(self.stretch), i64::from(self.stretch_den)) } - /// The time stretch in percent (`stretch / stretch_den * 100`); a zero denominator reads as 1. - pub fn stretch_percent(&self) -> f64 { - let den = if self.stretch_den == 0 { 1.0 } else { f64::from(self.stretch_den) }; - f64::from(self.stretch) / den * 100.0 - } - - /// The start time in seconds, `None` for a zero denominator. - pub fn start_seconds(&self) -> Option { - self.start.to_f64() - } - /// The absolute in point, `start + in * stretch`, exact and reduced. pub fn in_point(&self) -> Option { self.start.plus_scaled(&self.in_relative, &self.stretch_ratio()?) @@ -355,16 +338,6 @@ impl LayerHeader { pub fn out_point(&self) -> Option { self.start.plus_scaled(&self.out_relative, &self.stretch_ratio()?) } - - /// The absolute in point in seconds. - pub fn in_point_seconds(&self) -> Option { - self.in_point()?.to_f64() - } - - /// The absolute out point in seconds. - pub fn out_point_seconds(&self) -> Option { - self.out_point()?.to_f64() - } } impl<'f, 'a> Layer<'f, 'a> { @@ -464,64 +437,10 @@ impl CompHeader { self.time_base.frame_rate() } - /// The frame rate from the 16.16 fixed-point field (25 is `0x0019_0000`). - pub fn frame_rate_from_fixed(&self) -> f64 { - f64::from(self.frame_rate_fixed) / 65536.0 - } - /// The duration in seconds. pub fn duration_seconds(&self) -> Option { self.time_base.seconds(i32::try_from(self.duration_units).ok()?) } - - /// The work area start in seconds. - pub fn work_area_start_seconds(&self) -> Option { - self.time_base.seconds(i32::try_from(self.work_area_start_units).ok()?) - } - - /// The work area end in seconds; the composition duration when the work area is the whole - /// composition. - pub fn work_area_end_seconds(&self) -> Option { - match self.work_area_end_units { - Some(end) => self.time_base.seconds(i32::try_from(end).ok()?), - None => self.duration_seconds(), - } - } - - /// The background colour as fractions 0..1 (`byte / 255`). - pub fn background_rgb(&self) -> [f64; 3] { - self.background.map(|c| f64::from(c) / 255.0) - } - - /// The pixel aspect ratio as a number. - pub fn pixel_aspect_ratio(&self) -> Option { - self.pixel_aspect.to_f64() - } - - /// The display start time in seconds (the start timecode), `None` when absent or the - /// denominator is zero. - pub fn display_start_seconds(&self) -> Option { - self.display_start?.to_f64() - } - - /// The display start as a frame number (`display start * frame rate`, rounded); 100 at 25 fps - /// for a display start of 4 s. - pub fn display_start_frame(&self) -> Option { - let rate = self.frame_rate()?; - Some((self.display_start_seconds()? * rate).round() as i64) - } - - /// The frame rate as an exact fraction `timescale / frame_duration`, as typed: 29.97 fps is - /// `23976 / 800` (not `30000 / 1001`), 23.976 fps is `23976 / 1000`. - pub fn frame_rate_exact(&self) -> Option { - Rational::new(i64::from(self.time_base.timescale), i64::from(self.time_base.frame_duration)) - } - - /// The duration in whole frames (`duration / frame_duration`). After Effects snaps a duration - /// to a whole number of frames: 5 s at 29.97 fps becomes 150 frames (5.005 s). - pub fn duration_frames(&self) -> Option { - self.duration_units.checked_div(self.time_base.frame_duration) - } } impl<'f, 'a> Comp<'f, 'a> { diff --git a/crates/aep/src/index.rs b/crates/aep/src/index.rs new file mode 100644 index 000000000..76d5430da --- /dev/null +++ b/crates/aep/src/index.rs @@ -0,0 +1,1026 @@ +//! A read-only, flat index of the chunk tree for readers that only look (the importer). +//! +//! [`TreeIndex`] holds every chunk of a file in one `Vec` in depth-first order (a chunk, then its +//! whole subtree, then its next sibling). Each entry keeps its id, list type, pad byte, the bytes of +//! its body (borrowed from the input) and the index one past its subtree, so: +//! - a chunk's subtree is the index range `at + 1 .. end`, +//! - its direct children are found by stepping from `at + 1` to each child's `end`, +//! - the whole tree is one array, grown a few times while it is built and freed at once; it never +//! holds more slots than the input has room for chunk headers or the chunk limit allows. +//! +//! [`crate::parse`] builds the owned [`Chunk`] tree instead (one `Vec` per list), which +//! the exporter and editors need. [`TreeIndex::to_file`] and [`Node::to_chunk`] convert the index +//! into that tree where an owned one is needed. +//! +//! [`TreeIndex::parse_with_limits`] walks the input exactly as the [`Chunk`] parser does: the same +//! chunks are counted against [`Limits::max_chunks`] in the same order, the same lists are kept +//! opaque at [`Limits::max_depth`] or when damaged, and the same errors come back. A test compares +//! the two on the corpus and on generated and damaged trees. Two errors are its own, and both are +//! stricter than the [`Chunk`] parser (which would abort or could not address the tree): +//! [`AepError::TooLarge`] when the array cannot grow (a failed `try_reserve`), and +//! [`AepError::TooManyChunks`] for a tree of more than `u32::MAX` chunks. +//! +//! An `.aepx` is indexed by its own reader (`container/aepx.rs`), which decodes every body into +//! one buffer and fills the entries as it reads; the index then borrows that buffer +//! (`TreeIndex::from_drafts`). It gives the tree [`crate::read_aepx`] gives. +//! +//! [`Node`] is the handle the typed view ([`crate::Project`] and the types below it) +//! reads through: a chunk of either tree. The view works the same on both. + +use std::borrow::Cow; +use std::fmt; + +use crate::bytes::be_u32; +use crate::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk}; +use crate::error::AepError; +use crate::read::{Limits, container_end, id4}; + +/// What an entry's body is (the [`Body`] variants). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Kind { + Data, + /// [`Body::Chunks`]. + Nested, + List, + OpaqueList, +} + +/// One chunk of a [`TreeIndex`]. +#[derive(Debug, Clone, Copy)] +struct Entry<'a> { + /// The body bytes of a data chunk, or the bytes after the list type of an opaque list; empty + /// for a list or nested chunk (their content is their children). + data: &'a [u8], + id: [u8; 4], + /// The list type of a `LIST` (parsed or opaque); zero otherwise. + list_type: [u8; 4], + /// One past the last entry of this chunk's subtree. + end: u32, + kind: Kind, + pad: Option, +} + +impl<'a> Entry<'a> { + /// An entry for a chunk whose body is not read yet. + fn placeholder(id: [u8; 4]) -> Self { + Self { data: &[], id, list_type: [0; 4], end: 0, kind: Kind::Data, pad: None } + } +} + +/// An entry of an index whose bytes are still being written (the `.aepx` reader decodes into a +/// buffer that grows, so it keeps positions, not slices): the body is `start..start + len` of +/// that buffer. The fields are those of [`Entry`]; [`TreeIndex::from_drafts`] turns the list +/// into an index once the buffer is final. +#[derive(Debug, Clone, Copy)] +pub struct Draft { + pub(crate) start: usize, + pub(crate) len: usize, + pub(crate) id: [u8; 4], + pub(crate) list_type: [u8; 4], + pub(crate) end: u32, + pub(crate) kind: Kind, + pub(crate) pad: Option, +} + +impl Draft { + /// A data chunk with no body yet. + pub(crate) fn placeholder(id: [u8; 4]) -> Self { + Self { start: 0, len: 0, id, list_type: [0; 4], end: 0, kind: Kind::Data, pad: None } + } +} + +/// The chunk tree of a file as one flat, read-only array (see the module documentation). +#[derive(Clone)] +pub struct TreeIndex<'a> { + nodes: Vec>, + trailer: &'a [u8], +} + +impl fmt::Debug for TreeIndex<'_> { + /// The sizes only: the chunk count and the trailer length. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TreeIndex").field("chunks", &self.nodes.len()).field("trailer", &self.trailer.len()).finish() + } +} + +/// An index that does not fit a `u32` (more than 4 billion chunks) is refused as too many chunks. +fn index_u32(at: usize) -> Result { + u32::try_from(at).map_err(|_| AepError::TooManyChunks) +} + +impl<'a> TreeIndex<'a> { + /// Indexes an `.aep` with the default [`Limits`]. + /// + /// # Errors + /// The errors of [`crate::parse`], for the same inputs. + pub fn parse(data: &'a [u8]) -> Result { + Self::parse_with_limits(data, Limits::default()) + } + + /// Indexes an `.aep` with explicit [`Limits`]. + /// + /// # Errors + /// The errors of [`crate::parse_with_limits`], for the same inputs and limits; also + /// [`AepError::TooManyChunks`] for a tree of more than `u32::MAX` chunks and + /// [`AepError::TooLarge`] when the array cannot be allocated. + pub fn parse_with_limits(data: &'a [u8], limits: Limits) -> Result { + let end = container_end(data)?; + // Every chunk header takes 8 bytes of its own and is counted once, so the tree never has + // more chunks than this. + let bound = (end.saturating_sub(12) / 8).min(limits.max_chunks); + let mut builder = Builder { data, limits, count: 0, nodes: Vec::new(), bound }; + // A small start; [`Builder::push`] doubles it as chunks arrive, never past the bound, so + // the array stays proportional to the chunk count (a file of a few large chunks gets a few + // slots, not one per 32 bytes). `try_reserve_exact` so it fails nothing here. + let _ = builder.nodes.try_reserve_exact(bound.min(INITIAL_SLOTS)); + builder.sequence(12, end, 1)?; + let trailer = data.get(end..).unwrap_or(&[]); + Ok(Self { nodes: builder.nodes, trailer }) + } + + /// The index of the entries `drafts` (in depth-first order, see [`Draft`]) whose bodies and + /// trailer are ranges of `buffer`. A range outside `buffer` reads as empty. The list is turned + /// into entries; a [`Draft`] and an [`Entry`] have the same size and alignment, so the standard + /// library reuses the list's allocation for them. + pub fn from_drafts(buffer: &'a [u8], drafts: Vec, trailer: (usize, usize)) -> Self { + let slice = |start: usize, len: usize| start.checked_add(len).and_then(|end| buffer.get(start..end)).unwrap_or(&[]); + let nodes = drafts + .into_iter() + .map(|d| Entry { data: slice(d.start, d.len), id: d.id, list_type: d.list_type, end: d.end, kind: d.kind, pad: d.pad }) + .collect(); + let trailer = buffer.get(trailer.0..trailer.1).unwrap_or(&[]); + Self { nodes, trailer } + } + + /// Indexes an already parsed (or built) chunk tree. The index borrows the file's bytes. + /// + /// # Errors + /// [`AepError::TooManyChunks`] for a tree of more than `u32::MAX` chunks. + pub fn from_file(file: &'a AepFile<'_>) -> Result { + // Sized once, to the chunks the tree holds. + let mut nodes: Vec> = Vec::new(); + nodes.try_reserve_exact(file.walk().count()).map_err(|_| AepError::TooLarge)?; + // Each frame: the siblings still to visit and the entry whose subtree they fill. + let mut stack: Vec<(std::slice::Iter<'a, Chunk<'_>>, Option)> = vec![(file.chunks.iter(), None)]; + while let Some((iter, parent)) = stack.last_mut() { + let parent = *parent; + match iter.next() { + Some(chunk) => { + let at = nodes.len(); + // The entry after this one must still have a `u32` index. + let next = index_u32(at.checked_add(1).ok_or(AepError::TooManyChunks)?)?; + let (kind, data, list_type) = match &chunk.body { + Body::Data(d) => (Kind::Data, &d[..], [0; 4]), + Body::Chunks(_) => (Kind::Nested, &[][..], [0; 4]), + Body::List { list_type, .. } => (Kind::List, &[][..], *list_type), + Body::OpaqueList { list_type, data } => (Kind::OpaqueList, &data[..], *list_type), + }; + nodes.push(Entry { data, id: chunk.id, list_type, end: next, kind, pad: chunk.pad }); + let kids = chunk.children(); + if !kids.is_empty() { + stack.push((kids.iter(), Some(at))); + } + } + None => { + stack.pop(); + if let Some(p) = parent { + let end = index_u32(nodes.len())?; + if let Some(e) = nodes.get_mut(p) { + e.end = end; + } + } + } + } + } + Ok(Self { nodes, trailer: &file.trailer[..] }) + } + + /// The number of chunks in the tree (at every depth). + pub fn len(&self) -> usize { + self.nodes.len() + } + + /// True when the container holds no chunks. + pub fn is_empty(&self) -> bool { + self.nodes.is_empty() + } + + /// The bytes after the container's declared end (see [`AepFile::trailer`]). + pub fn trailer(&self) -> &'a [u8] { + self.trailer + } + + /// The top-level chunks. + pub fn chunks(&self) -> Nodes<'_, 'a> { + Nodes(NodesRepr::Index { tree: self, next: 0, end: u32::try_from(self.nodes.len()).unwrap_or(u32::MAX) }) + } + + /// The first top-level chunk with this id. + pub fn chunk(&self, id: &[u8; 4]) -> Option> { + self.chunks().find(|c| c.is(id)) + } + + /// The first top-level `LIST` of this type. + pub fn list(&self, list_type: &[u8; 4]) -> Option> { + self.chunks().find(|c| c.is_list(list_type)) + } + + /// Visits every chunk depth-first with its nesting depth (the top level is 1), as + /// [`AepFile::walk`] does. + pub fn walk(&self) -> NodeWalk<'_, 'a> { + NodeWalk(WalkRepr::Index { tree: self, next: 0, end: u32::try_from(self.nodes.len()).unwrap_or(u32::MAX), open: Vec::new() }) + } + + /// The owned chunk tree (the bodies stay borrowed from the input): what + /// [`crate::parse`] gives for the same file. + pub fn to_file(&self) -> AepFile<'a> { + AepFile { chunks: self.build(0, u32::try_from(self.nodes.len()).unwrap_or(u32::MAX)), trailer: Cow::Borrowed(self.trailer) } + } + + /// The entry at `at`, `None` past the end. + fn entry(&self, at: u32) -> Option<&Entry<'a>> { + self.nodes.get(usize::try_from(at).ok()?) + } + + /// The end of the subtree at `at`; never before `at + 1`, so walks always move on. + fn end_of(&self, at: u32) -> u32 { + self.entry(at).map_or(u32::MAX, |e| e.end).max(at.saturating_add(1)) + } + + /// The owned chunks for the siblings that start at `next` and fill `next..end`, without + /// recursion. + fn build(&self, next: u32, end: u32) -> Vec> { + struct Frame<'a> { + /// The list or nested chunk being filled; `None` for the outermost range. + at: Option, + kids: Vec>, + next: u32, + end: u32, + } + let mut stack = vec![Frame { at: None, kids: Vec::new(), next, end }]; + loop { + let Some(top) = stack.last_mut() else { return Vec::new() }; + if top.next < top.end { + let at = top.next; + top.next = self.end_of(at); + let Some(e) = self.entry(at).copied() else { + top.next = top.end; + continue; + }; + match e.kind { + Kind::List | Kind::Nested => { + let sub_end = self.end_of(at); + stack.push(Frame { at: Some(at), kids: Vec::new(), next: at.saturating_add(1), end: sub_end }); + } + Kind::Data => top.kids.push(Chunk { id: e.id, body: Body::Data(Cow::Borrowed(e.data)), pad: e.pad }), + Kind::OpaqueList => { + top.kids.push(Chunk { id: e.id, body: Body::OpaqueList { list_type: e.list_type, data: Cow::Borrowed(e.data) }, pad: e.pad }); + } + } + } else { + let Some(frame) = stack.pop() else { return Vec::new() }; + let Some(at) = frame.at else { return frame.kids }; + let Some(e) = self.entry(at).copied() else { continue }; + let body = match e.kind { + Kind::Nested => Body::Chunks(frame.kids), + Kind::List | Kind::Data | Kind::OpaqueList => Body::List { list_type: e.list_type, children: frame.kids }, + }; + let chunk = Chunk { id: e.id, body, pad: e.pad }; + match stack.last_mut() { + Some(parent) => parent.kids.push(chunk), + None => return vec![chunk], + } + } + } + } +} + +/// The slots a [`TreeIndex`] starts with (32 KiB); it doubles from there. +const INITIAL_SLOTS: usize = 1024; + +/// Builds a [`TreeIndex`]; mirrors `read::Parser` step for step (see the module documentation). +struct Builder<'a> { + data: &'a [u8], + limits: Limits, + count: usize, + nodes: Vec>, + /// The most chunks the input can hold under the limits: `nodes` never reserves past it. + bound: usize, +} + +impl<'a> Builder<'a> { + /// Appends an entry. A full array grows by its length (at least 16), but never past + /// [`Self::bound`]; an allocation the target cannot make is an error, not an abort. + fn push(&mut self, entry: Entry<'a>) -> Result<(), AepError> { + let len = self.nodes.len(); + if len == self.nodes.capacity() { + let more = len.max(16).min(self.bound.saturating_sub(len)).max(1); + self.nodes.try_reserve_exact(more).map_err(|_| AepError::TooLarge)?; + } + self.nodes.push(entry); + Ok(()) + } + + /// Appends the sibling chunks that exactly fill `start..end`, each followed by its subtree. + fn sequence(&mut self, start: usize, end: usize, depth: usize) -> Result<(), AepError> { + let mut pos = start; + while pos < end { + let short = AepError::Malformed { offset: pos, what: "bytes left over that are too short for a chunk header" }; + let body_start = pos.checked_add(8).filter(|b| *b <= end).ok_or(short)?; + let id = id4(self.data, pos).ok_or(AepError::Malformed { offset: pos, what: "short read" })?; + let size = be_u32(self.data, pos + 4).ok_or(AepError::Malformed { offset: pos, what: "short read" })? as usize; + let avail = end - body_start; + if size > avail { + return Err(AepError::ChunkTooLarge { offset: pos, size: size as u64, available: avail as u64 }); + } + self.count = self.count.saturating_add(1); + if self.count > self.limits.max_chunks { + return Err(AepError::TooManyChunks); + } + let at = self.nodes.len(); + // This entry and the one after it must have `u32` indices. + index_u32(at.checked_add(1).ok_or(AepError::TooManyChunks)?)?; + self.push(Entry::placeholder(id))?; + let body_end = body_start + size; + self.body(at, id, body_start, body_end, depth)?; + let mut next = body_end; + let mut pad = None; + if size % 2 == 1 && next < end { + pad = Some(self.data.get(next).copied().ok_or(AepError::Malformed { offset: next, what: "missing pad byte" })?); + next += 1; + } + let subtree_end = index_u32(self.nodes.len())?; + if let Some(e) = self.nodes.get_mut(at) { + e.pad = pad; + e.end = subtree_end; + } + pos = next; + } + Ok(()) + } + + /// Like [`Self::sequence`] but a structural problem yields `false` and removes what the + /// attempt appended (the caller keeps bytes). The chunk count keeps the attempt's chunks, as + /// the [`Chunk`] parser's does. + fn tentative(&mut self, start: usize, end: usize, depth: usize) -> Result { + let mark = self.nodes.len(); + match self.sequence(start, end, depth) { + Ok(()) => Ok(true), + Err(e) if e.is_structural() => { + self.nodes.truncate(mark); + Ok(false) + } + Err(e) => Err(e), + } + } + + /// The input bytes `start..end` (empty when out of range). + fn slice(&self, start: usize, end: usize) -> &'a [u8] { + self.data.get(start..end).unwrap_or(&[]) + } + + /// Fills in the body of the entry at `at` once the parser knows what it is. + fn set(&mut self, at: usize, kind: Kind, data: &'a [u8], list_type: [u8; 4]) { + if let Some(e) = self.nodes.get_mut(at) { + e.kind = kind; + e.data = data; + e.list_type = list_type; + } + } + + /// Fills in the entry at `at` for the body `start..end` and appends its subtree. + fn body(&mut self, at: usize, id: [u8; 4], start: usize, end: usize, depth: usize) -> Result<(), AepError> { + let len = end - start; + if id == LIST && len >= 4 { + let list_type = id4(self.data, start).ok_or(AepError::Malformed { offset: start, what: "short read" })?; + if depth < self.limits.max_depth && self.tentative(start + 4, end, depth + 1)? { + self.set(at, Kind::List, &[], list_type); + } else { + let data = self.slice(start + 4, end); + self.set(at, Kind::OpaqueList, data, list_type); + } + return Ok(()); + } + if NESTED_IDS.contains(&id) && len >= 8 && depth < self.limits.max_depth { + let mark = self.nodes.len(); + if self.tentative(start, end, depth + 1)? && self.nodes.len() > mark { + self.set(at, Kind::Nested, &[], [0; 4]); + return Ok(()); + } + } + let data = self.slice(start, end); + self.set(at, Kind::Data, data, [0; 4]); + Ok(()) + } +} + +/// A chunk of either tree: an owned [`Chunk`] or an entry of a [`TreeIndex`]. The typed view +/// reads through it, so it works the same on both. Cheap to copy. +#[derive(Clone, Copy)] +pub struct Node<'f, 'a>(NodeRepr<'f, 'a>); + +#[derive(Clone, Copy)] +enum NodeRepr<'f, 'a> { + Chunk(&'f Chunk<'a>), + Index(&'f TreeIndex<'a>, u32), +} + +impl<'f, 'a> From<&'f Chunk<'a>> for Node<'f, 'a> { + /// The handle for this value. + fn from(chunk: &'f Chunk<'a>) -> Self { + Node(NodeRepr::Chunk(chunk)) + } +} + +/// Prints the chunk as [`Chunk`]'s `Debug` does, whichever tree it is in, without copying the +/// subtree. +impl fmt::Debug for Node<'_, '_> { + /// The chunk as `Chunk`'s `Debug` prints it. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + NodeRepr::Chunk(c) => fmt::Debug::fmt(c, f), + NodeRepr::Index(..) => { + f.debug_struct("Chunk").field("id", &self.id()).field("body", &BodyDebug(*self)).field("pad", &self.pad()).finish() + } + } + } +} + +/// The body of an index [`Node`], printed as [`Body`]'s `Debug` prints it. +struct BodyDebug<'f, 'a>(Node<'f, 'a>); + +/// The children of a [`Node`], printed as a list. +struct ChildrenDebug<'f, 'a>(Node<'f, 'a>); + +impl fmt::Debug for BodyDebug<'_, '_> { + /// The body as `Body`'s `Debug` prints it. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Some(e) = self.0.entry() else { return f.write_str("?") }; + match e.kind { + Kind::Data => f.debug_tuple("Data").field(&e.data).finish(), + Kind::Nested => f.debug_tuple("Chunks").field(&ChildrenDebug(self.0)).finish(), + Kind::List => f.debug_struct("List").field("list_type", &e.list_type).field("children", &ChildrenDebug(self.0)).finish(), + Kind::OpaqueList => f.debug_struct("OpaqueList").field("list_type", &e.list_type).field("data", &e.data).finish(), + } + } +} + +impl fmt::Debug for ChildrenDebug<'_, '_> { + /// The children as a list. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.0.children()).finish() + } +} + +impl<'f, 'a> Node<'f, 'a> { + /// The entry at `at`, `None` past the end. + fn entry(self) -> Option<&'f Entry<'a>> { + match self.0 { + NodeRepr::Index(tree, at) => tree.entry(at), + NodeRepr::Chunk(_) => None, + } + } + + /// The [`Chunk`] when this node is one of an owned tree; `None` for an index entry (see + /// [`Self::to_chunk`]). + pub fn as_chunk(self) -> Option<&'f Chunk<'a>> { + match self.0 { + NodeRepr::Chunk(c) => Some(c), + NodeRepr::Index(..) => None, + } + } + + /// The chunk and its subtree as an owned [`Chunk`] (bodies stay borrowed). + pub fn to_chunk(self) -> Chunk<'a> { + match self.0 { + NodeRepr::Chunk(c) => c.clone(), + NodeRepr::Index(tree, at) => tree.build(at, tree.end_of(at)).into_iter().next().unwrap_or_else(|| Chunk::data(self.id(), &[][..])), + } + } + + /// The 4-byte id (see [`Chunk::id`]). + pub fn id(self) -> [u8; 4] { + match self.0 { + NodeRepr::Chunk(c) => c.id, + NodeRepr::Index(..) => self.entry().map_or([0; 4], |e| e.id), + } + } + + /// The pad byte (see [`Chunk::pad`]). + pub fn pad(self) -> Option { + match self.0 { + NodeRepr::Chunk(c) => c.pad, + NodeRepr::Index(..) => self.entry().and_then(|e| e.pad), + } + } + + /// The raw bytes of a data chunk, or the bytes after the list type of an opaque list (see + /// [`Chunk::bytes`]). + pub fn bytes(self) -> Option<&'f [u8]> { + match self.0 { + NodeRepr::Chunk(c) => c.bytes(), + NodeRepr::Index(..) => self.entry().filter(|e| matches!(e.kind, Kind::Data | Kind::OpaqueList)).map(|e| e.data), + } + } + + /// The child chunks of a list or nested chunk; none for data. + pub fn children(self) -> Nodes<'f, 'a> { + match self.0 { + NodeRepr::Chunk(c) => Nodes(NodesRepr::Slice(c.children().iter())), + NodeRepr::Index(tree, at) => { + let end = match tree.entry(at) { + Some(e) if matches!(e.kind, Kind::List | Kind::Nested) => tree.end_of(at), + _ => at.saturating_add(1), + }; + Nodes(NodesRepr::Index { tree, next: at.saturating_add(1), end }) + } + } + } + + /// The list type when this is a `LIST` (parsed or opaque). + pub fn list_type(self) -> Option<[u8; 4]> { + match self.0 { + NodeRepr::Chunk(c) => c.list_type(), + NodeRepr::Index(..) => self.entry().filter(|e| matches!(e.kind, Kind::List | Kind::OpaqueList)).map(|e| e.list_type), + } + } + + /// True when this is a `LIST` of the given type. + pub fn is_list(self, list_type: &[u8; 4]) -> bool { + match self.0 { + NodeRepr::Chunk(c) => c.is_list(list_type), + NodeRepr::Index(..) => { + self.entry().is_some_and(|e| e.id == LIST && matches!(e.kind, Kind::List | Kind::OpaqueList) && &e.list_type == list_type) + } + } + } + + /// True when this is a `LIST` whose content could not be read as chunks. + pub fn is_opaque_list(self) -> bool { + match self.0 { + NodeRepr::Chunk(c) => c.is_opaque_list(), + NodeRepr::Index(..) => self.entry().is_some_and(|e| e.kind == Kind::OpaqueList), + } + } + + /// True when this chunk has the given id. + pub fn is(self, id: &[u8; 4]) -> bool { + self.id() == *id + } + + /// The first child chunk with this id. + pub fn child(self, id: &[u8; 4]) -> Option { + self.children().find(|c| c.is(id)) + } + + /// The first child `LIST` of this type. + pub fn child_list(self, list_type: &[u8; 4]) -> Option { + self.children().find(|c| c.is_list(list_type)) + } + + /// Every chunk below this one depth-first (children before later siblings), with the depth + /// counted from 1 for the children of this chunk. + pub fn descendants(self) -> NodeWalk<'f, 'a> { + match self.0 { + NodeRepr::Chunk(c) => NodeWalk(WalkRepr::Chunk(c.descendants())), + NodeRepr::Index(tree, at) => { + let end = match tree.entry(at) { + Some(e) if matches!(e.kind, Kind::List | Kind::Nested) => tree.end_of(at), + _ => at.saturating_add(1), + }; + NodeWalk(WalkRepr::Index { tree, next: at.saturating_add(1), end, open: Vec::new() }) + } + } + } + + /// The first descendant `LIST` of this type, searching depth-first. + pub fn find_list(self, list_type: &[u8; 4]) -> Option { + match self.0 { + NodeRepr::Chunk(c) => c.find_list(list_type).map(Node::from), + // The subtree is a contiguous range in depth-first order: a plain scan. + NodeRepr::Index(tree, at) => { + let first = usize::try_from(at).ok()?.checked_add(1)?; + let end = usize::try_from(tree.end_of(at)).ok()?.min(tree.nodes.len()); + let range = tree.nodes.get(first..end)?; + let i = range.iter().position(|e| e.id == LIST && matches!(e.kind, Kind::List | Kind::OpaqueList) && &e.list_type == list_type)?; + let found = u32::try_from(first.checked_add(i)?).ok()?; + Some(Node(NodeRepr::Index(tree, found))) + } + } + } +} + +/// The children of a [`Node`] (or the top-level chunks of a [`TreeIndex`]), in file order. +#[derive(Clone)] +pub struct Nodes<'f, 'a>(NodesRepr<'f, 'a>); + +#[derive(Clone)] +enum NodesRepr<'f, 'a> { + Slice(std::slice::Iter<'f, Chunk<'a>>), + Index { tree: &'f TreeIndex<'a>, next: u32, end: u32 }, +} + +impl<'f, 'a> Iterator for Nodes<'f, 'a> { + type Item = Node<'f, 'a>; + + /// The next item, `None` at the end of the range. + fn next(&mut self) -> Option { + match &mut self.0 { + NodesRepr::Slice(it) => it.next().map(Node::from), + NodesRepr::Index { tree, next, end } => { + if *next >= *end { + return None; + } + let (tree, at) = (*tree, *next); + tree.entry(at)?; + *next = tree.end_of(at); + Some(Node(NodeRepr::Index(tree, at))) + } + } + } +} + +/// A depth-first walk over [`Node`]s with their depth; see [`Node::descendants`] and +/// [`TreeIndex::walk`]. +pub struct NodeWalk<'f, 'a>(WalkRepr<'f, 'a>); + +enum WalkRepr<'f, 'a> { + Chunk(Walk<'f, 'a>), + /// `open` holds the subtree ends of the entries above the next one (its ancestors inside the + /// walked range); their count is the next entry's depth minus one. + Index { + tree: &'f TreeIndex<'a>, + next: u32, + end: u32, + open: Vec, + }, +} + +impl<'f, 'a> Iterator for NodeWalk<'f, 'a> { + type Item = (usize, Node<'f, 'a>); + + /// The next item, `None` at the end of the range. + fn next(&mut self) -> Option { + match &mut self.0 { + WalkRepr::Chunk(w) => w.next().map(|(d, c)| (d, Node::from(c))), + WalkRepr::Index { tree, next, end, open } => { + if *next >= *end { + return None; + } + let (tree, at) = (*tree, *next); + tree.entry(at)?; + while open.last().is_some_and(|e| *e <= at) { + open.pop(); + } + let depth = open.len().saturating_add(1); + let sub_end = tree.end_of(at); + if sub_end > at.saturating_add(1) { + open.push(sub_end); + } + *next = at.saturating_add(1); + Some((depth, Node(NodeRepr::Index(tree, at)))) + } + } + } +} + +/// The top level of either tree: what the project settings and the version are read from. +#[derive(Clone, Copy)] +pub enum Root<'f, 'a> { + File(&'f AepFile<'a>), + Index(&'f TreeIndex<'a>), +} + +impl<'f, 'a> From<&'f AepFile<'a>> for Root<'f, 'a> { + /// The handle for this value. + fn from(file: &'f AepFile<'a>) -> Self { + Root::File(file) + } +} + +impl<'f, 'a> From<&'f TreeIndex<'a>> for Root<'f, 'a> { + /// The handle for this value. + fn from(index: &'f TreeIndex<'a>) -> Self { + Root::Index(index) + } +} + +impl<'f, 'a> Root<'f, 'a> { + /// The top-level chunks. + pub fn chunks(self) -> Nodes<'f, 'a> { + match self { + Root::File(f) => Nodes(NodesRepr::Slice(f.chunks.iter())), + Root::Index(t) => t.chunks(), + } + } + + /// The first top-level chunk with this id. + pub fn chunk(self, id: &[u8; 4]) -> Option> { + self.chunks().find(|c| c.is(id)) + } + + /// The first top-level `LIST` of this type. + pub fn list(self, list_type: &[u8; 4]) -> Option> { + self.chunks().find(|c| c.is_list(list_type)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{parse_with_limits, write}; + + /// A tiny deterministic generator (xorshift64*), so the tests need no extra crate. + struct Rng(u64); + + impl Rng { + /// The next pseudo-random number (xorshift64*). + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + + /// A number below `n` (0 for `n == 0`). + fn below(&mut self, n: u64) -> u64 { + if n == 0 { 0 } else { self.next() % n } + } + } + + /// A random tree: lists, nested-id chunks holding a `Utf8`, data of odd and even sizes, opaque + /// lists, empty lists, deep chains. + fn tree(rng: &mut Rng, depth: usize, budget: &mut usize) -> Vec> { + let n = rng.below(6); + let mut out = Vec::new(); + for _ in 0..n { + if *budget == 0 { + break; + } + *budget -= 1; + let pick = rng.below(10); + let chunk = if depth < 12 && pick < 4 { + let types: [&[u8; 4]; 4] = [b"Fold", b"tdgp", b"tdbs", b"Layr"]; + let t = *types[usize::try_from(rng.below(4)).expect("small")]; + Chunk::list(t, tree(rng, depth + 1, budget)) + } else if pick == 4 { + let ids: [&[u8; 4]; 3] = [b"tdsn", b"pdnm", b"fnam"]; + let id = *ids[usize::try_from(rng.below(3)).expect("small")]; + let text = vec![b'a'; usize::try_from(rng.below(5)).expect("small")]; + Chunk { id, body: Body::Chunks(vec![Chunk::data(*b"Utf8", text)]), pad: None } + } else if pick == 5 { + let raw = vec![0x5a; usize::try_from(rng.below(9)).expect("small")]; + Chunk { id: LIST, body: Body::OpaqueList { list_type: *b"btdk", data: raw.into() }, pad: None } + } else { + let ids: [&[u8; 4]; 4] = [b"cdat", b"tdmn", b"Utf8", b"idta"]; + let id = *ids[usize::try_from(rng.below(4)).expect("small")]; + Chunk::data(id, vec![u8::try_from(rng.below(256)).expect("byte"); usize::try_from(rng.below(13)).expect("small")]) + }; + out.push(chunk); + } + out + } + + /// Both readers on the same bytes and limits: the same result, errors included; and the + /// index's walk visits the same chunks at the same depths as the tree's. + fn same(bytes: &[u8], limits: Limits) { + let old = parse_with_limits(bytes, limits); + let new = TreeIndex::parse_with_limits(bytes, limits); + match (&old, &new) { + (Ok(file), Ok(index)) => { + assert_eq!(&index.to_file(), file, "the index converts to the parsed tree"); + let a: Vec<(usize, Chunk<'_>)> = file.walk().map(|(d, c)| (d, c.clone())).collect(); + let b: Vec<(usize, Chunk<'_>)> = index.walk().map(|(d, n)| (d, n.to_chunk())).collect(); + assert_eq!(a, b, "the walks agree"); + assert_eq!(index.len(), a.len()); + // Indexing the parsed tree gives the same index. + let again = TreeIndex::from_file(file).expect("index"); + assert_eq!(again.to_file(), *file); + } + (Err(a), Err(b)) => assert_eq!(a, b, "the same error"), + _ => panic!("one reader failed: {:?} vs {:?}", old.as_ref().err(), new.as_ref().err()), + } + } + + /// The default limits and four tight ones (depth 1 and 3, 7 and 40 chunks). + fn limits() -> [Limits; 5] { + [ + Limits::default(), + Limits { max_depth: 1, max_chunks: 10_000_000 }, + Limits { max_depth: 3, max_chunks: 10_000_000 }, + Limits { max_depth: 64, max_chunks: 7 }, + Limits { max_depth: 64, max_chunks: 40 }, + ] + } + + /// The index matches the chunk parser on generated and damaged trees. + #[test] + fn the_index_matches_the_chunk_parser_on_generated_and_damaged_trees() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for _ in 0..400 { + let mut budget = 120; + let chunks = tree(&mut rng, 0, &mut budget); + let file = AepFile { chunks, trailer: Cow::Borrowed(b"x") }; + let bytes = write(&file).expect("write"); + for l in limits() { + same(&bytes, l); + } + // Damage: overwrite a few bytes past the container header (sizes, ids, list types). + for _ in 0..4 { + let mut bad = bytes.clone(); + for _ in 0..1 + rng.below(3) { + let at = 12 + usize::try_from(rng.below(u64::try_from(bad.len().saturating_sub(12)).expect("len"))).expect("index"); + if let Some(b) = bad.get_mut(at) { + *b = u8::try_from(rng.below(256)).expect("byte"); + } + } + for l in limits() { + same(&bad, l); + } + } + // Truncated inputs (the container size then no longer fits). + let cut = bytes.len().saturating_sub(usize::try_from(rng.below(8)).expect("small") + 1); + same(&bytes[..cut], Limits::default()); + } + } + + /// Header errors are the same. + #[test] + fn header_errors_are_the_same() { + for bytes in + [&b""[..], b"RIFX", b"RIFX\0\0\0\x04Egg", b"RIFX\0\0\0\x04Fnord", b"RIFX\0\0\0\x08Egg!", b"RIFX\0\0\0\x03Egg!", b"RIFF\0\0\0\x04Egg!"] + { + same(bytes, Limits::default()); + } + } + + /// The typed accessors give the same answers through either tree. + #[test] + fn nodes_answer_alike_on_both_trees() { + let mut rng = Rng(42); + for _ in 0..100 { + let mut budget = 200; + let file = AepFile { chunks: tree(&mut rng, 0, &mut budget), trailer: Cow::Borrowed(&[]) }; + let bytes = write(&file).expect("write"); + let parsed = crate::parse(&bytes).expect("parse"); + let index = TreeIndex::parse(&bytes).expect("index"); + let a: Vec> = parsed.walk().map(|(_, c)| Node::from(c)).collect(); + let b: Vec> = index.walk().map(|(_, n)| n).collect(); + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(&b) { + assert_eq!( + (x.id(), x.pad(), x.bytes(), x.list_type(), x.is_opaque_list()), + (y.id(), y.pad(), y.bytes(), y.list_type(), y.is_opaque_list()) + ); + assert_eq!(x.children().map(Node::to_chunk).collect::>(), y.children().map(Node::to_chunk).collect::>()); + for t in [b"Fold", b"tdgp", b"tdbs", b"Layr", b"btdk"] { + assert_eq!(x.find_list(t).map(Node::to_chunk), y.find_list(t).map(Node::to_chunk)); + assert_eq!(x.child_list(t).map(Node::to_chunk), y.child_list(t).map(Node::to_chunk)); + assert_eq!(x.is_list(t), y.is_list(t)); + } + for id in [b"cdat", b"Utf8", b"tdsn"] { + assert_eq!(x.child(id).map(Node::to_chunk), y.child(id).map(Node::to_chunk)); + } + let dx: Vec<(usize, Chunk<'_>)> = x.descendants().map(|(d, n)| (d, n.to_chunk())).collect(); + let dy: Vec<(usize, Chunk<'_>)> = y.descendants().map(|(d, n)| (d, n.to_chunk())).collect(); + assert_eq!(dx, dy); + assert_eq!(format!("{x:?}"), format!("{y:?}")); + } + } + } + + /// The index never reserves more than the input or the limit allows. + #[test] + fn the_index_never_reserves_more_than_the_input_or_the_limit_allows() { + // 1000 empty headers: the most chunks the bytes can hold. + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + let index = TreeIndex::parse(&data).expect("index"); + assert_eq!(index.len(), 1000); + // The start (1024 slots) is cut to what the input can hold. + assert!(index.nodes.capacity() <= 1000, "{} slots for at most 1000 headers", index.nodes.capacity()); + // A short tail or a header that runs past the end does not raise the bound. + let mut big = data.clone(); + big[16..20].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(TreeIndex::parse(&big).is_err() && crate::parse(&big).is_err()); + // Under a tighter limit the parse fails as the chunk parser does, and the guess never + // exceeds the limit. + let tight = Limits { max_depth: 64, max_chunks: 10 }; + assert_eq!(TreeIndex::parse_with_limits(&data, tight).err(), Some(AepError::TooManyChunks)); + let small = Limits { max_depth: 64, max_chunks: 1000 }; + let index = TreeIndex::parse_with_limits(&data, small).expect("exactly at the limit"); + assert_eq!(index.len(), 1000); + // A limit below what the input holds bounds the reservation: 100 chunks, never more slots. + let mut wide = b"RIFX\0\0\0\0Egg!".to_vec(); + wide.extend_from_slice(b"LIST"); + wide.extend_from_slice(&u32::try_from(4 + 8 * 99).expect("small").to_be_bytes()); + wide.extend_from_slice(b"Fold"); + wide.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 99).flatten()); + let declared = u32::try_from(wide.len() - 8).expect("small"); + wide[4..8].copy_from_slice(&declared.to_be_bytes()); + let index = TreeIndex::parse_with_limits(&wide, Limits { max_depth: 64, max_chunks: 100 }).expect("100 chunks"); + assert_eq!(index.len(), 100); + assert!(index.nodes.capacity() <= 100); + // `from_file` is sized exactly. + let file = crate::parse(&wide).expect("parse"); + assert_eq!(TreeIndex::from_file(&file).expect("index").nodes.capacity(), 100); + } + + /// A file of `n` data chunks of `size` bytes each. + fn flat(n: usize, size: usize) -> Vec { + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + for _ in 0..n { + data.extend_from_slice(b"cdat"); + data.extend_from_slice(&u32::try_from(size).expect("small").to_be_bytes()); + data.extend(std::iter::repeat_n(0u8, size)); + } + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + data + } + + /// The index grows with the chunk count not the byte size. + #[test] + fn the_index_grows_with_the_chunk_count_not_the_byte_size() { + // 4 MB in 4 chunks: a few slots, not one per 32 bytes (that would be 131 072 slots, 4 MB). + let big = flat(4, 1 << 20); + let index = TreeIndex::parse(&big).expect("index"); + assert_eq!(index.len(), 4); + assert!(index.nodes.capacity() <= INITIAL_SLOTS, "{} slots for 4 chunks", index.nodes.capacity()); + // Many small chunks: at most twice the count (it doubles). + let many = flat(10_000, 2); + let index = TreeIndex::parse(&many).expect("index"); + assert_eq!(index.len(), 10_000); + assert!(index.nodes.capacity() <= 2 * 10_000, "{} slots for 10 000 chunks", index.nodes.capacity()); + same(&big, Limits::default()); + same(&many, Limits::default()); + } + + /// `LIST Fold` around `inner`, followed by 6 bytes too short for a header, so the list's + /// sequence fails and the list is kept opaque. + fn broken_level(inner: &[u8]) -> Vec { + let mut body = b"Fold".to_vec(); + body.extend_from_slice(inner); + body.extend_from_slice(&[0xee; 6]); + let mut out = b"LIST".to_vec(); + out.extend_from_slice(&u32::try_from(body.len()).expect("small").to_be_bytes()); + out.extend_from_slice(&body); + out + } + + /// Failed attempts count once and leave nothing behind. + #[test] + fn failed_attempts_count_once_and_leave_nothing_behind() { + let mut wide = b"Fold".to_vec(); + wide.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); + let mut level = b"LIST".to_vec(); + level.extend_from_slice(&u32::try_from(wide.len()).expect("small").to_be_bytes()); + level.extend_from_slice(&wide); + for _ in 0..50 { + level = broken_level(&level); + } + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend_from_slice(&level); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + let headers = 1 + 50 + 1000; + let index = TreeIndex::parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers }).expect("parse"); + assert_eq!(TreeIndex::parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers - 1 }).err(), Some(AepError::TooManyChunks)); + // Only the outermost list is left, opaque: every failed attempt was rolled back. + assert_eq!(index.len(), 1); + let top = index.chunks().next().expect("one top-level chunk"); + assert!(top.is_opaque_list() && top.bytes().map(<[u8]>::len) == Some(level.len() - 12)); + assert_eq!(write(&index.to_file()).expect("write"), data); + same(&data, Limits::default()); + } + + /// Depth beyond the limit stays opaque without recursion past it. + #[test] + fn depth_beyond_the_limit_stays_opaque_without_recursion_past_it() { + // 5000 nested lists: far deeper than the limit; everything below depth 64 stays bytes. + let mut level = b"LIST\0\0\0\x04tdgp".to_vec(); + for _ in 0..5000 { + let mut out = b"LIST".to_vec(); + out.extend_from_slice(&u32::try_from(level.len() + 4).expect("small").to_be_bytes()); + out.extend_from_slice(b"tdgp"); + out.extend_from_slice(&level); + level = out; + } + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend_from_slice(&level); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + let index = TreeIndex::parse(&data).expect("parse"); + assert_eq!(index.len(), 64); + assert_eq!(index.walk().map(|(d, _)| d).max(), Some(64)); + assert!(index.walk().last().is_some_and(|(_, n)| n.is_opaque_list())); + same(&data, Limits::default()); + // Converting and indexing a deep owned tree uses no recursion either. + let file = index.to_file(); + assert_eq!(TreeIndex::from_file(&file).expect("index").len(), 64); + } +} diff --git a/crates/aep/src/keys.rs b/crates/aep/src/keys.rs index 0c0c93ee6..6e107ad00 100644 --- a/crates/aep/src/keys.rs +++ b/crates/aep/src/keys.rs @@ -193,19 +193,10 @@ impl<'f> Keyframe<'f> { } } - /// The value of a 3-component spatial keyframe (Position), x, y and z in pixels. - pub fn spatial_value(&self) -> Option<[f64; 3]> { - let v = self.value()?; - if !matches!(self.kind(), KeyframeKind::Spatial { components: 3 }) { - return None; - } - Some([*v.first()?, *v.get(1)?, *v.get(2)?]) - } - /// The ease of the key: the four slots at byte 16 of a one-component plain record or at byte 24 /// of a spatial record or a mask path record. For linear and hold keys all four are 0 (a bezier key stores what /// `setTemporalEase` was given). Plain records with several components keep four slots per - /// component, see [`Keyframe::ease_component`] and [`Keyframe::plain_ease_slots`]. + /// component, see [`Keyframe::ease_component`]. pub fn ease(&self) -> Option { match self.kind() { KeyframeKind::Plain { components: 1 } => ease_at(self.record, 16), @@ -214,16 +205,6 @@ impl<'f> Keyframe<'f> { } } - /// The `4 n` ease `f64` of a plain record as stored (from byte `8 + 8 n`). With one component - /// they are [`Keyframe::ease`]; with several they are type-major, see - /// [`Keyframe::ease_component`]. - pub fn plain_ease_slots(&self) -> Option> { - match self.kind() { - KeyframeKind::Plain { components } => doubles(self.record, components.checked_mul(8)?.checked_add(8)?, components.checked_mul(4)?), - _ => None, - } - } - /// The ease of one value component. A plain record with `n` components stores the `4 n` ease /// doubles **type-major**: `[in speed x n][in influence x n][out speed x n][out influence x n]` /// starting at byte `8 + 8 n`, and component `i` uses slot `i` of each block (verified for the @@ -260,16 +241,6 @@ impl<'f> Keyframe<'f> { (0..n).map(|i| self.ease_component(i)).collect() } - /// The Euclidean ARGB distance to the next key that After Effects writes at byte 16 of a colour - /// (4-component spatial) record whose interpolation is not linear: 255 sqrt(2) = 360.6245 for - /// red to blue; 0 on the last key and on linear keys. `None` for other records. - pub fn color_distance(&self) -> Option { - match self.kind() { - KeyframeKind::Spatial { components: 4 } => be_f64(self.record, 16), - _ => None, - } - } - /// The decoded spatial record (Position: 128 bytes, colour: 152 bytes). pub fn spatial(&self) -> Option { let KeyframeKind::Spatial { components: n } = self.kind() else { return None }; @@ -300,11 +271,6 @@ pub struct ExpressionFlags { } impl ExpressionFlags { - /// True when bytes 76, 77 and 120 are all 1. - pub fn all_set(&self) -> bool { - self.byte_76 == 1 && self.byte_77 == 1 && self.byte_120 == 1 - } - /// True when byte 119 is 1. pub fn disabled(&self) -> bool { self.byte_119 == 1 @@ -324,11 +290,6 @@ impl<'f, 'a> Property<'f, 'a> { be_u32(self.chunk.child(b"tdsb")?.bytes()?, 0) } - /// True when `tdb4` byte 5 has bit 0 set: the property is static, it has no keyframes. - pub fn is_static_flag_set(&self) -> Option { - Some(self.header()?.get(5)? & 1 != 0) - } - /// The expression source: the raw UTF-8 text of the `Utf8` child that follows the value in the /// property (no length prefix, no engine tag; the engine is project-wide). pub fn expression(&self) -> Option { diff --git a/crates/aep/src/lib.rs b/crates/aep/src/lib.rs index a47cddfce..3e5dc2ceb 100644 --- a/crates/aep/src/lib.rs +++ b/crates/aep/src/lib.rs @@ -14,6 +14,8 @@ //! list) on damaged data instead of failing. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +// Ranges and borrowed bytes are passed around as plain tuples, as in EffectCraft, which allows this lint. +#![allow(clippy::type_complexity)] mod aepx; mod arbitrary; @@ -24,6 +26,7 @@ mod effects; mod error; mod footage; mod header; +pub mod index; mod keys; mod masks; mod matte; @@ -36,16 +39,17 @@ mod values; mod version; mod write; -pub use aepx::{is_aepx, parse_any, read_aepx, read_aepx_with_limits}; +pub use aepx::{AepxDrafts, index_aepx, is_aepx, parse_any, read_aepx, read_aepx_with_limits}; pub use arbitrary::{ CURVE_IDENTITY, CryptomatteData, CurvesData, ExtractorChannels, HueSaturationData, LevelsData, MeshData, curve_lut, identifier_channel_type, }; pub use camera::{CameraPosition, DEFAULT_CAMERA_ZOOM}; pub use chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk}; -pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue}; +pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue, Pard}; pub use error::AepError; pub use footage::{Footage, PsdLayer, SequenceInfo}; pub use header::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Quality, Rational, Renderer}; +pub use index::{Draft, Node, NodeWalk, Nodes, Root, TreeIndex}; pub use keys::{ExpressionFlags, Interpolation, KeyEase, KeyframeKind, SpatialKey}; pub use masks::{Mask, MaskAtom, MaskMode, PathVertex, ShapePath}; pub use matte::{MatteMode, TrackMatte}; diff --git a/crates/aep/src/masks.rs b/crates/aep/src/masks.rs index 203ccefd5..42b52f5f4 100644 --- a/crates/aep/src/masks.rs +++ b/crates/aep/src/masks.rs @@ -6,9 +6,9 @@ //! property (`tdbs`, with a key list when animated) and `omks` with one `LIST shap` per keyframe (a //! single one when the path is static). -use crate::Chunk; use crate::bytes::{be_f32, be_u32, until_nul}; -use crate::typed::{KeyList, Layer, Project, PropGroup, PropNode, Property}; +use crate::index::Node; +use crate::typed::{KeyList, Layer, PropGroup, PropNode, Property}; use crate::values::{Tracked, read}; /// The mask mode (`mkif` `u32` at byte 4). @@ -93,8 +93,10 @@ pub struct ShapePath { } impl ShapePath { - /// Decodes a `LIST shap`; `None` when `shph` or the point list is malformed. - pub fn from_chunk(shap: &Chunk<'_>) -> Option { + /// Decodes a `LIST shap` (a [`Chunk`](crate::Chunk) or a [`Node`]); `None` when + /// `shph` or the point list is malformed. + pub fn from_chunk<'f, 'a: 'f>(shap: impl Into>) -> Option { + let shap = shap.into(); let shph = shap.child(b"shph")?.bytes()?; let bbox = [be_f32(shph, 4)?, be_f32(shph, 8)?, be_f32(shph, 12)?, be_f32(shph, 16)?]; let closed_flag = *shph.get(20)?; @@ -187,22 +189,12 @@ fn mask_from_atom(atom: &PropGroup<'_, '_>, mkif: Option<&[u8]>) -> Mask { } } if let Some(omks) = oms.child_list(b"omks") { - mask.shapes = omks.children().iter().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect(); + mask.shapes = omks.children().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect(); } } mask } -impl<'f, 'a> Project<'f, 'a> { - /// The vertices of every path shape of a mask in pixels of the layer: mask boxes are normalised - /// to the **layer** size (the size of its source), not the composition's. `None` when the layer - /// has no source with a size. - pub fn mask_vertices_px(&self, layer: &Layer<'f, 'a>, mask: &Mask) -> Option>> { - let (width, height) = self.layer_source_size(layer)?; - Some(mask.shapes.iter().map(|s| s.vertices((f64::from(width), f64::from(height)))).collect()) - } -} - /// One mask with the views of its records, for readers that need more than [`Mask`]: the /// keyframes and expressions of the mask properties (in [`MaskAtom::atom`]: `ADBE Mask Feather`, /// `ADBE Mask Opacity`, `ADBE Mask Offset`) and the path keyframes paired with their shapes. @@ -246,7 +238,7 @@ impl<'f, 'a> Layer<'f, 'a> { if let Some(PropNode::Other(oms)) = atom.get("ADBE Mask Shape") { path = oms.child_list(b"tdbs").and_then(Property::from_chunk); if let Some(omks) = oms.child_list(b"omks") { - path_shapes = omks.children().iter().filter(|c| c.is_list(b"shap")).map(ShapePath::from_chunk).collect(); + path_shapes = omks.children().filter(|c| c.is_list(b"shap")).map(ShapePath::from_chunk).collect(); } } masks.push(MaskAtom { mask, atom, path, path_shapes }); diff --git a/crates/aep/src/read.rs b/crates/aep/src/read.rs index c769029e4..a969a3997 100644 --- a/crates/aep/src/read.rs +++ b/crates/aep/src/read.rs @@ -2,6 +2,7 @@ use std::borrow::Cow; +use crate::bytes::{array, be_u32}; use crate::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; use crate::error::AepError; @@ -36,10 +37,20 @@ pub fn parse(data: &[u8]) -> Result, AepError> { /// # Errors /// See [`parse`]; also fails with [`AepError::TooManyChunks`]. pub fn parse_with_limits(data: &[u8], limits: Limits) -> Result, AepError> { + let end = container_end(data)?; + let mut parser = Parser { data, limits, count: 0 }; + let chunks = parser.sequence(12, end, 1)?; + let trailer = data.get(end..).unwrap_or(&[]); + Ok(AepFile { chunks, trailer: Cow::Borrowed(trailer) }) +} + +/// Checks the `RIFX`/`Egg!` header and returns where the container ends (its chunks fill +/// `12..end`; the trailer follows). Shared with [`crate::index::TreeIndex::parse`]. +pub(super) fn container_end(data: &[u8]) -> Result { if id4(data, 0) != Some(*b"RIFX") { return Err(AepError::NotRifx); } - let declared = u64::from(be32(data, 4).ok_or(AepError::NotRifx)?); + let declared = u64::from(be_u32(data, 4).ok_or(AepError::NotRifx)?); let form = id4(data, 8).ok_or(AepError::NotRifx)?; if &form != b"Egg!" { return Err(AepError::BadFormType(form)); @@ -49,20 +60,12 @@ pub fn parse_with_limits(data: &[u8], limits: Limits) -> Result, Aep return Err(AepError::Truncated { declared, available }); } // `declared <= available < data.len()`, so the end is inside the input. - let end = usize::try_from(declared).map_err(|_| AepError::TooLarge)?.checked_add(8).ok_or(AepError::TooLarge)?; - let mut parser = Parser { data, limits, count: 0 }; - let chunks = parser.sequence(12, end, 1)?; - let trailer = data.get(end..).unwrap_or(&[]); - Ok(AepFile { chunks, trailer: Cow::Borrowed(trailer) }) + usize::try_from(declared).map_err(|_| AepError::TooLarge)?.checked_add(8).ok_or(AepError::TooLarge) } -fn be32(data: &[u8], at: usize) -> Option { - id4(data, at).map(u32::from_be_bytes) -} - -fn id4(data: &[u8], at: usize) -> Option<[u8; 4]> { - let b = data.get(at..at.checked_add(4)?)?; - Some([*b.first()?, *b.get(1)?, *b.get(2)?, *b.get(3)?]) +/// The 4-byte id at `at`, `None` when the input is too short. +pub(super) fn id4(data: &[u8], at: usize) -> Option<[u8; 4]> { + array::<4>(data, at) } struct Parser<'a> { @@ -74,13 +77,16 @@ struct Parser<'a> { impl<'a> Parser<'a> { /// Parses the sibling chunks that exactly fill `start..end`. fn sequence(&mut self, start: usize, end: usize, depth: usize) -> Result>, AepError> { + // Sized once: a well-formed sequence fills exactly this many slots. `try_reserve` so a + // limit raised past what the target can allocate fails nothing here (the Vec then grows). let mut out = Vec::new(); + let _ = out.try_reserve_exact(self.capacity_for(start, end)); let mut pos = start; while pos < end { let short = AepError::Malformed { offset: pos, what: "bytes left over that are too short for a chunk header" }; let body_start = pos.checked_add(8).filter(|b| *b <= end).ok_or(short)?; let id = id4(self.data, pos).ok_or(AepError::Malformed { offset: pos, what: "short read" })?; - let size = be32(self.data, pos + 4).ok_or(AepError::Malformed { offset: pos, what: "short read" })? as usize; + let size = be_u32(self.data, pos + 4).ok_or(AepError::Malformed { offset: pos, what: "short read" })? as usize; let avail = end - body_start; if size > avail { return Err(AepError::ChunkTooLarge { offset: pos, size: size as u64, available: avail as u64 }); @@ -103,6 +109,26 @@ impl<'a> Parser<'a> { Ok(out) } + /// The slots to reserve for the sequence `start..end`: its header count, bounded by the input + /// (one per 8 bytes at most) and by the chunks the limit still allows. + fn capacity_for(&self, start: usize, end: usize) -> usize { + self.count_siblings(start, end).min(self.limits.max_chunks.saturating_sub(self.count)) + } + + /// The number of chunk headers that tile `start..end` the way [`Self::sequence`] walks them, + /// stopping at the first that does not fit. Never more than `(end - start) / 8`. + fn count_siblings(&self, start: usize, end: usize) -> usize { + let mut n = 0usize; + let mut pos = start; + while let Some(body_start) = pos.checked_add(8).filter(|b| *b <= end) { + let Some(size) = be_u32(self.data, pos.saturating_add(4)) else { break }; + let Some(next) = usize::try_from(size).ok().and_then(|s| body_start.checked_add(s)).filter(|e| *e <= end) else { break }; + n = n.saturating_add(1); + pos = if size % 2 == 1 && next < end { next.saturating_add(1) } else { next }; + } + n + } + /// Like [`Self::sequence`] but a structural problem yields `None` (the caller keeps bytes). fn tentative(&mut self, start: usize, end: usize, depth: usize) -> Result>>, AepError> { match self.sequence(start, end, depth) { @@ -140,3 +166,113 @@ impl<'a> Parser<'a> { Ok(Body::Data(Cow::Borrowed(self.slice(start, end)))) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Every children `Vec` in the tree, depth first. + fn child_vecs<'f, 'a>(chunks: &'f [Chunk<'a>], out: &mut Vec<&'f Vec>>) { + for c in chunks { + match &c.body { + Body::List { children, .. } | Body::Chunks(children) => { + out.push(children); + child_vecs(children, out); + } + Body::Data(_) | Body::OpaqueList { .. } => {} + } + } + } + + /// Every sibling list is allocated once at its exact length. + #[test] + fn every_sibling_list_is_allocated_once_at_its_exact_length() { + let inner: Vec> = (0..37u8).map(|i| Chunk::data(*b"cdat", vec![i; usize::from(i % 5)])).collect(); + let middle: Vec> = (0..9).map(|_| Chunk::list(*b"tdbs", inner.clone())).collect(); + let file = AepFile { chunks: vec![Chunk::data(*b"head", vec![0; 3]), Chunk::list(*b"Fold", middle)], trailer: Cow::Borrowed(&[]) }; + let bytes = crate::write(&file).expect("write"); + let parsed = parse(&bytes).expect("parse"); + assert_eq!(crate::write(&parsed).expect("rewrite"), bytes); + let mut vecs = vec![&parsed.chunks]; + child_vecs(&parsed.chunks, &mut vecs); + assert_eq!(vecs.len(), 11); + // `try_reserve_exact` gives exactly the requested capacity with std's allocator today; a + // Vec grown push by push would have rounded up to a power of two (37 -> 64, 9 -> 16). + for v in vecs { + assert_eq!(v.capacity(), v.len(), "a sibling Vec grew past its length"); + } + } + + /// The preallocation is bounded by the input and the chunk limit. + #[test] + fn the_preallocation_is_bounded_by_the_input_and_the_chunk_limit() { + // 1000 empty headers: the most chunks the bytes can hold. + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + let parser = Parser { data: &data, limits: Limits::default(), count: 0 }; + assert_eq!(parser.count_siblings(12, data.len()), 1000); + assert!(parser.count_siblings(12, data.len()) <= (data.len() - 12) / 8); + // A header whose size runs past the end stops the count; a stray tail is not counted. + assert_eq!(parser.count_siblings(12, data.len() - 3), 999); + let mut big = data.clone(); + big[16..20].copy_from_slice(&u32::MAX.to_be_bytes()); + let parser = Parser { data: &big, limits: Limits::default(), count: 0 }; + assert_eq!(parser.count_siblings(12, big.len()), 0); + let f = parse(&data).expect("parse"); + assert_eq!((f.chunks.len(), f.chunks.capacity()), (1000, 1000)); + // Under a tighter limit the parse fails as before, without sizing for more than allowed. + let tight = Limits { max_depth: 64, max_chunks: 10 }; + assert_eq!(parse_with_limits(&data, tight), Err(AepError::TooManyChunks)); + // The reservation never exceeds what the chunk limit still allows. + let mut parser = Parser { data: &data, limits: tight, count: 0 }; + assert_eq!(parser.capacity_for(12, data.len()), 10); + parser.count = 7; + assert_eq!(parser.capacity_for(12, data.len()), 3); + parser.count = 11; + assert_eq!(parser.capacity_for(12, data.len()), 0); + let parser = Parser { data: &data, limits: Limits::default(), count: 0 }; + assert_eq!(parser.capacity_for(12, data.len()), 1000); + } + + /// `LIST Fold` around `inner`, followed by 6 bytes too short for a header, so the list's + /// sequence fails and the list is kept opaque. + fn broken_level(inner: &[u8]) -> Vec { + let mut body = b"Fold".to_vec(); + body.extend_from_slice(inner); + body.extend_from_slice(&[0xee; 6]); + let mut out = b"LIST".to_vec(); + out.extend_from_slice(&u32::try_from(body.len()).expect("small").to_be_bytes()); + out.extend_from_slice(&body); + out + } + + /// Nested lists with broken tails parse each header once. + #[test] + fn nested_lists_with_broken_tails_parse_each_header_once() { + // A wide, well-formed list at the bottom, then 50 levels that each fail and fall back to + // opaque: every level re-parses its child before giving up. + let mut wide = b"Fold".to_vec(); + wide.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); + let mut level = b"LIST".to_vec(); + level.extend_from_slice(&u32::try_from(wide.len()).expect("small").to_be_bytes()); + level.extend_from_slice(&wide); + for _ in 0..50 { + level = broken_level(&level); + } + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend_from_slice(&level); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + // 1 + 50 + 1000 headers in the file: the parse counts each exactly once (the count spans + // every attempt), so the work stays linear in the input. + let headers = 1 + 50 + 1000; + let f = parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers }).expect("parse"); + assert_eq!(parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers - 1 }), Err(AepError::TooManyChunks)); + // The outermost list keeps its bytes, and the file writes back unchanged. + let [top] = f.chunks.as_slice() else { panic!("one top-level chunk") }; + assert!(matches!(&top.body, Body::OpaqueList { list_type, data } if list_type == b"Fold" && data.len() + 12 == level.len())); + assert_eq!(crate::write(&f).expect("write"), data); + } +} diff --git a/crates/aep/src/settings.rs b/crates/aep/src/settings.rs index 1193dbc39..440983805 100644 --- a/crates/aep/src/settings.rs +++ b/crates/aep/src/settings.rs @@ -2,8 +2,10 @@ //! linear-light switches, the time display and the frame count start. Cases 620-634: one change //! each against the base project 620; every field below is the only byte (or chunk) that changes. +use crate::bytes::be_u32; use crate::chunk::AepFile; use crate::footage::json_string; +use crate::index::{Node, Root, TreeIndex}; /// The time display style (`nhed` byte 8, feet + frames byte 11, film type byte 13). #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -54,7 +56,17 @@ pub struct ProjectSettings { impl ProjectSettings { /// Reads the settings from the top-level chunks. pub fn read(file: &AepFile<'_>) -> ProjectSettings { - let nhed = file.chunk(b"nhed").and_then(|c| c.bytes()); + Self::of(Root::from(file)) + } + + /// Reads the settings from the top-level chunks of an indexed file. + pub fn read_index(index: &TreeIndex<'_>) -> ProjectSettings { + Self::of(Root::from(index)) + } + + /// Reads the settings from the top-level chunks of either tree. + pub fn of(file: Root<'_, '_>) -> ProjectSettings { + let nhed = file.chunk(b"nhed").and_then(Node::bytes); let byte = |i: usize| nhed.and_then(|b| b.get(i).copied()); let bits_per_channel = byte(15).and_then(|v| match v { 0 => Some(8), @@ -73,9 +85,9 @@ impl ProjectSettings { 1 => Some(1), _ => None, }); - let flag = |id: &[u8; 4]| file.chunk(id).and_then(|c| c.bytes()).and_then(|b| b.first().copied()) == Some(1); - let working_gamma_24 = file.chunk(b"dwga").and_then(|c| c.bytes()).and_then(|b| b.get(..4)).map(|b| b != [0, 0, 0, 0]); - let scene_compensation = file.chunk(b"acer").and_then(|c| c.bytes()).and_then(|b| b.first().copied()).map(|v| v != 0); + let flag = |id: &[u8; 4]| file.chunk(id).and_then(Node::bytes).and_then(|b| b.first().copied()) == Some(1); + let working_gamma_24 = file.chunk(b"dwga").and_then(Node::bytes).and_then(|b| b.get(..4)).map(|b| b != [0, 0, 0, 0]); + let scene_compensation = file.chunk(b"acer").and_then(Node::bytes).and_then(|b| b.first().copied()).map(|v| v != 0); ProjectSettings { bits_per_channel, working_space: working_space(file), @@ -90,9 +102,10 @@ impl ProjectSettings { } /// The working space: the `Utf8` right after `PwCs`. -fn working_space(file: &AepFile<'_>) -> Option { - let at = file.chunks.iter().position(|c| c.is(b"PwCs"))?; - let json = file.chunks.get(at.checked_add(1)?).filter(|c| c.is(b"Utf8"))?.bytes()?; +fn working_space(file: Root<'_, '_>) -> Option { + let mut chunks = file.chunks(); + chunks.find(|c| c.is(b"PwCs"))?; + let json = chunks.next().filter(|c| c.is(b"Utf8"))?.bytes()?; let trimmed: Vec = json.iter().copied().filter(|b| !b.is_ascii_whitespace() && *b != 0).collect(); if trimmed == b"{}" { return Some(WorkingSpace::None); @@ -130,7 +143,7 @@ fn base64_decode(text: &str) -> Option> { /// The profile description (ICC.1 tag `desc`): a v2 `desc` (ASCII) or a v4 `mluc` (its first /// record, UTF-16BE). `None` when the profile or the tag is cut short. fn icc_description(icc: &[u8]) -> Option { - let be32 = |at: usize| icc.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes); + let be32 = |at: usize| be_u32(icc, at); let count = be32(128)?; let tag = (0..count.min(1024)).find_map(|i| { let at = 132usize.checked_add(usize::try_from(i).ok()?.checked_mul(12)?)?; @@ -141,13 +154,13 @@ fn icc_description(icc: &[u8]) -> Option { let body = icc.get(off..off.checked_add(len)?)?; let text = match body.get(..4)? { b"desc" => { - let n = usize::try_from(u32::from_be_bytes(body.get(8..12)?.try_into().ok()?)).ok()?; + let n = usize::try_from(be_u32(body, 8)?).ok()?; let ascii = body.get(12..12usize.checked_add(n)?)?; String::from_utf8_lossy(ascii.split(|b| *b == 0).next().unwrap_or_default()).into_owned() } b"mluc" => { - let n = usize::try_from(u32::from_be_bytes(body.get(20..24)?.try_into().ok()?)).ok()?; - let at = usize::try_from(u32::from_be_bytes(body.get(24..28)?.try_into().ok()?)).ok()?; + let n = usize::try_from(be_u32(body, 20)?).ok()?; + let at = usize::try_from(be_u32(body, 24)?).ok()?; let units: Vec = body.get(at..at.checked_add(n)?)?.as_chunks::<2>().0.iter().map(|p| u16::from_be_bytes(*p)).collect(); String::from_utf16_lossy(&units) } diff --git a/crates/aep/src/shapes.rs b/crates/aep/src/shapes.rs index 864cfa55b..28b572506 100644 --- a/crates/aep/src/shapes.rs +++ b/crates/aep/src/shapes.rs @@ -10,7 +10,7 @@ //! points are in pixels relative to the layer origin. use crate::masks::ShapePath; -use crate::typed::{Layer, PropGroup, PropNode, Property}; +use crate::typed::{Layer, PropGroup, PropNode}; use crate::values::{Tracked, read, read_opt}; /// The stroke line cap (`ADBE Vector Stroke Line Cap`, stored as a double; butt is the default and @@ -145,7 +145,7 @@ fn number(group: &PropGroup<'_, '_>, name: &str) -> Option> { fn paths_of(group: &PropGroup<'_, '_>) -> Vec { let Some(PropNode::Other(oms)) = group.get("ADBE Vector Shape") else { return Vec::new() }; let Some(omks) = oms.child_list(b"omks") else { return Vec::new() }; - omks.children().iter().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect() + omks.children().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect() } fn item(match_name: String, group: &PropGroup<'_, '_>) -> ShapeItem { @@ -269,12 +269,3 @@ impl<'f, 'a> Layer<'f, 'a> { .collect() } } - -impl<'f, 'a> Property<'f, 'a> { - /// The ARGB fractions of a static colour property (4 components stored as doubles 0..255). - pub fn color_argb(&self) -> Option<[f64; 4]> { - let v = self.static_value()?; - let [a, r, g, b] = *v.as_slice().first_chunk::<4>()?; - Some([a / 255.0, r / 255.0, g / 255.0, b / 255.0]) - } -} diff --git a/crates/aep/src/textdoc.rs b/crates/aep/src/textdoc.rs index 373fd40db..1e7569b67 100644 --- a/crates/aep/src/textdoc.rs +++ b/crates/aep/src/textdoc.rs @@ -5,8 +5,11 @@ //! as `(` + BOM `fe ff` + UTF-16BE + `)` with `\` escapes. [`parse_text_dict`] reads it (depth //! limited, never panics) and [`Layer::text_document`] pulls out the verified fields. -use crate::Chunk; +use std::borrow::Cow; +use std::sync::LazyLock; + use crate::bytes::{be_u32, text}; +use crate::index::Node; use crate::typed::{Comp, Layer, Property}; /// How deep dictionaries and arrays may nest before the parser gives up. @@ -73,15 +76,99 @@ impl TextValue { _ => None, } } +} - fn key_text(&self) -> String { +/// The text of a key the way the dictionary stores it: a `/name` as written, any other value in +/// its canonical form (`06` and `+6` are `6`, `1.0` is `1`, a string its decoded text). +fn owned_key(value: &V<'_>) -> String { + match value { + V::Name(s) | V::Token(s) => text(s), + V::Str(utf16) => decode_utf16be(utf16), + V::Int(i) => i.to_string(), + V::Float(f) => f.to_string(), + V::Bool(b) => b.to_string(), + V::Bytes(b) => text(b), + V::Dict(_) | V::Array(_) => String::new(), + } +} + +/// A value of the text dictionary as [`TextDocument::parse`] reads it: it borrows names, bare +/// words and strings from the body, so a document is read without a `String` per token. A key is +/// borrowed when it is a `/name` (every key After Effects writes); its text is the same as the +/// [`TextValue`] key's. [`V::into_owned`] gives the public [`TextValue`]. +#[derive(Debug, Clone)] +enum V<'b> { + Dict(Vec<(Cow<'b, str>, V<'b>)>), + Array(Vec>), + /// A string that started with the byte order mark: the UTF-16BE bytes after it, unescaped. + Str(Cow<'b, [u8]>), + Bytes(Cow<'b, [u8]>), + Name(&'b [u8]), + Int(i64), + Float(f64), + Bool(bool), + Token(&'b [u8]), +} + +impl<'b> V<'b> { + /// The value of a dictionary key (the last one when a key repeats). + fn get(&self, key: &str) -> Option<&V<'b>> { match self { - Self::Name(s) | Self::Str(s) | Self::Token(s) => s.clone(), - Self::Int(i) => i.to_string(), - Self::Float(f) => f.to_string(), - Self::Bool(b) => b.to_string(), - Self::Bytes(b) => text(b), - Self::Dict(_) | Self::Array(_) => String::new(), + Self::Dict(pairs) => pairs.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + fn at(&self, index: usize) -> Option<&V<'b>> { + match self { + Self::Array(items) => items.get(index), + _ => None, + } + } + + /// The decoded text of a string value. + fn string(&self) -> Option { + match self { + Self::Str(utf16) => Some(decode_utf16be(utf16)), + _ => None, + } + } + + fn as_f64(&self) -> Option { + match self { + Self::Int(i) => Some(*i as f64), + Self::Float(f) => Some(*f), + _ => None, + } + } + + fn as_i64(&self) -> Option { + match self { + Self::Int(i) => Some(*i), + _ => None, + } + } + + /// The key a value makes when it is written in a key position. + fn into_key(self) -> Cow<'b, str> { + match self { + Self::Name(s) => String::from_utf8_lossy(s), + other => Cow::Owned(owned_key(&other)), + } + } + + /// The public form. Recursion is bounded: a parsed value nests at most [`MAX_DEPTH`] + 1 deep. + fn into_owned(self) -> TextValue { + match self { + Self::Dict(pairs) => TextValue::Dict(pairs.into_iter().map(|(k, v)| (k.into_owned(), v.into_owned())).collect()), + Self::Array(items) => TextValue::Array(items.into_iter().map(V::into_owned).collect()), + Self::Str(utf16) => TextValue::Str(decode_utf16be(&utf16)), + Self::Bytes(b) => TextValue::Bytes(b.into_owned()), + Self::Name(s) => TextValue::Name(text(s)), + Self::Int(i) => TextValue::Int(i), + Self::Float(f) => TextValue::Float(f), + Self::Bool(b) => TextValue::Bool(b), + Self::Token(s) => TextValue::Token(text(s)), } } } @@ -89,32 +176,44 @@ impl TextValue { struct Parser<'b> { b: &'b [u8], i: usize, + /// The pairs of the dictionaries being read, innermost last: a dictionary's pairs are moved + /// into a vector of their exact size when it closes (one allocation per dictionary instead of + /// one per doubling). + pairs: Vec<(Cow<'b, str>, V<'b>)>, + /// The same for the items of arrays. + items: Vec>, } +/// Whitespace between tokens. fn is_ws(c: u8) -> bool { matches!(c, b' ' | b'\t' | b'\r' | b'\n') } +/// A byte that ends a bare word. fn is_delimiter(c: u8) -> bool { is_ws(c) || matches!(c, b'/' | b'[' | b']' | b'<' | b'>' | b'(' | b')') } -impl Parser<'_> { +impl<'b> Parser<'b> { + /// The next byte, `None` at the end. fn peek(&self) -> Option { self.b.get(self.i).copied() } + /// Moves past whitespace. fn skip_ws(&mut self) { while self.peek().is_some_and(is_ws) { self.i = self.i.saturating_add(1); } } + /// True when the unread bytes start with `s`. fn starts_with(&self, s: &[u8]) -> bool { self.b.get(self.i..).is_some_and(|rest| rest.starts_with(s)) } - fn word(&mut self) -> &[u8] { + /// The bare word at the position (up to the next delimiter), borrowed from the body. + fn word(&mut self) -> &'b [u8] { let start = self.i; while self.peek().is_some_and(|c| !is_delimiter(c)) { self.i = self.i.saturating_add(1); @@ -122,79 +221,106 @@ impl Parser<'_> { self.b.get(start..self.i).unwrap_or(&[]) } - fn parse(&mut self, depth: usize) -> Option { + /// The body of a `( ... )` string after the `(`, with `\` escapes resolved: borrowed when it + /// has none. `None` when the string or an escape is not closed. + fn string_body(&mut self) -> Option> { + let rest = self.b.get(self.i..)?; + let stop = rest.iter().position(|c| matches!(c, b')' | b'\\'))?; + let head = rest.get(..stop)?; + self.i = self.i.saturating_add(stop); + if self.peek()? == b')' { + self.i = self.i.saturating_add(1); + return Some(Cow::Borrowed(head)); + } + let mut out = head.to_vec(); + loop { + let c = self.peek()?; + if c == b'\\' { + out.push(*self.b.get(self.i.saturating_add(1))?); + self.i = self.i.saturating_add(2); + } else if c == b')' { + self.i = self.i.saturating_add(1); + return Some(Cow::Owned(out)); + } else { + out.push(c); + self.i = self.i.saturating_add(1); + } + } + } + + /// The value at the position, `None` when it is malformed or nested deeper than the limit. + fn parse(&mut self, depth: usize) -> Option> { self.skip_ws(); if depth > MAX_DEPTH { return None; } if self.starts_with(b"<<") { self.i = self.i.saturating_add(2); - let mut pairs = Vec::new(); + // On an error the pairs read so far stay on the stack: the error ends the whole parse. + let mark = self.pairs.len(); loop { self.skip_ws(); if self.starts_with(b">>") { self.i = self.i.saturating_add(2); - return Some(TextValue::Dict(pairs)); + return Some(V::Dict(self.pairs.drain(mark..).collect())); } let key = self.parse(depth.saturating_add(1))?; let value = self.parse(depth.saturating_add(1))?; - pairs.push((key.key_text(), value)); + self.pairs.push((key.into_key(), value)); } } match self.peek()? { b'[' => { self.i = self.i.saturating_add(1); - let mut items = Vec::new(); + let mark = self.items.len(); loop { self.skip_ws(); if self.peek()? == b']' { self.i = self.i.saturating_add(1); - return Some(TextValue::Array(items)); + return Some(V::Array(self.items.drain(mark..).collect())); } - items.push(self.parse(depth.saturating_add(1))?); + let item = self.parse(depth.saturating_add(1))?; + self.items.push(item); } } b'(' => { self.i = self.i.saturating_add(1); - let mut out = Vec::new(); - loop { - let c = self.peek()?; - if c == b'\\' { - out.push(*self.b.get(self.i.saturating_add(1))?); - self.i = self.i.saturating_add(2); - } else if c == b')' { - self.i = self.i.saturating_add(1); - break; - } else { - out.push(c); - self.i = self.i.saturating_add(1); - } - } - Some(match out.strip_prefix(&[0xfe, 0xff]) { - Some(utf16) => TextValue::Str(decode_utf16be(utf16)), - None => TextValue::Bytes(out), + let body = self.string_body()?; + Some(if body.starts_with(&[0xfe, 0xff]) { + V::Str(match body { + Cow::Borrowed(b) => Cow::Borrowed(b.get(2..).unwrap_or(&[])), + Cow::Owned(mut v) => { + let n = v.len().min(2); + v.drain(..n); + Cow::Owned(v) + } + }) + } else { + V::Bytes(body) }) } b'/' => { self.i = self.i.saturating_add(1); - Some(TextValue::Name(text(self.word()))) + Some(V::Name(self.word())) } _ => { let word = self.word(); if word.is_empty() { return None; } - let w = text(word); - Some(match w.as_str() { - "true" => TextValue::Bool(true), - "false" => TextValue::Bool(false), + // A word that is not UTF-8 reads as text with replacement characters, which is + // neither a boolean nor a number: a token. + let Ok(w) = std::str::from_utf8(word) else { return Some(V::Token(word)) }; + Some(match w { + "true" => V::Bool(true), + "false" => V::Bool(false), _ => match w.parse::() { - Ok(i) => TextValue::Int(i), + Ok(i) => V::Int(i), // `parse` also takes `nan`, `inf` and overflowing exponents; those are not // numbers a text document holds, so they stay tokens and read as missing. Err(_) => match w.parse::() { - Ok(f) if f.is_finite() => TextValue::Float(f), - _ => TextValue::Token(w), + Ok(f) if f.is_finite() => V::Float(f), + _ => V::Token(word), }, }, }) @@ -203,6 +329,7 @@ impl Parser<'_> { } } +/// A big-endian UTF-16 string as text (unpaired surrogates become U+FFFD). fn decode_utf16be(bytes: &[u8]) -> String { let (pairs, rest) = bytes.as_chunks::<2>(); let units = pairs.iter().map(|p| u16::from_be_bytes(*p)); @@ -213,11 +340,9 @@ fn decode_utf16be(bytes: &[u8]) -> String { s } -/// Parses the body of a `btdk` list into its top-level `key value` pairs (as a [`TextValue::Dict`]). -/// Parsing stops silently at the first syntax error or at nesting deeper than 64 levels; what was -/// read before is returned. -pub fn parse_text_dict(body: &[u8]) -> TextValue { - let mut parser = Parser { b: body, i: 0 }; +/// The top-level `key value` pairs of a `btdk` body, borrowed (see [`parse_text_dict`]). +fn parse_dict(body: &[u8]) -> V<'_> { + let mut parser = Parser { b: body, i: 0, pairs: Vec::new(), items: Vec::new() }; let mut pairs = Vec::new(); loop { parser.skip_ws(); @@ -226,13 +351,20 @@ pub fn parse_text_dict(body: &[u8]) -> TextValue { } let Some(key) = parser.parse(0) else { break }; let Some(value) = parser.parse(0) else { break }; - pairs.push((key.key_text(), value)); + pairs.push((key.into_key(), value)); } - TextValue::Dict(pairs) + V::Dict(pairs) +} + +/// Parses the body of a `btdk` list into its top-level `key value` pairs (as a [`TextValue::Dict`]). +/// Parsing stops silently at the first syntax error or at nesting deeper than 64 levels; what was +/// read before is returned. +pub fn parse_text_dict(body: &[u8]) -> TextValue { + parse_dict(body).into_owned() } /// The run style slots (`RUN/6/0[n]/0/0/6/`) that are decoded; every other slot is compared -/// with its default (`style_defaults`) and listed in +/// with its default (`STYLE_DEFAULTS`) and listed in /// [`TextDocument::undecoded_style_fields`] when it differs. pub const DECODED_STYLE_SLOTS: &[&str] = &["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "11", "12", "13", "18", "35", "36", "52", "53", "54", "56", "57", "58", "62", "63", "70"]; @@ -241,25 +373,27 @@ pub const DECODED_STYLE_SLOTS: &[&str] = pub const DECODED_PARAGRAPH_SLOTS: &[&str] = &["0", "1", "2", "3", "4", "5", "8", "9", "21", "29", "33"]; /// A number slot. -fn val(v: f64) -> TextValue { - TextValue::Float(v) +fn val(v: f64) -> V<'static> { + V::Float(v) } -fn dict(pairs: Vec<(&str, TextValue)>) -> TextValue { - TextValue::Dict(pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) +/// A dictionary value with these keys, for the built-in defaults. +fn dict(pairs: Vec<(&'static str, V<'static>)>) -> V<'static> { + V::Dict(pairs.into_iter().map(|(k, v)| (Cow::Borrowed(k), v)).collect()) } -fn numbers(v: &[f64]) -> TextValue { - TextValue::Array(v.iter().map(|x| val(*x)).collect()) +/// An array of numbers, for the built-in defaults. +fn numbers(v: &[f64]) -> V<'static> { + V::Array(v.iter().map(|x| val(*x)).collect()) } /// The default of every run style slot that is not decoded and not neutral (zero, `false`, /// empty, `/nil`): the value an untouched point text holds in every sample (110, 243-245). A slot /// with a neutral default is left out; [`undecoded_fields`] treats a missing default as neutral. -fn style_defaults() -> TextValue { - let paint = - |a: f64| dict(vec![("99", TextValue::Name("SimplePaint".into())), ("0", dict(vec![("0", val(1.0)), ("1", numbers(&[1.0, 1.0, 1.0, a]))]))]); - let class = |name: &str| dict(vec![("99", TextValue::Name(name.into()))]); +/// Built once. +static STYLE_DEFAULTS: LazyLock> = LazyLock::new(|| { + let paint = |a: f64| dict(vec![("99", V::Name(b"SimplePaint")), ("0", dict(vec![("0", val(1.0)), ("1", numbers(&[1.0, 1.0, 1.0, a]))]))]); + let class = |name: &'static [u8]| dict(vec![("99", V::Name(name))]); dict(vec![ ("37", val(2.0)), ("41", val(2.0)), @@ -269,24 +403,24 @@ fn style_defaults() -> TextValue { ("46", val(7.0)), ("49", val(-1.0)), ("50", val(-1.0)), - ("55", class("SimpleBlender")), + ("55", class(b"SimpleBlender")), ("64", val(4.0)), ("71", val(4.0)), - ("77", TextValue::Bool(true)), - ("78", TextValue::Bool(true)), + ("77", V::Bool(true)), + ("78", V::Bool(true)), ("79", paint(0.0)), ("82", val(3.0)), ("83", val(3.0)), - ("86", class("SimpleCustomFeature")), + ("86", class(b"SimpleCustomFeature")), ("87", val(100.0)), - ("88", TextValue::Bool(true)), + ("88", V::Bool(true)), ("95", dict(vec![("0", val(0.0)), ("1", val(0.0))])), - ("96", TextValue::Bool(true)), + ("96", V::Bool(true)), ]) -} +}); -/// The same for the paragraph slots (110, 243-245). -fn paragraph_defaults() -> TextValue { +/// The same for the paragraph slots (110, 243-245). Built once. +static PARAGRAPH_DEFAULTS: LazyLock> = LazyLock::new(|| { dict(vec![ ("6", val(1.0)), ("7", val(1.2)), @@ -294,30 +428,35 @@ fn paragraph_defaults() -> TextValue { ("11", val(2.0)), ("12", val(2.0)), ("14", val(36.0)), - ("15", TextValue::Bool(true)), + ("15", V::Bool(true)), ("16", val(0.5)), ("17", numbers(&[0.8, 1.0, 1.33])), ("18", numbers(&[0.0, 0.0, 0.0])), ("19", numbers(&[1.0, 1.0, 1.0])), ("20", val(6.0)), ("22", val(1.0)), - ("23", TextValue::Bool(true)), + ("23", V::Bool(true)), ("24", val(1.0)), - ("26", TextValue::Bool(true)), + ("26", V::Bool(true)), ("31", val(36.0)), ("35", val(1.0)), ("40", val(2.0)), ]) -} +}); -/// Equal values; numbers compare by value (`0` equals `0.0`). -fn same(a: &TextValue, b: &TextValue) -> bool { +/// Equal values; numbers compare by value (`0` equals `0.0`), names and words by their text, +/// strings by their decoded text. +fn same(a: &V<'_>, b: &V<'_>) -> bool { match (a, b) { - (TextValue::Dict(x), TextValue::Dict(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.iter().any(|(k2, v2)| k == k2 && same(v, v2))), - (TextValue::Array(x), TextValue::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)), + (V::Dict(x), V::Dict(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.iter().any(|(k2, v2)| k == k2 && same(v, v2))), + (V::Array(x), V::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)), + (V::Str(x), V::Str(y)) => x == y || decode_utf16be(x) == decode_utf16be(y), + (V::Bytes(x), V::Bytes(y)) => x == y, + (V::Name(x), V::Name(y)) | (V::Token(x), V::Token(y)) => x == y || text(x) == text(y), + (V::Bool(x), V::Bool(y)) => x == y, _ => match (a.as_f64(), b.as_f64()) { (Some(p), Some(q)) => p == q, - _ => a == b, + _ => false, }, } } @@ -326,12 +465,12 @@ fn same(a: &TextValue, b: &TextValue) -> bool { /// listed when it holds something else (a neutral value carries nothing that could be lost). /// `/nil` is how an untouched document stores a slot without a value (244: paragraph `/27`, `/28`, /// `/36`). -fn is_neutral(v: &TextValue) -> bool { +fn is_neutral(v: &V<'_>) -> bool { match v { - TextValue::Name(n) => n == "nil", - TextValue::Bool(b) => !b, - TextValue::Array(a) => a.is_empty(), - TextValue::Dict(d) => d.is_empty(), + V::Name(n) => *n == b"nil", + V::Bool(b) => !b, + V::Array(a) => a.is_empty(), + V::Dict(d) => d.is_empty(), other => other.as_f64() == Some(0.0), } } @@ -356,13 +495,13 @@ pub const MAX_UNDECODED_FIELDS: usize = 64; /// Adds to `out` the slots of `actual` that are not decoded and differ from `sampled`, each once /// and at most [`MAX_UNDECODED_FIELDS`] in all. -fn undecoded_fields(actual: &TextValue, sampled: Option<&TextValue>, decoded: &[&str], neutral: &[(&str, &[i64])], out: &mut Vec) { - let TextValue::Dict(pairs) = actual else { return }; +fn undecoded_fields(actual: &V<'_>, sampled: Option<&V<'_>>, decoded: &[&str], neutral: &[(&str, &[i64])], out: &mut Vec) { + let V::Dict(pairs) = actual else { return }; for (key, value) in pairs { if out.len() >= MAX_UNDECODED_FIELDS { return; } - if decoded.contains(&key.as_str()) || out.contains(key) { + if decoded.contains(&key.as_ref()) || out.iter().any(|o| o == key) { continue; } if neutral.iter().any(|(slot, values)| slot == key && value.as_i64().is_some_and(|v| values.contains(&v))) { @@ -373,7 +512,7 @@ fn undecoded_fields(actual: &TextValue, sampled: Option<&TextValue>, decoded: &[ None => !is_neutral(value), }; if differs { - out.push(key.clone()); + out.push(key.to_string()); } } } @@ -433,13 +572,13 @@ pub struct KernRun { /// The manual kerning list of a text run dictionary (`RUN/8/0`): entries `<< /0 << /0 amount >> /1 /// length >>` (554 kerns each of `HHHH` by 50; the closing `\r` has an entry without an amount). -fn kern_runs(run: &TextValue) -> Vec { - let Some(TextValue::Array(items)) = run.get("8").and_then(|v| v.get("0")) else { return Vec::new() }; +fn kern_runs(run: &V<'_>) -> Vec { + let Some(V::Array(items)) = run.get("8").and_then(|v| v.get("0")) else { return Vec::new() }; let runs: Vec = items .iter() .filter_map(|e| { let length = e.get("1").and_then(usize_of)?; - let amount = e.get("0").and_then(|v| v.get("0")).and_then(TextValue::as_f64).filter(|v| v.is_finite()); + let amount = e.get("0").and_then(|v| v.get("0")).and_then(V::as_f64).filter(|v| v.is_finite()); Some(KernRun { length, amount }) }) .collect(); @@ -602,7 +741,7 @@ pub struct StyleRun { impl StyleRun { /// The style of the sampled untouched document (244), used for a damaged first run. - pub(crate) const SAMPLED: StyleRun = StyleRun { + pub const SAMPLED: StyleRun = StyleRun { length: 0, font_size: 100.0, fill_argb: [1.0; 4], @@ -645,24 +784,26 @@ pub struct TextBox { pub height: f64, } -fn colour_of(style: &TextValue, slot: &str) -> Option<[f64; 4]> { +/// The RGBA colour in a style slot (`slot/0/1`), `None` when it is not four numbers. +fn colour_of(style: &V<'_>, slot: &str) -> Option<[f64; 4]> { let c = style.get(slot)?.get("0")?.get("1")?; Some([c.at(0)?.as_f64()?, c.at(1)?.as_f64()?, c.at(2)?.as_f64()?, c.at(3)?.as_f64()?]) } -fn usize_of(v: &TextValue) -> Option { +/// A non-negative integer value as `usize`. +fn usize_of(v: &V<'_>) -> Option { usize::try_from(v.as_i64()?).ok() } /// A finite number slot of a style, `default` when it is missing or not a finite number. -fn num(style: &TextValue, slot: &str, default: f64) -> f64 { - style.get(slot).and_then(TextValue::as_f64).filter(|v| v.is_finite()).unwrap_or(default) +fn num(style: &V<'_>, slot: &str, default: f64) -> f64 { + style.get(slot).and_then(V::as_f64).filter(|v| v.is_finite()).unwrap_or(default) } /// A boolean slot of a style, `default` when it is missing or not a boolean. -fn flag(style: &TextValue, slot: &str, default: bool) -> bool { +fn flag(style: &V<'_>, slot: &str, default: bool) -> bool { match style.get(slot) { - Some(TextValue::Bool(b)) => *b, + Some(V::Bool(b)) => *b, _ => default, } } @@ -676,9 +817,9 @@ struct RunNotes { } /// The paragraph runs of a text run dictionary (`RUN/5/0`). -fn paragraph_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { - let Some(TextValue::Array(items)) = run.get("5").and_then(|v| v.get("0")) else { return Vec::new() }; - let sampled = Some(paragraph_defaults()); +fn paragraph_runs(run: &V<'_>, notes: &mut RunNotes) -> Vec { + let Some(V::Array(items)) = run.get("5").and_then(|v| v.get("0")) else { return Vec::new() }; + let sampled = Some(&*PARAGRAPH_DEFAULTS); let mut out: Vec = Vec::with_capacity(items.len()); for e in items { let Some(length) = e.get("1").and_then(usize_of) else { @@ -686,7 +827,7 @@ fn paragraph_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { continue; }; let para = e.get("0").and_then(|v| v.get("0")).and_then(|v| v.get("5")); - let justification = match para.and_then(|p| p.get("0")).and_then(TextValue::as_i64) { + let justification = match para.and_then(|p| p.get("0")).and_then(V::as_i64) { Some(0) => Justification::Left, Some(1) => Justification::Right, Some(2) => Justification::Center, @@ -701,12 +842,12 @@ fn paragraph_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { } }; if let Some(p) = para { - undecoded_fields(p, sampled.as_ref(), DECODED_PARAGRAPH_SLOTS, NEUTRAL_PARAGRAPH_VALUES, &mut notes.paragraph_fields); + undecoded_fields(p, sampled, DECODED_PARAGRAPH_SLOTS, NEUTRAL_PARAGRAPH_VALUES, &mut notes.paragraph_fields); } - let num = |slot: &str| para.and_then(|p| p.get(slot)).and_then(TextValue::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0); - let int = |slot: &str, default: i64| para.and_then(|p| p.get(slot)).and_then(TextValue::as_i64).unwrap_or(default); + let num = |slot: &str| para.and_then(|p| p.get(slot)).and_then(V::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0); + let int = |slot: &str, default: i64| para.and_then(|p| p.get(slot)).and_then(V::as_i64).unwrap_or(default); let flag = |slot: &str, default: bool| match para.and_then(|p| p.get(slot)) { - Some(TextValue::Bool(b)) => *b, + Some(V::Bool(b)) => *b, _ => default, }; out.push(ParagraphRun { @@ -728,9 +869,9 @@ fn paragraph_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { } /// The style runs of a text run dictionary (`RUN/6/0`). -fn style_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { - let Some(TextValue::Array(items)) = run.get("6").and_then(|v| v.get("0")) else { return Vec::new() }; - let sampled = Some(style_defaults()); +fn style_runs(run: &V<'_>, notes: &mut RunNotes) -> Vec { + let Some(V::Array(items)) = run.get("6").and_then(|v| v.get("0")) else { return Vec::new() }; + let sampled = Some(&*STYLE_DEFAULTS); let mut out: Vec = Vec::with_capacity(items.len()); for e in items { let Some(length) = e.get("1").and_then(usize_of) else { @@ -743,31 +884,31 @@ fn style_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { out.push(StyleRun { length, ..prev }); continue; }; - let font_size = style.get("1").and_then(TextValue::as_f64); + let font_size = style.get("1").and_then(V::as_f64); let fill_argb = colour_of(style, "53"); let font_index = style.get("0").and_then(usize_of); if font_size.is_none() || fill_argb.is_none() || font_index.is_none() { notes.incomplete = notes.incomplete.saturating_add(1); } - undecoded_fields(style, sampled.as_ref(), DECODED_STYLE_SLOTS, NEUTRAL_STYLE_VALUES, &mut notes.style_fields); + undecoded_fields(style, sampled, DECODED_STYLE_SLOTS, NEUTRAL_STYLE_VALUES, &mut notes.style_fields); out.push(StyleRun { length, font_size: font_size.unwrap_or(prev.font_size), fill_argb: fill_argb.unwrap_or(prev.fill_argb), stroke_argb: colour_of(style, "54"), - tracking: style.get("8").and_then(TextValue::as_f64).unwrap_or(0.0), - faux_bold: matches!(style.get("2"), Some(TextValue::Bool(true))), - faux_italic: matches!(style.get("3"), Some(TextValue::Bool(true))), - caps: match style.get("12").and_then(TextValue::as_i64) { + tracking: style.get("8").and_then(V::as_f64).unwrap_or(0.0), + faux_bold: matches!(style.get("2"), Some(V::Bool(true))), + faux_italic: matches!(style.get("3"), Some(V::Bool(true))), + caps: match style.get("12").and_then(V::as_i64) { None | Some(0) => Caps::Normal, Some(1) => Caps::Small, Some(2) => Caps::All, Some(other) => Caps::Other(other), }, - auto_leading: matches!(style.get("4"), Some(TextValue::Bool(true))), - leading: style.get("5").and_then(TextValue::as_f64), + auto_leading: matches!(style.get("4"), Some(V::Bool(true))), + leading: style.get("5").and_then(V::as_f64), font_index: font_index.unwrap_or(prev.font_index), - baseline: match style.get("13").and_then(TextValue::as_i64) { + baseline: match style.get("13").and_then(V::as_i64) { None | Some(0) => FontBaseline::Normal, Some(1) => FontBaseline::Superscript, Some(2) => FontBaseline::Subscript, @@ -776,22 +917,22 @@ fn style_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { horizontal_scale: num(style, "6", 1.0), vertical_scale: num(style, "7", 1.0), baseline_shift: num(style, "9", 0.0), - auto_kern: match style.get("11").and_then(TextValue::as_i64) { + auto_kern: match style.get("11").and_then(V::as_i64) { Some(0) => AutoKern::None, None | Some(1) => AutoKern::Metrics, Some(2) => AutoKern::Optical, Some(other) => AutoKern::Other(other), }, ligatures: flag(style, "18", false), - baseline_direction: style.get("35").and_then(TextValue::as_i64).unwrap_or(1), + baseline_direction: style.get("35").and_then(V::as_i64).unwrap_or(1), tsume: num(style, "36", 0.0), no_break: flag(style, "52", false), apply_fill: flag(style, "56", true), apply_stroke: flag(style, "57", false), stroke_over_fill: flag(style, "58", true), - line_join: style.get("62").and_then(TextValue::as_i64).unwrap_or(0), + line_join: style.get("62").and_then(V::as_i64).unwrap_or(0), stroke_width: num(style, "63", 1.0), - digit_set: style.get("70").and_then(TextValue::as_i64).unwrap_or(0), + digit_set: style.get("70").and_then(V::as_i64).unwrap_or(0), }); } out @@ -799,13 +940,13 @@ fn style_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { /// The box of paragraph text from the frame dictionary `/0/8/0[0]/0`: key `/1/0` holds 16 x, y pairs /// that trace the rectangle, and `/2/0` is 1; both keys are absent for point text. -fn text_box(top: &TextValue) -> Option { +fn text_box(top: &V<'_>) -> Option { let frame = top.get("0")?.get("8")?.get("0")?.at(0)?.get("0")?; if frame.get("2")?.get("0")?.as_i64()? != 1 { return None; } - let TextValue::Array(coords) = frame.get("1")?.get("0")? else { return None }; - let numbers: Vec = coords.iter().map(TextValue::as_f64).collect::>()?; + let V::Array(coords) = frame.get("1")?.get("0")? else { return None }; + let numbers: Vec = coords.iter().map(V::as_f64).collect::>()?; let (pairs, _) = numbers.as_chunks::<2>(); if pairs.is_empty() { return None; @@ -819,18 +960,16 @@ fn text_box(top: &TextValue) -> Option { impl TextDocument { /// Decodes the body of a `btdk` list. pub fn parse(body: &[u8]) -> Option { - let top = parse_text_dict(body); + let top = parse_dict(body); let run = top.get("1")?.get("1")?.at(0)?.get("0")?; - let raw_text = run.get("0")?.as_str()?.to_string(); + let raw_text = run.get("0")?.string()?; let style = run.get("6")?.get("0")?.at(0)?.get("0")?.get("0")?.get("6")?; let fill_argb = colour_of(style, "53")?; let font_index = usize::try_from(style.get("0")?.as_i64()?).ok()?; let mut fonts = Vec::new(); - if let Some(TextValue::Array(list)) = top.get("0").and_then(|v| v.get("1")).and_then(|v| v.get("0")) { - fonts = list - .iter() - .map(|f| f.get("0").and_then(|v| v.get("0")).and_then(|v| v.get("0")).and_then(TextValue::as_str).unwrap_or_default().to_string()) - .collect(); + if let Some(V::Array(list)) = top.get("0").and_then(|v| v.get("1")).and_then(|v| v.get("0")) { + fonts = + list.iter().map(|f| f.get("0").and_then(|v| v.get("0")).and_then(|v| v.get("0")).and_then(V::string).unwrap_or_default()).collect(); } let mut notes = RunNotes::default(); let paragraphs = paragraph_runs(run, &mut notes); @@ -858,7 +997,7 @@ impl TextDocument { .and_then(|v| v.get("0")) .and_then(|v| v.get("2")) .and_then(|v| v.get("1")) - .and_then(TextValue::as_i64), + .and_then(V::as_i64), }) } @@ -882,23 +1021,32 @@ impl TextDocument { } impl<'f, 'a> Layer<'f, 'a> { - /// The text document of a text layer (`LIST btdk` below `ADBE Text Properties`). + /// The Source Text record `LIST btds` (`ADBE Text Document`). It is a direct child of the + /// `ADBE Text Properties` group, which is a direct child of the layer's root `tdgp` + /// (`Layr/tdgp/tdgp/btds` in every sample, and where the exporter writes it), so only that + /// level is searched rather than the whole layer. + fn source_text_record(&self) -> Option> { + let root = self.chunk.child_list(b"tdgp")?; + root.children().filter(|g| g.is_list(b"tdgp")).find_map(|g| g.child_list(b"btds")) + } + + /// The text document of a text layer: the first `LIST btdk` in the Source Text record `btds` + /// (the same documents [`Layer::text_document_count`] counts). pub fn text_document(&self) -> Option { - TextDocument::parse(self.chunk.find_list(b"btdk")?.bytes()?) + TextDocument::parse(self.source_text_record()?.find_list(b"btdk")?.bytes()?) } /// The Source Text property record: the `tdbs` in `btds[ADBE Text Document]` (a placeholder /// in every sample: no keys, no expression). Source Text keyframes and expressions were not /// sampled; a `list` (keys) or an expression in it marks them. pub fn source_text_property(&self) -> Option> { - let btds = self.chunk.descendants().map(|(_, c)| c).find(|c| c.is_list(b"btds"))?; - Property::from_chunk(btds.child_list(b"tdbs")?) + Property::from_chunk(self.source_text_record()?.child_list(b"tdbs")?) } - /// The number of text documents (`LIST btdk`) of the layer: 1 in every sample; more would be - /// one per Source Text keyframe (not sampled). + /// The number of text documents (`LIST btdk`) in the Source Text record: 1 in every sample; + /// more would be one per Source Text keyframe (not sampled). pub fn text_document_count(&self) -> usize { - self.chunk.descendants().filter(|(_, c)| c.is_list(b"btdk")).count() + self.source_text_record().map_or(0, |btds| btds.descendants().filter(|(_, c)| c.is_list(b"btdk")).count()) } } @@ -943,10 +1091,24 @@ pub enum CueType { Other(u32), } +impl<'f, 'a> Node<'f, 'a> { + /// The marker list `LIST mrst` of a marker holder: a layer (`LIST Layr`) or a composition's + /// `SecL` list. A layer's `mrst` is a direct child of its root `tdgp` (`ADBE Marker`, where + /// After Effects and the exporter write it), so only that place is looked at; most layers have + /// none, and searching their whole property tree for it was a large part of an import. Any + /// other holder is searched depth-first. + pub fn marker_list(self) -> Option> { + if self.is_list(b"Layr") { + return self.child_list(b"tdgp")?.child_list(b"mrst"); + } + self.find_list(b"mrst") + } +} + /// Reads the markers below `holder` (a layer or the composition's `SecL` list): the `mrst` list has a /// property whose 16-byte records give the times and one `Nmrd` list per marker with the strings. -fn markers_in(holder: &Chunk<'_>) -> Vec { - let Some(mrst) = holder.find_list(b"mrst") else { return Vec::new() }; +fn markers_in(holder: Node<'_, '_>) -> Vec { + let Some(mrst) = holder.marker_list() else { return Vec::new() }; let Some(prop) = mrst.child_list(b"tdbs").and_then(Property::from_chunk) else { return Vec::new() }; let Some(keys) = prop.keys() else { return Vec::new() }; let scale = prop.time_scale().unwrap_or(0); @@ -956,11 +1118,11 @@ fn markers_in(holder: &Chunk<'_>) -> Vec { .filter_map(|(k, nmrd)| { let time_units = k.time_units()?; // The five strings, in the order comment, chapter, URL, frame target, cue point name. - let mut strings = nmrd.children().iter().filter(|c| c.is(b"Utf8")).map(|c| c.bytes().map(text).unwrap_or_default()); + let mut strings = nmrd.children().filter(|c| c.is(b"Utf8")).map(|c| c.bytes().map(text).unwrap_or_default()); let mut next = || strings.next().unwrap_or_default(); let (comment, chapter, url, frame_target, cue_point_name) = (next(), next(), next(), next(), next()); let extras: Vec = strings.collect(); - let header = nmrd.child(b"NmHd").and_then(Chunk::bytes); + let header = nmrd.child(b"NmHd").and_then(Node::bytes); let duration_seconds = header.and_then(|h| { let (duration, per_second) = (be_u32(h, 8)?, be_u32(h, 12)?); (per_second != 0).then(|| f64::from(duration) / f64::from(per_second)) @@ -1003,9 +1165,647 @@ impl<'f, 'a> Comp<'f, 'a> { } } +/// The dictionary parser and the defaults as they were before they borrowed from the body (#3276), +/// kept as the reference the differential tests compare with. +#[cfg(test)] +mod oracle { + use super::{MAX_DEPTH, MAX_UNDECODED_FIELDS, TextValue}; + use crate::bytes::text; + + pub(super) fn same(a: &TextValue, b: &TextValue) -> bool { + match (a, b) { + (TextValue::Dict(x), TextValue::Dict(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.iter().any(|(k2, v2)| k == k2 && same(v, v2))), + (TextValue::Array(x), TextValue::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)), + _ => match (a.as_f64(), b.as_f64()) { + (Some(p), Some(q)) => p == q, + _ => a == b, + }, + } + } + + pub(super) fn is_neutral(v: &TextValue) -> bool { + match v { + TextValue::Name(n) => n == "nil", + TextValue::Bool(b) => !b, + TextValue::Array(a) => a.is_empty(), + TextValue::Dict(d) => d.is_empty(), + other => other.as_f64() == Some(0.0), + } + } + + pub(super) fn undecoded_fields( + actual: &TextValue, + sampled: Option<&TextValue>, + decoded: &[&str], + neutral: &[(&str, &[i64])], + out: &mut Vec, + ) { + let TextValue::Dict(pairs) = actual else { return }; + for (key, value) in pairs { + if out.len() >= MAX_UNDECODED_FIELDS { + return; + } + if decoded.contains(&key.as_str()) || out.contains(key) { + continue; + } + if neutral.iter().any(|(slot, values)| slot == key && value.as_i64().is_some_and(|v| values.contains(&v))) { + continue; + } + let differs = match sampled.and_then(|s| s.get(key)) { + Some(default) => !same(value, default), + None => !is_neutral(value), + }; + if differs { + out.push(key.clone()); + } + } + } + + impl TextValue { + /// The canonical text of a key, as the owning parser built it. + fn key_text(&self) -> String { + match self { + Self::Name(s) | Self::Str(s) | Self::Token(s) => s.clone(), + Self::Int(i) => i.to_string(), + Self::Float(f) => f.to_string(), + Self::Bool(b) => b.to_string(), + Self::Bytes(b) => text(b), + Self::Dict(_) | Self::Array(_) => String::new(), + } + } + } + + struct Parser<'b> { + b: &'b [u8], + i: usize, + } + + /// Whitespace between tokens. + fn is_ws(c: u8) -> bool { + matches!(c, b' ' | b'\t' | b'\r' | b'\n') + } + + /// A byte that ends a bare word. + fn is_delimiter(c: u8) -> bool { + is_ws(c) || matches!(c, b'/' | b'[' | b']' | b'<' | b'>' | b'(' | b')') + } + + impl Parser<'_> { + /// The next byte, `None` at the end. + fn peek(&self) -> Option { + self.b.get(self.i).copied() + } + + /// Moves past whitespace. + fn skip_ws(&mut self) { + while self.peek().is_some_and(is_ws) { + self.i = self.i.saturating_add(1); + } + } + + /// True when the unread bytes start with `s`. + fn starts_with(&self, s: &[u8]) -> bool { + self.b.get(self.i..).is_some_and(|rest| rest.starts_with(s)) + } + + /// The bare word at the position (up to the next delimiter), borrowed from the body. + fn word(&mut self) -> &[u8] { + let start = self.i; + while self.peek().is_some_and(|c| !is_delimiter(c)) { + self.i = self.i.saturating_add(1); + } + self.b.get(start..self.i).unwrap_or(&[]) + } + + /// The value at the position, `None` when it is malformed or nested deeper than the limit. + fn parse(&mut self, depth: usize) -> Option { + self.skip_ws(); + if depth > MAX_DEPTH { + return None; + } + if self.starts_with(b"<<") { + self.i = self.i.saturating_add(2); + let mut pairs = Vec::new(); + loop { + self.skip_ws(); + if self.starts_with(b">>") { + self.i = self.i.saturating_add(2); + return Some(TextValue::Dict(pairs)); + } + let key = self.parse(depth.saturating_add(1))?; + let value = self.parse(depth.saturating_add(1))?; + pairs.push((key.key_text(), value)); + } + } + match self.peek()? { + b'[' => { + self.i = self.i.saturating_add(1); + let mut items = Vec::new(); + loop { + self.skip_ws(); + if self.peek()? == b']' { + self.i = self.i.saturating_add(1); + return Some(TextValue::Array(items)); + } + items.push(self.parse(depth.saturating_add(1))?); + } + } + b'(' => { + self.i = self.i.saturating_add(1); + let mut out = Vec::new(); + loop { + let c = self.peek()?; + if c == b'\\' { + out.push(*self.b.get(self.i.saturating_add(1))?); + self.i = self.i.saturating_add(2); + } else if c == b')' { + self.i = self.i.saturating_add(1); + break; + } else { + out.push(c); + self.i = self.i.saturating_add(1); + } + } + Some(match out.strip_prefix(&[0xfe, 0xff]) { + Some(utf16) => TextValue::Str(decode_utf16be(utf16)), + None => TextValue::Bytes(out), + }) + } + b'/' => { + self.i = self.i.saturating_add(1); + Some(TextValue::Name(text(self.word()))) + } + _ => { + let word = self.word(); + if word.is_empty() { + return None; + } + let w = text(word); + Some(match w.as_str() { + "true" => TextValue::Bool(true), + "false" => TextValue::Bool(false), + _ => match w.parse::() { + Ok(i) => TextValue::Int(i), + // `parse` also takes `nan`, `inf` and overflowing exponents; those are not + // numbers a text document holds, so they stay tokens and read as missing. + Err(_) => match w.parse::() { + Ok(f) if f.is_finite() => TextValue::Float(f), + _ => TextValue::Token(w), + }, + }, + }) + } + } + } + } + + /// A big-endian UTF-16 string as text (unpaired surrogates become U+FFFD). + fn decode_utf16be(bytes: &[u8]) -> String { + let (pairs, rest) = bytes.as_chunks::<2>(); + let units = pairs.iter().map(|p| u16::from_be_bytes(*p)); + let mut s: String = char::decode_utf16(units).map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)).collect(); + if !rest.is_empty() { + s.push(char::REPLACEMENT_CHARACTER); + } + s + } + + /// Parses the body of a `btdk` list into its top-level `key value` pairs (as a [`TextValue::Dict`]). + /// Parsing stops silently at the first syntax error or at nesting deeper than 64 levels; what was + /// read before is returned. + pub(super) fn parse_text_dict(body: &[u8]) -> TextValue { + let mut parser = Parser { b: body, i: 0 }; + let mut pairs = Vec::new(); + loop { + parser.skip_ws(); + if parser.i >= body.len() { + break; + } + let Some(key) = parser.parse(0) else { break }; + let Some(value) = parser.parse(0) else { break }; + pairs.push((key.key_text(), value)); + } + TextValue::Dict(pairs) + } + + fn val(v: f64) -> TextValue { + TextValue::Float(v) + } + + /// A dictionary value with these keys, for the built-in defaults. + fn dict(pairs: Vec<(&str, TextValue)>) -> TextValue { + TextValue::Dict(pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) + } + + /// An array of numbers, for the built-in defaults. + fn numbers(v: &[f64]) -> TextValue { + TextValue::Array(v.iter().map(|x| val(*x)).collect()) + } + + /// The default of every run style slot that is not decoded and not neutral (zero, `false`, + /// empty, `/nil`): the value an untouched point text holds in every sample (110, 243-245). A slot + /// with a neutral default is left out; [`undecoded_fields`] treats a missing default as neutral. + pub(super) fn style_defaults() -> TextValue { + let paint = |a: f64| { + dict(vec![("99", TextValue::Name("SimplePaint".into())), ("0", dict(vec![("0", val(1.0)), ("1", numbers(&[1.0, 1.0, 1.0, a]))]))]) + }; + let class = |name: &str| dict(vec![("99", TextValue::Name(name.into()))]); + dict(vec![ + ("37", val(2.0)), + ("41", val(2.0)), + ("43", dict(vec![("0", val(0.5))])), + ("44", val(2.0)), + ("45", val(2.0)), + ("46", val(7.0)), + ("49", val(-1.0)), + ("50", val(-1.0)), + ("55", class("SimpleBlender")), + ("64", val(4.0)), + ("71", val(4.0)), + ("77", TextValue::Bool(true)), + ("78", TextValue::Bool(true)), + ("79", paint(0.0)), + ("82", val(3.0)), + ("83", val(3.0)), + ("86", class("SimpleCustomFeature")), + ("87", val(100.0)), + ("88", TextValue::Bool(true)), + ("95", dict(vec![("0", val(0.0)), ("1", val(0.0))])), + ("96", TextValue::Bool(true)), + ]) + } + + /// The same for the paragraph slots (110, 243-245). + pub(super) fn paragraph_defaults() -> TextValue { + dict(vec![ + ("6", val(1.0)), + ("7", val(1.2)), + ("10", val(6.0)), + ("11", val(2.0)), + ("12", val(2.0)), + ("14", val(36.0)), + ("15", TextValue::Bool(true)), + ("16", val(0.5)), + ("17", numbers(&[0.8, 1.0, 1.33])), + ("18", numbers(&[0.0, 0.0, 0.0])), + ("19", numbers(&[1.0, 1.0, 1.0])), + ("20", val(6.0)), + ("22", val(1.0)), + ("23", TextValue::Bool(true)), + ("24", val(1.0)), + ("26", TextValue::Bool(true)), + ("31", val(36.0)), + ("35", val(1.0)), + ("40", val(2.0)), + ]) + } +} + #[cfg(test)] mod tests { use super::*; + use crate::Chunk; + + /// A `LIST` of this type holding `kids`. + fn list(t: &[u8; 4], kids: Vec>) -> Chunk<'static> { + Chunk::list(*t, kids) + } + + /// A document with every kind of value, close to what After Effects writes: names, numbers, + /// a UTF-16 string with escapes, a plain string, nested dictionaries and arrays, an undecoded + /// style slot, a font list and a box frame. + const DOC: &[u8] = b"/0 << /1 << /0 [ << /0 << /0 << /0 (\xfe\xff\0M\0y\0r) >> /1 1 >> >> << /0 << /0 << /0 (\xfe\xff\0A\0\\)\0b) >> >> >> ] >> \ + /8 << /0 [ << /0 << /1 << /0 [ 0 0 10 0 10 5 0 5 ] >> /2 << /0 1 /1 2 >> >> >> ] >> >> \ + /1 << /1 [ << /0 << /0 (\xfe\xff\0H\0i\0\r) /5 << /0 [ << /0 << /0 << /5 << /0 2 /9 false /24 0 /34 7 /17 [ .8 1.0 1.33 ] >> >> >> /1 3 >> ] >> \ + /6 << /0 [ << /0 << /0 << /6 << /0 1 /1 36.5 /53 << /0 << /0 1 /1 [ 1 0.5 0 1 ] >> >> /79 << /99 /SimplePaint /0 << /0 1 /1 [ 1 1 1 0 ] >> >> /68 1 /90 /x /91 (plain) /92 word >> >> >> /1 3 >> ] >> \ + /8 << /0 [ << /0 << /0 50 >> /1 2 >> << /1 1 >> ] >> >> >> ] >>"; + + /// A deterministic xorshift generator: the tests need varied input, not a dependency. + struct Rng(u64); + + impl Rng { + /// The next pseudo-random number (xorshift). + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + /// A number below `n` (0 for `n == 0`). + fn below(&mut self, n: usize) -> usize { + usize::try_from(self.next() % (n as u64)).unwrap_or(0) + } + } + + /// The borrowing parser reads what the owning one read. + #[test] + fn the_borrowing_parser_reads_what_the_owning_one_read() { + // Every key form the owned keys canonicalise (`06`, `+6`, `-0`, `1.0`, `1e2`, strings, + // booleans, containers), names that are not UTF-8, escapes, unclosed strings and escapes, + // non-finite numbers, and bare words. + let parts: &[&[u8]] = &[ + b"<<", + b">>", + b"[", + b"]", + b"/0", + b"/1", + b"/nil", + b"/SimplePaint", + b"/\xff\xfe", + b"/\xc3\xa9", + b"/", + b"06", + b"+6", + b"-0", + b"1.0", + b"1.50", + b"1e2", + b"-2.5", + b".8", + b"inf", + b"nan", + b"1e999", + b"9223372036854775808", + b"true", + b"false", + b"(abc)", + b"(\xfe\xff\0A\0B)", + b"(\xfe\xff\0A\0)", + b"(a\\)b)", + b"(\\", + b"(\xfe\xff\\)\0)", + b"(\\\xfe\xff\0C)", + b"()", + b"(\xfe\xff)", + b"(unclosed", + b"word", + b"\xc3\x28", + b"\xff", + b" ", + b"\n", + b"\t\r", + b"<", + b">", + b")", + ]; + // A value: mostly well formed, with a random part in its place now and then. + /// Appends one generated value to `out`: mostly well formed, now and then a random part. + fn value(rng: &mut Rng, parts: &[&[u8]], depth: usize, out: &mut Vec) { + let pick = |rng: &mut Rng| parts.get(rng.below(parts.len())).copied().unwrap_or_default(); + match rng.below(if depth > 6 { 5 } else { 10 }) { + 0 => out.extend_from_slice(pick(rng)), + 1..=4 => out.extend_from_slice([&b"/0"[..], b"1", b"(\xfe\xff\0z)", b"0.5", b"/nil"].get(rng.below(5)).copied().unwrap_or_default()), + 5..=7 => { + out.extend_from_slice(b"<< "); + for _ in 0..rng.below(5) { + let key = if rng.below(4) == 0 { + pick(rng) + } else { + [&b"/0"[..], b"/1", b"/6", b"/53"].get(rng.below(4)).copied().unwrap_or_default() + }; + out.extend_from_slice(key); + out.push(b' '); + value(rng, parts, depth + 1, out); + out.push(b' '); + } + if rng.below(20) != 0 { + out.extend_from_slice(b">>"); + } + } + _ => { + out.extend_from_slice(b"[ "); + for _ in 0..rng.below(5) { + value(rng, parts, depth + 1, out); + out.push(b' '); + } + if rng.below(20) != 0 { + out.push(b']'); + } + } + } + } + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let (mut read, mut nested) = (0, 0); + for case in 0..40_000 { + let mut body = Vec::new(); + if case % 2 == 0 { + for _ in 0..rng.below(60) { + body.extend_from_slice(parts.get(rng.below(parts.len())).copied().unwrap_or_default()); + if rng.below(3) != 0 { + body.push(b' '); + } + } + } else { + for _ in 0..1 + rng.below(4) { + body.extend_from_slice(b"/0 "); + value(&mut rng, parts, 0, &mut body); + body.push(b'\n'); + } + } + let parsed = parse_text_dict(&body); + assert_eq!(parsed, oracle::parse_text_dict(&body), "case {case}: {}", String::from_utf8_lossy(&body)); + let _ = TextDocument::parse(&body); + if let TextValue::Dict(pairs) = &parsed { + read += usize::from(!pairs.is_empty()); + nested += usize::from(pairs.iter().any(|(_, v)| matches!(v, TextValue::Dict(d) if !d.is_empty()))); + } + } + // The input is not all rejected at the first token. + assert!(read > 25_000 && nested > 3_000, "{read} cases read something, {nested} a dictionary"); + // Every cut of a realistic document, and nesting past the limit. + for end in 0..=DOC.len() { + let body = DOC.get(..end).unwrap_or_default(); + assert_eq!(parse_text_dict(body), oracle::parse_text_dict(body), "cut at {end}"); + let _ = TextDocument::parse(body); + } + for depth in [63, 64, 65, 66, 200] { + let body = [b"/k ".to_vec(), b"<< /a ".repeat(depth), b"1".to_vec(), b" >>".repeat(depth), b" /z 2".to_vec()].concat(); + assert_eq!(parse_text_dict(&body), oracle::parse_text_dict(&body), "depth {depth}"); + let body = [b"/k ".to_vec(), b"[ ".repeat(depth), b"]".repeat(depth)].concat(); + assert_eq!(parse_text_dict(&body), oracle::parse_text_dict(&body), "array depth {depth}"); + } + // Dictionaries and arrays mixed (`<< /a [ << /a [ ...`), closed, and left open exactly + // at the limit. + for depth in 60..=68 { + let open: Vec = (0..depth).flat_map(|i| if i % 2 == 0 { &b"<< /a "[..] } else { &b"[ "[..] }).copied().collect(); + let close: Vec = (0..depth).rev().flat_map(|i| if i % 2 == 0 { &b" >>"[..] } else { &b" ]"[..] }).copied().collect(); + for body in + [[b"/k ".to_vec(), open.clone(), b"1".to_vec(), close, b" /z 2".to_vec()].concat(), [b"/k ".to_vec(), open, b"1".to_vec()].concat()] + { + assert_eq!(parse_text_dict(&body), oracle::parse_text_dict(&body), "mixed depth {depth}"); + let _ = TextDocument::parse(&body); + } + } + } + + /// A realistic document is read in full. + #[test] + fn a_realistic_document_is_read_in_full() { + let doc = TextDocument::parse(DOC).expect("a document"); + assert_eq!((doc.text.as_str(), doc.font_size, doc.fill_argb, doc.font.as_deref()), ("Hi", 36.5, [1.0, 0.5, 0.0, 1.0], Some("A)b"))); + assert_eq!(doc.fonts, ["Myr", "A)b"]); + assert_eq!(doc.paragraphs.first().map(|p| (p.length, p.justification, p.auto_hyphenate)), Some((3, Justification::Center, false))); + // `/68 1` and `/34 7` are neutral; `/90 /x`, `/91 (plain)` and `/92 word` differ from the + // (missing, neutral) default; `/79` equals its default. + assert_eq!(doc.undecoded_style_fields, ["90", "91", "92"]); + assert!(doc.undecoded_paragraph_fields.is_empty()); + assert_eq!(doc.kerning, [KernRun { length: 2, amount: Some(50.0) }, KernRun { length: 1, amount: None }]); + assert_eq!(doc.text_box, Some(TextBox { x: 0.0, y: 0.0, width: 10.0, height: 5.0 })); + assert_eq!(doc.line_orientation, Some(2)); + } + + /// The defaults are the sampled ones and built once. + #[test] + fn the_defaults_are_the_sampled_ones_and_built_once() { + assert_eq!(STYLE_DEFAULTS.clone().into_owned(), oracle::style_defaults()); + assert_eq!(PARAGRAPH_DEFAULTS.clone().into_owned(), oracle::paragraph_defaults()); + assert!(std::ptr::eq(&*STYLE_DEFAULTS, &*STYLE_DEFAULTS)); + } + + /// Names keys and strings are borrowed from the body. + #[test] + fn names_keys_and_strings_are_borrowed_from_the_body() { + let V::Dict(pairs) = parse_dict(b"/a /b /c (\xfe\xff\0x) /d (plain) /e word /f 1.5 /g (\\(esc) 07 1") else { panic!("a dict") }; + // Every `/name` key, name, string without escapes and bare word points into the body. + assert!(pairs.iter().take(6).all(|(k, _)| matches!(k, Cow::Borrowed(_)))); + assert!(matches!(pairs.first().map(|p| &p.1), Some(V::Name(b"b")))); + assert!(matches!(pairs.get(1).map(|p| &p.1), Some(V::Str(Cow::Borrowed(b"\0x"))))); + assert!(matches!(pairs.get(2).map(|p| &p.1), Some(V::Bytes(Cow::Borrowed(b"plain"))))); + assert!(matches!(pairs.get(3).map(|p| &p.1), Some(V::Token(b"word")))); + // An escaped string is copied; a number key is written in its canonical form. + assert!(matches!(pairs.get(5).map(|p| &p.1), Some(V::Bytes(Cow::Owned(b))) if b == b"(esc")); + assert_eq!(pairs.get(6).map(|p| p.0.as_ref()), Some("7")); + // Containers hold what was read. + let V::Dict(outer) = parse_dict(b"/0 << /a 1 /b 2 /c 3 /d 4 /e 5 >> /1 [ 1 2 3 4 5 6 7 8 9 ]") else { panic!("a dict") }; + assert!(matches!(outer.first().map(|p| &p.1), Some(V::Dict(d)) if d.len() == 5 && d.capacity() >= d.len())); + assert!(matches!(outer.get(1).map(|p| &p.1), Some(V::Array(a)) if a.len() == 9 && a.capacity() >= a.len())); + } + + /// Slot checks agree with the owned ones. + #[test] + fn slot_checks_agree_with_the_owned_ones() { + // Slots: defaults, decoded, neutral-listed and unknown ones. Values: each default as + // stored (also as `Int` where it is `2.0`), near misses, neutral values and every kind. + let slots = ["0", "6", "7", "17", "24", "34", "35", "37", "43", "55", "68", "77", "79", "86", "95", "96", "200", "x"]; + let values: &[&[u8]] = &[ + b"2", + b"2.0", + b"7", + b"1", + b"0", + b"-1", + b"0.5", + b"1.2", + b"36", + b"true", + b"false", + b"/nil", + b"/x", + b"/SimpleBlender", + b"[ ]", + b"<< >>", + b"[ .8 1 1.33 ]", + b"[ 0.8 1.0 ]", + b"[ 1 1 1 ]", + b"<< /0 .5 >>", + b"<< /0 0 /1 0 >>", + b"<< /1 0 /0 0 >>", + b"<< /99 /SimpleBlender >>", + b"<< /99 /SimplePaint /0 << /0 1 /1 [ 1 1 1 0 ] >> >>", + b"<< /99 /SimplePaint /0 << /0 1 /1 [ 1 1 1 1 ] >> >>", + b"(plain)", + b"(\xfe\xff\0a)", + b"word", + b"/\xff", + ]; + let mut rng = Rng(0x2545_f491_4f6c_dd1d); + let mut listed = 0; + for case in 0..20_000 { + let mut body = b"/s << ".to_vec(); + for _ in 0..rng.below(12) { + body.push(b'/'); + body.extend_from_slice(slots.get(rng.below(slots.len())).copied().unwrap_or_default().as_bytes()); + body.push(b' '); + body.extend_from_slice(values.get(rng.below(values.len())).copied().unwrap_or_default()); + body.push(b' '); + } + body.extend_from_slice(b">>"); + let (new, old) = (parse_dict(&body), oracle::parse_text_dict(&body)); + let (Some(new), Some(old)) = (new.get("s"), old.get("s")) else { panic!("case {case}: a dict") }; + for (sampled, old_sampled, decoded, neutral) in [ + (&*STYLE_DEFAULTS, oracle::style_defaults(), DECODED_STYLE_SLOTS, NEUTRAL_STYLE_VALUES), + (&*PARAGRAPH_DEFAULTS, oracle::paragraph_defaults(), DECODED_PARAGRAPH_SLOTS, NEUTRAL_PARAGRAPH_VALUES), + ] { + let (mut a, mut b) = (Vec::new(), Vec::new()); + undecoded_fields(new, Some(sampled), decoded, neutral, &mut a); + oracle::undecoded_fields(old, Some(&old_sampled), decoded, neutral, &mut b); + assert_eq!(a, b, "case {case}: {}", String::from_utf8_lossy(&body)); + listed += a.len(); + } + // Every pair of values compares and reads as neutral alike. + if let (V::Dict(x), TextValue::Dict(y)) = (new, old) { + for ((_, p), (_, q)) in x.iter().zip(y) { + assert_eq!(is_neutral(p), oracle::is_neutral(q), "case {case}"); + for ((_, r), (_, t)) in x.iter().zip(y) { + assert_eq!(same(p, r), oracle::same(q, t), "case {case}"); + } + } + } + } + assert!(listed > 10_000, "{listed} slots listed"); + } + + /// Values compare by their text. + #[test] + fn values_compare_by_their_text() { + // Two names that are not UTF-8 read as the same text with replacement characters, as the + // owned values did. + assert!(same(&V::Name(b"\xff"), &V::Name(b"\xfe"))); + assert!(!same(&V::Name(b"a"), &V::Name(b"b"))); + assert!(same(&V::Str(Cow::Borrowed(b"\xd8\x00")), &V::Str(Cow::Owned(b"\xd8\x01".to_vec())))); + assert!(same(&V::Int(0), &V::Float(0.0)) && !same(&V::Int(0), &V::Bool(false)) && !same(&V::Name(b"x"), &V::Token(b"x"))); + assert!( + is_neutral(&V::Name(b"nil")) && !is_neutral(&V::Token(b"nil")) && is_neutral(&V::Float(0.0)) && !is_neutral(&V::Str(Cow::Borrowed(b""))) + ); + } + + /// A layers marker list is the one in its root group. + #[test] + fn a_layers_marker_list_is_the_one_in_its_root_group() { + let marked = |tag: u8| list(b"mrst", vec![Chunk::data(*b"test", vec![tag])]); + // The stored place: `Layr/tdgp/mrst`. + let layer = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![]), marked(1)])]); + assert_eq!(Node::from(&layer).marker_list().and_then(|m| m.child(b"test")).and_then(Node::bytes), Some(&[1u8][..])); + // A list deeper in the layer is not the layer's marker list (the old depth-first search + // found it); a layer without a marker list in its root group has no markers. + let deep = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![marked(2)])])]); + assert!(Node::from(&deep).marker_list().is_none()); + assert!(Layer { chunk: Node::from(&deep) }.markers().is_empty()); + // Any other holder (a composition's `SecL`) is still searched depth-first. + let secl = list(b"SecL", vec![list(b"tdgp", vec![list(b"tdgp", vec![marked(3)])])]); + assert_eq!(Node::from(&secl).marker_list().and_then(|m| m.child(b"test")).and_then(Node::bytes), Some(&[3u8][..])); + } + + /// The source text record is found in the text group. + #[test] + fn the_source_text_record_is_found_in_the_text_group() { + let doc = b"/1 << /1 [ << /0 << /0 (\xfe\xff\0H\0\r) /6 << /0 [ << /0 << /0 << /6 << /0 0 /1 50 /53 << /0 << /1 [ 1 1 0 0 ] >> >> >> >> >> /1 2 >> ] >> >> >> ] >>"; + // `btdk` is an opaque list (its body is not a chunk sequence), as the reader makes it. + let btdk = || Chunk { id: *b"LIST", body: crate::Body::OpaqueList { list_type: *b"btdk", data: doc.to_vec().into() }, pad: None }; + let btds_real = |n: usize| list(b"btds", std::iter::once(list(b"tdbs", vec![])).chain((0..n).map(|_| btdk())).collect()); + let layer = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![]), list(b"tdgp", vec![btds_real(2)])])]); + let view = Layer { chunk: Node::from(&layer) }; + assert_eq!(view.text_document().map(|d| d.text), Some("H".to_string())); + assert!(view.source_text_property().is_some()); + assert_eq!(view.text_document_count(), 2); + // A record anywhere else in the layer is not its Source Text. + let elsewhere = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![list(b"tdgp", vec![btds_real(1)])])])]); + let view = Layer { chunk: Node::from(&elsewhere) }; + assert!(view.text_document().is_none() && view.source_text_property().is_none()); + assert_eq!(view.text_document_count(), 0); + } #[test] fn non_finite_numbers_are_not_numbers() { @@ -1018,13 +1818,13 @@ mod tests { fn undecoded_fields_are_capped_and_linear() { // 300 000 distinct undecoded slots that differ from a sampled default: before, each was // checked against every slot recorded so far (4.5e10 compares) and all were listed. - let actual = TextValue::Dict((0..300_000).map(|i| (format!("{}", 9000 + i), TextValue::Int(1))).collect()); + let actual = V::Dict((0..300_000).map(|i| (Cow::Owned(format!("{}", 9000 + i)), V::Int(1))).collect()); let mut out = Vec::new(); undecoded_fields(&actual, None, &["0"], &[], &mut out); assert_eq!(out.len(), MAX_UNDECODED_FIELDS); assert_eq!(out.first().map(String::as_str), Some("9000")); // A slot listed once is not listed again. - let again = TextValue::Dict(vec![("9000".into(), TextValue::Int(1))]); + let again = V::Dict(vec![(Cow::Borrowed("9000"), V::Int(1))]); let mut short = vec!["9000".to_string()]; undecoded_fields(&again, None, &[], &[], &mut short); assert_eq!(short, ["9000"]); diff --git a/crates/aep/src/typed.rs b/crates/aep/src/typed.rs index 16fcda33c..9334b45cc 100644 --- a/crates/aep/src/typed.rs +++ b/crates/aep/src/typed.rs @@ -4,42 +4,57 @@ //! //! Only facts that were established from our own one-change-per-file corpus and are checked by //! tests against it are decoded (see `docs/aep-format.md` for the evidence). Everything else -//! stays reachable through the raw [`Chunk`] tree. Views borrow the file and never fail loudly: -//! a chunk that does not have the expected shape yields `None` or is skipped. +//! stays reachable through the raw chunk tree ([`Node`]). Views borrow the file and never fail +//! loudly: a chunk that does not have the expected shape yields `None` or is skipped. +//! +//! A view reads either tree: the owned [`Chunk`](crate::Chunk) tree +//! ([`Project::new`]) or the flat [`TreeIndex`] the importer builds ([`Project::from_index`]); +//! both give the same answers. use crate::bytes::{be_f64, be_u16, be_u32, text, until_nul}; -use crate::chunk::{AepFile, Chunk}; +use crate::chunk::AepFile; +use crate::index::{Node, Root, TreeIndex}; /// The name a user gave a property or group: the `Utf8` inside its `tdsn` chunk. `None` for the /// sentinel `-_0_/-` ("no custom name") and for empty names. -pub(crate) fn user_name(chunk: &Chunk<'_>) -> Option { - let name = chunk.child(b"tdsn")?.children().iter().find(|c| c.is(b"Utf8"))?.bytes().map(text)?; +pub(crate) fn user_name(chunk: Node<'_, '_>) -> Option { + let name = chunk.child(b"tdsn")?.child(b"Utf8")?.bytes().map(text)?; (!name.is_empty() && name != "-_0_/-").then_some(name) } /// The content of a `Utf8` child as text (not trimmed). -pub(crate) fn utf8_child(chunk: &Chunk<'_>) -> Option { - chunk.child(b"Utf8").and_then(Chunk::bytes).map(text) +pub(crate) fn utf8_child(chunk: Node<'_, '_>) -> Option { + chunk.child(b"Utf8").and_then(Node::bytes).map(text) } /// The project: the top-level `LIST Fold`, which holds the project items. #[derive(Debug, Clone, Copy)] pub struct Project<'f, 'a> { - pub(crate) fold: &'f Chunk<'a>, + pub(crate) fold: Node<'f, 'a>, /// The top-level `LIST EfdG` (project-level effect definitions), when there is one. - pub(crate) effect_defs: Option<&'f Chunk<'a>>, + pub(crate) effect_defs: Option>, } impl<'f, 'a> Project<'f, 'a> { /// The project view of a file, or `None` when it has no `LIST Fold`. pub fn new(file: &'f AepFile<'a>) -> Option { - file.list(b"Fold").map(|fold| Self { fold, effect_defs: file.list(b"EfdG") }) + Self::of(Root::from(file)) + } + + /// The project view of an indexed file ([`TreeIndex`]), or `None` when it has no `LIST Fold`. + pub fn from_index(index: &'f TreeIndex<'a>) -> Option { + Self::of(Root::from(index)) + } + + /// The project view of either tree: its `LIST Fold` and `LIST EfdG`. + pub fn of(root: Root<'f, 'a>) -> Option { + root.list(b"Fold").map(|fold| Self { fold, effect_defs: root.list(b"EfdG") }) } /// The top-level items (the project panel's root; folders hold their children, see /// [`Item::children`]). pub fn items(&self) -> impl Iterator> + 'f { - self.fold.children().iter().filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) + self.fold.children().filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) } /// True when the `LIST Fold` could not be read as chunks (damaged): its items cannot be seen. @@ -78,12 +93,12 @@ pub enum ItemKind { /// A project item (`LIST Item`). #[derive(Debug, Clone, Copy)] pub struct Item<'f, 'a> { - pub(crate) chunk: &'f Chunk<'a>, + pub(crate) chunk: Node<'f, 'a>, } impl<'f, 'a> Item<'f, 'a> { /// The underlying chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } @@ -106,7 +121,7 @@ impl<'f, 'a> Item<'f, 'a> { /// The items inside a folder (`LIST Sfdr`). pub fn children(&self) -> impl Iterator> + 'f { - self.chunk.child_list(b"Sfdr").into_iter().flat_map(|sfdr| sfdr.children().iter()).filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) + self.chunk.child_list(b"Sfdr").into_iter().flat_map(Node::children).filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) } /// Whether the item has the `LIST Sfdr` of a folder's contents (After Effects writes an empty @@ -117,7 +132,7 @@ impl<'f, 'a> Item<'f, 'a> { /// True when the folder's `LIST Sfdr` is there but could not be read as chunks (damaged). pub fn folder_contents_unreadable(&self) -> bool { - self.chunk.child_list(b"Sfdr").is_some_and(Chunk::is_opaque_list) + self.chunk.child_list(b"Sfdr").is_some_and(Node::is_opaque_list) } /// The composition view when this item has composition data (`cdta`). @@ -135,6 +150,10 @@ pub struct TimeBase { } impl TimeBase { + /// The NTSC rates as `(numerator, denominator)` and the value After Effects stores for each (a + /// float32 of exactly these decimals): the one table an importer and an exporter use. + pub const NTSC: [((u32, u32), f32); 4] = [((24000, 1001), 23.976), ((30000, 1001), 29.97), ((60000, 1001), 59.94), ((120000, 1001), 119.88)]; + /// Frames per second (`timescale / frame_duration`), `None` for a zero duration. pub fn frame_rate(&self) -> Option { (self.frame_duration != 0).then(|| f64::from(self.timescale) / f64::from(self.frame_duration)) @@ -149,7 +168,7 @@ impl TimeBase { /// A composition item (an [`Item`] with `cdta`). #[derive(Debug, Clone, Copy)] pub struct Comp<'f, 'a> { - pub(crate) item: &'f Chunk<'a>, + pub(crate) item: Node<'f, 'a>, } impl<'f, 'a> Comp<'f, 'a> { @@ -163,19 +182,19 @@ impl<'f, 'a> Comp<'f, 'a> { /// The layers, top layer first (`LIST Layr`; the `DLay`/`SLay`/`CLay`/`SecL` lists next to /// them are not layers). pub fn layers(&self) -> impl Iterator> + 'f { - self.item.children().iter().filter(|c| c.is_list(b"Layr")).map(|chunk| Layer { chunk }) + self.item.children().filter(|c| c.is_list(b"Layr")).map(|chunk| Layer { chunk }) } } /// A layer (`LIST Layr`). #[derive(Debug, Clone, Copy)] pub struct Layer<'f, 'a> { - pub(crate) chunk: &'f Chunk<'a>, + pub(crate) chunk: Node<'f, 'a>, } impl<'f, 'a> Layer<'f, 'a> { /// The underlying chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } @@ -205,12 +224,12 @@ pub enum PropNode<'f, 'a> { /// A property (`LIST tdbs`). Property(Property<'f, 'a>), /// Any other list that follows a match name (observed: `otst`, the effect instance `sspc`). - Other(&'f Chunk<'a>), + Other(Node<'f, 'a>), } impl<'f, 'a> PropNode<'f, 'a> { /// The node a `LIST` after a match name is. - fn of(c: &'f Chunk<'a>) -> Self { + fn of(c: Node<'f, 'a>) -> Self { if c.is_list(b"tdgp") { PropNode::Group(PropGroup { chunk: c }) } else if c.is_list(b"tdbs") { @@ -233,17 +252,18 @@ pub struct PropEntry<'f, 'a> { /// `ADBE Group End` closes the group and names nothing. #[derive(Debug, Clone, Copy)] pub struct PropGroup<'f, 'a> { - pub(crate) chunk: &'f Chunk<'a>, + pub(crate) chunk: Node<'f, 'a>, } impl<'f, 'a> PropGroup<'f, 'a> { - /// A group view of a `LIST tdgp` chunk. - pub fn from_chunk(chunk: &'f Chunk<'a>) -> Option { + /// A group view of a `LIST tdgp` chunk (a [`Chunk`](crate::Chunk) or a [`Node`]). + pub fn from_chunk(chunk: impl Into>) -> Option { + let chunk = chunk.into(); chunk.is_list(b"tdgp").then_some(Self { chunk }) } /// The underlying chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } @@ -264,7 +284,7 @@ impl<'f, 'a> PropGroup<'f, 'a> { for c in self.chunk.children() { if c.is(b"tdmn") { pending = c.bytes().map(match_name); - } else if c.id == crate::chunk::LIST + } else if c.is(&crate::chunk::LIST) && let Some(name) = pending.take() { out.push(PropEntry { match_name: name, node: PropNode::of(c) }); @@ -285,9 +305,9 @@ impl<'f, 'a> PropGroup<'f, 'a> { for c in self.chunk.children() { if c.is(b"tdmn") { pending = c.bytes(); - } else if c.id == crate::chunk::LIST + } else if c.is(&crate::chunk::LIST) && let Some(body) = pending.take() - && match_name(body) == name + && match_name_is(body, name) { return Some(PropNode::of(c)); } @@ -314,21 +334,30 @@ fn match_name(body: &[u8]) -> String { text(until_nul(body)) } +/// `match_name(body) == name` without building the `String`: equal bytes match; otherwise only +/// a body that is not valid UTF-8 can still match (through its U+FFFD replacements), and only a +/// name that holds U+FFFD. +fn match_name_is(body: &[u8], name: &str) -> bool { + let bytes = until_nul(body); + bytes == name.as_bytes() || (name.contains('\u{FFFD}') && String::from_utf8_lossy(bytes) == name) +} + /// A property (`LIST tdbs`): `tdsb`, `tdsn`, the 124-byte header `tdb4`, then either the static /// value `cdat` or a keyframe `LIST list`. #[derive(Debug, Clone, Copy)] pub struct Property<'f, 'a> { - pub(crate) chunk: &'f Chunk<'a>, + pub(crate) chunk: Node<'f, 'a>, } impl<'f, 'a> Property<'f, 'a> { - /// A property view of a `LIST tdbs` chunk. - pub fn from_chunk(chunk: &'f Chunk<'a>) -> Option { + /// A property view of a `LIST tdbs` chunk (a [`Chunk`](crate::Chunk) or a [`Node`]). + pub fn from_chunk(chunk: impl Into>) -> Option { + let chunk = chunk.into(); chunk.is_list(b"tdbs").then_some(Self { chunk }) } /// The underlying chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } @@ -436,12 +465,13 @@ pub struct KeyLayout { impl<'f> KeyList<'f> { /// A view of a `LIST list` chunk. `None` when `lhd3` is not 52 bytes or `ldat` is not exactly /// `count * record_size` bytes (a list without `ldat` must have no records). - pub fn from_chunk<'a>(chunk: &'f Chunk<'a>) -> Option { + pub fn from_chunk<'a: 'f>(chunk: impl Into>) -> Option { + let chunk = chunk.into(); if !chunk.is_list(b"list") { return None; } let header = ListHeader::parse(chunk.child(b"lhd3")?.bytes()?)?; - let ldat: &[u8] = chunk.child(b"ldat").and_then(Chunk::bytes).unwrap_or(&[]); + let ldat: &[u8] = chunk.child(b"ldat").and_then(Node::bytes).unwrap_or(&[]); let expected = usize::try_from(header.count).ok()?.checked_mul(usize::try_from(header.record_size).ok()?)?; (ldat.len() == expected).then_some(Self { header, ldat, layout: None }) } @@ -500,6 +530,7 @@ impl<'f> Keyframe<'f> { #[cfg(test)] mod tests { use super::*; + use crate::Chunk; fn key_list(count: u32, record_size: u32, ldat: &[u8]) -> Chunk<'static> { let mut lhd3 = vec![0u8; 52]; @@ -543,4 +574,31 @@ mod tests { assert!(g.get("C").is_none()); assert_eq!(g.names(), ["A", "B", "A"]); } + + /// Match name is agrees with comparing the decoded name. + #[test] + fn match_name_is_agrees_with_comparing_the_decoded_name() { + let bodies: [&[u8]; 9] = [ + b"ADBE Position\0\0\0", + b"ADBE Position", + b"ADBE Pos", + b"", + b"\0ADBE", + b"ADBE \xff Bad\0", + b"\xff", + b"\xef\xbf\xbd", + "Gr\u{fc}n\0".as_bytes(), + ]; + let names = ["ADBE Position", "ADBE Pos", "", "ADBE \u{FFFD} Bad", "\u{FFFD}", "Gr\u{fc}n", "ADBE Position\0", "ADBE \u{FFFD}"]; + for body in bodies { + for name in names { + assert_eq!(match_name_is(body, name), match_name(body) == name, "{body:?} vs {name:?}"); + } + } + // Names read back from a group find their entries, a damaged one included. + let group = Chunk::list(*b"tdgp", vec![Chunk::data(*b"tdmn", b"X\xffY\0".to_vec()), Chunk::list(*b"tdbs", Vec::new())]); + let g = PropGroup::from_chunk(&group).expect("group"); + let names = g.names(); + assert!(g.get(&names[0]).is_some()); + } } diff --git a/crates/aep/src/values.rs b/crates/aep/src/values.rs index 5613e07a3..b6857165a 100644 --- a/crates/aep/src/values.rs +++ b/crates/aep/src/values.rs @@ -8,6 +8,7 @@ //! 100 %. These defaults are verified for AV layers (solids); cameras and lights use other //! conventions (see the `camera` module). +use crate::bytes::be_f64; use crate::typed::{Layer, Project, PropGroup, PropNode}; /// Where a [`Tracked`] value came from. @@ -192,8 +193,7 @@ impl<'f, 'a> Layer<'f, 'a> { let otda = otst.child_list(b"otky")?.child(b"otda")?.bytes()?; let mut degrees = [0.0; 3]; for (i, slot) in degrees.iter_mut().enumerate() { - let b = otda.get(i * 8..i * 8 + 8)?; - *slot = f64::from_be_bytes(b.try_into().ok()?); + *slot = be_f64(otda, i * 8)?; } Some(Orientation { degrees, @@ -223,12 +223,10 @@ impl<'f, 'a> Layer<'f, 'a> { .child_list(b"otky") .map(|k| { k.children() - .iter() .filter(|c| c.is(b"otda")) .map(|c| { let b = c.bytes()?; - let at = |i: usize| b.get(i * 8..i * 8 + 8).and_then(|s| s.try_into().ok()).map(f64::from_be_bytes); - Some([at(0)?, at(1)?, at(2)?]) + Some([be_f64(b, 0)?, be_f64(b, 8)?, be_f64(b, 16)?]) }) .collect() }) diff --git a/crates/aep/src/version.rs b/crates/aep/src/version.rs index 53de0834a..023793037 100644 --- a/crates/aep/src/version.rs +++ b/crates/aep/src/version.rs @@ -8,8 +8,9 @@ use std::fmt; -use crate::bytes::{be_u16, be_u32}; +use crate::bytes::be_u32; use crate::chunk::AepFile; +use crate::index::{Root, TreeIndex}; /// An After Effects version as packed in `head` / `svap`: `26.2.1x2` is major 26, minor 2, bug-fix /// 1, build 2 (the form of the scripting API's `app.version`). @@ -71,21 +72,38 @@ impl AepFile<'_> { /// version there, and the older version for File ▸ Save a Copy As 25.x / 24.x. `None` when the /// chunk is missing, short or holds no version. pub fn file_version(&self) -> Option { - AeVersion::from_word(be_u32(self.chunk(b"head")?.bytes()?, 4)?) + Root::from(self).file_version() } /// The version of the After Effects that wrote the file: `svap` bytes 0 to 3 (the same word in a /// down-saved copy as in a normal save). `None` when the chunk is missing (After Effects opens such /// a file), short or holds no version. pub fn saved_by_version(&self) -> Option { - AeVersion::from_word(be_u32(self.chunk(b"svap")?.bytes()?, 0)?) + Root::from(self).saved_by_version() + } +} + +impl TreeIndex<'_> { + /// [`AepFile::file_version`] of the indexed file. + pub fn file_version(&self) -> Option { + Root::from(self).file_version() } - /// The `u16` at `head` byte 0: 97 (`0x61`) in a 2026 file, 96 in a copy saved as 25.x, 95 as - /// 24.x. It steps with the major version of [`AepFile::file_version`]; what it counts is not - /// known, so nothing is derived from it. - pub fn head_revision(&self) -> Option { - be_u16(self.chunk(b"head")?.bytes()?, 0) + /// [`AepFile::saved_by_version`] of the indexed file. + pub fn saved_by_version(&self) -> Option { + Root::from(self).saved_by_version() + } +} + +impl Root<'_, '_> { + /// The version the file is written for (`head` bytes 4 to 7). + pub fn file_version(self) -> Option { + AeVersion::from_word(be_u32(self.chunk(b"head")?.bytes()?, 4)?) + } + + /// The version of the application that wrote the file (`svap`). + pub fn saved_by_version(self) -> Option { + AeVersion::from_word(be_u32(self.chunk(b"svap")?.bytes()?, 0)?) } } diff --git a/crates/aep/src/write.rs b/crates/aep/src/write.rs index 1adf3126d..cadd84f0d 100644 --- a/crates/aep/src/write.rs +++ b/crates/aep/src/write.rs @@ -17,6 +17,18 @@ const MAX_WRITE_DEPTH: usize = 256; /// [`AepError::TooDeep`] for an absurdly deep hand-built tree. pub fn write(file: &AepFile<'_>) -> Result, AepError> { let mut out = Vec::new(); + // Sized once to the exact output. A tree past the 32-bit container size fails at once (the + // same error the write below would give after serialising it). `try_reserve` so a hand-built + // tree that repeats one large borrowed body many times cannot abort on the allocation; the + // writer then grows as it goes, as before. + if let Some(len) = sequence_len(&file.chunks, 1) { + if u32::try_from(len.saturating_add(4)).is_err() { + return Err(AepError::TooLarge); + } + if let Some(total) = len.checked_add(12).and_then(|n| n.checked_add(file.trailer.len())) { + let _ = out.try_reserve_exact(total); + } + } out.extend_from_slice(b"RIFX"); out.extend_from_slice(&[0; 4]); out.extend_from_slice(b"Egg!"); @@ -56,6 +68,28 @@ fn write_sequence(out: &mut Vec, chunks: &[Chunk<'_>], depth: usize) -> Resu Ok(()) } +/// The number of bytes [`write_sequence`] produces for `chunks`; `None` past the depth limit or +/// on overflow (both make the write fail). +fn sequence_len(chunks: &[Chunk<'_>], depth: usize) -> Option { + if depth > MAX_WRITE_DEPTH { + return None; + } + let count = chunks.len(); + let mut total = 0usize; + for (i, chunk) in chunks.iter().enumerate() { + let body = match &chunk.body { + Body::Data(d) => d.len(), + Body::Chunks(c) => sequence_len(c, depth + 1)?, + Body::List { children, .. } => sequence_len(children, depth + 1)?.checked_add(4)?, + Body::OpaqueList { data, .. } => data.len().checked_add(4)?, + }; + // The same pad rule as `write_chunk`. + let pad = usize::from(body % 2 == 1 && (chunk.pad.is_some() || i + 1 != count)); + total = total.checked_add(8)?.checked_add(body)?.checked_add(pad)?; + } + Some(total) +} + fn write_chunk(out: &mut Vec, chunk: &Chunk<'_>, is_last: bool, depth: usize) -> Result<(), AepError> { out.extend_from_slice(&chunk.id); let size_at = out.len(); @@ -84,3 +118,62 @@ fn write_chunk(out: &mut Vec, chunk: &Chunk<'_>, is_last: bool, depth: usize } Ok(()) } + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + + use super::*; + + /// The output is sized once to its exact length. + #[test] + fn the_output_is_sized_once_to_its_exact_length() { + let odd = |n: u8| Chunk::data(*b"cdat", vec![n; usize::from(n)]); + let mut padded = odd(3); + padded.pad = Some(0x7f); + let trees = [ + AepFile { chunks: Vec::new(), trailer: Cow::Borrowed(&[]) }, + AepFile { + chunks: vec![ + odd(1), + Chunk::list(*b"Fold", vec![odd(2), odd(3), Chunk::list(*b"tdgp", vec![odd(5)])]), + Chunk { id: *b"LIST", body: Body::OpaqueList { list_type: *b"btdk", data: Cow::Owned(vec![1, 2, 3]) }, pad: None }, + Chunk { id: *b"tdmn", body: Body::Chunks(vec![odd(7), padded]), pad: None }, + odd(9), + ], + trailer: Cow::Borrowed(b""), + }, + ]; + for file in &trees { + let out = write(file).expect("write"); + assert_eq!(sequence_len(&file.chunks, 1).map(|n| n + 12 + file.trailer.len()), Some(out.len())); + // Exact with std's allocator today; grown push by push it would be rounded up. + assert_eq!(out.capacity(), out.len(), "the output grew past its size"); + } + } + + /// A tree past the container size fails before serialising. + #[cfg(target_pointer_width = "64")] + #[test] + fn a_tree_past_the_container_size_fails_before_serialising() { + // 4097 chunks borrowing one 1 MiB body: over 4 GiB of output, none of it written. + let body = vec![0u8; 1 << 20]; + let chunks: Vec> = (0..4097).map(|_| Chunk::data(*b"cdat", &body[..])).collect(); + let file = AepFile { chunks, trailer: Cow::Borrowed(&[]) }; + assert_eq!(write(&file), Err(AepError::TooLarge)); + // Just under the limit still sizes, and fails nothing up front. + assert!(sequence_len(&file.chunks[..4000], 1).is_some_and(|n| u32::try_from(n + 4).is_ok())); + } + + /// A tree past the depth limit has no size. + #[test] + fn a_tree_past_the_depth_limit_has_no_size() { + let mut deep = Chunk::data(*b"cdat", vec![0]); + for _ in 0..=MAX_WRITE_DEPTH { + deep = Chunk::list(*b"tdgp", vec![deep]); + } + let file = AepFile { chunks: vec![deep], trailer: Cow::Borrowed(&[]) }; + assert_eq!(sequence_len(&file.chunks, 1), None); + assert_eq!(write(&file), Err(AepError::TooDeep)); + } +} diff --git a/crates/aep/tests/it/common/mod.rs b/crates/aep/tests/it/common/mod.rs index 791c3bbc9..b5605bb95 100644 --- a/crates/aep/tests/it/common/mod.rs +++ b/crates/aep/tests/it/common/mod.rs @@ -128,6 +128,13 @@ pub fn resolve(name: &str) -> Option { locate(name).map(|s| s.path().clone()) } +/// The ids of the compositions an item uses as precomposition layers, as the file stores them: +/// the little-endian `u32` of each `idpi` chunk (the importer does not read them; the exporter +/// writes them). +pub fn used_item_ids(item: &craft_aep::Item<'_, '_>) -> Vec { + item.chunk().children().filter(|c| c.is(b"idpi")).filter_map(|c| Some(u32::from_le_bytes(c.bytes()?.get(..4)?.try_into().ok()?))).collect() +} + /// The bytes of a case (see the module comment), or `None` when it is missing. pub fn try_fixture(name: &str) -> Option> { match locate(name)? { diff --git a/crates/aep/tests/it/container.rs b/crates/aep/tests/it/container.rs index d937d296c..514bbde1c 100644 --- a/crates/aep/tests/it/container.rs +++ b/crates/aep/tests/it/container.rs @@ -25,5 +25,6 @@ mod shapes; mod text_fields; mod text_markers_footage; mod text_style_slots; +mod tree_index; mod typed; mod values; diff --git a/crates/aep/tests/it/container/batch3_core.rs b/crates/aep/tests/it/container/batch3_core.rs index 8c2518a9f..83bd942b8 100644 --- a/crates/aep/tests/it/container/batch3_core.rs +++ b/crates/aep/tests/it/container/batch3_core.rs @@ -117,8 +117,8 @@ fn a_transform_set_to_its_default_adds_no_record() { assert_eq!(t.opacity_percent.source, ValueSource::Default); assert!(layer.properties().unwrap().find(&["ADBE Transform Group", "ADBE Position"]).is_none()); // The two cases are layers of one file: they differ in the layer id only. - let a = without_layer_id(layer.chunk()); - skip!(with_layer("299-save-noise.aep", L, |_, other| assert_eq!(a, without_layer_id(other.chunk())))); + let a = without_layer_id(&layer.chunk().to_chunk()); + skip!(with_layer("299-save-noise.aep", L, |_, other| assert_eq!(a, without_layer_id(&other.chunk().to_chunk())))); })); } @@ -140,16 +140,13 @@ fn scale_keys_keep_their_ease_type_major() { } assert_near(&keys[0].value().unwrap(), &[1.0, 1.0, 1.0], 1e-9); assert_near(&keys[1].value().unwrap(), &[2.0, 1.5, 1.0], 1e-9); - // The raw block: [in speed x3][in influence x3][out speed x3][out influence x3]. - assert_near(&keys[0].plain_ease_slots().unwrap(), &[0.0, 0.0, 0.0, 0.33, 0.33, 0.33, 0.2, 0.2, 0.2, 0.66, 0.66, 0.66], 1e-9); - assert_near(&keys[1].plain_ease_slots().unwrap(), &[0.1, 0.1, 0.1, 0.66, 0.66, 0.66, 0.0, 0.0, 0.0, 0.33, 0.33, 0.33], 1e-9); + // The raw block is [in speed x3][in influence x3][out speed x3][out influence x3]. for i in 0..3 { assert!(same_ease(&keys[0].ease_component(i).unwrap(), &ease(0.0, 0.33, 0.2, 0.66)), "key 1 component {i}"); assert!(same_ease(&keys[1].ease_component(i).unwrap(), &ease(0.1, 0.66, 0.0, 0.33)), "key 2 component {i}"); } assert!(keys[0].ease_component(3).is_none()); assert_eq!(keys[0].ease_components().unwrap().len(), 3); - assert!(keys[0].color_distance().is_none()); })); } @@ -172,7 +169,6 @@ fn mask_feather_keys_keep_their_ease_type_major() { } assert_near(&keys[0].value().unwrap(), &[0.0, 0.0], 1e-9); assert_near(&keys[1].value().unwrap(), &[50.0, 30.0], 1e-9); - assert_near(&keys[0].plain_ease_slots().unwrap(), &[0.0, 0.0, 0.33, 0.33, 15.0, 15.0, 0.66, 0.66], 1e-9); for i in 0..2 { assert!(same_ease(&keys[0].ease_component(i).unwrap(), &ease(0.0, 0.33, 15.0, 0.66)), "key 1 component {i}"); assert!(same_ease(&keys[1].ease_component(i).unwrap(), &ease(8.0, 0.66, 0.0, 0.33)), "key 2 component {i}"); @@ -213,14 +209,15 @@ fn bezier_colour_keys_carry_the_distance_to_the_next_key() { assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); assert!(same_ease(&k.ease_component(0).unwrap(), &ease(0.0, 0.0, 0.0, 0.0))); } - assert!(near(keys[0].color_distance().unwrap(), 255.0 * 2f64.sqrt(), 1e-3), "{:?}", keys[0].color_distance()); - assert!(near(keys[0].color_distance().unwrap(), 360.6245, 1e-3)); - assert_eq!(keys[1].color_distance(), Some(0.0)); + let distance = |k: &craft_aep::Keyframe<'_>| k.spatial().unwrap().segment_length; + assert!(near(distance(&keys[0]), 255.0 * 2f64.sqrt(), 1e-3), "{}", distance(&keys[0])); + assert!(near(distance(&keys[0]), 360.6245, 1e-3)); + assert_eq!(distance(&keys[1]), 0.0); })); skip!(with_layer("210-key-fill-color-2key-linear.aep", L, |_, layer| { let p = layer.effects()[0].params().into_iter().find(|p| p.name == "Color").unwrap(); let k = p.stored().unwrap().keys().unwrap().keyframes().next().unwrap(); - assert_eq!(k.color_distance(), Some(0.0)); + assert_eq!(k.spatial().unwrap().segment_length, 0.0); })); } @@ -243,21 +240,19 @@ fn time_stretch_is_an_exact_ratio() { let (h, in_p, out_p, scale) = skip!(stretch_facts("316-layer-stretch50.aep")); assert_eq!((h.stretch, h.stretch_den), (1, 2)); assert_eq!(h.stretch_ratio(), Some(rat(1, 2))); - assert_eq!(h.stretch_percent(), 50.0); assert_eq!(h.out_relative, rat(128000, 25600)); assert_eq!((in_p, out_p, scale), (Some(rat(0, 1)), Some(rat(5, 2)), 25600)); // 317: 150 %: 3/2, ends at 7.5 s, the property time scale is 25600 x 3/2. let (h, in_p, out_p, scale) = skip!(stretch_facts("317-layer-stretch150.aep")); assert_eq!((h.stretch, h.stretch_den), (3, 2)); assert_eq!(h.stretch_ratio(), Some(rat(3, 2))); - assert_eq!(h.stretch_percent(), 150.0); assert_eq!((in_p, out_p, scale), (Some(rat(0, 1)), Some(rat(15, 2)), 38400)); // 018: 200 %: 2/1, ends at 10 s, time scale 51200. The base is 1/1. let (h, _, out_p, scale) = skip!(stretch_facts("018-layer-stretch200.aep")); assert_eq!((h.stretch, h.stretch_den, h.stretch_ratio()), (2, 1, Some(rat(2, 1)))); assert_eq!((out_p, scale), (Some(rat(10, 1)), 51200)); let (h, _, out_p, scale) = skip!(stretch_facts("000-base.aep")); - assert_eq!((h.stretch, h.stretch_den, h.stretch_percent()), (1, 1, 100.0)); + assert_eq!((h.stretch, h.stretch_den, h.stretch_ratio()), (1, 1, Some(rat(1, 1)))); assert_eq!((out_p, scale), (Some(rat(5, 1)), 25600)); } @@ -269,9 +264,9 @@ fn fractional_times_are_exact_multiples_of_one_over_25600() { assert_eq!(h.in_relative, rat(8532, 25600)); assert_eq!(h.out_relative, rat(136532, 25600)); assert_eq!(h.start, rat(0, 25600)); + // 0.33328125 s and 5.33328125 s. assert_eq!(h.in_point(), Some(rat(2133, 6400))); - assert_eq!(h.in_point_seconds(), Some(0.33328125)); - assert_eq!(h.out_point_seconds(), Some(5.33328125)); + assert_eq!(h.out_point(), Some(rat(34133, 6400))); assert_eq!(h.stretch_ratio(), Some(rat(1, 1))); } @@ -364,18 +359,17 @@ fn pixel_aspect_shutter_phase_and_display_start() { // 325: pixelAspect 0.9091 reads back 0.90909090909091 = the exact ratio 10/11. let h = skip!(comp_header("325-comp-pixelaspect-0.9091.aep")); assert_eq!(h.pixel_aspect.reduced(), Some(rat(10, 11))); - assert!(near(h.pixel_aspect_ratio().unwrap(), 0.90909090909091, 1e-12)); // 326: shutterPhase -90, the shutter angle stays 180. let h = skip!(comp_header("326-comp-shutterphase-m90.aep")); assert_eq!((h.shutter_phase, h.shutter_angle), (Some(-90), 180)); // 327: displayStartFrame 100 at 25 fps = 4 s = 102400/25600; the shutter phase is back to 0. let h = skip!(comp_header("327-comp-displaystartframe-100.aep")); assert_eq!(h.display_start, Some(rat(102400, 25600))); - assert_eq!((h.display_start_seconds(), h.display_start_frame(), h.shutter_phase), (Some(4.0), Some(100), Some(0))); + assert_eq!(h.shutter_phase, Some(0)); // The base: no phase, start 0. let h = skip!(comp_header("000-base.aep")); - assert_eq!((h.shutter_phase, h.display_start_seconds(), h.display_start_frame()), (Some(0), Some(0.0), Some(0))); - assert_eq!(h.pixel_aspect_ratio(), Some(1.0)); + assert_eq!((h.shutter_phase, h.display_start.and_then(|r| r.reduced())), (Some(0), Some(rat(0, 1)))); + assert_eq!(h.pixel_aspect.reduced(), Some(rat(1, 1))); // A short chunk still decodes the old fields. let bytes = [0u8; 176]; let h = craft_aep::CompHeader::parse(&bytes).unwrap(); diff --git a/crates/aep/tests/it/container/batch3_objects.rs b/crates/aep/tests/it/container/batch3_objects.rs index bbb7040b4..c78525a00 100644 --- a/crates/aep/tests/it/container/batch3_objects.rs +++ b/crates/aep/tests/it/container/batch3_objects.rs @@ -148,19 +148,21 @@ fn a_mask_box_is_normalised_to_the_layer_size() { for (got, want) in m.shapes[0].bbox.iter().zip(want_box) { assert!(near(f64::from(*got), want, 1e-6), "{:?}", m.shapes[0].bbox); } - let shapes = project.mask_vertices_px(&layer, m).unwrap(); - assert_eq!(shapes.len(), 1); - let got: Vec<[f64; 2]> = shapes[0].iter().map(|v| v.position).collect(); + // The box scales by the size of the layer's source (the importer takes that size from the + // source item it matched, the same item `layer_source_size` reads). + let (w, h) = project.layer_source_size(&layer).unwrap(); + assert_eq!(m.shapes.len(), 1); + let got: Vec<[f64; 2]> = m.shapes[0].vertices((f64::from(w), f64::from(h))).iter().map(|v| v.position).collect(); for (g, w) in got.iter().zip([[20.0, 30.0], [80.0, 30.0], [80.0, 70.0], [20.0, 70.0]]) { assert_near(g, &w, 1e-3); } assert_eq!(got.len(), 4); - // A layer without a sized source has no pixel vertices. + // A layer without a sized source has no size to scale by. let bytes = fixture!("333-shape-group-two-rects.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); let shape = layer_named(&first_comp(&project), "Shape"); - assert!(project.mask_vertices_px(&shape, m).is_none()); + assert!(project.layer_source_size(&shape).is_none()); } #[test] @@ -178,12 +180,14 @@ fn one_mkif_per_mask_and_the_mode_none() { assert_eq!((m.mode, m.inverted, m.counter), (Some(MaskMode::Add), Some(false), Some(counter))); assert_eq!(m.shapes.len(), 1); } - let v1 = project.mask_vertices_px(&layer, &masks[0]).unwrap(); + let (w, h) = project.layer_source_size(&layer).unwrap(); + let px = |m: &craft_aep::Mask| m.shapes.iter().map(|s| s.vertices((f64::from(w), f64::from(h)))).collect::>(); + let v1 = px(&masks[0]); for (v, w) in v1[0].iter().zip(ellipse_vertices()) { assert_near(&v.position, &w, 1e-2); } // Mask 2 has its own box (500..900 x 350..650) normalised to the layer. - let v2 = project.mask_vertices_px(&layer, &masks[1]).unwrap(); + let v2 = px(&masks[1]); for (v, w) in v2[0].iter().zip([[500.0, 350.0], [900.0, 350.0], [900.0, 650.0], [500.0, 650.0]]) { assert_near(&v.position, &w, 1e-2); } @@ -384,81 +388,16 @@ fn the_last_style_run_absorbs_the_final_carriage_return() { // ------------------------------------------------------------------ camera and light (341-345) +/// Camera zoom keeps the auto position. #[test] -fn camera_zoom_and_depth_of_field() { - let camera = |name: &str| { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_of_type(&first_comp(&project), LayerType::Camera); - ( - layer.camera_zoom(), - layer.camera_depth_of_field(), - layer.camera_focus_distance(), - layer.camera_aperture(), - layer.camera_position().map(|p| (p.stored, p.auto_state)), - ) - }) - }; - // 341: Zoom 2000 is stored; the auto Position keeps [0, 0, -2666.67]. - let (zoom, dof, focus, aperture, pos) = skip!(camera("341-camera-zoom-2000.aep")); - assert_eq!(zoom.map(|z| (z.value, z.source)), Some((2000.0, ValueSource::Stored))); - assert_eq!((dof.map(|d| (d.value, d.source)), focus, aperture), (Some((false, ValueSource::Default)), None, None)); - let (stored, auto) = pos.unwrap(); - assert!(auto && near(stored[2], -2666.67, 0.01) && stored[0] == 0.0, "{stored:?}"); - // 342: DOF on, Focus Distance 800, Aperture 30; Zoom stays the default. - let (zoom, dof, focus, aperture, _) = skip!(camera("342-camera-dof-800-30.aep")); - assert_eq!(zoom.map(|z| (z.source, near(z.value, 2666.67, 0.01))), Some((ValueSource::Default, true))); - assert_eq!(dof.map(|d| (d.value, d.source)), Some((true, ValueSource::Stored))); - assert_eq!(focus.map(|f| (f.value, f.source)), Some((800.0, ValueSource::Stored))); - assert_eq!(aperture.map(|f| (f.value, f.source)), Some((30.0, ValueSource::Stored))); - // The default camera (256) has nothing but the default zoom. - let (zoom, dof, ..) = skip!(camera("256-camera-two-node-default.aep")); - assert_eq!((zoom.unwrap().source, dof.unwrap().value), (ValueSource::Default, false)); - assert_eq!(zoom.unwrap().value, craft_aep::DEFAULT_CAMERA_ZOOM); -} - -#[test] -fn light_colour_cone_angle_and_feather() { - let light = |name: &str| { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_of_type(&first_comp(&project), LayerType::Light); - assert_eq!(layer.header().unwrap().light_type(), Some(craft_aep::LightType::Spot), "{name}"); - let t = |x: Option>| x.map(|x| (x.value, x.source)); - (layer.light_color().map(|c| (c.value, c.source)), t(layer.light_cone_angle()), t(layer.light_cone_feather())) - }) - }; - // The default spot light: white, 90, 50, all absent. - let (colour, angle, feather) = skip!(light("254-light-spot-intensity-50.aep")); - assert_eq!( - (colour, angle, feather), - (Some(([1.0; 4], ValueSource::Default)), Some((90.0, ValueSource::Default)), Some((50.0, ValueSource::Default))) - ); - // 343: colour [1,0,0,1] = ARGB doubles [255,255,0,0]. - let (colour, angle, feather) = skip!(light("343-light-spot-color-red.aep")); - assert_eq!(colour, Some(([1.0, 1.0, 0.0, 0.0], ValueSource::Stored))); - assert_eq!((angle, feather), (Some((90.0, ValueSource::Default)), Some((50.0, ValueSource::Default)))); - // 344: Cone Angle 60. 345: Cone Feather 30. - let (colour, angle, feather) = skip!(light("344-light-spot-coneangle-60.aep")); - assert_eq!((colour.unwrap().1, angle, feather), (ValueSource::Default, Some((60.0, ValueSource::Stored)), Some((50.0, ValueSource::Default)))); - let (_, angle, feather) = skip!(light("345-light-spot-conefeather-30.aep")); - assert_eq!((angle, feather), (Some((90.0, ValueSource::Default)), Some((30.0, ValueSource::Stored)))); - // A point light (252) stores Cone Angle 90 / Feather 50 in their default state. - let bytes = fixture!("252-light-point.aep"); +fn camera_zoom_keeps_the_auto_position() { + // 341: Zoom 2000 is stored (checked on import); the auto Position keeps [0, 0, -2666.67]. + let bytes = fixture!("341-camera-zoom-2000.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); - let layer = layer_of_type(&first_comp(&project), LayerType::Light); - assert_eq!(layer.light_cone_angle().map(|a| (a.value, a.source)), Some((90.0, ValueSource::Stored))); - // Layers without light options have no light accessors. - let bytes = fixture!("000-base.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let solid = base_layer(&first_comp(&project)); - assert!(solid.light_color().is_none() && solid.camera_zoom().is_none() && solid.camera_depth_of_field().is_none()); + let layer = layer_of_type(&first_comp(&project), LayerType::Camera); + let pos = layer.camera_position().unwrap(); + assert!(pos.auto_state && near(pos.stored[2], -2666.67, 0.01) && pos.stored[0] == 0.0, "{:?}", pos.stored); } // ------------------------------------------------------------------ marker data (347-349, 249) @@ -508,7 +447,7 @@ fn audio_footage_item() { assert_eq!((f.width, f.height, f.is_solid), (0, 0, false)); assert_eq!(f.duration, Some(rat(48000, 48000))); assert_eq!((f.audio_sample_rate, f.file_size, f.bits_per_pixel, f.native_frame_rate), (Some(48000.0), 96044, 0, 0)); - assert!(!f.is_sequence && f.sequence_frame_count().is_none()); + assert!(!f.is_sequence && item.sequence_info().is_none()); // The combined file stores no display name for the item (the single-case file had // "test-tone.wav"); the path names the file. assert_eq!(item.label(), Some(7)); @@ -532,7 +471,7 @@ fn image_sequence_is_one_item() { assert_eq!(f.duration, Some(rat(3, 30)), "{name}"); assert_eq!((f.native_frame_rate, f.bits_per_pixel, f.file_size, f.audio_sample_rate), (30, 24, 504, None), "{name}"); assert!(f.is_sequence, "{name}"); - assert_eq!(f.sequence_frame_count(), Some(3), "{name}"); + assert_eq!(item.sequence_info().map(|s| s.frame_count()), Some(3), "{name}"); // The first file name sits in opti; the alias points at the sequence folder. assert_eq!(f.name.as_deref(), Some("seq_001.png"), "{name}"); assert!(f.path.as_deref().is_some_and(|p| p.ends_with("test-seq")), "{name}"); diff --git a/crates/aep/tests/it/container/cases_600.rs b/crates/aep/tests/it/container/cases_600.rs index 210fb0916..43df3052a 100644 --- a/crates/aep/tests/it/container/cases_600.rs +++ b/crates/aep/tests/it/container/cases_600.rs @@ -38,7 +38,7 @@ fn a_composition_counts_the_compositions_it_shows() { let id = |n: &str| items.iter().find(|i| i.display_name().as_deref() == Some(n)).and_then(|i| i.id()).expect(n); let c = items.iter().find(|i| i.display_name().as_deref() == Some("C")).expect("C"); // The list holds each used composition once (in no particular order). - let mut used = c.used_item_ids(); + let mut used = crate::common::used_item_ids(c); used.sort(); let mut want = vec![id("P30"), id("Q")]; want.sort(); @@ -60,8 +60,8 @@ fn an_image_sequence_knows_its_numbering() { let item = project.all_items().into_iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).expect("sequence"); let f = item.footage().expect("footage"); assert_eq!((f.file_type.as_str(), f.width, f.height, f.native_frame_rate, f.is_sequence), ("oEXR", 64, 48, 30, true)); - assert_eq!(f.sequence_frame_count(), Some(3)); let s = item.sequence_info().expect("numbering"); + assert_eq!(s.frame_count(), 3); assert_eq!((s.prefix.as_str(), s.suffix.as_str(), s.start, s.end, s.digits), ("shot_", ".exr", 101, 103, 4)); assert_eq!(s.file_name(101), "shot_0101.exr"); // A still has no numbering (000: the solid; the base has no other footage). diff --git a/crates/aep/tests/it/container/header.rs b/crates/aep/tests/it/container/header.rs index f78b0bba9..f9252f7fd 100644 --- a/crates/aep/tests/it/container/header.rs +++ b/crates/aep/tests/it/container/header.rs @@ -55,7 +55,6 @@ fn assert_plain(h: &LayerHeader) { assert_eq!(h.label, 1); // No name was set, so the copy of the name at byte 64 is empty (the layer shows its source name). assert_eq!(h.name_copy, ""); - assert!(!h.name_is_user_set()); assert!(!h.is_null_object()); assert_eq!(h.parent_id, None); assert_eq!(h.source_id, Some(0x1a)); @@ -67,16 +66,13 @@ fn base_layer_header() { assert_plain(&h); assert_eq!(h.quality, Quality::Best); assert_eq!(h.blend_mode, BlendMode::Normal); - assert_eq!(h.stretch, 1); - assert_eq!(h.stretch_percent(), 100.0); + assert_eq!((h.stretch, h.stretch_den), (1, 1)); assert_eq!(switches(&h), NONE); // start 0 s, in 0 s, out 5 s; denominator = the composition timescale. assert_eq!(h.start, Rational { num: 0, den: 25600 }); assert_eq!(h.in_relative, Rational { num: 0, den: 25600 }); assert_eq!(h.out_relative, Rational { num: 128_000, den: 25600 }); - assert_eq!(h.start_seconds(), Some(0.0)); - assert_eq!(h.in_point_seconds(), Some(0.0)); - assert_eq!(h.out_point_seconds(), Some(5.0)); + assert_eq!(h.in_point(), Rational::new(0, 1)); assert_eq!(h.out_point(), Rational::new(5, 1)); } @@ -98,7 +94,7 @@ fn one_switch_per_case() { assert_eq!(switches(&h), expected, "{name}"); assert_plain(&h); assert_eq!((h.quality, h.blend_mode, h.stretch), (Quality::Best, BlendMode::Normal, 1), "{name}"); - assert_eq!(h.out_point_seconds(), Some(5.0), "{name}"); + assert_eq!(h.out_point(), Rational::new(5, 1), "{name}"); } } @@ -106,7 +102,6 @@ fn one_switch_per_case() { fn name_blend_mode_and_quality() { let h = skip!(l_header("010-layer-name.aep")); assert_eq!(h.name_copy, "Renamed"); - assert!(h.name_is_user_set()); let bytes = fixture!("010-layer-name.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); @@ -114,7 +109,6 @@ fn name_blend_mode_and_quality() { // The layer name is the user's; the source footage keeps its own name. assert_eq!(layer.name().as_deref(), Some("Renamed")); assert_eq!(project.layer_source(&layer).and_then(|i| i.display_name()).as_deref(), Some("L")); - assert_eq!(project.layer_display_name(&layer).as_deref(), Some("Renamed")); assert_eq!(skip!(l_header("016-layer-blend-multiply.aep")).blend_mode, BlendMode::Multiply); assert_eq!(skip!(l_header("023-layer-quality-draft.aep")).quality, Quality::Draft); @@ -127,7 +121,7 @@ fn display_name_falls_back_to_the_source_name() { let project = Project::new(&file).unwrap(); let layer = base_layer(&first_comp(&project)); assert_eq!(layer.name(), None); - assert_eq!(project.layer_display_name(&layer).as_deref(), Some("L")); + assert_eq!(project.layer_source(&layer).and_then(|i| i.display_name()).as_deref(), Some("L")); assert_eq!(project.layer_source_size(&layer), Some((1920, 1080))); let source = project.layer_source(&layer).unwrap(); assert_eq!(source.id(), Some(0x1a)); @@ -139,26 +133,23 @@ fn time_stretch_and_the_in_out_start_convention() { // 018: stretch 100 -> 200: the stored out point stays 5 s, the layer ends at 10 s. let h = skip!(l_header("018-layer-stretch200.aep")); assert_eq!(h.stretch, 2); - assert_eq!(h.stretch_percent(), 200.0); + assert_eq!(h.stretch_ratio(), Rational::new(2, 1)); assert_eq!(h.out_relative, Rational { num: 128_000, den: 25600 }); - assert_eq!(h.out_point_seconds(), Some(10.0)); - assert_eq!(h.in_point_seconds(), Some(0.0)); + assert_eq!(h.out_point(), Rational::new(10, 1)); + assert_eq!(h.in_point(), Rational::new(0, 1)); // 019: inPoint 0 -> 1; AE moved the out point to 6 s and left the start at 0. let h = skip!(l_header("019-layer-inpoint1.aep")); - assert_eq!(h.start_seconds(), Some(0.0)); + assert_eq!(h.start.num, 0); assert_eq!(h.in_relative, Rational { num: 25600, den: 25600 }); assert_eq!(h.in_point(), Rational::new(1, 1)); - assert_eq!(h.out_point_seconds(), Some(6.0)); + assert_eq!(h.out_point(), Rational::new(6, 1)); // 021: startTime 0 -> 0.5: in 0.5 s and out 5.5 s although the stored in point stays 0. let h = skip!(l_header("021-layer-starttime0.5.aep")); assert_eq!(h.start, Rational { num: 12800, den: 25600 }); - assert_eq!(h.start_seconds(), Some(0.5)); assert_eq!(h.in_relative.num, 0); assert_eq!(h.in_point(), Rational::new(1, 2)); - assert_eq!(h.in_point_seconds(), Some(0.5)); - assert_eq!(h.out_point_seconds(), Some(5.5)); assert_eq!(h.out_point(), Rational::new(11, 2)); } @@ -175,7 +166,6 @@ fn parent_link_and_null_object() { let nh = null.header().unwrap(); assert_eq!(null.name().as_deref(), Some("Null")); assert!(nh.is_null_object()); - assert!(nh.name_is_user_set()); assert_eq!(nh.layer_type, LayerType::Av); assert_eq!(nh.parent_id, None); assert_eq!(project.layer_source(null).and_then(|i| i.display_name()).as_deref(), Some("Null 1")); @@ -225,17 +215,14 @@ fn base_comp_header() { assert_eq!((h.width, h.height), (1920, 1080)); assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 25600)); assert_eq!(h.frame_rate(), Some(25.0)); - assert_eq!(h.frame_rate_from_fixed(), 25.0); + assert_eq!(h.frame_rate_fixed, 25 << 16); assert_eq!(h.duration_units, 128_000); assert_eq!(h.duration_seconds(), Some(5.0)); assert_eq!(h.background, [0, 0, 0]); - assert_eq!(h.background_rgb(), [0.0, 0.0, 0.0]); assert_eq!(h.shutter_angle, 180); - assert_eq!(h.work_area_start_seconds(), Some(0.0)); + assert_eq!(h.work_area_start_units, 0); assert_eq!(h.work_area_end_units, None); - assert_eq!(h.work_area_end_seconds(), Some(5.0)); assert_eq!(h.pixel_aspect, Rational { num: 1, den: 1 }); - assert_eq!(h.pixel_aspect_ratio(), Some(1.0)); assert!(!h.motion_blur); // The manifest calls the classic renderer `ADBE Advanced 3d`; the file stores `ADBE Escher` // and the display name `Classic 3D`. @@ -255,7 +242,7 @@ fn one_comp_change_per_case() { let (h, _, _) = skip!(comp_header("031-comp-fps30.aep")); assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 30720)); assert_eq!(h.frame_rate(), Some(30.0)); - assert_eq!(h.frame_rate_from_fixed(), 30.0); + assert_eq!(h.frame_rate_fixed, 30 << 16); assert_eq!(h.duration_units, 153_600); assert_eq!(h.duration_seconds(), Some(5.0)); @@ -263,12 +250,11 @@ fn one_comp_change_per_case() { let (h, _, _) = skip!(comp_header("032-comp-duration10.aep")); assert_eq!(h.duration_units, 256_000); assert_eq!(h.duration_seconds(), Some(10.0)); - assert_eq!(h.work_area_end_seconds(), Some(10.0)); + assert_eq!(h.work_area_end_units, None); // 033: bgColor [0,0,0] -> [0,1,0]. let (h, _, _) = skip!(comp_header("033-comp-bg-green.aep")); assert_eq!(h.background, [0, 255, 0]); - assert_eq!(h.background_rgb(), [0.0, 1.0, 0.0]); // 034: shutterAngle 180 -> 90. let (h, _, _) = skip!(comp_header("034-comp-shutter90.aep")); @@ -279,8 +265,6 @@ fn one_comp_change_per_case() { let (h, _, _) = skip!(comp_header("035-comp-workarea-1-2.aep")); assert_eq!(h.work_area_start_units, 25600); assert_eq!(h.work_area_end_units, Some(76_800)); - assert_eq!(h.work_area_start_seconds(), Some(1.0)); - assert_eq!(h.work_area_end_seconds(), Some(3.0)); } #[test] @@ -290,7 +274,6 @@ fn one_comp_change_per_case_aspect_blur_renderer() { // 037: pixelAspect 1 -> 2. let (h, _, _) = skip!(comp_header("037-comp-pixelaspect2.aep")); assert_eq!(h.pixel_aspect, Rational { num: 2, den: 1 }); - assert_eq!(h.pixel_aspect_ratio(), Some(2.0)); // 038: comp motion blur on. let (h, _, _) = skip!(comp_header("038-comp-motionblur.aep")); @@ -328,17 +311,16 @@ fn precomp_item_ids_and_labels() { assert_eq!(h.source_id, pre_item.id()); assert_eq!(project.layer_source(layer).unwrap().id(), pre_item.id()); assert_eq!(h.label, 15); - assert!(!h.name_is_user_set()); assert_eq!(layer.name(), None); - assert_eq!(project.layer_display_name(layer).as_deref(), Some("Pre")); + assert_eq!(project.layer_source(layer).and_then(|i| i.display_name()).as_deref(), Some("Pre")); assert_eq!(project.layer_source_size(layer), Some((1920, 1080))); // The precomp layer's start time has the denominator 1; the Pre comp is 1920x1080, 25 fps, 5 s. assert_eq!(h.start.den, 1); let ph = pre.header().unwrap(); assert_eq!((ph.width, ph.height, ph.frame_rate(), ph.duration_seconds()), (1920, 1080, Some(25.0), Some(5.0))); // C records that it uses the comp Pre (chunk idpi, a little-endian u32). - assert_eq!(c_item.used_item_ids(), [pre_item.id().unwrap()]); - assert!(pre_item.used_item_ids().is_empty()); + assert_eq!(crate::common::used_item_ids(c_item), [pre_item.id().unwrap()]); + assert!(crate::common::used_item_ids(pre_item).is_empty()); assert_eq!(pre_item.label(), Some(15)); // The layer inside Pre is a new layer made from the solid L (moving the layers into a precomp // creates new layers). @@ -347,7 +329,7 @@ fn precomp_item_ids_and_labels() { let ih = inner[0].header().unwrap(); assert_ne!(ih.id, L); assert_eq!(ih.source_id, Some(0x1a)); - assert_eq!(project.layer_display_name(&inner[0]).as_deref(), Some("L")); + assert_eq!(project.layer_source(&inner[0]).and_then(|i| i.display_name()).as_deref(), Some("L")); } #[test] @@ -356,9 +338,8 @@ fn a_negative_stretch_is_a_reversed_layer() { // point 0 and out point 5 s relative, so the layer runs from 5 s back to 0 s; 983: -50 % = -1/2. let h = skip!(l_header("981-layer-stretch-minus100-start5.aep")); assert_eq!((h.stretch, h.stretch_den), (-1, 1)); - assert_eq!(h.stretch_percent(), -100.0); - assert_eq!((h.in_point_seconds(), h.out_point_seconds()), (Some(5.0), Some(0.0))); + assert_eq!((h.in_point(), h.out_point()), (Rational::new(5, 1), Rational::new(0, 1))); let h = skip!(l_header("983-layer-stretch-minus50-opacity-keys.aep")); assert_eq!((h.stretch, h.stretch_den), (-1, 2)); - assert_eq!((h.in_point_seconds(), h.out_point_seconds()), (Some(5.0), Some(2.5))); + assert_eq!((h.in_point(), h.out_point()), (Rational::new(5, 1), Rational::new(5, 2))); } diff --git a/crates/aep/tests/it/container/helpers.rs b/crates/aep/tests/it/container/helpers.rs index b6ab11432..af2282ab8 100644 --- a/crates/aep/tests/it/container/helpers.rs +++ b/crates/aep/tests/it/container/helpers.rs @@ -379,7 +379,8 @@ pub fn layer_named<'f, 'a>(comp: &Comp<'f, 'a>, name: &str) -> Layer<'f, 'a> { /// The layer that shows this name: its own name, or its source's while it has none. pub fn layer_shown_as<'f, 'a>(project: &Project<'f, 'a>, comp: &Comp<'f, 'a>, name: &str) -> Layer<'f, 'a> { - comp.layers().find(|l| project.layer_display_name(l).as_deref() == Some(name)).unwrap_or_else(|| panic!("no layer shown as {name}")) + let shown = |l: &Layer<'f, 'a>| l.name().or_else(|| project.layer_source(l)?.display_name()); + comp.layers().find(|l| shown(l).as_deref() == Some(name)).unwrap_or_else(|| panic!("no layer shown as {name}")) } /// The first layer of this type in a composition. diff --git a/crates/aep/tests/it/container/keyframes.rs b/crates/aep/tests/it/container/keyframes.rs index 56ec367cc..27b8073ab 100644 --- a/crates/aep/tests/it/container/keyframes.rs +++ b/crates/aep/tests/it/container/keyframes.rs @@ -19,6 +19,9 @@ fn prop_of(name: &str, path: &[&str], f: impl FnOnce(Property<'_, '_>) -> R) const POSITION: &[&str] = &["ADBE Transform Group", "ADBE Position"]; const OPACITY: &[&str] = &["ADBE Transform Group", "ADBE Opacity"]; +/// The ease of a linear key: all four slots 0. +const NO_EASE: KeyEase = KeyEase { in_speed: 0.0, in_influence: 0.0, out_speed: 0.0, out_influence: 0.0 }; + fn ease(in_speed: f64, in_influence: f64, out_speed: f64, out_influence: f64) -> KeyEase { KeyEase { in_speed, in_influence, out_speed, out_influence } } @@ -33,7 +36,7 @@ fn in_and_out_interpolation_are_separate_bytes() { assert_eq!((keys[0].interpolation_in(), keys[0].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Hold))); assert_eq!((keys[1].interpolation_in(), keys[1].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 1.0]); - assert_eq!(keys[1].spatial_value(), Some([100.0, 0.0, 0.0])); + assert_eq!(keys[1].value(), Some(vec![100.0, 0.0, 0.0])); })); // 203: key 1 inType HOLD, outType LINEAR (bytes 03 01): byte 4 is the incoming side. skip!(prop_of("203-key-in-hold-out-linear.aep", POSITION, |p| { @@ -76,7 +79,7 @@ fn opacity_ease_speed_is_in_stored_units_per_second() { assert_near(&[e0.in_speed, e0.in_influence, e0.out_speed, e0.out_influence], &[0.05, 0.2, 0.2, 0.8], 1e-12); let e1 = keys[1].ease().unwrap(); assert_near(&[e1.in_speed, e1.in_influence, e1.out_speed, e1.out_influence], &[0.3, 0.6, 0.09, 0.4], 1e-12); - assert_eq!(keys[0].plain_ease_slots().unwrap().len(), 4); + assert_eq!(keys[0].ease_components(), Some(vec![e0])); for k in &keys { assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); } @@ -94,7 +97,7 @@ fn scale_keys_use_the_plain_template_with_three_components() { // A 128-byte record is not always spatial: the header's template flag decides. assert_eq!(k.kind(), KeyframeKind::Plain { components: 3 }); assert_eq!(k.spatial(), None); - assert_eq!(k.plain_ease_slots(), Some(vec![0.0; 12])); + assert_eq!(k.ease_components(), Some(vec![NO_EASE; 3])); assert_eq!(k.ease(), None); assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); } @@ -125,7 +128,7 @@ fn two_dimensional_mask_feather_keys() { assert!(keys.iter().all(|k| k.raw().len() == 88 && k.kind() == KeyframeKind::Plain { components: 2 })); assert_eq!(keys.iter().map(|k| k.value().unwrap()).collect::>(), [vec![0.0, 0.0], vec![40.0, 20.0]]); assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 1.0]); - assert_eq!(keys[0].plain_ease_slots(), Some(vec![0.0; 8])); + assert_eq!(keys[0].ease_components(), Some(vec![NO_EASE; 2])); let mask = &layer.masks()[0]; assert!(mask.feather.source == ValueSource::Keyframed && mask.feather.value == [0.0, 0.0]); } diff --git a/crates/aep/tests/it/container/layer_switches.rs b/crates/aep/tests/it/container/layer_switches.rs index 5e2179d53..05e939c38 100644 --- a/crates/aep/tests/it/container/layer_switches.rs +++ b/crates/aep/tests/it/container/layer_switches.rs @@ -2,7 +2,7 @@ //! colours, checked against the values the corpus was made with (its MANIFEST, batch 2). use crate::container::helpers::{assert_near, base_layer, first_comp, layer_of_type, layer_shown_as, open}; -use craft_aep::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Project, Rational, ValueSource}; +use craft_aep::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Project}; fn l_header(name: &str) -> Option { Some({ @@ -80,22 +80,24 @@ fn ntsc_frame_rates_are_exact_fractions() { // 229: frameRate 29.97 -> read back 29.9700012207031; the duration snaps from 5 s to 150 frames (5.005005 s). let h = skip!(comp_header("229-comp-fps-29.97.aep")); assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (800, 23976)); - assert_eq!(h.frame_rate_exact(), Some(Rational { num: 2997, den: 100 })); assert!((h.frame_rate().unwrap() - 29.97).abs() < 1e-12); - assert!((h.frame_rate_from_fixed() - 29.970_001_220_703_1).abs() < 1e-7); - assert_eq!((h.duration_units, h.duration_frames()), (120_000, Some(150))); + // The 16.16 rate holds the float32 29.97 (29.9700012207031). + assert_eq!(h.frame_rate_fixed, 1_964_114); + // 150 frames of 800 units. + assert_eq!(h.duration_units, 120_000); assert!((h.duration_seconds().unwrap() - 5.005_005_005_005_01).abs() < 1e-9); // 230: frameRate 23.976 -> read back 23.9759979248047; 120 frames. let h = skip!(comp_header("230-comp-fps-23.976.aep")); assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1000, 23976)); - assert_eq!(h.frame_rate_exact(), Some(Rational { num: 2997, den: 125 })); assert!((h.frame_rate().unwrap() - 23.976).abs() < 1e-12); - assert!((h.frame_rate_from_fixed() - 23.975_997_924_804_7).abs() < 1e-7); - assert_eq!((h.duration_units, h.duration_frames()), (120_000, Some(120))); + // The 16.16 rate holds the float32 23.976 (23.9759979248047). + assert_eq!(h.frame_rate_fixed, 1_571_291); + // 120 frames of 1000 units. + assert_eq!(h.duration_units, 120_000); assert!((h.duration_seconds().unwrap() - 5.005_005_005_005_01).abs() < 1e-9); // 25 fps stays 25. let h = skip!(comp_header("000-base.aep")); - assert_eq!((h.frame_rate_exact(), h.duration_frames()), (Some(Rational { num: 25, den: 1 }), Some(125))); + assert_eq!((h.time_base.timescale, h.time_base.frame_duration, h.duration_units), (25600, 1024, 128_000)); } #[test] @@ -128,7 +130,6 @@ fn background_is_8_bits_per_channel() { // 231: bgColor [0.5, 0.5, 0.5] is stored as 128 and reads back as 128/255 = 0.50196. let h = skip!(comp_header("231-comp-bg-grey-0.5.aep")); assert_eq!(h.background, [128, 128, 128]); - assert_near(&h.background_rgb(), &[0.501_960_784_313_73; 3], 1e-12); // The frame rate stays 25 even though an earlier edit of the AE session left other numbers in the cache-like fields. assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 25600)); } @@ -143,12 +144,10 @@ fn cameras_auto_orient_and_position() { let camera = layer_of_type(&comp, LayerType::Camera); let h = camera.header().unwrap(); assert_eq!((h.flag_bytes[1], h.is_auto_oriented(), h.is_three_d(), h.source_id, h.light_type()), (0x44, true, true, None, None)); - // The default Position is an "auto state" record that stores [0, 0, -2666.67]; the two-node camera reports the comp centre. + // The default Position is an "auto state" record that stores [0, 0, -2666.67]. let pos = camera.camera_position().unwrap(); assert!(pos.auto_state); assert_near(&pos.stored, &[0.0, 0.0, -2666.67], 0.01); - assert_near(&pos.reported(1920, 1080, true), &[960.0, 540.0, -2666.67], 0.01); - assert_eq!(camera.camera_point_of_interest(), Some([960.0, 540.0, 0.0])); let bytes = fixture!("251-camera-one-node.aep"); let file = open(&bytes); @@ -159,10 +158,9 @@ fn cameras_auto_orient_and_position() { // AE reports [0, 0, -2666.67] for the one-node camera: the stored value. let pos = camera.camera_position().unwrap(); assert!(pos.auto_state); - assert_near(&pos.reported(1920, 1080, h.is_auto_oriented()), &[0.0, 0.0, -2666.67], 0.01); - assert_eq!(camera.camera_point_of_interest(), Some([960.0, 540.0, 0.0])); + assert_near(&pos.stored, &[0.0, 0.0, -2666.67], 0.01); - // 253: Position set to [100, 200, -1000]: stored as given, no auto state; the point of interest stays [960, 540, 0]. + // 253: Position set to [100, 200, -1000]: stored as given, no auto state. let bytes = fixture!("253-camera-position-100-200-m1000.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); @@ -170,35 +168,28 @@ fn cameras_auto_orient_and_position() { let pos = camera.camera_position().unwrap(); assert!(!pos.auto_state); assert_eq!(pos.stored, [100.0, 200.0, -1000.0]); - assert_eq!(pos.reported(1920, 1080, true), [100.0, 200.0, -1000.0]); - assert_eq!(camera.camera_point_of_interest(), Some([960.0, 540.0, 0.0])); - // A camera has no light intensity. - assert_eq!(camera.light_intensity(), None); } +/// Lights type and position. #[test] -fn lights_type_and_intensity() { - // 254: a spot light, Intensity 100 -> 50 (stored as 50.0 percent, absent at the default 100). +fn lights_type_and_position() { + // 254: a spot light (its Intensity 50 is checked on import). let bytes = fixture!("254-light-spot-intensity-50.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); let light = layer_of_type(&first_comp(&project), LayerType::Light); let h = light.header().unwrap(); assert_eq!((h.light_type(), h.light_type_code, h.source_id, h.is_auto_oriented(), h.is_three_d()), (Some(LightType::Spot), 1, None, true, true)); - let intensity = light.light_intensity().unwrap(); - assert_eq!((intensity.value, intensity.source), (50.0, ValueSource::Stored)); assert!(light.camera_position().unwrap().auto_state); assert_near(&light.camera_position().unwrap().stored, &[0.0, 0.0, -1333.33], 0.01); - // 252: a point light (light type 2) at the default intensity, which is not stored. + // 252: a point light (light type 2). let bytes = fixture!("252-light-point.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); let light = layer_of_type(&first_comp(&project), LayerType::Light); let h = light.header().unwrap(); assert_eq!((h.light_type(), h.light_type_code), (Some(LightType::Point), 2)); - let intensity = light.light_intensity().unwrap(); - assert_eq!((intensity.value, intensity.source), (100.0, ValueSource::Default)); // The solid under it is no light. let solid = base_layer(&first_comp(&project)).header().unwrap(); assert_eq!((solid.light_type(), solid.light_type_code), (None, 0)); @@ -220,6 +211,6 @@ fn solid_colour_is_four_float32_argb() { // L is still red. let red = project.layer_source(&base_layer(&comp)).unwrap().footage().unwrap(); assert_eq!(red.solid_rgb(), Some([1.0, 0.0, 0.0])); - // The new layer has no user-set name flag (it shows its source's name). - assert!(!blue.header().unwrap().name_is_user_set()); + // The new layer has no name of its own (it shows its source's name). + assert_eq!(blue.name(), None); } diff --git a/crates/aep/tests/it/container/matte.rs b/crates/aep/tests/it/container/matte.rs index 97c8aad74..c05045e39 100644 --- a/crates/aep/tests/it/container/matte.rs +++ b/crates/aep/tests/it/container/matte.rs @@ -13,7 +13,7 @@ fn layers(name: &str) -> Option, u32)>> { comp.layers() .map(|l| { let h = l.header().expect("header"); - (project.layer_display_name(&l).unwrap_or_default(), h.is_video_enabled(), l.track_matte(), h.id) + (l.name().or_else(|| project.layer_source(&l)?.display_name()).unwrap_or_default(), h.is_video_enabled(), l.track_matte(), h.id) }) .collect() }) diff --git a/crates/aep/tests/it/container/robustness.rs b/crates/aep/tests/it/container/robustness.rs index f27f53d25..0f26cdd4c 100644 --- a/crates/aep/tests/it/container/robustness.rs +++ b/crates/aep/tests/it/container/robustness.rs @@ -154,16 +154,15 @@ use craft_aep::{AepFile, Body, Chunk, Comp, Layer, Project, PropGroup, PropNode, /// Touches the property accessors; none may panic on a damaged property. fn exercise_property(p: &Property<'_, '_>) { - let _ = (p.header(), p.dims(), p.is_animated(), p.static_value(), p.time_scale(), p.flags(), p.is_static_flag_set()); - let _ = (p.expression(), p.expression_flags().map(|f| (f.all_set(), f.disabled())), p.expression_enabled(), p.user_name(), p.first_key_value()); - let _ = p.color_argb(); + let _ = (p.header(), p.dims(), p.is_animated(), p.static_value(), p.time_scale(), p.flags()); + let _ = (p.expression(), p.expression_flags().map(|f| f.disabled()), p.expression_enabled(), p.user_name(), p.first_key_value()); if let Some(keys) = p.keys() { let scale = p.time_scale().unwrap_or(0); for k in keys.keyframes() { - let _ = (k.time_units(), k.spatial_value(), k.raw().len(), k.kind(), k.seconds(scale), k.seconds(0)); + let _ = (k.time_units(), k.raw().len(), k.kind(), k.seconds(scale), k.seconds(0)); let _ = (k.interpolation_in(), k.interpolation_out(), k.flags(), k.label(), k.is_roving()); - let _ = (k.scalar_value(), k.ease(), k.spatial(), k.components(), k.value(), k.plain_ease_slots()); - let _ = (k.ease_components(), k.color_distance()); + let _ = (k.scalar_value(), k.ease(), k.spatial(), k.components(), k.value()); + let _ = k.ease_components(); for component in [0, 1, 2, 3, 7, 255, usize::MAX] { let _ = k.ease_component(component); } @@ -193,10 +192,9 @@ fn exercise_group(g: &PropGroup<'_, '_>, depth: usize) { fn exercise_layer(project: &Project<'_, '_>, comp_size: (u32, u32), layer: &Layer<'_, '_>) { let _ = (layer.name(), layer.is_three_d(), layer.id(), layer.track_matte()); if let Some(h) = layer.header() { - let _ = (h.in_point(), h.out_point(), h.in_point_seconds(), h.out_point_seconds(), h.start_seconds(), h.stretch_percent()); - let _ = (h.stretch_ratio(), h.stretch_den); + let _ = (h.in_point(), h.out_point(), h.stretch_ratio(), h.stretch_den); let _ = (h.is_shy(), h.is_locked(), h.is_solo(), h.is_three_d(), h.is_motion_blur(), h.is_adjustment(), h.is_guide()); - let _ = (h.is_null_object(), h.collapses_transformations(), h.name_is_user_set(), h.quality, h.blend_mode, h.layer_type); + let _ = (h.is_null_object(), h.collapses_transformations(), h.quality, h.blend_mode, h.layer_type); let _ = ( h.is_enabled(), h.is_video_enabled(), @@ -208,10 +206,8 @@ fn exercise_layer(project: &Project<'_, '_>, comp_size: (u32, u32), layer: &Laye ); } let _ = (layer.is_enabled(), layer.is_audio_enabled(), layer.is_effects_enabled()); - let _ = (layer.camera_position().map(|p| p.reported(comp_size.0, comp_size.1, true)), layer.camera_point_of_interest(), layer.light_intensity()); + let _ = layer.camera_position().map(|p| (p.stored, p.auto_state)); let _ = project.layer_anchor_px(layer); - let _ = (layer.camera_zoom(), layer.camera_depth_of_field(), layer.camera_focus_distance(), layer.camera_aperture()); - let _ = (layer.light_color(), layer.light_cone_angle(), layer.light_cone_feather()); let _ = layer .time_remap() .map(|t| (t.enabled, t.keys.iter().fold(0.0, |acc, k| acc + k.value_seconds + k.time_seconds.unwrap_or(0.0) + f64::from(k.time_units)))); @@ -238,7 +234,8 @@ fn exercise_layer(project: &Project<'_, '_>, comp_size: (u32, u32), layer: &Laye } } } - let _ = (project.layer_source(layer).map(|i| i.id()), project.layer_display_name(layer), project.layer_source_size(layer)); + let _ = + (project.layer_source(layer).map(|i| i.id()), project.layer_source(layer).and_then(|i| i.display_name()), project.layer_source_size(layer)); if let Some(t) = layer.transform(comp_size.0, comp_size.1) { let _ = (t.anchor_px(f64::from(comp_size.0), f64::from(comp_size.1)), t.position.value, t.opacity_percent.value); } @@ -271,7 +268,6 @@ fn exercise_layer(project: &Project<'_, '_>, comp_size: (u32, u32), layer: &Laye } for m in layer.masks() { let _ = (m.name.clone(), m.mode, m.inverted, m.counter, m.feather, m.opacity_percent, m.expansion, m.path_animated, m.path_key_seconds.len()); - let _ = project.mask_vertices_px(layer, &m).map(|shapes| shapes.iter().map(Vec::len).sum::()); for s in &m.shapes { let _ = (s.vertex_count(), s.vertices((1920.0, 1080.0)).len(), s.vertices((f64::NAN, f64::INFINITY)).len(), s.open); } @@ -302,10 +298,9 @@ fn exercise_comp(project: &Project<'_, '_>, comp: &Comp<'_, '_>) { let mut size = (1920, 1080); if let Some(h) = comp.header() { size = (u32::from(h.width), u32::from(h.height)); - let _ = (h.frame_rate(), h.frame_rate_from_fixed(), h.duration_seconds(), h.work_area_start_seconds(), h.work_area_end_seconds()); - let _ = (h.frame_rate_exact(), h.duration_frames()); - let _ = (h.background_rgb(), h.pixel_aspect_ratio(), h.pixel_aspect.reduced(), h.shutter_angle, h.motion_blur); - let _ = (h.shutter_phase, h.display_start, h.display_start_seconds(), h.display_start_frame()); + let _ = (h.frame_rate(), h.frame_rate_fixed, h.duration_seconds(), h.work_area_start_units, h.work_area_end_units); + let _ = (h.background, h.pixel_aspect.to_f64(), h.pixel_aspect.reduced(), h.shutter_angle, h.motion_blur); + let _ = (h.shutter_phase, h.display_start.map(|r| r.to_f64())); } for layer in comp.layers() { exercise_layer(project, size, &layer); @@ -316,10 +311,8 @@ fn exercise_comp(project: &Project<'_, '_>, comp: &Comp<'_, '_>) { fn exercise(file: &AepFile<'_>) { let Some(project) = Project::new(file) else { return }; for item in project.all_items() { - let _ = (item.kind(), item.name(), item.id(), item.label(), item.used_item_ids(), item.footage(), item.display_name()); - let _ = item - .footage() - .map(|f| (f.duration, f.native_frame_rate, f.bits_per_pixel, f.file_size, f.audio_sample_rate, f.is_sequence, f.sequence_frame_count())); + let _ = (item.kind(), item.name(), item.id(), item.label(), item.footage(), item.display_name()); + let _ = item.footage().map(|f| (f.duration, f.native_frame_rate, f.bits_per_pixel, f.file_size, f.audio_sample_rate, f.is_sequence)); let _ = item.id().and_then(|id| project.item_by_id(id)); if let Some(comp) = item.comp() { exercise_comp(&project, &comp); @@ -572,12 +565,12 @@ fn extreme_values_in_the_decoded_headers() { use craft_aep::{CompHeader, LayerHeader, Rational, ShapePath}; // Every field at its maximum: no overflow, no division by zero, no panic. let h = LayerHeader::parse(&[0xff; 164]).unwrap(); - let _ = (h.in_point(), h.out_point(), h.in_point_seconds(), h.out_point_seconds(), h.start_seconds(), h.stretch_percent()); + let _ = (h.in_point(), h.out_point(), h.start.to_f64(), h.stretch_ratio()); let mut zero_den = [0u8; 164]; zero_den[8..12].copy_from_slice(&u32::MAX.to_be_bytes()); zero_den[12..16].copy_from_slice(&i32::MIN.to_be_bytes()); let h = LayerHeader::parse(&zero_den).unwrap(); - assert_eq!((h.in_point(), h.out_point(), h.start_seconds()), (None, None, None)); + assert_eq!((h.in_point(), h.out_point(), h.start.to_f64()), (None, None, None)); let mut wide = [0u8; 164]; wide[8..12].copy_from_slice(&u32::MAX.to_be_bytes()); wide[12..16].copy_from_slice(&i32::MIN.to_be_bytes()); @@ -585,14 +578,12 @@ fn extreme_values_in_the_decoded_headers() { wide[20..24].copy_from_slice(&i32::MAX.to_be_bytes()); wide[24..28].copy_from_slice(&u32::MAX.to_be_bytes()); let h = LayerHeader::parse(&wide).unwrap(); - let _ = (h.in_point(), h.in_point_seconds()); + let _ = h.in_point(); let c = CompHeader::parse(&[0xff; 204]).unwrap(); - assert_eq!((c.duration_seconds(), c.work_area_start_seconds(), c.work_area_end_units), (None, None, None)); - let _ = (c.frame_rate(), c.frame_rate_from_fixed(), c.background_rgb(), c.pixel_aspect_ratio(), c.frame_rate_exact()); - assert_eq!(c.duration_frames(), Some(1)); + assert_eq!((c.duration_seconds(), c.work_area_end_units), (None, None)); + let _ = (c.frame_rate(), c.pixel_aspect.to_f64()); let zero = CompHeader::parse(&[0; 204]).unwrap(); - assert_eq!((zero.frame_rate(), zero.pixel_aspect_ratio(), zero.duration_seconds()), (None, None, None)); - assert_eq!((zero.frame_rate_exact(), zero.duration_frames()), (None, None)); + assert_eq!((zero.frame_rate(), zero.pixel_aspect.to_f64(), zero.duration_seconds()), (None, None, None)); let all = LayerHeader::parse(&[0xff; 164]).unwrap(); let _ = (all.is_enabled(), all.is_auto_oriented(), all.light_type(), all.blend_mode.code()); assert_eq!(LayerHeader::parse(&[0u8; 164]).unwrap().light_type(), None); @@ -691,7 +682,7 @@ fn hostile_text_dictionaries_and_marker_headers_never_panic() { #[test] fn extreme_values_in_the_batch_3_fields() { - use craft_aep::{CompHeader, Footage, LayerHeader, Rational}; + use craft_aep::{CompHeader, LayerHeader}; // Time stretch: zero and maximal numerators and denominators (bytes 8 and 108), with extreme times. for (num, den) in [(0u32, 0u32), (1, 0), (0, 1), (u32::MAX, 1), (1, u32::MAX), (u32::MAX, u32::MAX), (3, 2)] { let mut ldta = [0u8; 164]; @@ -704,7 +695,7 @@ fn extreme_values_in_the_batch_3_fields() { ldta[28..32].copy_from_slice(&i32::MIN.to_be_bytes()); ldta[32..36].copy_from_slice(&1u32.to_be_bytes()); let h = LayerHeader::parse(&ldta).unwrap(); - let _ = (h.stretch_ratio(), h.stretch_percent(), h.in_point(), h.out_point(), h.in_point_seconds(), h.out_point_seconds()); + let _ = (h.stretch_ratio(), h.in_point(), h.out_point()); if den == 0 { assert_eq!((h.stretch_ratio(), h.in_point(), h.out_point()), (None, None, None)); } @@ -712,34 +703,8 @@ fn extreme_values_in_the_batch_3_fields() { // Display start and shutter phase from extreme bytes; a missing tail leaves them unknown. for fill in [0x00u8, 0x7f, 0x80, 0xff] { let c = CompHeader::parse(&[fill; 204]).unwrap(); - let _ = (c.shutter_phase, c.display_start, c.display_start_seconds(), c.display_start_frame()); + let _ = (c.shutter_phase, c.display_start.map(|r| r.to_f64())); } - let zero_rate = CompHeader::parse(&[0; 204]).unwrap(); - assert_eq!((zero_rate.display_start_seconds(), zero_rate.display_start_frame()), (None, None)); - // Footage durations: zero denominator, negative and maximal numerators, a huge frame rate. - let base = Footage { - file_type: String::new(), - width: 0, - height: 0, - name: None, - is_solid: false, - solid_argb: None, - path: None, - duration: None, - native_frame_rate: 0, - bits_per_pixel: 0, - file_size: 0, - audio_sample_rate: None, - is_sequence: true, - psd_layer: None, - }; - for (num, den, rate) in - [(3i64, 30i64, 30u32), (3, 0, 30), (-3, 30, 30), (i64::MAX, 1, u32::MAX), (i64::MIN, -1, u32::MAX), (1, i64::MAX, 1), (0, 1, 0)] - { - let f = Footage { duration: Some(Rational { num, den }), native_frame_rate: rate, ..base.clone() }; - let _ = f.sequence_frame_count(); - } - assert_eq!(Footage { duration: Some(Rational { num: 3, den: 30 }), native_frame_rate: 30, ..base.clone() }.sequence_frame_count(), Some(3)); - assert_eq!(Footage { duration: Some(Rational { num: 3, den: 0 }), native_frame_rate: 30, ..base.clone() }.sequence_frame_count(), None); - assert_eq!(Footage { duration: None, ..base }.sequence_frame_count(), None); + // A zero denominator has no value. + assert_eq!(CompHeader::parse(&[0; 204]).unwrap().display_start.and_then(|r| r.to_f64()), None); } diff --git a/crates/aep/tests/it/container/text_markers_footage.rs b/crates/aep/tests/it/container/text_markers_footage.rs index 6d666fbee..f6f81eed1 100644 --- a/crates/aep/tests/it/container/text_markers_footage.rs +++ b/crates/aep/tests/it/container/text_markers_footage.rs @@ -13,7 +13,6 @@ fn text_layer_document(name: &str) -> Option { let layer = comp.layers().find(|l| l.name().as_deref() == Some("T")).expect("the text layer T"); let h = layer.header().unwrap(); assert_eq!(h.layer_type, LayerType::Text); - assert!(h.name_is_user_set()); layer.text_document().expect("text document") }) } @@ -192,7 +191,6 @@ fn png_footage_layer() { // The path comes from the alias JSON (the fixture holds a neutral replacement of the original). assert!(f.path.as_deref().is_some_and(|p| p.ends_with("test8x8.png")), "{:?}", f.path); assert_eq!(project.layer_source_size(&layer), Some((8, 8))); - assert_eq!(project.layer_display_name(&layer).as_deref(), Some("png")); // L is still there below it. assert_eq!(comp.layers().count(), 2); } diff --git a/crates/aep/tests/it/container/tree_index.rs b/crates/aep/tests/it/container/tree_index.rs new file mode 100644 index 000000000..c1bed0163 --- /dev/null +++ b/crates/aep/tests/it/container/tree_index.rs @@ -0,0 +1,231 @@ +//! The flat tree index the importer reads ([`TreeIndex`]) against the owned chunk tree, on every +//! file of the fixture directory: the same tree, and the same answers from the typed view. + +use std::fmt::Write as _; + +use craft_aep::index::TreeIndex; +use craft_aep::{ + AepFile, Chunk, CryptomatteData, CurvesData, Effect, HueSaturationData, LevelsData, Limits, MeshData, Project, PropGroup, PropNode, is_aepx, + parse, parse_with_limits, read_aepx, write, +}; + +/// Every `.aep` and `.aepx` in the fixture directory (the real projects included), sorted. +fn every_file() -> Vec { + let Some(dir) = crate::common::dir() else { + crate::common::skipped("*.aep"); + return Vec::new(); + }; + let Ok(entries) = std::fs::read_dir(&dir) else { + crate::common::skipped("*.aep"); + return Vec::new(); + }; + let mut out: Vec = + entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "aep" || x == "aepx")).collect(); + out.sort(); + out +} + +/// What the typed view reads from a project, as text: items, compositions, layers with their +/// headers, transforms, masks, effects with every parameter value, text, markers, the whole +/// property tree with static values and key records, settings and versions. +fn dump(view: &Project<'_, '_>) -> String { + let mut s = String::new(); + let defs = view.effect_definition_index(); + for item in view.all_items() { + let _ = writeln!(s, "item {:?} {:?} {:?} {:?} {:?}", item.kind(), item.name(), item.display_name(), item.id(), item.label()); + let _ = writeln!(s, " footage {:?} {:?} {:?}", item.footage(), item.sequence_info(), item.conform_frame_rate()); + let _ = writeln!(s, " folder {} {}", item.has_folder_contents(), item.folder_contents_unreadable()); + let Some(comp) = item.comp() else { continue }; + let _ = writeln!(s, " comp {:?} {:?} {:?}", comp.time_base(), comp.header(), comp.markers()); + for layer in comp.layers() { + let _ = writeln!(s, " layer {:?} {:?} {:?} {:?}", layer.name(), layer.id(), layer.header(), layer.track_matte()); + let _ = writeln!(s, " transform {:?}", layer.transform(1920, 1080)); + let _ = writeln!(s, " time remap {:?} orientation {:?} {:?}", layer.time_remap(), layer.orientation(), layer.orientation_keys()); + let _ = writeln!(s, " masks {:?}", layer.mask_atoms().iter().map(|m| (&m.mask, &m.path_shapes)).collect::>()); + let _ = writeln!(s, " shapes {:?}", layer.shape_groups()); + let _ = writeln!( + s, + " text {:?} {} {:?}", + layer.text_document(), + layer.text_document_count(), + layer.source_text_property().map(|p| p.is_animated()) + ); + let _ = writeln!(s, " markers {:?} source {:?}", layer.markers(), view.layer_source(&layer).map(|i| i.id())); + for fx in layer.effects() { + let _ = writeln!( + s, + " fx {} {:?} {:?} {:?} {:?}", + fx.match_name(), + fx.display_name(), + fx.enabled(), + defs.source(&fx), + fx.value_record_names() + ); + let _ = + writeln!(s, " names {:?} {:?} {:?} {:?}", fx.name(), fx.user_name(), fx.declared_param_count(), fx.has_own_definitions()); + for p in defs.params(&fx) { + let _ = writeln!(s, " {} {:?} {:?} {:?} {:?}", p.match_name, p.kind, p.name, p.items, p.value()); + arbitrary(&fx, &p.match_name, &mut s); + } + for name in fx.value_record_names() { + arbitrary(&fx, &name, &mut s); + } + } + if let Some(root) = layer.properties() { + tree(&root, 0, &mut s); + } + } + } + s +} + +/// The arbitrary data stored for a parameter and what each decoder reads from it. +fn arbitrary(fx: &Effect<'_, '_>, name: &str, s: &mut String) { + let Some(data) = fx.arbitrary_data(name) else { return }; + let _ = writeln!(s, " arbitrary {name} {data:?}"); + let _ = writeln!(s, " {:?} {:?}", HueSaturationData::parse(data), LevelsData::parse(data)); + let _ = writeln!(s, " {:?} {:?} {:?}", CurvesData::parse(data), MeshData::parse(data), CryptomatteData::parse(data)); +} + +/// Appends a group and everything below it to the dump, depth-limited. +fn tree(group: &PropGroup<'_, '_>, depth: usize, s: &mut String) { + if depth > 32 { + return; + } + let _ = writeln!(s, "{:depth$}group {:?} {:?}", "", group.user_name(), group.flags()); + for e in group.entries() { + match e.node { + PropNode::Group(g) => tree(&g, depth + 1, s), + PropNode::Property(p) => { + let keys: Option>> = p.keys().map(|k| k.records().map(<[u8]>::to_vec).collect()); + let _ = writeln!(s, "{:depth$} {} {:?} {:?} {:?} {:?}", "", e.match_name, p.user_name(), p.header(), p.static_value(), keys); + } + PropNode::Other(c) => { + let _ = writeln!(s, "{:depth$} {} other {:?} {}", "", e.match_name, c.list_type(), c.descendants().count()); + } + } + } +} + +/// The index is the parsed tree and the view reads the same on every file. +#[test] +fn the_index_is_the_parsed_tree_and_the_view_reads_the_same_on_every_file() { + for path in every_file() { + let name = path.display().to_string(); + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{name}: {e}")); + // `.aepx` is read into the chunk tree and indexed from it; `.aep` is indexed in place. + // A file that does not read (a damaged sample) must fail the index the same way. + let file: AepFile<'_> = match if is_aepx(&bytes) { read_aepx(&bytes) } else { parse(&bytes) } { + Ok(file) => file, + Err(e) => { + if !is_aepx(&bytes) { + assert_eq!(TreeIndex::parse(&bytes).err(), Some(e), "{name}"); + } + continue; + } + }; + let index = (if is_aepx(&bytes) { TreeIndex::from_file(&file) } else { TreeIndex::parse(&bytes) }).unwrap_or_else(|e| panic!("{name}: {e}")); + assert!(index.to_file() == file, "{name}: the index is not the parsed tree"); + assert_eq!(index.len(), file.walk().count(), "{name}"); + assert_eq!(index.file_version(), file.file_version(), "{name}"); + assert_eq!(index.saved_by_version(), file.saved_by_version(), "{name}"); + assert_eq!(craft_aep::ProjectSettings::read_index(&index), craft_aep::ProjectSettings::read(&file), "{name}"); + let (Some(a), Some(b)) = (Project::new(&file), Project::from_index(&index)) else { + assert!(Project::new(&file).is_none() && Project::from_index(&index).is_none(), "{name}"); + continue; + }; + let (da, db) = (dump(&a), dump(&b)); + assert!(da == db, "{name}: the view reads differently through the index"); + } +} + +/// The index and the parser fail alike under tight limits. +#[test] +fn the_index_and_the_parser_fail_alike_under_tight_limits() { + for path in every_file().into_iter().filter(|p| p.extension().is_some_and(|x| x == "aep")) { + let name = path.display().to_string(); + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{name}: {e}")); + let total = parse(&bytes).map(|f| f.walk().count()).unwrap_or(0); + for limits in [ + Limits { max_depth: 2, max_chunks: 10_000_000 }, + Limits { max_depth: 6, max_chunks: 10_000_000 }, + Limits { max_depth: 64, max_chunks: total }, + Limits { max_depth: 64, max_chunks: total.saturating_sub(1) }, + Limits { max_depth: 64, max_chunks: total / 2 }, + ] { + let old = parse_with_limits(&bytes, limits); + let new = TreeIndex::parse_with_limits(&bytes, limits); + match (old, new) { + (Ok(f), Ok(i)) => assert!(i.to_file() == f, "{name}: {limits:?}"), + (Err(a), Err(b)) => assert_eq!(a, b, "{name}: {limits:?}"), + (a, b) => panic!("{name}: {limits:?}: {:?} vs {:?}", a.err(), b.err()), + } + } + } +} + +/// A 40-byte NUL-padded match name. +fn tdmn(name: &str) -> Chunk<'static> { + let mut b = name.as_bytes().to_vec(); + b.resize(40, 0); + Chunk::data(*b"tdmn", b) +} + +/// A nested chunk `id` holding one `Utf8` with `text`. +fn utf8(id: [u8; 4], text: &str) -> Chunk<'static> { + Chunk { id, body: craft_aep::Body::Chunks(vec![Chunk::data(*b"Utf8", text.as_bytes().to_vec())]), pad: None } +} + +/// A project with one composition, one layer and one effect whose five parameters carry arbitrary +/// data in the sizes the decoders read (Hue/Saturation, Levels, Curves, a 2 x 2 mesh, Cryptomatte), +/// so the arbitrary-data path runs without the fixture directory. +fn synthetic() -> Vec { + let mut mesh = vec![0u8; 180]; + mesh[..8].copy_from_slice(&[0, 0, 0, 2, 0, 0, 0, 2]); + let mut cry = vec![0u8; 200]; + cry[..4].copy_from_slice(b"cry1"); + cry[32..37].copy_from_slice(b"Layer"); + let mut levels = vec![0u8; 108]; + levels[8..16].copy_from_slice(&1.0f64.to_be_bytes()); + let payloads: [Vec; 5] = [vec![7u8; 180], levels, vec![0u8; CurvesData::SIZE], mesh, cry]; + let (mut part, mut values) = + (vec![Chunk::data(*b"parn", 6u32.to_be_bytes().to_vec())], vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), utf8(*b"tdsn", "Mine")]); + for (i, data) in payloads.into_iter().enumerate() { + let name = format!("FX-{:04}", i + 1); + let mut pard = vec![0u8; 148]; + pard[12..16].copy_from_slice(&11u32.to_be_bytes()); + part.extend([tdmn(&name), Chunk::data(*b"pard", pard)]); + let record = Chunk::list(*b"tdbs", vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), Chunk::data(*b"cdat", vec![0, 0, 0, 1])]); + values.extend([tdmn(&name), record, Chunk::list(*b"aRbs", vec![Chunk::data(*b"aRbp", data)])]); + } + values.push(tdmn("ADBE Group End")); + let sspc = Chunk::list(*b"sspc", vec![utf8(*b"fnam", "Effect"), Chunk::list(*b"parT", part), Chunk::list(*b"tdgp", values)]); + let parade = Chunk::list(*b"tdgp", vec![tdmn("FX"), sspc, tdmn("ADBE Group End")]); + let root = Chunk::list(*b"tdgp", vec![tdmn("ADBE Effect Parade"), parade, tdmn("ADBE Group End")]); + let layer = Chunk::list(*b"Layr", vec![Chunk::data(*b"ldta", vec![0u8; 160]), Chunk::data(*b"Utf8", b"Layer".to_vec()), root]); + let mut idta = vec![0u8; 64]; + idta[..2].copy_from_slice(&4u16.to_be_bytes()); + idta[16..20].copy_from_slice(&2u32.to_be_bytes()); + let mut cdta = vec![0u8; 200]; + cdta[4..12].copy_from_slice(&[0, 0, 0, 1, 0, 0, 0, 30]); + let item = Chunk::list(*b"Item", vec![Chunk::data(*b"idta", idta), Chunk::data(*b"Utf8", b"Comp".to_vec()), Chunk::data(*b"cdta", cdta), layer]); + let file = + AepFile { chunks: vec![Chunk::data(*b"head", vec![0u8; 20]), Chunk::list(*b"Fold", vec![item])], trailer: std::borrow::Cow::Borrowed(&[]) }; + write(&file).expect("write") +} + +/// The view reads arbitrary effect data the same through the index. +#[test] +fn the_view_reads_arbitrary_effect_data_the_same_through_the_index() { + let bytes = synthetic(); + let file = parse(&bytes).expect("parse"); + let index = TreeIndex::parse(&bytes).expect("index"); + let (a, b) = (Project::new(&file).expect("project"), Project::from_index(&index).expect("project")); + let (da, db) = (dump(&a), dump(&b)); + assert_eq!(da, db); + // The synthetic effect really reaches every decoder (the dump is not empty of them). + assert_eq!(da.matches("arbitrary FX-").count(), 10, "{da}"); + assert!(da.contains("Some(HueSaturationData") && da.contains("Some(LevelsData") && da.contains("Some(CurvesData"), "{da}"); + assert!(da.contains("Some(MeshData") && da.contains("Some(CryptomatteData"), "{da}"); + assert!(da.contains("Some(\"Mine\")"), "the user name is read: {da}"); +} diff --git a/crates/aep/tests/it/container/typed.rs b/crates/aep/tests/it/container/typed.rs index 7299043e9..9be97f3fd 100644 --- a/crates/aep/tests/it/container/typed.rs +++ b/crates/aep/tests/it/container/typed.rs @@ -111,7 +111,7 @@ fn match_names_come_from_the_tdmn_chunks() { assert!(!names.iter().any(|n| n == "ADBE Group End")); assert!(root.find(&["ADBE Transform Group", "ADBE Nonexistent"]).is_none()); // The raw tdmn body is 40 bytes, NUL padded. - let raw = root.chunk().children().iter().find(|c| c.is(b"tdmn")).unwrap(); + let raw = root.chunk().children().find(|c| c.is(b"tdmn")).unwrap(); assert_eq!(raw.bytes().unwrap().len(), 40); } @@ -150,8 +150,8 @@ fn effect_parameter_value() { assert!(instance.is_list(b"sspc")); // The effect's name is in a nested fnam chunk. let fnam = instance.child(b"fnam").unwrap(); - assert!(matches!(fnam.body, Body::Chunks(_))); - assert_eq!(fnam.children()[0].bytes(), Some(&b"Slider Control"[..])); + assert!(matches!(fnam.to_chunk().body, Body::Chunks(_))); + assert_eq!(fnam.children().next().unwrap().bytes(), Some(&b"Slider Control"[..])); // The parameters are a property group inside the instance. let params = PropGroup::from_chunk(instance.child_list(b"tdgp").unwrap()).unwrap(); assert_eq!(params.names(), ["ADBE Slider Control-0000", "ADBE Slider Control-0001", "ADBE Effect Built In Params"]); @@ -186,7 +186,7 @@ fn position_keyframes() { assert_eq!(times, [0, 25_600, 64_000]); let seconds: Vec = times.iter().map(|t| tb.seconds(*t).unwrap()).collect(); assert_eq!(seconds, [0.0, 1.0, 2.5]); - let values: Vec<[f64; 3]> = keys.keyframes().map(|k| k.spatial_value().unwrap()).collect(); + let values: Vec> = keys.keyframes().map(|k| k.value().unwrap()).collect(); assert_eq!(values, [[0.0, 0.0, 0.0], [100.0, 0.0, 0.0], [200.0, 100.0, 0.0]]); } diff --git a/crates/aep/tests/it/container/values.rs b/crates/aep/tests/it/container/values.rs index 17fccf62f..6c3616012 100644 --- a/crates/aep/tests/it/container/values.rs +++ b/crates/aep/tests/it/container/values.rs @@ -119,7 +119,7 @@ fn linear_position_keys() { let values: Vec<_> = keys.iter().map(|k| k.spatial().unwrap().value).collect(); assert_eq!(values, [[0.0, 0.0, 0.0], [100.0, 0.0, 0.0], [200.0, 100.0, 0.0]]); assert_eq!(p.first_key_value(), Some(vec![0.0, 0.0, 0.0])); - assert_eq!(p.is_static_flag_set(), Some(false)); + assert!(p.is_animated()); })); // The transform of the layer reports the animated Position as keyframed (value at the first key). let (t, _) = skip!(transform("055-key-position-3key-inserted-t2.5.aep")); @@ -181,7 +181,7 @@ fn roving_and_label_flags() { assert_eq!(roving, [false, true, false]); assert_eq!(keys[1].time_units(), Some(26509)); assert_eq!(keys[1].seconds(25600), Some(1.0355078125)); - assert_eq!(keys[1].spatial_value(), Some([100.0, 0.0, 0.0])); + assert_eq!(keys[1].value(), Some(vec![100.0, 0.0, 0.0])); assert_eq!(keys[1].flags(), Some(0x0027)); assert_eq!(keys[1].label(), Some(0)); })); @@ -193,7 +193,7 @@ fn roving_and_label_flags() { assert_eq!(keys[1].flags(), Some(0x0247)); assert_eq!(keys[0].flags(), Some(0x0007)); assert_eq!(keys[1].is_roving(), Some(false)); - assert_eq!(keys[1].spatial_value(), Some([100.0, 0.0, 0.0])); + assert_eq!(keys[1].value(), Some(vec![100.0, 0.0, 0.0])); })); } @@ -204,7 +204,6 @@ fn scalar_opacity_keys() { assert!(p.is_animated()); assert_eq!(p.dims(), Some(1)); assert_eq!(p.time_scale(), Some(25600)); - assert_eq!(p.is_static_flag_set(), Some(false)); let list = p.keys().unwrap(); assert_eq!(list.header.record_size, 48); let keys: Vec<_> = list.keyframes().collect(); @@ -243,10 +242,8 @@ fn expression_text_and_flag_bytes() { assert_eq!(p.expression(), None); let flags = p.expression_flags().unwrap(); assert_eq!((flags.byte_76, flags.byte_77, flags.byte_120), (0, 0, 0)); - assert!(!flags.all_set()); // A written static property: tdsb 1, byte 5 of tdb4 has bit 0 set (15 for Position). assert_eq!(p.flags(), Some(1)); - assert_eq!(p.is_static_flag_set(), Some(true)); assert_eq!(p.header().and_then(|h| h.get(5).copied()), Some(15)); })); } diff --git a/crates/audio/README.md b/crates/audio/README.md index a1eb059d2..0c9f63a97 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -26,11 +26,11 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | Feature | Provides | Pulls in | |---|---|---| | `decode` | `decode`, `probe`, `Decoder`, `tracks`, `TrackDecoder`; every format in [Format support](#format-support) | `decode-native`, `symphonia` | -| `decode-native` | the same, native formats only (others are `Unsupported`) | the five decoders below, craft-media `isobmff`/`matroska`/`ogg`, `log` | +| `decode-native` | the same, native formats only (others are `Unsupported`); `wav_pcm`, `aiff_pcm` (a file's integer PCM bit for bit, as `RawPcm`) | the five decoders below, craft-media `isobmff`/`matroska`/`ogg`, `log` | | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | | `encode` | every encoder: the WAV, AIFF and FLAC file writers, and the AAC, ALAC, AC-3/E-AC-3 and MP3 encoders | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | -| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header` | none | +| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | | `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder` | craft-media `bitstream` | | `alac-decode` | `alac::Decoder` | none | diff --git a/crates/audio/src/aac/mod.rs b/crates/audio/src/aac/mod.rs index eb1c7d40a..34b081ea6 100644 --- a/crates/audio/src/aac/mod.rs +++ b/crates/audio/src/aac/mod.rs @@ -113,6 +113,26 @@ pub fn wav_order(channel_config: u8) -> Option<&'static [usize]> { }) } +/// The channel configuration whose speakers a stream has: its own, or for configuration 0 the +/// configuration 3–6 that its program config element spells out. A program config element lists +/// front, side, back and LFE elements in that order, so one that opens with a centre and a front +/// pair and goes on with exactly the elements of a configuration has that configuration's speakers +/// (and [`wav_order`]). Any other list has no speaker order that can be told, and gives 0: ffmpeg's +/// 5.1(side), for one, lists the pair first and already decodes in WAV order. +#[cfg(feature = "aac-decode")] +pub fn speaker_config(asc: &AudioSpecificConfig) -> u8 { + if asc.channel_config != 0 { + return asc.channel_config; + } + let centre_then_pair = asc.pce.as_ref().is_some_and(|p| p.front.iter().map(|e| e.0).eq([false, true])); + if !centre_then_pair { + return 0; + } + let elements = asc.layout(); + let same = |config: &u8| config_layout(*config).is_some_and(|l| l.iter().map(|e| e.0).eq(elements.iter().map(|e| e.0))); + (3..=6).find(same).unwrap_or(0) +} + /// The order the [`Encoder`] takes its input in, from WAV order: for each encoder input channel /// (AAC element order, see [`EncoderConfig::channels`]), the WAV-order channel to feed it. The /// inverse of [`wav_order`] for 3 to 7 channels; `None` for mono and stereo (already in order) and @@ -279,6 +299,30 @@ mod tests { mod order_tests { use super::*; + /// A program config element in the shape of a channel configuration has that configuration's + /// speakers, with the centre first. ffmpeg's 5.1(side) lists its pair first and already decodes + /// in WAV order, so it stays as it is. + #[cfg(feature = "aac-decode")] + #[test] + fn a_program_config_element_takes_the_configuration_it_matches() { + let with = |pce| AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(3, 0) }; + let centre_first = ProgramConfig { front: vec![(false, 0), (true, 0)], back: vec![(true, 1)], lfe: vec![0], ..Default::default() }; + assert_eq!(speaker_config(&with(centre_first)), 6); + let three = ProgramConfig { front: vec![(false, 0), (true, 0)], ..Default::default() }; + assert_eq!(speaker_config(&with(three)), 3); + let ffmpeg = ProgramConfig { front: vec![(true, 0), (false, 0)], side: vec![(false, 1)], back: vec![(true, 1)], ..Default::default() }; + assert_eq!(speaker_config(&with(ffmpeg)), 0); + // the same element types with no front pair: the side pair is not left and right + let no_front_pair = + ProgramConfig { front: vec![(false, 0)], side: vec![(true, 0)], back: vec![(true, 1)], lfe: vec![0], ..Default::default() }; + assert_eq!(speaker_config(&with(no_front_pair)), 0); + // 7.1 in a program config element is not one of the unambiguous configurations + let wide = + ProgramConfig { front: vec![(false, 0), (true, 0)], side: vec![(true, 1)], back: vec![(true, 2)], lfe: vec![0], ..Default::default() }; + assert_eq!(speaker_config(&with(wide)), 0); + assert_eq!(speaker_config(&AudioSpecificConfig::lc(3, 6)), 6); + } + /// `aac_order` undoes `wav_order` for each channel count the encoder maps to a configuration /// (3–6 channels: configurations 3–6; 7: configuration 11). #[test] diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 5916b91e8..4964166a7 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -19,6 +19,9 @@ //! gives [`wav_float_header`]) and FLAC (feature `flac-encode`), whole-buffer or incremental into //! any `Write + Seek`. Feature `lossless-encode` turns on both; feature `encode` turns on //! `lossless-encode` and every codec's encoder. +//! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`], +//! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF +//! file bit for bit, and minimal files around such PCM, for essence embedded in other containers. //! - [`peaks`] (feature `peaks`): min/max/RMS pyramid for waveform drawing. //! - Codec modules for packet-level use, each with its own features: [`aac`] (`aac-decode`, //! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`), [`ac3`] @@ -91,12 +94,16 @@ pub use read::{ DECODE_EXTENSIONS, DEFAULT_MAX_SAMPLES, DecodeOptions, Decoder, TrackInfo, decode, decode_with, detect_container, probe, probe_with, tracks, tracks_of, }; +#[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"))] pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; #[cfg(feature = "pcm-encode")] pub use write::wav_float_header; #[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] pub use write::{ENCODE_EXTENSIONS, FileEncoder, encode, encode_format_for}; +#[cfg(feature = "pcm-encode")] +pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; /// Errors from probing, decoding and encoding. #[non_exhaustive] diff --git a/crates/audio/src/read/mod.rs b/crates/audio/src/read/mod.rs index 533e996a6..35a220767 100644 --- a/crates/audio/src/read/mod.rs +++ b/crates/audio/src/read/mod.rs @@ -14,6 +14,7 @@ mod flac; #[cfg(feature = "symphonia")] mod mp4; mod native; +mod raw; mod source; #[cfg(feature = "symphonia")] mod symph; @@ -21,6 +22,7 @@ mod wav; use crate::{AudioBuffer, AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result}; use native::Native; +pub use raw::{RawPcm, aiff_pcm, wav_pcm}; pub use source::SharedSource; use source::Src; use std::sync::Arc; diff --git a/crates/audio/src/read/raw.rs b/crates/audio/src/read/raw.rs new file mode 100644 index 000000000..e63f9d2cb --- /dev/null +++ b/crates/audio/src/read/raw.rs @@ -0,0 +1,58 @@ +//! The integer PCM of a WAV or AIFF file as stored, for a caller that moves it bit for bit +//! (essence embedded in an AAF or OMF file) instead of decoding it to `f32`. + +use super::source::Src; +use super::{aiff, wav}; +use crate::pcm::PcmKind; + +/// Integer PCM taken out of a WAV or AIFF file: interleaved little-endian samples of +/// `bits.div_ceil(8)` bytes each, signed except for 8-bit, which is unsigned (the WAVE convention). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RawPcm { + /// The samples; empty for a header with no data after it (a descriptor's summary). + pub data: Vec, + /// Interleaved channels (at least 1). + pub channels: u16, + /// Sample rate in Hz (at least 1). + pub sample_rate: u32, + /// Bits a sample occupies in `data`: 8, 16, 24 or 32. + pub bits: u16, +} + +/// The samples of a layout: `len` bytes at `start`, as far as the file has them. +fn stored(b: &[u8], start: u64, len: u64) -> &[u8] { + let start = usize::try_from(start).unwrap_or(usize::MAX).min(b.len()); + let end = start.saturating_add(usize::try_from(len).unwrap_or(usize::MAX)).min(b.len()); + b.get(start..end).unwrap_or_default() +} + +/// The integer PCM of a WAV file (plain or `WAVE_FORMAT_EXTENSIBLE` PCM), bit for bit. `None` for +/// anything else: not a WAV, float or compressed samples, no `fmt ` or `data` chunk. A file cut +/// short gives the samples that are there. +pub fn wav_pcm(bytes: &[u8]) -> Option { + let wav::WavParse::Native(layout) = wav::parse(&Src::Slice(bytes)).ok()? else { return None }; + let PcmKind::Int { bytes: width, big_endian: false, .. } = layout.kind else { return None }; + Some(RawPcm { + data: stored(bytes, layout.data_start, layout.data_len).to_vec(), + channels: layout.info.channels, + sample_rate: layout.info.sample_rate, + bits: u16::try_from(width.checked_mul(8)?).ok()?, + }) +} + +/// The integer PCM of an AIFF or AIFF-C (`NONE`, `twos`, `sowt`) file, converted to the layout of +/// [`RawPcm`]: little-endian, and 8-bit samples made unsigned. `None` for anything else. +pub fn aiff_pcm(bytes: &[u8]) -> Option { + let aiff::AiffParse::Native(layout) = aiff::parse(&Src::Slice(bytes)).ok()? else { return None }; + let PcmKind::Int { bytes: width, big_endian, .. } = layout.kind else { return None }; + let stored = stored(bytes, layout.data_start, layout.data_len); + let mut data = Vec::with_capacity(stored.len()); + for s in stored.chunks_exact(width.max(1)) { + match (width, big_endian) { + (1, _) => data.extend(s.iter().map(|b| b ^ 0x80)), + (_, true) => data.extend(s.iter().rev()), + (_, false) => data.extend_from_slice(s), + } + } + Some(RawPcm { data, channels: layout.info.channels, sample_rate: layout.info.sample_rate, bits: u16::try_from(width.checked_mul(8)?).ok()? }) +} diff --git a/crates/audio/src/track.rs b/crates/audio/src/track.rs index 3d9ed7dfb..af984d718 100644 --- a/crates/audio/src/track.rs +++ b/crates/audio/src/track.rs @@ -156,7 +156,8 @@ impl TrackDecoder { let codec = if up.is_some() { CodecId::HeAac } else { CodecId::Aac }; // Only twice the core rate is upsampled to; any other signalled rate plays the core. let out = if up.is_some() { out } else { dec.sample_rate() }; - let cfg = dec.config().channel_config; + // a program config element that spells out a configuration has its speakers + let cfg = aac::speaker_config(dec.config()); let layout = aac_layout(cfg, dec.channels()); let order = layout.is_ordered().then(|| aac::wav_order(cfg)).flatten(); (Inner::Aac { dec: Box::new(dec), up, order, adts_format }, codec, out, layout, SampleFormat::Compressed) @@ -1079,6 +1080,8 @@ mod tests { let mut dec = TrackDecoder::new(&aac_params(), &[&frame]).unwrap(); assert_eq!(dec.channels(), 3); assert_eq!(dec.decode(&frame).unwrap().channels.len(), 3); + // its element lists a centre and a front pair, as configuration 3 does: L R C, in WAV order + assert_eq!(dec.layout(), ChannelLayout::SURROUND_3_0); // no program config element where one is needed let bare = aac::AdtsHeader::write(2, 3, 0, 1, 0x7FF).unwrap(); let bare = [&bare[..], &[0xE0]].concat(); diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 25c9b2528..2355a7b05 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -7,9 +7,13 @@ mod aiff; pub(crate) mod flac; mod pcm; #[cfg(feature = "pcm-encode")] +mod raw; +#[cfg(feature = "pcm-encode")] mod wav; use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, Result}; +#[cfg(feature = "pcm-encode")] +pub use raw::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; use std::io::{Seek, Write}; /// Encode `buf` as WAV/BWF, AIFF/AIFF-C or FLAC. Integer depths clamp samples to [-1, 1]; float diff --git a/crates/audio/src/write/raw.rs b/crates/audio/src/write/raw.rs new file mode 100644 index 000000000..dc9a31649 --- /dev/null +++ b/crates/audio/src/write/raw.rs @@ -0,0 +1,120 @@ +//! Minimal WAVE and AIFF files around integer PCM the caller already has as bytes (essence +//! embedded in an AAF or OMF file): the 44-byte canonical WAVE header and the plain AIFF header, +//! with nothing a reader of such a summary could trip over (no `JUNK`, no extensible `fmt `). +//! [`crate::encode`] writes full WAV/BWF/RF64 and AIFF files from `f32`. +//! +//! PCM here is interleaved little-endian samples of `bits.div_ceil(8)` bytes, 8-bit unsigned +//! (the layout of a WAVE `data` chunk). Sizes saturate at the 32-bit fields instead of wrapping. + +use super::aiff::u32_to_extended; + +/// A complete WAVE file around little-endian PCM. +pub fn pcm_wav_file(pcm: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Vec { + let mut v = pcm_wav_header(u32::try_from(pcm.len()).unwrap_or(u32::MAX), channels, sample_rate, bits); + v.extend_from_slice(pcm); + if pcm.len() % 2 == 1 { + v.push(0); + } + v +} + +/// The 44 bytes of a canonical WAVE file up to and including the `data` chunk header, for +/// `data_len` bytes of PCM. +pub fn pcm_wav_header(data_len: u32, channels: u16, sample_rate: u32, bits: u16) -> Vec { + let block = channels.max(1).saturating_mul(bits.div_ceil(8)); + let mut v = Vec::with_capacity(44); + v.extend_from_slice(b"RIFF"); + v.extend_from_slice(&36u32.saturating_add(data_len).saturating_add(data_len & 1).to_le_bytes()); + v.extend_from_slice(b"WAVEfmt "); + v.extend_from_slice(&16u32.to_le_bytes()); + v.extend_from_slice(&1u16.to_le_bytes()); + v.extend_from_slice(&channels.max(1).to_le_bytes()); + v.extend_from_slice(&sample_rate.to_le_bytes()); + v.extend_from_slice(&sample_rate.saturating_mul(u32::from(block)).to_le_bytes()); + v.extend_from_slice(&block.to_le_bytes()); + v.extend_from_slice(&bits.to_le_bytes()); + v.extend_from_slice(b"data"); + v.extend_from_slice(&data_len.to_le_bytes()); + v +} + +/// A complete AIFF file (big-endian, 8-bit signed) from little-endian PCM. +pub fn pcm_aiff_file(pcm: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Vec { + let width = usize::from(bits.div_ceil(8)).max(1); + let frames = pcm.len() / (width * usize::from(channels.max(1))); + let mut v = pcm_aiff_header(u32::try_from(frames).unwrap_or(u32::MAX), channels, sample_rate, bits); + let head = v.len(); + for s in pcm.chunks_exact(width) { + if width == 1 { + v.extend(s.iter().map(|b| b ^ 0x80)); // WAVE 8-bit is unsigned, AIFF signed + } else { + v.extend(s.iter().rev()); + } + } + if (v.len() - head) % 2 == 1 { + v.push(0); + } + v +} + +/// The 54 bytes of an AIFF file up to the sound data (`FORM`, `COMM`, `SSND` with its offset and +/// block size), for `frames` sample frames. +pub fn pcm_aiff_header(frames: u32, channels: u16, sample_rate: u32, bits: u16) -> Vec { + let data_len = u64::from(frames).saturating_mul(u64::from(channels.max(1))).saturating_mul(u64::from(bits.div_ceil(8))); + let chunk = |extra: u64| u32::try_from(extra.saturating_add(data_len)).unwrap_or(u32::MAX); + let mut v = Vec::with_capacity(54); + v.extend_from_slice(b"FORM"); + v.extend_from_slice(&chunk(4 + 26 + 16 + (data_len & 1)).to_be_bytes()); + v.extend_from_slice(b"AIFFCOMM"); + v.extend_from_slice(&18u32.to_be_bytes()); + v.extend_from_slice(&channels.max(1).to_be_bytes()); + v.extend_from_slice(&frames.to_be_bytes()); + v.extend_from_slice(&bits.to_be_bytes()); + v.extend_from_slice(&u32_to_extended(sample_rate)); + v.extend_from_slice(b"SSND"); + v.extend_from_slice(&chunk(8).to_be_bytes()); + v.extend_from_slice(&[0; 8]); + v +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A descriptor for more than 4 GiB of PCM: the RIFF and FORM size fields saturate. + #[test] + fn huge_headers_saturate() { + let h = pcm_wav_header(u32::MAX, 2, u32::MAX, 24); + assert_eq!(h.get(4..8), Some(&u32::MAX.to_le_bytes()[..])); + assert_eq!(h.get(28..32), Some(&u32::MAX.to_le_bytes()[..]), "byte rate"); + let a = pcm_aiff_header(u32::MAX, u16::MAX, 48_000, 32); + assert_eq!(a.get(4..8), Some(&u32::MAX.to_be_bytes()[..])); + assert_eq!(a.len(), 54); + } + + #[test] + fn headers_have_the_canonical_layout() { + let h = pcm_wav_header(96, 2, 48_000, 24); + assert_eq!(h.len(), 44); + let mut expect = b"RIFF".to_vec(); + expect.extend_from_slice(&132u32.to_le_bytes()); + expect.extend_from_slice(b"WAVEfmt "); + for x in [16u32, 1 | 2 << 16, 48_000, 288_000, 6 | 24 << 16] { + expect.extend_from_slice(&x.to_le_bytes()); + } + expect.extend_from_slice(b"data"); + expect.extend_from_slice(&96u32.to_le_bytes()); + assert_eq!(h, expect); + // zero channels are written as one, and an odd data length counts its pad byte + let odd = pcm_wav_file(&[1, 2, 3], 0, 8_000, 8); + assert_eq!(odd.len(), 48); + assert_eq!(odd.get(4..8), Some(&40u32.to_le_bytes()[..])); + assert_eq!(odd.get(22..24), Some(&1u16.to_le_bytes()[..])); + let a = pcm_aiff_header(8, 2, 44_100, 24); + assert_eq!(a.get(..4), Some(&b"FORM"[..])); + assert_eq!(a.get(4..8), Some(&(46u32 + 48).to_be_bytes()[..])); + // 44 100 Hz as an 80-bit extended float + assert_eq!(a.get(28..38), Some(&[0x40, 0x0E, 0xAC, 0x44, 0, 0, 0, 0, 0, 0][..])); + assert_eq!(a.get(42..46), Some(&(8u32 + 48).to_be_bytes()[..])); + } +} diff --git a/crates/audio/tests/audio/main.rs b/crates/audio/tests/audio/main.rs index f247167b5..8c37256d6 100644 --- a/crates/audio/tests/audio/main.rs +++ b/crates/audio/tests/audio/main.rs @@ -6,6 +6,7 @@ mod flac_damage; mod float_headroom; mod malformed; mod mp4_length; +mod raw_pcm; mod roundtrip; mod stream; mod wav_empty_data; diff --git a/crates/audio/tests/audio/raw_pcm.rs b/crates/audio/tests/audio/raw_pcm.rs new file mode 100644 index 000000000..1b5fed669 --- /dev/null +++ b/crates/audio/tests/audio/raw_pcm.rs @@ -0,0 +1,73 @@ +//! Integer PCM in and out of WAV and AIFF files bit for bit (`wav_pcm`, `aiff_pcm`, `pcm_*`). + +use craft_audio::{ + AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, RawPcm, aiff_pcm, encode, pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header, + wav_pcm, +}; + +fn raw(data: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Option { + Some(RawPcm { data: data.to_vec(), channels, sample_rate, bits }) +} + +#[test] +fn wav_and_aiff_round_trip_bit_for_bit() { + let pcm: Vec = (0..48u8).collect(); // 8 stereo 24-bit frames + let w = pcm_wav_file(&pcm, 2, 48_000, 24); + assert_eq!(wav_pcm(&w), raw(&pcm, 2, 48_000, 24)); + let a = pcm_aiff_file(&pcm, 2, 44_100, 24); + assert_eq!(aiff_pcm(&a), raw(&pcm, 2, 44_100, 24)); + let p16: Vec = (0..32u8).collect(); + assert_eq!(aiff_pcm(&pcm_aiff_file(&p16, 1, 96_000, 16)), raw(&p16, 1, 96_000, 16)); + // 8-bit: unsigned in WAVE and in `RawPcm`, signed in AIFF + let p8 = [0u8, 0x7F, 0x80, 0xFF, 3]; + assert_eq!(wav_pcm(&pcm_wav_file(&p8, 1, 8_000, 8)), raw(&p8, 1, 8_000, 8)); + let a8 = pcm_aiff_file(&p8, 1, 8_000, 8); + assert_eq!(a8.get(54..59), Some(&[0x80, 0xFF, 0x00, 0x7F, 0x83][..])); + assert_eq!(a8.len(), 60, "odd sound data is padded"); + assert_eq!(aiff_pcm(&a8), raw(&p8, 1, 8_000, 8)); + // neither reads the other's container + assert_eq!(wav_pcm(&a), None); + assert_eq!(aiff_pcm(&w), None); +} + +/// A descriptor's summary is the header alone: the format is read, with no samples. +#[test] +fn headers_without_data_give_the_format() { + assert_eq!(wav_pcm(&pcm_wav_header(4800, 2, 48_000, 16)), raw(&[], 2, 48_000, 16)); + assert_eq!(aiff_pcm(&pcm_aiff_header(1200, 2, 48_000, 16)), raw(&[], 2, 48_000, 16)); +} + +#[test] +fn files_cut_short_never_panic_and_give_what_is_there() { + let pcm: Vec = (0..48u8).collect(); + let w = pcm_wav_file(&pcm, 2, 48_000, 24); + let a = pcm_aiff_file(&pcm, 2, 44_100, 24); + for cut in 0..w.len().max(a.len()) { + if let Some(p) = w.get(..cut).and_then(wav_pcm) { + assert_eq!(Some(&p.data[..]), pcm.get(..cut.saturating_sub(44)), "wav cut at {cut}"); + } + if let Some(p) = a.get(..cut).and_then(aiff_pcm) { + assert!(pcm.starts_with(&p.data) && p.data.len() <= cut.saturating_sub(54), "aiff cut at {cut}"); + } + } + assert_eq!(wav_pcm(b"RIFF"), None); + assert_eq!(aiff_pcm(a.get(..30).unwrap()), None); +} + +#[test] +fn only_integer_pcm_is_taken() { + let buf = AudioBuffer::new(48_000, 2, 16); + let float = encode(&buf, &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Float32)).unwrap(); + assert_eq!(wav_pcm(&float), None); + let float = encode(&buf, &EncodeOptions::new(EncodeFormat::Aiff).with_bit_depth(BitDepth::Float32)).unwrap(); + assert_eq!(aiff_pcm(&float), None); + // the full writer's 24-bit WAV (extensible `fmt `, a JUNK chunk before it) is integer PCM too + let int = encode(&buf, &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap(); + assert_eq!(wav_pcm(&int), raw(&[0; 96], 2, 48_000, 24)); + let int = encode(&buf, &EncodeOptions::new(EncodeFormat::Aiff).with_bit_depth(BitDepth::Int16)).unwrap(); + assert_eq!(aiff_pcm(&int), raw(&[0; 64], 2, 48_000, 16)); + // zero channels or a zero rate is not a format + let mut bad = pcm_wav_file(&[0; 8], 1, 48_000, 16); + bad[24..28].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(wav_pcm(&bad), None); +} diff --git a/crates/audio/tests/codecs/routing_oracle.rs b/crates/audio/tests/codecs/routing_oracle.rs index c35a89002..6472979b3 100644 --- a/crates/audio/tests/codecs/routing_oracle.rs +++ b/crates/audio/tests/codecs/routing_oracle.rs @@ -669,10 +669,14 @@ fn adts_with_a_program_config_element_decodes() { assert_eq!(bytes[3] >> 6 | (bytes[2] & 1) << 2, 0, "the fixture signals its layout in a PCE"); let (info, buf) = decode(&bytes, None).unwrap(); assert_eq!((info.container, info.codec, buf.channels.len()), (c.container, c.codec, c.channels)); - assert_eq!(info.layout, c.layout); + // A program config element that lists a centre, a front pair and then the elements of 5.1 has + // 5.1's speakers, in WAV order like ffmpeg's decode; any other list keeps the decoded order, + // which ffmpeg versions write differently. + let ordered = info.layout.is_ordered(); + assert_eq!(info.layout, if ordered { ChannelLayout::SURROUND_5_1_SIDE } else { c.layout }); assert_eq!(buf.frames(), reference(&ff, &path).len() / c.channels); - // A program config's channels come in its own order, and which order ffmpeg writes differs by - // version: each of ours must match a different one of ffmpeg's. + // Each of our channels must match a different one of ffmpeg's: the same one when the layout is + // ordered. let refr = reference(&ff, &path); let mut matched = Vec::new(); for plane in &buf.channels { @@ -686,7 +690,9 @@ fn adts_with_a_program_config_element_decodes() { assert!(s >= c.min_snr, "channel {} matches ffmpeg's {best} at only {s:.1} dB", matched.len()); matched.push(best); } - matched.sort_unstable(); + if !ordered { + matched.sort_unstable(); + } assert_eq!(matched, (0..c.channels).collect::>()); } diff --git a/crates/cms/README.md b/crates/cms/README.md index 7953539ba..71f3146d5 100644 --- a/crates/cms/README.md +++ b/crates/cms/README.md @@ -30,8 +30,16 @@ Buffers are checked once per call, before any pixel is written. * `Transform::proof(src, proof, display, intent, bpc, simulate_paper)`: soft-proof chain. * `GamutCheck::new(src, proof, ΔE)`: out-of-gamut test (gamut warning). -* `Lut3d::from_transform(&t, 33)?.to_rgba16f_bytes()`: display transform as a 3D texture. + `check.mask_rgba(&rgba, &mut mask)?` fills a whole mask (255 where alpha > 0 and out of gamut) on + the thread pool and returns the count; it needs an RGB source profile. +* `Lut3d::from_transform(&t, 33)?.to_rgba16f_bytes()`: display transform as a 3D texture; + `Lut3d::from_fn(size, f)` samples any RGB function. +* `Transform::gpu_matrix_shaper()`: accurate RGB input curves + matrix + output curves for + display shaders. Float tables retain near-black detail; unsupported chains return `None` + for the 3D LUT fallback. No GPU dependency is required by this crate. * `transform::cached(src, dst, opts)`: process-wide transform cache. +* `builtin::cicp_rgb(primaries, transfer, linear)`: the RGB profile for an ITU-T H.273 colour + description (a HEIF `nclx` box, a video stream). * `lutfile::parse(name, bytes)` / `lutfile::write_cube(&lut)`: `.cube`, `.3dl` and `.look` LUT files; `lutfile::builtin(id)` returns generated looks (`lutfile::BUILTIN`). * `Profile::to_bytes()`: original bytes of parsed profiles (byte-exact), or an ICC v4.3 encoding @@ -59,6 +67,10 @@ Buffers are checked once per call, before any pixel is written. tetrahedral interpolation (4D: linear on the first input between two tetrahedra); purely analytic chains (e.g. Lab ↔ RGB) are evaluated exactly. Buffers ≥ 16k pixels run on rayon (native only). +* GPU matrix/TRC display transforms reuse the 4097-entry input curves, 3×3 matrix plus + offsets, and 4096-entry output curves indexed by `x^(1/4)`. Each channel is interpolated + separately using float texels; SDR input/output are clamped to `[0, 1]`. A final RGB + 33³ table cannot resolve steep inverse gamma curves near black, even with float texels. * Rendering intents: AToB0/1/2 and BToA0/1/2 by intent with AToB0/BToA0 fallback; absolute colorimetric scales by media white (`wtpt`; v2 display profiles treated as D50; a zero, negative or non-finite white is refused with `CmsError::Invalid`); BPC uses @@ -73,7 +85,8 @@ Buffers are checked once per call, before any pixel is written. ## Built-in profiles (all CC0-1.0, generated by this crate) The profile descriptions and copyright text keep the PhotoCraft names they were first -published with, so profiles embedded in existing files still match byte for byte. +published with (spelled "PhotoCraft" since PhotoCraft's #5614), so profiles embedded in +existing files still match byte for byte. | id | description | |---|---| @@ -82,10 +95,12 @@ published with, so profiles embedded in existing files still match byte for byte | `adobe-rgb-compat` | Adobe RGB (1998)-compatible (published primaries, gamma 563/256) | | `prophoto-compat` | ProPhoto-compatible (ROMM primaries, D50, gamma 1.8) | | `linear-srgb` | sRGB primaries, linear | +| `aces-cg` | ACEScg: AP1 primaries, ACES white (~D60), linear | | `rec2020` | Rec. 2020 primaries, Rec. 709 OETF | -| `gray-gamma-2.2`, `sgray` | gray gamma 2.2; gray with the sRGB curve (default gray working space) | +| `gray-gamma-2.2`, `sgray` | gray gamma 2.2; gray with the sRGB curve | +| `dot-gain-20-compat` | gray, gamma 1.732, fitted to Photoshop's Dot Gain 20 % (default gray working space) | | `lab-d50` | Lab identity (v4 encoding) | -| `coated-cmyk` | **Photocraft Coated CMYK (synthetic, 300% TAC, medium GCR)**: default CMYK | +| `coated-cmyk` | **PhotoCraft Coated CMYK (synthetic, 300% TAC, medium GCR)**: default CMYK | | `coated-fogra39` | Coated FOGRA39 (fitted, craft-cms): fitted to Fogra's FOGRA39 data, 330% TAC, medium GCR | ### The CMYK profiles diff --git a/crates/cms/profiles/photocraft-coated-cmyk.icc b/crates/cms/profiles/photocraft-coated-cmyk.icc index 0d2d1da16..b553fe9ce 100644 Binary files a/crates/cms/profiles/photocraft-coated-cmyk.icc and b/crates/cms/profiles/photocraft-coated-cmyk.icc differ diff --git a/crates/cms/src/builtin.rs b/crates/cms/src/builtin.rs index 361f228c1..ca7034286 100644 --- a/crates/cms/src/builtin.rs +++ b/crates/cms/src/builtin.rs @@ -34,12 +34,18 @@ pub enum Builtin { ProPhotoCompat, /// sRGB primaries with a linear transfer function. LinearSrgb, + /// ACEScg: AP1 primaries, the ACES white point (~D60), linear transfer. The ACES working space for CG renders. + AcesCg, /// Rec. 2020 primaries, D65, Rec. 709 transfer function. Rec2020, /// Gray, gamma 2.2. GrayGamma22, /// Gray with the sRGB transfer function (sGray): gray `v` looks like RGB `(v, v, v)` in sRGB. SGray, + /// Gray matching Photoshop's default working gray (Dot Gain 20 %) with our own curve: a pure + /// gamma of 1.732, fitted on Photoshop 27.11's RGB → Grayscale (sRGB 64 / 128 / 192 and pure red + /// become 46 / 105 / 177 / 107, all within 1 level). Not Adobe's profile. + DotGain20Compat, /// CIE L*a*b* D50 identity (device Lab = PCS Lab, ICC v4 encoding). LabD50, /// Synthetic coated-offset CMYK (300 % total ink, medium GCR); see [`crate::synth`]. @@ -51,15 +57,17 @@ pub enum Builtin { } impl Builtin { - pub const ALL: [Builtin; 11] = [ + pub const ALL: [Builtin; 13] = [ Builtin::Srgb, Builtin::DisplayP3, Builtin::AdobeRgbCompat, Builtin::ProPhotoCompat, Builtin::LinearSrgb, + Builtin::AcesCg, Builtin::Rec2020, Builtin::GrayGamma22, Builtin::SGray, + Builtin::DotGain20Compat, Builtin::LabD50, Builtin::CoatedCmyk, Builtin::CoatedFogra39, @@ -73,9 +81,11 @@ impl Builtin { Builtin::AdobeRgbCompat => "adobe-rgb-compat", Builtin::ProPhotoCompat => "prophoto-compat", Builtin::LinearSrgb => "linear-srgb", + Builtin::AcesCg => "aces-cg", Builtin::Rec2020 => "rec2020", Builtin::GrayGamma22 => "gray-gamma-2.2", Builtin::SGray => "sgray", + Builtin::DotGain20Compat => "dot-gain-20-compat", Builtin::LabD50 => "lab-d50", Builtin::CoatedCmyk => "coated-cmyk", Builtin::CoatedFogra39 => "coated-fogra39", @@ -87,13 +97,15 @@ impl Builtin { match self { Builtin::Srgb => "sRGB IEC61966-2.1", Builtin::DisplayP3 => "Display P3", - Builtin::AdobeRgbCompat => "Adobe RGB (1998)-compatible (Photocraft)", - Builtin::ProPhotoCompat => "ProPhoto RGB-compatible (ROMM primaries, Photocraft)", - Builtin::LinearSrgb => "Linear sRGB (Photocraft)", - Builtin::Rec2020 => "Rec. ITU-R BT.2020 (Photocraft)", - Builtin::GrayGamma22 => "Gray Gamma 2.2 (Photocraft)", - Builtin::SGray => "sGray (sRGB tone curve, Photocraft)", - Builtin::LabD50 => "Lab D50 identity (Photocraft)", + Builtin::AdobeRgbCompat => "Adobe RGB (1998)-compatible (PhotoCraft)", + Builtin::ProPhotoCompat => "ProPhoto RGB-compatible (ROMM primaries, PhotoCraft)", + Builtin::LinearSrgb => "Linear sRGB (PhotoCraft)", + Builtin::AcesCg => "ACEScg (AP1, linear, PhotoCraft)", + Builtin::Rec2020 => "Rec. ITU-R BT.2020 (PhotoCraft)", + Builtin::GrayGamma22 => "Gray Gamma 2.2 (PhotoCraft)", + Builtin::SGray => "sGray (sRGB tone curve, PhotoCraft)", + Builtin::DotGain20Compat => "Dot Gain 20%-compatible (gamma 1.732, PhotoCraft)", + Builtin::LabD50 => "Lab D50 identity (PhotoCraft)", Builtin::CoatedCmyk => crate::synth::DESCRIPTION, Builtin::CoatedFogra39 => COATED_FOGRA39_DESCRIPTION, } @@ -111,6 +123,8 @@ impl Builtin { "rec2020" | "bt2020" => Some(Builtin::Rec2020), "gray" | "graygamma22" | "gamma22" => Some(Builtin::GrayGamma22), "sgray" | "graysrgb" => Some(Builtin::SGray), + "dotgain20" | "dotgain20compat" | "dotgain" => Some(Builtin::DotGain20Compat), + "aces-cg" | "acescg" => Some(Builtin::AcesCg), "lab" | "labd50" | "cielab" => Some(Builtin::LabD50), "cmyk" | "coatedcmyk" | "defaultcmyk" | "photocraftcoatedcmyk" => Some(Builtin::CoatedCmyk), "fogra39" | "coatedfogra39" => Some(Builtin::CoatedFogra39), @@ -151,7 +165,7 @@ impl Builtin { /// The profile (built once per process). pub fn profile(self) -> &'static Profile { - static CELLS: [OnceLock; 11] = [const { OnceLock::new() }; 11]; + static CELLS: [OnceLock; 13] = [const { OnceLock::new() }; 13]; // `ALL` lists the variants in declaration order (checked by `all_in_declaration_order`), // so the discriminant is the cell index. CELLS[self as usize].get_or_init(|| build(self)) @@ -163,11 +177,12 @@ fn profile_name_key(s: &str) -> String { s.chars().filter(|c| !c.is_whitespace()).flat_map(char::to_lowercase).collect() } -/// The default profile for a colour space: sRGB, sGray, the coated CMYK profile, Lab D50. +/// The default profile for a colour space: sRGB, Dot Gain 20 %-compatible gray (Photoshop's default +/// working gray), the coated CMYK profile, Lab D50. pub fn default_for(cs: ColorSpace) -> Option<&'static Profile> { Some(match cs { ColorSpace::Rgb => Builtin::Srgb.profile(), - ColorSpace::Gray => Builtin::SGray.profile(), + ColorSpace::Gray => Builtin::DotGain20Compat.profile(), ColorSpace::Cmyk => Builtin::CoatedCmyk.profile(), ColorSpace::Lab => Builtin::LabD50.profile(), _ => return None, @@ -182,7 +197,7 @@ pub fn srgb() -> &'static Profile { /// only assigned to such files, never offered as a working space. pub fn linear_gray() -> &'static Profile { static PROFILE: OnceLock = OnceLock::new(); - PROFILE.get_or_init(|| gray("Linear Gray (Photocraft)", Curve::Gamma(1.0))) + PROFILE.get_or_init(|| gray("Linear Gray (PhotoCraft)", Curve::Gamma(1.0))) } /// The ICC D65 used for the RGB spaces (chromaticity 0.3127, 0.3290). @@ -211,6 +226,8 @@ const P3_SPACE: RgbSpace = rgb_space!([[0.680, 0.320], [0.265, 0.690], [0.150, 0 const ADOBE_SPACE: RgbSpace = rgb_space!([[0.64, 0.33], [0.21, 0.71], [0.15, 0.06]], D65); const ROMM_SPACE: RgbSpace = rgb_space!([[0.7347, 0.2653], [0.1596, 0.8404], [0.0366, 0.0001]], math::D50); const BT2020_SPACE: RgbSpace = rgb_space!([[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]], D65); +/// ACEScg: the AP1 primaries with the ACES white point (~D60, xy 0.32168/0.33767, the ACES 2065-1 neutral). +const AP1_SPACE: RgbSpace = rgb_space!([[0.713, 0.293], [0.165, 0.830], [0.128, 0.044]], math::xy_to_xyz([0.32168, 0.33767])); /// Colorant matrix adapted to D50 and quantized to s15Fixed16, with each row nudged so that /// RGB (1, 1, 1) maps exactly to the stored D50 white (keeps neutrals neutral). @@ -321,6 +338,46 @@ pub const COATED_FOGRA39_ICC: &[u8] = include_bytes!("../profiles/craft-coated-f /// with `CRAFT_CMS_REGEN_PROFILES=1 cargo test -p craft-cms --release regen`). pub const COATED_CMYK_ICC: &[u8] = include_bytes!("../profiles/photocraft-coated-cmyk.icc"); +/// Rec. 709 OETF inverse: V = 1.099 L^0.45 − 0.099 (L ≥ 0.018), 4.5 L below. +fn rec709_trc() -> Curve { + let a = 1.099; + Curve::Parametric { kind: 3, p: [1.0 / 0.45, 1.0 / a, (a - 1.0) / a, 1.0 / 4.5, 0.081, 0.0, 0.0] } +} + +/// The RGB profile for an ITU-T H.273 (CICP) colour description, as a HEIF `nclx` or a video +/// stream declares it: BT.709, BT.2020 or P3-D65 primaries (codes 1, 9, 12) with the sRGB, +/// BT.709, linear or gamma 2.2/2.8 transfer (13; 1, 6, 14, 15; 8; 4; 5). `linear` means the +/// samples were already decoded to linear light, which is how PQ and HLG (16, 18) images are +/// held, since no ICC curve represents those transfers. `None` for anything else. +pub fn cicp_rgb(primaries: u16, transfer: u16, linear: bool) -> Option { + let (prim, name) = match primaries { + 1 => (SRGB_SPACE, "BT.709"), + 9 => (BT2020_SPACE, "Rec. ITU-R BT.2020"), + 12 => (P3_SPACE, "Display P3"), + _ => return None, + }; + let transfer = if linear { 8 } else { transfer }; + let builtin = match (primaries, transfer) { + (1, 13) => Some(Builtin::Srgb), + (1, 8) => Some(Builtin::LinearSrgb), + (12, 13) => Some(Builtin::DisplayP3), + (9, 1 | 6 | 14 | 15) => Some(Builtin::Rec2020), + _ => None, + }; + if let Some(b) = builtin { + return Some(b.profile().clone()); + } + let (trc, curve) = match transfer { + 8 => (Curve::Gamma(1.0), "linear"), + 13 => (srgb_trc(), "sRGB curve"), + 1 | 6 | 14 | 15 => (rec709_trc(), "BT.709 curve"), + 4 => (Curve::Gamma(2.2), "gamma 2.2"), + 5 => (Curve::Gamma(2.8), "gamma 2.8"), + _ => return None, + }; + Some(rgb(&format!("{name} {curve} (PhotoCraft)"), prim, trc)) +} + fn build(b: Builtin) -> Profile { match b { Builtin::Srgb => rgb(b.description(), SRGB_SPACE, srgb_trc()), @@ -328,14 +385,11 @@ fn build(b: Builtin) -> Profile { Builtin::AdobeRgbCompat => rgb(b.description(), ADOBE_SPACE, Curve::Gamma(563.0 / 256.0)), Builtin::ProPhotoCompat => rgb(b.description(), ROMM_SPACE, Curve::Gamma(1.8)), Builtin::LinearSrgb => rgb(b.description(), SRGB_SPACE, Curve::Gamma(1.0)), - Builtin::Rec2020 => { - // Rec. 709 OETF inverse: V = 1.099 L^0.45 − 0.099 (L ≥ 0.018), 4.5 L below. - let a = 1.099; - let trc = Curve::Parametric { kind: 3, p: [1.0 / 0.45, 1.0 / a, (a - 1.0) / a, 1.0 / 4.5, 0.081, 0.0, 0.0] }; - rgb(b.description(), BT2020_SPACE, trc) - } + Builtin::AcesCg => rgb(b.description(), AP1_SPACE, Curve::Gamma(1.0)), + Builtin::Rec2020 => rgb(b.description(), BT2020_SPACE, rec709_trc()), Builtin::GrayGamma22 => gray(b.description(), Curve::Gamma(2.2)), Builtin::SGray => gray(b.description(), srgb_trc()), + Builtin::DotGain20Compat => gray(b.description(), Curve::Gamma(1.732)), Builtin::LabD50 => lab(), // The shipped bytes are `synth::coated_cmyk()` (checked by the `regen` test). Builtin::CoatedCmyk => shipped_cmyk(COATED_CMYK_ICC, b), @@ -369,3 +423,30 @@ fn shipped_cmyk(bytes: &[u8], b: Builtin) -> Profile { hash: Default::default(), }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cicp_maps_onto_the_builtins_and_linear_bt2020() { + let desc = |p: Option| p.map(|p| p.description); + assert_eq!(desc(cicp_rgb(1, 13, false)), Some(Builtin::Srgb.description().to_string())); + assert_eq!(desc(cicp_rgb(12, 13, false)), Some(Builtin::DisplayP3.description().to_string())); + assert_eq!(desc(cicp_rgb(9, 14, false)), Some(Builtin::Rec2020.description().to_string())); + assert_eq!(desc(cicp_rgb(1, 18, true)), Some(Builtin::LinearSrgb.description().to_string())); + + // An HLG BT.2020 image decoded to linear light: BT.2020's colorants, a linear curve. + let hlg = cicp_rgb(9, 18, true).unwrap(); + assert_eq!(hlg.trc, Some([Curve::Gamma(1.0), Curve::Gamma(1.0), Curve::Gamma(1.0)])); + assert_eq!(hlg.matrix, Builtin::Rec2020.profile().matrix); + assert!(hlg.description.contains("BT.2020") && hlg.description.contains("linear"), "{}", hlg.description); + assert!(Profile::parse(&hlg.to_bytes()).is_ok(), "encodes as a valid ICC profile"); + + // HLG and PQ have no ICC curve; unknown primaries have no profile. + assert!(cicp_rgb(9, 18, false).is_none()); + assert!(cicp_rgb(9, 16, false).is_none()); + assert!(cicp_rgb(2, 13, false).is_none()); + assert!(cicp_rgb(u16::MAX, u16::MAX, true).is_none()); + } +} diff --git a/crates/cms/src/clut.rs b/crates/cms/src/clut.rs index dd0315c20..766fa837e 100644 --- a/crates/cms/src/clut.rs +++ b/crates/cms/src/clut.rs @@ -350,4 +350,18 @@ mod tests { narrow.eval_multilinear(&[0.3, 0.7], &mut b).unwrap(); assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "{a:?} {b:?}"); } + + #[test] + fn degenerate_dimensions_do_not_change_the_result() { + // Axes 1 and 3 have a single grid point (degenerate); axes 0, 2, 4 vary. Interpolating + // over the effective dimensions only gives the same answer as the function sampled. + let f = |p: &[f32], o: &mut [f32]| o[0] = 0.25 * p[0] + 0.5 * p[2] + 0.125 * p[4]; + let c = Clut::sample(vec![3, 1, 4, 1, 5], 1, f).unwrap(); + let mut got = [0.0]; + for p in [[0.2f32, 0.0, 0.7, 0.0, 0.4], [1.0, 0.0, 0.0, 0.0, 1.0], [0.5, 0.0, 0.5, 0.0, 0.5]] { + c.eval_multilinear(&p, &mut got).unwrap(); + let want = 0.25 * p[0] + 0.5 * p[2] + 0.125 * p[4]; + assert!((got[0] - want).abs() < 1e-5, "got {} want {want}", got[0]); + } + } } diff --git a/crates/cms/src/curve.rs b/crates/cms/src/curve.rs index a26ec428b..5da1be801 100644 --- a/crates/cms/src/curve.rs +++ b/crates/cms/src/curve.rs @@ -305,15 +305,22 @@ fn table_inverse_with(t: &[f32], y: f32, edge: impl Fn(bool) -> f32) -> f32 { /// For a flat run at the table start (`start = true`) the last index of the run, or for a flat /// run at the end the first index of it, as a normalised input. +/// +/// A table that is inverted is monotonic, so the run is found by bisection, not by a scan: a long +/// constant table is inverted once per pixel, and scanning it each time made the cost the curve's +/// length times the image's. fn edge_index(t: &[f32], start: bool) -> f32 { let n = t.len(); if start { let v = t[0]; - let i = t.iter().position(|x| (*x - v).abs() > 1e-7).map_or(n - 1, |i| i - 1); + // The first value that differs, given they do so from there on. + let first_other = t.partition_point(|x| (*x - v).abs() <= 1e-7); + let i = if first_other >= n { n - 1 } else { first_other.saturating_sub(1) }; i as f32 / (n - 1) as f32 } else { let v = t[n - 1]; - let i = t.iter().rposition(|x| (*x - v).abs() > 1e-7).map_or(0, |i| i + 1); + // The start of the trailing run equal to the last value. + let i = t.partition_point(|x| (*x - v).abs() > 1e-7); i as f32 / (n - 1) as f32 } } @@ -390,4 +397,19 @@ mod tests { let g = Curve::Gamma(2.2); assert!((g.eval64(-0.5) + 0.5f64.powf(2.2)).abs() < 1e-12); } + + #[test] + fn inverting_a_long_flat_table_does_not_rescan_it_for_every_pixel() { + // Four million zeros and a one: a scan per call would be 8·10¹¹ steps for these calls. + let mut t = vec![0.0f32; 4_000_000]; + t.push(1.0); + let c = Curve::Table(t); + let started = std::time::Instant::now(); + let mut last = 0.0; + for _ in 0..200_000 { + last = c.eval_inverse(0.0); + } + assert!(last > 0.99, "the flat start ends at the last zero: {last}"); + assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); + } } diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs index 247b183f2..11dd17732 100644 --- a/crates/cms/src/gamut.rs +++ b/crates/cms/src/gamut.rs @@ -2,13 +2,18 @@ use crate::clut::Clut; use crate::pipeline::{Pipeline, Stage}; -use crate::profile::Profile; +use crate::profile::{ColorSpace, Profile}; use crate::transform::link_stages; -use crate::{CmsError, Intent, check_len}; +use crate::{CmsError, Intent, check_len, invalid_arg}; /// Default ΔE76 threshold above which a colour counts as out of gamut. pub const DEFAULT_THRESHOLD: f32 = 4.0; +#[cfg(not(target_arch = "wasm32"))] +const PAR_MIN_PIXELS: usize = 16 * 1024; +#[cfg(not(target_arch = "wasm32"))] +const PAR_CHUNK_PIXELS: usize = 16 * 1024; + /// Precomputed out-of-gamut test for colours of `src` against `proof`. /// /// A colour is out of gamut when sending it to the proof device (relative colorimetric, @@ -17,6 +22,7 @@ pub const DEFAULT_THRESHOLD: f32 = 4.0; #[derive(Debug)] pub struct GamutCheck { inputs: usize, + source_space: ColorSpace, grid: Option, exact: (Pipeline, Pipeline), pub threshold: f32, @@ -44,7 +50,7 @@ impl GamutCheck { 4 => Some(Clut::sample(vec![17; 4], 1, de)?), _ => None, }; - Ok(GamutCheck { inputs: n, grid, exact: (direct, via), threshold }) + Ok(GamutCheck { inputs: n, source_space: src.color_space, grid, exact: (direct, via), threshold }) } pub fn inputs(&self) -> usize { @@ -76,4 +82,84 @@ impl GamutCheck { pub fn out_of_gamut(&self, px: &[f32]) -> Result { Ok(self.delta_e(px)? > self.threshold) } + + /// Out-of-gamut mask for RGBA pixels: `255` where the pixel has alpha > 0 and its RGB + /// channels are out of gamut, `0` elsewhere. Returns the number of flagged pixels. Only + /// `min(px.len(), mask.len())` pixels are processed. Runs on the rayon pool (not on wasm); + /// the result is identical to calling [`Self::out_of_gamut`] per pixel. + /// + /// # Errors + /// [`CmsError::InvalidArgument`] when the check was not built from an RGB source profile: an + /// RGBA pixel carries only RGB colour channels, so it cannot be tested against a CMYK, gray + /// or Lab source. Nothing is written to `mask` in that case. + pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> Result { + if self.source_space != ColorSpace::Rgb || self.inputs != 3 { + return Err(invalid_arg(format!("gamut mask needs an RGB source profile, got {:?} with {} channels", self.source_space, self.inputs))); + } + let n = px.len().min(mask.len()); + let (Some(px), Some(mask)) = (px.get(..n), mask.get_mut(..n)) else { return Ok(0) }; + let run = |p: &[[f32; 4]], m: &mut [u8]| { + let mut count = 0; + for (p, m) in p.iter().zip(m.iter_mut()) { + // The source has three channels (checked above), so the check cannot fail. + let hit = p[3] > 0.0 && self.out_of_gamut(&[p[0], p[1], p[2]]).unwrap_or(false); + *m = if hit { 255 } else { 0 }; + count += usize::from(hit); + } + count + }; + #[cfg(not(target_arch = "wasm32"))] + if n >= PAR_MIN_PIXELS { + use rayon::prelude::*; + return Ok(px.par_chunks(PAR_CHUNK_PIXELS).zip(mask.par_chunks_mut(PAR_CHUNK_PIXELS)).map(|(p, m)| run(p, m)).sum()); + } + Ok(run(px, mask)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Builtin; + + fn image(n: usize) -> Vec<[f32; 4]> { + let mut s = 0x9E37_79B9u32; + let mut rnd = move || { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s >> 8) as f32 / (1u32 << 24) as f32 + }; + // Includes out-of-range values and zero alpha. + (0..n).map(|i| [rnd() * 1.2 - 0.1, rnd(), rnd(), if i % 7 == 0 { 0.0 } else { rnd() }]).collect() + } + + #[test] + fn mask_rgba_matches_per_pixel_check() { + let src = Builtin::Srgb.profile(); + // Sizes straddle the parallel threshold and the chunk size, odd ones included. + for (proof, threshold) in [(Builtin::CoatedCmyk, 4.0), (Builtin::CoatedCmyk, 1.5), (Builtin::GrayGamma22, 4.0), (Builtin::DisplayP3, 0.5)] { + let check = GamutCheck::new(src, proof.profile(), threshold).unwrap(); + for n in [0, 1, 1023, 16 * 1024 - 1, 16 * 1024, 16 * 1024 + 1, 50_001] { + let px = image(n); + let want: Vec = px.iter().map(|p| if p[3] > 0.0 && check.out_of_gamut(&p[..3]).unwrap() { 255 } else { 0 }).collect(); + let mut got = vec![7u8; n]; + let count = check.mask_rgba(&px, &mut got).unwrap(); + assert_eq!(got, want, "{proof:?} threshold {threshold} n {n}"); + assert_eq!(count, want.iter().filter(|&&m| m == 255).count()); + } + } + } + + #[test] + fn mask_rgba_rejects_non_rgb_source() { + // A CMYK (4-channel), gray (1-channel) and Lab (3-channel, not RGB) source cannot be tested from RGBA pixels. + for src in [Builtin::CoatedCmyk, Builtin::GrayGamma22, Builtin::LabD50] { + let check = GamutCheck::new(src.profile(), Builtin::Srgb.profile(), 4.0).unwrap(); + let px = image(64); + let mut mask = vec![9u8; 64]; + assert!(matches!(check.mask_rgba(&px, &mut mask), Err(CmsError::InvalidArgument(_))), "{src:?}"); + assert!(mask.iter().all(|&m| m == 9), "mask must stay untouched"); + } + } } diff --git a/crates/cms/src/gpu_matrix_shaper.rs b/crates/cms/src/gpu_matrix_shaper.rs new file mode 100644 index 000000000..0d5c0f078 --- /dev/null +++ b/crates/cms/src/gpu_matrix_shaper.rs @@ -0,0 +1,131 @@ +//! Separable RGB display transforms without a coarse 3D interpolation near black. + +/// RGB input curves, a 3×3 matrix with offsets, and RGB output curves for a GPU display +/// transform. Values are floats independent of the document's pixel depth. +/// +/// The input table is sampled linearly at `clamp(rgb, 0, 1) * INPUT_INTERVALS`. Apply +/// [`Self::matrix_rows`] to that result, then sample the output table at +/// `clamp(linear_rgb, 0, 1)^(1/4) * (OUTPUT_ENTRIES - 1)`. Interpolate each channel +/// separately between its two adjacent table entries. These nonuniform output samples +/// retain shadow detail where a pure gamma curve's inverse has an infinite slope. +/// +/// Tables contain RGB values and a padding alpha of 1, suitable for RGBA32Float texels. +/// Use unfiltered texture loads and manual interpolation if float filtering is unavailable. +/// This representation covers SDR display output; input and output are clamped to `[0, 1]`. +/// Construction validates all sizes and values; arbitrary CLUT/proofing chains retain the +/// [`crate::Lut3d`] fallback. +#[derive(Clone, Debug, PartialEq)] +pub struct GpuMatrixShaper { + matrix: [[f32; 4]; 3], + input: Vec<[f32; 4]>, + output: Vec<[f32; 4]>, +} + +impl GpuMatrixShaper { + /// The input table has one more entry than this number of equal intervals. + pub const INPUT_INTERVALS: usize = 4096; + /// Output entries are spaced uniformly in the fourth root of the linear value. + pub const OUTPUT_ENTRIES: usize = 4096; + + /// Row-major matrix: each row contains three RGB coefficients followed by its offset. + pub fn matrix_rows(&self) -> [[f32; 4]; 3] { + self.matrix + } + + /// RGB input curves at `i / INPUT_INTERVALS`, with padding alpha 1. + pub fn input_table(&self) -> &[[f32; 4]] { + &self.input + } + + /// RGB output curves at `(i / (OUTPUT_ENTRIES - 1))^4`, with padding alpha 1. + pub fn output_table(&self) -> &[[f32; 4]] { + &self.output + } + + pub(crate) fn from_parts(matrix: [[f32; 4]; 3], input: &[Vec], output: Option<&[Vec]>) -> Option { + if !matrix.iter().flatten().all(|v| v.is_finite()) { + return None; + } + let input = pack_table(if input.is_empty() { None } else { Some(input) }, Self::INPUT_INTERVALS + 1, |u| u)?; + let output = pack_table(output, Self::OUTPUT_ENTRIES, |u| u * u * u * u)?; + let maxima: [f64; 3] = std::array::from_fn(|channel| input.iter().map(|entry| f64::from(entry[channel]).abs()).fold(0.0, f64::max)); + for row in matrix { + let magnitude = row[..3].iter().zip(maxima).map(|(coefficient, maximum)| f64::from(*coefficient).abs() * maximum).sum::() + + f64::from(row[3]).abs(); + if magnitude > f64::from(f32::MAX) { + return None; + } + } + Some(Self { matrix, input, output }) + } +} + +fn pack_table(tables: Option<&[Vec]>, entries: usize, identity: impl Fn(f32) -> f32) -> Option> { + if let Some(tables) = tables + && (tables.len() != 3 || tables.iter().any(|t| t.len() != entries)) + { + return None; + } + let mut packed: Vec<[f32; 4]> = Vec::new(); + // Both lengths are fixed constants, but a failed allocation still means the caller + // should retain its existing fallback rather than abort while opening a document. + packed.try_reserve_exact(entries).ok()?; + for i in 0..entries { + let rgb = match tables { + Some(tables) => [*tables.first()?.get(i)?, *tables.get(1)?.get(i)?, *tables.get(2)?.get(i)?], + None => [identity(i as f32 / (entries - 1) as f32); 3], + }; + if !rgb.iter().all(|v| v.is_finite()) { + return None; + } + if let Some(previous) = packed.last() + && rgb.iter().zip(previous).any(|(next, before)| !(*next - *before).is_finite()) + { + return None; + } + packed.push([rgb[0], rgb[1], rgb[2], 1.0]); + } + Some(packed) +} + +#[cfg(test)] +mod tests { + use super::*; + + const IDENTITY: [[f32; 4]; 3] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; + + #[test] + fn rejects_invalid_tables_and_nonfinite_values() { + let inputs = vec![vec![0.0; GpuMatrixShaper::INPUT_INTERVALS + 1]; 3]; + let outputs = vec![vec![0.0; GpuMatrixShaper::OUTPUT_ENTRIES]; 3]; + assert!(GpuMatrixShaper::from_parts(IDENTITY, &inputs, Some(&outputs)).is_some()); + assert!(GpuMatrixShaper::from_parts(IDENTITY, &inputs[..2], Some(&outputs)).is_none()); + assert!(GpuMatrixShaper::from_parts(IDENTITY, &inputs, Some(&outputs[..2])).is_none()); + assert!(GpuMatrixShaper::from_parts(IDENTITY, &inputs, Some(&[])).is_none()); + let mut invalid = inputs.clone(); + invalid[0].pop(); + assert!(GpuMatrixShaper::from_parts(IDENTITY, &invalid, Some(&outputs)).is_none()); + for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let mut invalid = inputs.clone(); + invalid[1][123] = v; + assert!(GpuMatrixShaper::from_parts(IDENTITY, &invalid, Some(&outputs)).is_none()); + let mut invalid = outputs.clone(); + invalid[2][321] = v; + assert!(GpuMatrixShaper::from_parts(IDENTITY, &inputs, Some(&invalid)).is_none()); + let mut invalid = IDENTITY; + invalid[1][3] = v; + assert!(GpuMatrixShaper::from_parts(invalid, &inputs, Some(&outputs)).is_none()); + } + } + + #[test] + fn rejects_finite_data_that_overflows_shader_arithmetic() { + let mut matrix = IDENTITY; + matrix[0] = [f32::MAX; 4]; + assert!(GpuMatrixShaper::from_parts(matrix, &[], None).is_none()); + let mut inputs = vec![vec![0.0; GpuMatrixShaper::INPUT_INTERVALS + 1]; 3]; + inputs[0][100] = -f32::MAX; + inputs[0][101] = f32::MAX; + assert!(GpuMatrixShaper::from_parts(IDENTITY, &inputs, None).is_none()); + } +} diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs index e484f8fd8..8d4f99f49 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -13,6 +13,7 @@ //! * [`NamedColors`] reads a named-colour profile's spot colours and converts them into a //! destination profile. //! * [`Lut3d`] samples a display transform into a 3D texture for the GPU canvas. +//! * [`GpuMatrixShaper`] preserves near-black precision for separable RGB display transforms. //! //! Implemented from the public ICC.1:2010 (v4.3) and ICC.1:2001-04 (v2) specifications, //! CIE 15, and Adobe's published black point compensation paper. @@ -22,6 +23,7 @@ pub mod builtin; pub mod clut; pub mod curve; pub mod gamut; +mod gpu_matrix_shaper; pub mod lut3d; pub mod lutfile; pub mod math; @@ -36,6 +38,7 @@ pub use builtin::Builtin; pub use clut::Clut; pub use curve::Curve; pub use gamut::GamutCheck; +pub use gpu_matrix_shaper::GpuMatrixShaper; pub use lut3d::Lut3d; pub use named::{NamedColor, NamedColors}; pub use profile::{ColorSpace, Pcs, Profile, ProfileClass}; diff --git a/crates/cms/src/lut3d.rs b/crates/cms/src/lut3d.rs index 9103b2388..b1a010e74 100644 --- a/crates/cms/src/lut3d.rs +++ b/crates/cms/src/lut3d.rs @@ -37,6 +37,25 @@ impl Lut3d { Ok(Lut3d { size, data }) } + /// Samples `f` (RGB in, RGB out) on a `size`³ grid, `size` from 2 to [`MAX_SIZE`]: a display + /// chain that is more than one [`Transform`]. + pub fn from_fn(size: usize, mut f: impl FnMut([f32; 3]) -> [f32; 3]) -> Result { + if !(2..=MAX_SIZE).contains(&size) { + return Err(invalid_arg(format!("3D LUT size {size} (2 to {MAX_SIZE})"))); + } + let s = (size - 1) as f32; + let mut data = Vec::with_capacity(size * size * size); + for b in 0..size { + for g in 0..size { + for r in 0..size { + let v = f([r as f32 / s, g as f32 / s, b as f32 / s]); + data.push([v[0], v[1], v[2], 1.0]); + } + } + } + Ok(Lut3d { size, data }) + } + /// Edge length. pub fn size(&self) -> usize { self.size @@ -156,4 +175,17 @@ mod tests { assert_eq!(f32_to_f16(1.0), 0x3C00); assert_eq!(f32_to_f16(1e6), 0x7C00); } + + #[test] + fn from_fn_samples_red_fastest_and_bounds_the_size() { + let lut = Lut3d::from_fn(3, |[r, g, b]| [r, g * 0.5, 1.0 - b]).unwrap(); + assert_eq!(lut.size(), 3); + assert_eq!(lut.data().len(), 27); + assert_eq!(lut.data()[1], [0.5, 0.0, 1.0, 1.0]); + assert_eq!(lut.data()[3], [0.0, 0.25, 1.0, 1.0]); + assert_eq!(lut.data()[26], [1.0, 0.5, 0.0, 1.0]); + for size in [0, 1, MAX_SIZE + 1, usize::MAX] { + assert!(matches!(Lut3d::from_fn(size, |v| v), Err(CmsError::InvalidArgument(_))), "{size}"); + } + } } diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index 1bd0e6e30..404b5a315 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -88,16 +88,65 @@ impl LutFile { } } +/// A LUT file format. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Format { + Cube, + ThreeDl, + Look, +} + +impl Format { + /// The format [`parse`] reads `bytes` as: from `file_name`'s extension, else sniffed + /// (XML is `.look`, anything else `.cube`). + pub fn detect(file_name: &str, bytes: &[u8]) -> Self { + let lower = file_name.to_ascii_lowercase(); + if lower.ends_with(".3dl") { + Format::ThreeDl + } else if lower.ends_with(".look") || decode_text(bytes).trim_start().starts_with('<') { + Format::Look + } else { + Format::Cube + } + } + + /// The file extension, without the dot. + pub fn extension(self) -> &'static str { + match self { + Format::Cube => "cube", + Format::ThreeDl => "3dl", + Format::Look => "look", + } + } +} + /// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing). pub fn parse(file_name: &str, bytes: &[u8]) -> Result { - let lower = file_name.to_ascii_lowercase(); - let text = String::from_utf8_lossy(bytes); - if lower.ends_with(".3dl") { - parse_3dl(&text) - } else if lower.ends_with(".look") || text.trim_start().starts_with('<') { - parse_look(&text) - } else { - parse_cube(&text) + parse_as(Format::detect(file_name, bytes), bytes) +} + +/// Parses a LUT in a known format. +pub fn parse_as(format: Format, bytes: &[u8]) -> Result { + let text = decode_text(bytes); + match format { + Format::Cube => parse_cube(&text), + Format::ThreeDl => parse_3dl(&text), + Format::Look => parse_look(&text), + } +} + +/// UTF-16 with a byte-order mark (Photoshop loads such `.look` files, #9118), else UTF-8 +/// (a UTF-8 BOM is stripped). +fn decode_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> { + let utf16 = |rest: &[u8], from: fn([u8; 2]) -> u16| { + let units: Vec = rest.as_chunks::<2>().0.iter().map(|&c| from(c)).collect(); + String::from_utf16_lossy(&units).into() + }; + match bytes { + [0xFF, 0xFE, rest @ ..] => utf16(rest, u16::from_le_bytes), + [0xFE, 0xFF, rest @ ..] => utf16(rest, u16::from_be_bytes), + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest), + _ => String::from_utf8_lossy(bytes), } } @@ -108,6 +157,18 @@ pub fn parse_cube(text: &str) -> Result { let (mut dmin, mut dmax) = ([0.0f32; 3], [1.0f32; 3]); let mut rows: Vec = Vec::new(); for line in text.lines() { + // Only a quote at the beginning of a TITLE value protects '#'. Quotes inside an + // unquoted title's comment must not turn that comment into part of the title. + if let Some(quoted) = line + .trim_start() + .strip_prefix("TITLE") + .filter(|rest| rest.starts_with(char::is_whitespace)) + .and_then(|rest| rest.trim_start().strip_prefix('"')) + { + let Some((value, _)) = quoted.split_once('"') else { return err("unterminated quoted TITLE") }; + title = value.to_string(); + continue; + } let line = line.split('#').next().unwrap_or("").trim(); if line.is_empty() { continue; @@ -133,7 +194,9 @@ pub fn parse_cube(text: &str) -> Result { } k if k.starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '+' || c == '.') => { let mut v = vec![k.parse::().map_err(|_| LutError(format!("bad number in `{line}`")))?]; - v.extend(it.filter_map(|s| s.parse::().ok())); + for value in it { + v.push(value.parse::().map_err(|_| LutError(format!("bad number in `{line}`")))?); + } if v.len() != 3 { return err(format!("bad data line `{line}`")); } @@ -155,6 +218,15 @@ pub fn parse_cube(text: &str) -> Result { if rows.len() != expected_rows { return err("no LUT_3D_SIZE in .cube file"); } + // #8913: the resample below bakes the curve onto a fixed 33-point grid, so a steep + // curve over a narrow domain cannot survive the resample — the baked table silently + // shifts colours (measured 42 RGB8 levels for a two-node ramp over 0.24..0.26, where + // Photoshop renders the ramp exactly). Rather than proxy the risk by domain width (a + // 0.1..0.17 ramp spans two grid cells yet still loses ~28 levels), measure the + // resample's actual error against the exact curve and refuse only tables whose baked + // output shifts by more than a couple of RGB8 levels. Default-domain tables keep the + // existing bake untouched; gentle curves over any domain bake within tolerance and + // stay accepted. // The 1D table is resampled onto a 0..1 cube anyway, so its input domain // (`DOMAIN_MIN`/`MAX`, `LUT_1D_INPUT_RANGE`) is baked into the resample: an input `v` // reads the table at `(v - min) / (max - min)`, saturating outside. @@ -167,46 +239,261 @@ pub fn parse_cube(text: &str) -> Result { }; let mut l = LutFile::from_fn(&title, 33, |c| [curve(0, c[0]), curve(1, c[1]), curve(2, c[2])])?; l.title = title; + let non_default = dmin.iter().any(|v| *v != 0.0) || dmax.iter().any(|v| *v != 1.0); + if non_default { + // Worst baked-vs-exact error per channel, in RGB8 levels: the baked cube is read + // by linear interpolation between grid points (red fastest, so channel `ch` sits + // at stride 33^ch), while `curve` is what the file actually says. + const MAX_BAKE_ERROR: f32 = 2.0 / 255.0; + for ch in 0..3 { + let stride = [1usize, 33, 33 * 33][ch]; + let mut worst = 0.0f32; + for k in 0..=256 { + let v = k as f32 / 256.0; + let x = v * 32.0; + let i = (x as usize).min(31); + let f = x - i as f32; + let baked = l.data[i * stride * 3 + ch] * (1.0 - f) + l.data[(i + 1).min(32) * stride * 3 + ch] * f; + worst = worst.max((baked - curve(ch, v)).abs()); + } + if worst > MAX_BAKE_ERROR { + return err(format!( + "1D LUT domain on {} is {min}..{max}: the curve changes faster than the 33-point grid can \ + hold (baking shifts colours by up to {levels:.0} RGB8 levels); export the look as a 3D LUT \ + or widen DOMAIN_MIN/DOMAIN_MAX", + ["red", "green", "blue"][ch], + min = dmin[ch], + max = dmax[ch], + levels = worst * 255.0, + )); + } + } + } return l.check(); } err("no LUT_3D_SIZE in .cube file") } -/// Lustre `.3dl`: an optional shaper line of input values, then integer RGB rows with **blue** -/// varying fastest; the output bit depth is inferred from the largest value. +/// Lustre `.3dl`: an optional `3DMESH` magic and `Mesh ` line, an optional +/// shaper line of input values, then integer RGB rows with **blue** varying fastest. The +/// `Mesh` line declares the cube edge (2^inBits + 1) and the output code range (up to +/// 2^outBits − 1), and Photoshop honours both (#9073, #9078); without it the edge is the cube +/// root of the row count and the range is inferred from the largest value (#9121). A shaper that +/// isn't the even ramp is applied before the table, as Photoshop does (#8982): see [`apply_shaper`]. pub fn parse_3dl(text: &str) -> Result { + let mut mesh: Option<(u32, u32)> = None; let mut rows: Vec<[f64; 3]> = Vec::new(); + // How many numbers the first numeric line carried: a shaper of exactly `n` values (n ≤ 3) + // is otherwise indistinguishable from a node row. + let mut first_len: Option = None; + // Any text line before the rows is a header: a headerless table peaking at 255 or 1023 is + // on the 12-bit scale, as Photoshop 27.11 reads it (#9121). + let mut header = false; + let mut shaper: Option> = None; for line in text.lines() { let line = line.split('#').next().unwrap_or("").trim(); - if line.is_empty() || line.starts_with(|c: char| c.is_ascii_alphabetic()) { + // A header is `3DMESH` or starts with a word (`Mesh 4 12`): a letter, and not a number. + // `NaN` and `inf` are numbers, and `0oops` starts like one: those rows are read strictly. + let Some(first) = line.split_whitespace().next() else { continue }; + if first.eq_ignore_ascii_case("3DMESH") || first.starts_with(char::is_alphabetic) && first.parse::().is_err() { + header = true; + // The only header keyword that carries data. A malformed or out-of-range `Mesh` + // line is ignored, as every text line always was. + let mut it = line.split_whitespace(); + if it.next().is_some_and(|k| k.eq_ignore_ascii_case("Mesh")) { + // A declaration is exactly two integer fields after the keyword. Anything else + // (a non-numeric field, too few or too many) is not a declaration: `mesh` stays + // unset so headerless inference applies, rather than recovering numbers from + // the wrong positions (#9078). + let fields: Vec<&str> = it.collect(); + if let [a, b] = fields.as_slice() + && let (Ok(n), Ok(bits)) = (a.parse::(), b.parse::()) + && (1..=7).contains(&n) + && (1..=16).contains(&bits) + { + mesh = Some((n, bits)); + } + } continue; } - let v: Vec = line.split_whitespace().filter_map(|s| s.parse().ok()).collect(); + // Every token is a number: a malformed one is refused rather than dropped, which could + // turn a shaper into an even ramp and lose it silently. + let v: Vec = line.split_whitespace().map(str::parse).collect::>().map_err(|_| LutError(format!("bad line `{line}`")))?; + first_len.get_or_insert(v.len()); if v.len() == 3 { rows.push([v[0], v[1], v[2]]); + } else if v.len() >= 2 { + // Two values are a 2-point shaper (a 2³ table's), not something to drop. + // The input shaper: one row of values ahead of the table, and only one. + if shaper.is_some() || !rows.is_empty() { + return err(format!("a second shaper row `{line}`")); + } + shaper = Some(v); } - // Lines with more than three numbers are the input shaper; it is assumed linear. } - let n = (rows.len() as f64).cbrt().round() as usize; - if n < 2 || n * n * n != rows.len() { - return err(format!("{} rows is not a cube", rows.len())); - } - let max = rows.iter().flatten().fold(0.0f64, |a, &b| a.max(b)); - let scale = if max <= 1.0 { 1.0 } else { [1023.0, 4095.0, 16383.0, 65535.0].into_iter().find(|&s| max <= s).unwrap_or(max) }; + let (n, nodes, scale) = match mesh { + Some((in_bits, out_bits)) => { + let n = 2usize.pow(in_bits) + 1; + let expected = n.checked_pow(3).ok_or_else(|| LutError(format!("unsupported 3dl cube size {n}")))?; + // One row more than the declared cube, and the first row has exactly `n` values: + // that row is the shaper, not a 28th node of a 3³ cube (#9078). + let nodes = if shaper.is_none() && rows.len() == expected + 1 && first_len == Some(n) { + shaper = rows.first().map(|row| row.to_vec()); + &rows[1..] + } else { + &rows[..] + }; + if nodes.len() != expected { + return err(format!("expected {expected} rows for the declared {n}³ cube, found {}", nodes.len())); + } + // Under a valid declaration the node codes are integers in the declared range, so + // the declaration wins for every in-range value — including a small max, where 1 is + // 1/declared of full output, not full output itself (#9073). Only a node beyond the + // declared range is a wrong declaration, and the old inference keeps such a file + // loading as before. + let max = nodes.iter().flatten().fold(0.0f64, |a, &b| a.max(b)); + let declared = 2f64.powi(i32::try_from(out_bits).unwrap_or(16)) - 1.0; + (n, nodes, if max > declared { inferred_3dl_scale(max, header) } else { declared }) + } + None => { + let n = (rows.len() as f64).cbrt().round() as usize; + if n < 2 || n * n * n != rows.len() { + return err(format!("{} rows is not a cube", rows.len())); + } + let max = rows.iter().flatten().fold(0.0f64, |a, &b| a.max(b)); + (n, &rows[..], inferred_3dl_scale(max, header)) + } + }; let mut data = vec![0.0f32; n * n * n * 3]; - for (i, row) in rows.iter().enumerate() { + for (i, row) in nodes.iter().enumerate() { let (r, g, b) = (i / (n * n), (i / n) % n, i % n); let at = ((b * n + g) * n + r) * 3; for k in 0..3 { data[at + k] = (row[k] / scale) as f32; } } - LutFile { title: String::new(), size: n, data, domain_min: [0.0; 3], domain_max: [1.0; 3] }.check() + let lut = LutFile { title: String::new(), size: n, data, domain_min: [0.0; 3], domain_max: [1.0; 3] }.check()?; + Ok(match shaper { + Some(shaper) => apply_shaper(lut, &shaper)?, + None => lut, + }) +} + +/// Bakes a `.3dl` shaper into the table. Photoshop applies the shaper row as a 1-D curve on each +/// input channel ahead of the 3-D table (input `x` reads the shaper, sampled evenly over 0..1, +/// at `x`, interpolated linearly), so each node of the table becomes the table's own trilinear +/// value at the shaped input. An even ramp (the usual shaper) changes nothing and is skipped. +/// The table is baked on a grid holding both its own nodes and the shaper's knots: exact for an +/// identity table, an approximation at that resolution otherwise. A shaper that would need more +/// than [`MAX_SIZE`] nodes for that, or that holds a value that isn't finite, is refused. +fn apply_shaper(lut: LutFile, shaper: &[f64]) -> Result { + let m = shaper.len(); + if m < 2 { + return Ok(lut); + } + // Apply or refuse: a shaper that can't be applied never leaves the table to render alone. + if shaper.iter().any(|v| !v.is_finite()) { + return err("the .3dl shaper holds a value that isn't finite"); + } + // The shaper's own depth, from 10 bits up: a 0..1023 ramp is the even ramp with or without a header. + let scale = inferred_3dl_scale(shaper.iter().fold(0.0f64, |a, &b| a.max(b)), true); + let even = |k: usize| scale * k as f64 / (m - 1) as f64; + // Shapers round their ramp: within one code is still the even ramp. An integer shaper's code + // is 1; a float shaper (0..1) is held to one 10-bit step. + let code = if scale > 1.0 { 1.0 } else { 1.0 / 1023.0 }; + if shaper.iter().enumerate().all(|(k, &v)| (v - even(k)).abs() <= code) { + return Ok(lut); + } + // Scaled to 0..1 first, so interpolating between two extreme values can't overflow. + let shaped: Vec = shaper.iter().map(|v| v / scale).collect(); + let curve = |x: f64| -> f32 { + let p = x.clamp(0.0, 1.0) * (m - 1) as f64; + let i = (p.floor() as usize).min(m - 2); + let f = p - i as f64; + let (a, b) = (shaped.get(i).copied().unwrap_or(0.0), shaped.get(i + 1).copied().unwrap_or(0.0)); + (a + (b - a) * f).clamp(0.0, 1.0) as f32 + }; + // The bake grid holds both the table's nodes and the shaper's knots (lcm of their intervals), + // so the curve keeps its breakpoints whatever the table's size: exact on an identity table. A + // grid that would pass MAX_SIZE is refused: sampled more coarsely, a bent shaper could read as + // even and be lost without a word. + let gcd = |mut a: usize, mut b: usize| { + while b != 0 { + (a, b) = (b, a % b); + } + a + }; + let (a, k) = (lut.size - 1, m - 1); + let aligned = (a / gcd(a, k)).checked_mul(k).map(|l| l + 1).filter(|&l| l <= MAX_SIZE); + let Some(n) = aligned else { + return err(format!("the .3dl shaper's {m} points can't be kept on a table of at most {MAX_SIZE} nodes")); + }; + let step = (n - 1) as f64; + let mut out = LutFile { size: n, data: vec![0.0; n * n * n * 3], ..lut.clone() }; + for b in 0..n { + for g in 0..n { + for r in 0..n { + let at = ((b * n + g) * n + r) * 3; + let v = sample(&lut, [curve(r as f64 / step), curve(g as f64 / step), curve(b as f64 / step)]); + if let Some(dst) = out.data.get_mut(at..at + 3) { + dst.copy_from_slice(&v); + } + } + } + } + out.check() +} + +/// Trilinear lookup of `rgb` (0..1) in a [`LutFile`] (red fastest). +fn sample(l: &LutFile, rgb: [f32; 3]) -> [f32; 3] { + let n = l.size; + let loc = |v: f32| { + let p = v.clamp(0.0, 1.0) * (n - 1) as f32; + let i = (p as usize).min(n.saturating_sub(2)); + (i, p - i as f32) + }; + let (r0, fr) = loc(rgb[0]); + let (g0, fg) = loc(rgb[1]); + let (b0, fb) = loc(rgb[2]); + let at = |r: usize, g: usize, b: usize, k: usize| l.data.get(((b * n + g) * n + r) * 3 + k).copied().unwrap_or(0.0); + let mut o = [0.0f32; 3]; + for (k, ov) in o.iter_mut().enumerate() { + let c = |r, g, b| at(r, g, b, k); + let x00 = c(r0, g0, b0) + (c(r0 + 1, g0, b0) - c(r0, g0, b0)) * fr; + let x10 = c(r0, g0 + 1, b0) + (c(r0 + 1, g0 + 1, b0) - c(r0, g0 + 1, b0)) * fr; + let x01 = c(r0, g0, b0 + 1) + (c(r0 + 1, g0, b0 + 1) - c(r0, g0, b0 + 1)) * fr; + let x11 = c(r0, g0 + 1, b0 + 1) + (c(r0 + 1, g0 + 1, b0 + 1) - c(r0, g0 + 1, b0 + 1)) * fr; + let y0 = x00 + (x10 - x00) * fg; + let y1 = x01 + (x11 - x01) * fg; + *ov = y0 + (y1 - y0) * fb; + } + o +} + +/// The code range a `.3dl` node table without a declared output depth was written with: the +/// smallest common integer depth that covers the largest value; a table of 0..1 floats passes +/// through. A headerless table has no 10-bit reading — 255 and 1023 are on the 12-bit scale, as +/// Photoshop 27.11 reads them (#9121). +fn inferred_3dl_scale(max: f64, header: bool) -> f64 { + if max <= 1.0 { + return 1.0; + } + let depths: &[f64] = if header { &[1023.0, 4095.0, 16383.0, 65535.0] } else { &[4095.0, 16383.0, 65535.0] }; + depths.iter().copied().find(|&s| max <= s).unwrap_or(max) } /// SpeedGrade `.look`: `` and a hex `` string of little-endian float32 RGB triplets /// (red fastest). pub fn parse_look(text: &str) -> Result { + // Comments may hold tag-like text, so drop them before looking for tags (#9109). + let mut clean = String::with_capacity(text.len()); + let mut rest = text; + while let Some(i) = rest.find("").map_or("", |e| &rest[i + 4 + e + 3..]); + } + clean.push_str(rest); + let text = clean.as_str(); let tag = |name: &str| -> Option { let open = format!("<{name}>"); let start = text.find(&open)? + open.len(); @@ -215,7 +502,14 @@ pub fn parse_look(text: &str) -> Result { }; let size: usize = tag("size").and_then(|s| s.parse().ok()).ok_or_else(|| LutError("no in .look".into()))?; let (entries, _) = checked_data_len(size)?; - let hex: Vec = tag("data").ok_or_else(|| LutError("no in .look".into()))?.bytes().filter(u8::is_ascii_hexdigit).collect(); + let hex: Vec = tag("data").ok_or_else(|| LutError("no in .look".into()))?.bytes().filter(|b| !b.is_ascii_whitespace()).collect(); + if hex.iter().any(|b| !b.is_ascii_hexdigit()) { + return err("invalid hexadecimal in .look"); + } + // Each float needs eight hex digits; as_chunks would silently discard a partial value. + if !hex.len().is_multiple_of(8) { + return err("incomplete float in .look "); + } let nib = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8; let bytes: Vec = hex.as_chunks::<2>().0.iter().map(|p| nib(p[0]) << 4 | nib(p[1])).collect(); let floats: Vec = bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); @@ -308,6 +602,268 @@ pub fn builtin(id: &str) -> Option { mod tests { use super::*; + #[test] + fn cube_title_hashes_and_comment_quotes_are_distinct() { + let rows = "LUT_1D_SIZE 2\n0 0 0 # low\n1 1 1 # high\n"; + for (line, title) in [ + (r#"TITLE "Look #3" # comment "ignored""#, "Look #3"), + (r#"TITLE Look # "draft""#, "Look"), + (" TITLE\t\"Été #2\"", "Été #2"), + (r#"TITLE "" # empty"#, ""), + ] { + assert_eq!(parse_cube(&format!("{line}\n{rows}")).unwrap().title, title); + } + let lut = LutFile::from_fn("Look #3", 2, |c| c).unwrap(); + assert_eq!(parse_cube(&write_cube(&lut)).unwrap().title, "Look #3"); + assert!(parse_cube(&format!("TITLE \"unterminated # title\n{rows}")).is_err()); + } + + #[test] + fn cube_rejects_invalid_numeric_fields() { + let text = "LUT_3D_SIZE 2\n0.25 nope 0.5 0.75\n0 0 1\n0 1 0\n0 1 1\n1 0 0\n1 0 1\n1 1 0\n1 1 1\n"; + assert!(parse_cube(text).is_err(), "invalid numeric field must not be ignored"); + } + + #[test] + fn utf8_bom_is_stripped() { + let l = LutFile::identity(3).unwrap(); + let mut bytes = vec![0xEF, 0xBB, 0xBF]; + bytes.extend_from_slice(write_cube(&l).as_bytes()); + let p = parse("a.cube", &bytes).unwrap(); + assert_eq!(p.size, l.size); + assert_eq!(p.title, l.title); + let titled = LutFile::from_fn("Look", 3, |c| c).unwrap(); + let mut bytes = vec![0xEF, 0xBB, 0xBF]; + bytes.extend_from_slice(write_cube(&titled).as_bytes()); + assert_eq!(parse("a.cube", &bytes).unwrap().title, "Look"); + let mut bytes = vec![0xEF, 0xBB, 0xBF]; + bytes.extend_from_slice(b"LUT_3D_SIZE 2\n"); + for i in 0..8 { + bytes.extend_from_slice(format!("{} {} {}\n", i & 1, (i >> 1) & 1, i >> 2).as_bytes()); + } + assert_eq!(parse("a.cube", &bytes).unwrap().size, 2); + } + + /// An identity `.3dl` of edge `n` (12-bit nodes, blue fastest) under `shaper`. + fn identity_3dl(shaper: &[u32], n: usize) -> String { + let mut t = shaper.iter().map(u32::to_string).collect::>().join(" ") + "\n"; + let node = |i: usize| (i * 4095 / (n - 1)).to_string(); + for r in 0..n { + for g in 0..n { + for b in 0..n { + t += &format!("{} {} {}\n", node(r), node(g), node(b)); + } + } + } + t + } + + #[test] + fn three_dl_shaper_applies_before_the_table() { + // #8982: Photoshop applies a .3dl's shaper row as a curve ahead of the 3-D table. On grey + // 128 an identity table with the shaper 0 114 455 1023 gives 71 there, and a 17-point + // squared shaper 64 (reported measurements); even ramps leave grey 128 as it is. + let grey = |l: &LutFile| (sample(l, [128.0 / 255.0; 3])[0] * 255.0).round(); + let bent = parse_3dl(&identity_3dl(&[0, 114, 455, 1023], 4)).unwrap(); + assert_eq!(grey(&bent), 71.0); + let squared: Vec = (0..17).map(|i| (1023.0 * (i as f64 / 16.0).powi(2)).round() as u32).collect(); + assert_eq!(grey(&parse_3dl(&identity_3dl(&squared, 17)).unwrap()), 64.0); + let even4 = parse_3dl(&identity_3dl(&[0, 341, 682, 1023], 4)).unwrap(); + assert_eq!(grey(&even4), 128.0); + assert_eq!(even4, parse_3dl(&identity_3dl(&[0, 341, 682, 1023], 4).lines().skip(1).collect::>().join("\n")).unwrap()); + let even17: Vec = (0..17).map(|i| (1023.0 * i as f64 / 16.0).round() as u32).collect(); + assert_eq!(grey(&parse_3dl(&identity_3dl(&even17, 17)).unwrap()), 128.0); + // The ends stay put, and the shaper bends each channel on its own. + assert_eq!(sample(&bent, [0.0, 1.0, 0.0]), [0.0, 1.0, 0.0]); + let c = sample(&bent, [1.0 / 3.0, 0.0, 2.0 / 3.0]); + assert!((c[0] - 114.0 / 1023.0).abs() < 1e-4 && (c[2] - 455.0 / 1023.0).abs() < 1e-4, "{c:?}"); + // A shaper that isn't finite is refused rather than dropped (see + // `three_dl_non_finite_shaper_is_refused`). + assert!(parse_3dl(&identity_3dl(&[0, 341, 682, 1023], 4).replacen("341", "NaN", 1)).is_err()); + } + + /// #9170 review: a float shaper (values in 0..1) is held to a float ramp, not to one integer + /// code, so a bent float shaper is applied. + #[test] + fn three_dl_float_shaper_is_applied() { + let grey = |l: &LutFile| (sample(l, [128.0 / 255.0; 3])[0] * 255.0).round(); + let with = |shaper: &str| { + let table = identity_3dl(&[0, 1, 2, 3], 4); + parse_3dl(&format!("{shaper}\n{}", table.split_once('\n').unwrap().1)).unwrap() + }; + // 0.502 lands between 0.1 and 0.3 at 0.506 of the way: 0.2012, so grey 51. + assert_eq!(grey(&with("0 0.1 0.3 1.0")), 51.0); + // An even float ramp, written to three decimals, still changes nothing. + assert_eq!(grey(&with("0 0.333 0.667 1.0")), 128.0); + } + + /// #9170 review: a shaper with more points than the table keeps its curve: the table is + /// resampled at the shaper's resolution rather than reading the shaper at its own two nodes. + #[test] + fn three_dl_shaper_finer_than_the_table_keeps_its_curve() { + let grey = |l: &LutFile| (sample(l, [128.0 / 255.0; 3])[0] * 255.0).round(); + let small = parse_3dl(&identity_3dl(&[0, 0, 512, 1023], 2)).unwrap(); + // 0.502 lands between 0 and 512 at 0.506 of the way: 259 / 1023, so grey 65. + assert_eq!(grey(&small), 65.0); + assert_eq!(sample(&small, [1.0, 0.0, 1.0]), [1.0, 0.0, 1.0], "the ends stay put"); + } + + /// #9170 review: a finite but extreme shaper can't overflow into NaN when it is baked. + #[test] + fn three_dl_extreme_shaper_bakes_only_finite_values() { + let table = identity_3dl(&[0, 1, 2, 3], 2); + let text = format!("0 1e308 -1e308 0\n{}", table.split_once('\n').unwrap().1); + // Refused or baked, but never a table holding NaN. + if let Ok(l) = parse_3dl(&text) { + assert!(l.data.iter().all(|v| v.is_finite()), "baked a non-finite value"); + } + } + + /// #9170 review (bommerts): the shaper's breakpoints survive a table whose grid doesn't line + /// up with them. The bake grid holds both the table's nodes and the shaper's knots, so on an + /// identity table the curve is exact: `0 0 512 1023` is 0 at ⅓ over 5³ and 17³ tables. + #[test] + fn three_dl_shaper_knots_survive_a_nonaligned_table() { + for n in [5, 17] { + let l = parse_3dl(&identity_3dl(&[0, 0, 512, 1023], n)).unwrap(); + let at = |x: f32| sample(&l, [x, 0.0, 0.0])[0]; + assert!(at(1.0 / 3.0).abs() < 1e-6, "{n}³: {}", at(1.0 / 3.0)); + // The helper's 12-bit nodes are truncated, so the table itself is within a 12-bit step. + assert!((at(2.0 / 3.0) - 512.0 / 1023.0).abs() < 1.0 / 4095.0, "{n}³: {}", at(2.0 / 3.0)); + assert!((at(0.5) - 256.0 / 1023.0).abs() < 1.0 / 4095.0, "{n}³: halfway between the knots"); + } + } + + /// A two-value shaper row (a 2³ table's) is applied like a longer one, not dropped; the even + /// two-point ramp changes nothing. + #[test] + fn three_dl_two_point_shaper_is_applied() { + let bent = parse_3dl(&identity_3dl(&[0, 512], 2)).unwrap(); + let top = sample(&bent, [1.0, 1.0, 1.0]); + assert!(top.iter().all(|v| (v - 512.0 / 1023.0).abs() < 1e-4), "{top:?}"); + assert!((sample(&bent, [0.5, 0.0, 0.0])[0] - 256.0 / 1023.0).abs() < 1e-4); + let even = parse_3dl(&identity_3dl(&[0, 1023], 2)).unwrap(); + assert_eq!( + even, + parse_3dl(&identity_3dl(&[0, 1023], 2).lines().skip(1).collect::>().join( + " +" + )) + .unwrap() + ); + // A second two-value row is a second shaper, refused like a longer one. + let body = identity_3dl(&[0, 512], 2); + assert!( + parse_3dl(&format!( + "{body}0 512 +" + )) + .is_err() + ); + } + + /// #9170 review (bommerts): a shaper row with a token that isn't a number, or a second + /// shaper row, is refused rather than silently dropped. + #[test] + fn three_dl_malformed_shaper_rows_are_refused() { + let table = identity_3dl(&[0, 1, 2, 3], 4); + let body = table.split_once('\n').unwrap().1; + assert!(parse_3dl(&format!("0 341 junk 682 1023\n{body}")).is_err(), "a junk token"); + assert!(parse_3dl(&format!("0 114 455 1023\n0 114 455 1023\n{body}")).is_err(), "two shaper rows"); + assert!(parse_3dl(&format!("0 114 455 1023\n{body}")).is_ok()); + } + + /// #9170 review (bommerts): the standard `3DMESH` / `Title lut 12` preamble still reads; only + /// the rows after it are parsed strictly. + #[test] + fn three_dl_mesh_preamble_is_accepted() { + let grey = |l: &LutFile| (sample(l, [128.0 / 255.0; 3])[0] * 255.0).round(); + let plain = identity_3dl(&[0, 114, 455, 1023], 4); + let headed = parse_3dl(&format!("3DMESH\nTitle lut 12\n{plain}")).unwrap(); + assert_eq!(headed, parse_3dl(&plain).unwrap(), "the preamble changes nothing"); + assert_eq!(grey(&headed), 71.0, "the bent shaper still applies"); + let even = identity_3dl(&[0, 341, 682, 1023], 4); + assert_eq!(grey(&parse_3dl(&format!("3dmesh\nTitle lut 12\n{even}")).unwrap()), 128.0); + assert!( + parse_3dl(&format!("3DMESH\nTitle lut 12\n0 341 junk 682 1023\n{}", even.split_once('\n').unwrap().1)).is_err(), + "still strict after it" + ); + } + + /// #9170 review: a shaper that isn't finite is refused, not dropped, so a Color Lookup never + /// renders the table alone for a file whose shaper it can't apply. + #[test] + fn three_dl_non_finite_shaper_is_refused() { + let body = identity_3dl(&[0, 1, 2, 3], 4); + let body = body.split_once('\n').unwrap().1; + for shaper in ["0 NaN 682 1023", "0 341 inf 1023", "-inf 341 682 1023"] { + assert!(parse_3dl(&format!("{shaper}\n{body}")).is_err(), "{shaper}"); + } + } + + /// #9170 review: a shaper row that starts with `NaN` or `inf` is a shaper, not a header, so + /// it reaches the non-finite refusal instead of being skipped. + #[test] + fn three_dl_shaper_starting_non_finite_is_refused() { + let body = identity_3dl(&[0, 1, 2, 3], 4); + let body = body.split_once('\n').unwrap().1; + for shaper in ["NaN 341 682 1023", "inf 341 682 1023", "-inf 341 682 1023"] { + assert!(parse_3dl(&format!("{shaper}\n{body}")).is_err(), "{shaper}"); + } + } + + /// #9170 review: only a line starting with a word is a header. One whose first token looks + /// like a number but isn't (`0oops`) is read strictly and refused, not skipped with its shaper. + #[test] + fn three_dl_malformed_first_token_is_refused() { + let body = identity_3dl(&[0, 1, 2, 3], 4); + let body = body.split_once('\n').unwrap().1; + for shaper in ["0oops 114 455 1023", "-x 114 455 1023", ".5x 114 455 1023", "+ 114 455 1023"] { + assert!(parse_3dl(&format!("{shaper}\n{body}")).is_err(), "{shaper}"); + } + let (first, rest) = body.split_once('\n').unwrap(); + assert!(parse_3dl(&format!("0 114 455 1023\n{first}\n1x 0 0\n{rest}")).is_err(), "a table row too"); + assert!(parse_3dl(&format!("3DMESH\nTitle lut 12\n0 114 455 1023\n{body}")).is_ok(), "headers still skip"); + } + + /// #9170 review: a bent shaper whose knots can't all be kept within MAX_SIZE is refused rather + /// than sampled where it may look even (here a 257-point shaper bent only at odd knots, whose + /// 129-node fallback would read the identity). + #[test] + fn three_dl_shaper_too_fine_to_keep_is_refused() { + let shaper: Vec = (0..257u32).map(|i| (i * 1023 / 256 + if i % 2 == 1 { 40 } else { 0 }).min(1023)).collect(); + assert!(parse_3dl(&identity_3dl(&shaper, 2)).is_err()); + // As many knots as nodes stays within reach. + let same: Vec = (0..17u32).map(|i| (1023.0 * (f64::from(i) / 16.0).powi(2)).round() as u32).collect(); + assert!(parse_3dl(&identity_3dl(&same, 17)).is_ok()); + } + + #[test] + fn cube_title_with_hash_round_trips() { + let l = LutFile::from_fn("Look #3", 2, |c| c).unwrap(); + assert_eq!(parse_cube(&write_cube(&l)).unwrap().title, "Look #3"); + let t = "TITLE \"A #b\" # note\nLUT_3D_SIZE 2 # c\n# comment\n"; + let rows = "0 0 0 # x\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n"; + let p = parse_cube(&format!("{t}{rows}")).unwrap(); + assert_eq!(p.title, "A #b"); + } + + #[test] + fn write_cube_keeps_non_default_domain() { + let mut l = LutFile::identity(2).unwrap(); + l.domain_min = [0.1; 3]; + l.domain_max = [0.9; 3]; + let back = parse_cube(&write_cube(&l)).unwrap(); + assert_eq!(back.domain_min, [0.1; 3]); + assert_eq!(back.domain_max, [0.9; 3]); + l.domain_min = [0.0, 0.0, 0.5]; + l.domain_max = [1.0; 3]; + let back = parse_cube(&write_cube(&l)).unwrap(); + assert_eq!(back.domain_min, [0.0, 0.0, 0.5]); + assert_eq!(back.domain_max, [1.0; 3]); + assert!(!write_cube(&LutFile::identity(2).unwrap()).contains("DOMAIN")); + } + #[test] fn cube_domain_is_kept_and_validated() { let base = "TITLE \"t\" @@ -345,6 +901,49 @@ DOMAIN_MAX 0.5 1 1 assert!(e.0.contains("below DOMAIN_MAX"), "{e}"); } + #[test] + fn cube_1d_narrow_domain_is_refused() { + // #8913: the issue's fixture — a two-node ramp over 0.24..0.26. Baking it onto the + // 33-point grid rendered grey-65 as 148 where Photoshop renders 190 (42-level error). + // It must now be an actionable parse error rather than a silently wrong table. + let e = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0.24 0.24 0.24\nDOMAIN_MAX 0.26 0.26 0.26\n0 0 0\n1 1 1\n").unwrap_err(); + assert!(e.0.contains("changes faster than the 33-point grid"), "{e}"); + // The same domain via LUT_1D_INPUT_RANGE is refused identically. + let e = parse_cube("LUT_1D_SIZE 2\nLUT_1D_INPUT_RANGE 0.24 0.26\n0 0 0\n1 1 1\n").unwrap_err(); + assert!(e.0.contains("changes faster"), "{e}"); + // A per-channel narrow domain names the offending channel. + let e = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0.24\nDOMAIN_MAX 1 1 0.26\n0 0 0\n1 1 1\n").unwrap_err(); + assert!(e.0.contains("blue"), "{e}"); + } + + #[test] + fn cube_1d_wide_domain_still_bakes() { + // A steep ramp over 0.1..0.17 spans two grid cells but still loses ~28 RGB8 levels + // to the resample, so the measured-error check refuses it even though the old width + // check let it through. + let e = parse_cube("LUT_1D_SIZE 2\nLUT_1D_INPUT_RANGE 0.1 0.17\n0 0 0\n1 1 1\n").unwrap_err(); + assert!(e.0.contains("changes faster"), "steep ramp over 0.1..0.17 refused: {e}"); + // A gentle (here linear) curve over a grid-aligned domain bakes exactly and stays + // accepted — the check measures the bake's error, not the domain's width. Value + // assertions, not just a successful parse: the baked table must reproduce the curve. + // Table row k sits at t = k/32 of the domain 0.25..0.75; the curve y = 0.4 + 0.4t + // is gentle (a half-level per grid step), so the bake must reproduce it exactly. + let mut table = String::from("LUT_1D_SIZE 33\nLUT_1D_INPUT_RANGE 0.25 0.75\n"); + for k in 0..33 { + let y = 0.4 + 0.4 * (k as f32 / 32.0); + table.push_str(&format!("{y} {y} {y}\n")); + } + let l = parse_cube(&table).expect("gentle curve over a non-default domain still bakes"); + let at = |r: usize| l.data[r * 3]; + // Grid entry r is input r/32: 0.5 is the middle of the domain (t=0.5) -> 0.6. + assert!((at(16) - 0.6).abs() < 1.0 / 255.0, "baked value at 0.5 tracks the curve: {}", at(16)); + // Domain top (input 0.75 = grid 24, t=1) -> 0.8. + assert!((at(24) - 0.8).abs() < 1.0 / 255.0, "baked value at the domain top tracks the curve: {}", at(24)); + // Below the domain saturates to the first row. + assert!((at(8) - 0.4).abs() < 1.0 / 255.0, "below the domain saturates: {}", at(8)); + parse_cube("LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").expect("default domain"); + } + #[test] fn cube_1d_domain_is_baked_into_the_resample() { // An identity ramp over the domain 0.25..0.75: 0.25 maps to 0, 0.5 to 0.5, 0.75 to 1. @@ -403,6 +1002,26 @@ DOMAIN_MAX 0.5 1 1 assert!(parse_cube(&text).is_err()); } + #[test] + fn three_dl_without_a_header_reads_low_nodes_as_12_bit() { + let table = |peak: u32| -> String { + let mut text = String::from("0 1023\n"); + for i in 0..8 { + let on = |bit: u32| if i & bit != 0 { peak } else { 0 }; + text.push_str(&format!("{} {} {}\n", on(4), on(2), on(1))); + } + text + }; + for peak in [255, 1023, 4095] { + let white = parse_3dl(&table(peak)).unwrap().data[21..24].to_vec(); + assert_eq!(white, [peak as f32 / 4095.0; 3], "peak {peak}"); + } + // A header keeps the inferred 10-bit depth. The bare `3DMESH` magic is a header without a + // cube declaration; `Mesh 1 10` would declare a 3³ cube and refuse this 2³ table (#9078). + let white = parse_3dl(&format!("3DMESH\n{}", table(1023))).unwrap().data[21..24].to_vec(); + assert_eq!(white, [1.0; 3]); + } + #[test] fn three_dl_blue_fastest_and_bit_depth() { let mut text = String::from("0 1023\n"); @@ -418,12 +1037,210 @@ DOMAIN_MAX 0.5 1 1 assert_eq!(l.data, LutFile::identity(2).unwrap().data); } + /// A `size`³ inverse-identity `.3dl` (blue fastest): node (r,g,b) outputs `max - max·v/(size-1)` + /// per channel, with a uniform shaper of `size` codes up to 1023. + fn mesh_3dl(n_bits: u32, out_bits: u32, size: usize, max: f64, shaper: bool) -> String { + let mut text = format!("3DMESH\nMesh {n_bits} {out_bits}\n"); + if shaper { + for i in 0..size { + if i > 0 { + text.push(' '); + } + text.push_str(&format!("{}", (1023.0 * i as f64 / (size - 1) as f64).round())); + } + text.push('\n'); + } + for r in 0..size { + for g in 0..size { + for b in 0..size { + let v = [r, g, b].map(|c| (max - max * c as f64 / (size - 1) as f64).round()); + text.push_str(&format!("{} {} {}\n", v[0], v[1], v[2])); + } + } + } + text + } + #[test] - fn look_hex_floats() { + fn three_dl_mesh_three_point_shaper_is_not_a_node() { + // #9078: Photoshop loads a 3³ cube whose shaper line has three values; counting it as a + // 28th node rejected the whole file. + let l = parse_3dl(&mesh_3dl(1, 12, 3, 4095.0, true)).unwrap(); + assert_eq!(l.size, 3); + assert_eq!(l.data.len(), 3 * 3 * 3 * 3); + // The inverse identity: node (0,0,0) is full, node (2,2,2) black. + assert!((l.data[0] - 1.0).abs() < 1e-6 && (l.data[1] - 1.0).abs() < 1e-6 && (l.data[2] - 1.0).abs() < 1e-6); + let last = &l.data[l.data.len() - 3..]; + assert_eq!(last, [0.0, 0.0, 0.0]); + // The same 27 nodes without the shaper row still load (the node-only control). + assert_eq!(parse_3dl(&mesh_3dl(1, 12, 3, 4095.0, false)).unwrap().data, l.data); + } + + #[test] + fn three_dl_mesh_declares_the_output_depth() { + // #9073: identical node codes divide by the declared range, not by the largest value. + let mut text_10 = String::new(); + let mut text_12 = String::new(); + for (n_bits, out_bits, dst) in [(2, 10, &mut text_10), (2, 12, &mut text_12)] { + // A 5³ identity scaled to 10-bit codes (max 1023). + *dst = format!("3DMESH\nMesh {n_bits} {out_bits}\n0 256 512 768 1023\n"); + for r in 0..5 { + for g in 0..5 { + for b in 0..5 { + dst.push_str(&format!("{} {} {}\n", r * 255, g * 255, b * 255)); + } + } + } + } + let white_10 = parse_3dl(&text_10).unwrap(); + let white_12 = parse_3dl(&text_12).unwrap(); + assert_eq!(white_10.size, 5); + let last_10 = &white_10.data[white_10.data.len() - 3..]; + let last_12 = &white_12.data[white_12.data.len() - 3..]; + assert!((last_10[0] - 1020.0 / 1023.0).abs() < 1e-6, "{last_10:?}"); + // 1020/4095 ≈ 0.249: white renders grey, as Photoshop measures it. + assert!((last_12[0] - 1020.0 / 4095.0).abs() < 1e-6, "{last_12:?}"); + } + + #[test] + fn three_dl_mesh_header_mismatch_is_rejected() { + // A Mesh header that disagrees with the row count is refused, not silently re-inferred. + assert!(parse_3dl("3DMESH\nMesh 1 12\n0 0 0\n0 0 1\n").is_err()); + // A node beyond the declared range is a wrong declaration: the old inference from the + // largest value keeps the file loading as it did before the header was honoured. + let mut text = String::from("3DMESH\nMesh 1 10\n"); + for r in 0..3 { + for g in 0..3 { + for b in 0..3 { + text.push_str(&format!("{} {} {}\n", r * 2047, g * 2047, b * 2047)); + } + } + } + let l = parse_3dl(&text).unwrap(); + let last = &l.data[l.data.len() - 3..]; + assert!((last[0] - 4094.0 / 4095.0).abs() < 1e-6, "{last:?}"); + } + + #[test] + fn three_dl_mesh_extra_node_cannot_replace_a_captured_shaper() { + for (bits, size) in [(2, 5), (3, 9)] { + let mut text = mesh_3dl(bits, 12, size, 4095.0, true); + let valid = parse_3dl(&text).unwrap(); + assert_eq!(valid.size, size); + assert_eq!(valid.data, parse_3dl(&mesh_3dl(bits, 12, size, 4095.0, false)).unwrap().data); + text.push_str("4095 4095 4095\n"); + let error = parse_3dl(&text).unwrap_err().to_string(); + assert!(error.contains(&format!("expected {} rows", size * size * size)), "{error}"); + } + } + + #[test] + fn three_dl_malformed_mesh_header_falls_back_to_inference() { + // A `Mesh` line that is not exactly two integer fields is not a declaration: it is + // ignored and the table is inferred as if headerless, rather than recovering numbers + // from the wrong positions (#9078). A 2³ cube would otherwise be read as a 3³ cube. + for header in ["Mesh invalid 1 12", "Mesh 1 12 13", "Mesh 1 x", "Mesh 1"] { + let mut text = format!("3DMESH\n{header}\n"); + for r in 0..2 { + for g in 0..2 { + for b in 0..2 { + text.push_str(&format!("{} {} {}\n", r * 1023, g * 1023, b * 1023)); + } + } + } + let l = parse_3dl(&text).unwrap(); + assert_eq!(l.size, 2, "{header}"); + assert_eq!(l.data, LutFile::identity(2).unwrap().data, "{header}"); + } + } + + #[test] + fn three_dl_mesh_uses_declared_range_for_small_integer_codes() { + // #9073: under a valid `Mesh` declaration the node codes are integers in the declared + // range, so a max value of 1 is 1/4095 of full output — not full output itself. + let mut text = String::from("3DMESH\nMesh 1 12\n"); + for r in 0..3 { + for g in 0..3 { + for b in 0..3 { + let v = u8::from(r == 0 && g == 0 && b == 0); + text.push_str(&format!("{v} {v} {v}\n")); + } + } + } + let l = parse_3dl(&text).unwrap(); + assert_eq!(l.size, 3); + // blue fastest: node (0,0,0) is the first entry, code 1 → 1/4095. + assert!((l.data[0] - 1.0 / 4095.0).abs() < 1e-6, "{:?}", &l.data[0..3]); + assert!(l.data[3..].iter().all(|&v| v == 0.0), "{:?}", l.data); + } + + #[test] + fn look_data_is_little_endian_float32() { + // Bytes written out by hand rather than by the encoder the parser mirrors, so a wrong byte + // order fails: 0.25, 0.5, 1.0 (3E800000, 3F000000, 3F800000 stored low byte first), then zeros. + let hex = format!("0000803E 0000003F 0000803F {}", "00000000 ".repeat(21)); + let xml = format!("\"2\"\"{hex}\""); + let data = parse("a.look", xml.as_bytes()).unwrap().data; + assert_eq!(data[..3], [0.25, 0.5, 1.0]); + assert!(data[3..].iter().all(|&v| v == 0.0)); + } + + #[test] + fn look_reads_utf16_with_either_byte_order() { let id = LutFile::identity(2).unwrap(); let hex: String = id.data.iter().flat_map(|v| v.to_le_bytes()).map(|b| format!("{b:02X}")).collect(); - let xml = format!("\"2\"\"{hex}\""); - assert_eq!(parse("a.look", xml.as_bytes()).unwrap().data, id.data); + let xml = format!("\"2\"\"{hex}\""); + let le: Vec = [0xFF, 0xFE].into_iter().chain(xml.encode_utf16().flat_map(u16::to_le_bytes)).collect(); + let be: Vec = [0xFE, 0xFF].into_iter().chain(xml.encode_utf16().flat_map(u16::to_be_bytes)).collect(); + assert_eq!(parse("a.look", &le).unwrap().data, id.data); + assert_eq!(parse("a.look", &be).unwrap().data, id.data); + // Sniffed as XML through the byte-order mark too, so the recorded format is the one parsed. + assert_eq!(Format::detect("a.lut", &le), Format::Look); + assert_eq!(parse_as(Format::Look, &be).unwrap().data, id.data); + } + + #[test] + fn look_ignores_tags_inside_xml_comments() { + let hex = |l: &LutFile| -> String { l.data.iter().flat_map(|v| v.to_le_bytes()).map(|b| format!("{b:02X}")).collect() }; + let inverse = LutFile::from_fn("", 2, |[r, g, b]| [1.0 - r, 1.0 - g, 1.0 - b]).unwrap(); + let xml = format!( + "\"2\"\"{}\"").map_or(b.len(), |i| i + 3) + } + } else { + find_byte(b, self.pos, b'>').map_or(b.len(), |i| i + 1) + }; + self.pos = end.min(b.len()); + } + + /// Read the end tag at `self.pos` (``). + fn close_tag(&mut self) -> Option> { + let b = self.bytes(); + let start = self.pos + 2; + let mut i = start; + while let Some(c) = b.get(i) { + if c.is_ascii_whitespace() || *c == b'/' || *c == b'>' { + break; + } + i += 1; + } + let name = self.slice(start, i); + self.pos = find_byte(b, i, b'>').map_or(b.len(), |j| j + 1); + // `` is nothing at all. + (!name.is_empty()).then(|| Token::End(self.tag_name(name))) + } + + /// Read the start tag at `self.pos` (``). + fn open_tag(&mut self) -> Tag<'a> { + let b = self.bytes(); + let start = self.pos + 1; + let mut i = start; + while let Some(c) = b.get(i) { + if c.is_ascii_whitespace() || *c == b'/' || *c == b'>' { + break; + } + i += 1; + } + let name = self.tag_name(self.slice(start, i)); + let mut attrs = Vec::new(); + let mut self_close = false; + loop { + while matches!(b.get(i), Some(c) if c.is_ascii_whitespace() || *c == b'/') { + self_close = b.get(i) == Some(&b'/') && b.get(i + 1) == Some(&b'>'); + i += 1; + } + match b.get(i) { + None => break, + Some(b'>') => { + i += 1; + break; + } + Some(_) => {} + } + // An attribute name runs to white space, `/`, `>` or `=`; a leading `=` is part of it. + let name_start = i; + i += 1; + while let Some(c) = b.get(i) { + if c.is_ascii_whitespace() || matches!(*c, b'/' | b'>' | b'=') { + break; + } + i += 1; + } + let attr = self.slice(name_start, i); + let (value, next) = self.attr_value(i); + i = next; + if attrs.len() < self.opts.limits.max_attrs { + attrs.push((attr, value)); + } + } + self.pos = i.min(b.len()); + Tag { name, attrs, self_close } + } + + /// The value after an attribute name that ends at `i` (empty when it has none), and where + /// reading goes on. + fn attr_value(&self, i: usize) -> (&'a str, usize) { + let b = self.bytes(); + let mut j = i; + while matches!(b.get(j), Some(c) if c.is_ascii_whitespace()) { + j += 1; + } + if b.get(j) != Some(&b'=') { + return ("", j); + } + j += 1; + while matches!(b.get(j), Some(c) if c.is_ascii_whitespace()) { + j += 1; + } + match b.get(j) { + Some(&q) if q == b'"' || q == b'\'' => { + let end = find_byte(b, j + 1, q).unwrap_or(b.len()); + (self.slice(j + 1, end), (end + 1).min(b.len())) + } + _ => { + let mut end = j; + while let Some(c) = b.get(end) { + if c.is_ascii_whitespace() || *c == b'>' { + break; + } + end += 1; + } + (self.slice(j, end), end) + } + } + } +} + +impl<'a> Iterator for Lexer<'a, '_> { + type Item = Token<'a>; + + fn next(&mut self) -> Option> { + loop { + let b = self.bytes(); + if self.pos >= b.len() { + return None; + } + if let Some(name) = self.raw.take() { + let end = find_end_tag(b, self.pos, &name).unwrap_or(b.len()); + let text = self.slice(self.pos, end); + self.pos = end; + if !text.is_empty() { + return Some(Token::Text(text)); + } + continue; + } + if b.get(self.pos) != Some(&b'<') || !self.markup_at(self.pos) { + let start = self.pos; + self.pos = self.text_end(); + return Some(Token::Text(self.slice(start, self.pos))); + } + match b.get(self.pos + 1) { + Some(b'!' | b'?') => self.skip_declaration(), + Some(b'/') => { + if let Some(token) = self.close_tag() { + return Some(token); + } + } + _ => { + let tag = self.open_tag(); + if self.opts.drop.contains(&tag.name.as_str()) { + self.raw_content(&tag.name); + continue; + } + if self.opts.raw_text.contains(&tag.name.as_str()) { + self.raw = Some(tag.name.clone()); + } + return Some(Token::Start(tag)); + } + } + } + } +} + +fn find_byte(b: &[u8], from: usize, byte: u8) -> Option { + b.get(from..)?.iter().position(|c| *c == byte).map(|i| i + from) +} + +fn find_sub(b: &[u8], from: usize, needle: &[u8]) -> Option { + b.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|i| i + from) +} + +/// Where `` or the end), at or after `from`. +fn find_end_tag(b: &[u8], from: usize, name: &str) -> Option { + let mut i = from; + while let Some(lt) = find_byte(b, i, b'<') { + let after = lt + 2 + name.len(); + let named = b.get(lt + 1) == Some(&b'/') && b.get(lt + 2..after).is_some_and(|n| n.eq_ignore_ascii_case(name.as_bytes())); + if named && b.get(after).is_none_or(|c| c.is_ascii_whitespace() || matches!(*c, b'/' | b'>')) { + return Some(lt); + } + i = lt + 1; + } + None +} + +#[cfg(test)] +mod tests; diff --git a/crates/html/src/lex/tests.rs b/crates/html/src/lex/tests.rs new file mode 100644 index 000000000..4f19e5b7c --- /dev/null +++ b/crates/html/src/lex/tests.rs @@ -0,0 +1,177 @@ +use super::{Lexer, Limits, Options, Token}; + +/// As a mail reader sets it up. +const MAIL: Options<'static> = + Options { limits: Limits { max_attrs: 32, max_tag_name: 24 }, drop: &["script", "style", "title", "iframe"], raw_text: &["textarea", "xmp"] }; + +fn show<'a>(lexer: impl Iterator>) -> Vec { + lexer + .map(|t| match t { + Token::Text(t) => format!("T:{t}"), + Token::Start(tag) => { + let attrs: Vec = tag.attrs.iter().map(|(n, v)| format!("{n}={v}")).collect(); + if attrs.is_empty() { format!("<{}>", tag.name) } else { format!("<{} {}>", tag.name, attrs.join(" ")) } + } + Token::End(n) => format!(""), + }) + .collect() +} + +fn tokens(html: &str) -> Vec { + show(Lexer::with(html, MAIL)) +} + +#[test] +fn text_and_tags() { + assert_eq!(tokens("Hi there!"), ["T:Hi ", "", "T:there", "", "T:!"]); + assert_eq!(tokens(""), Vec::::new()); + assert_eq!(tokens("plain"), ["T:plain"]); + assert_eq!(tokens("

"), ["
", "
"]); +} + +#[test] +fn attributes_in_every_quoting_style() { + assert_eq!(tokens(r#"
"#), [r#""#]); + assert_eq!(tokens("t"), ["", "T:t"]); + assert_eq!(tokens(""), [""]); + assert_eq!(tokens("

"), ["

"]); + // A `>` inside a quoted value does not end the tag. + assert_eq!(tokens(r#"t"#), ["b>", "T:t", ""]); +} + +#[test] +fn attribute_values_are_decoded_on_demand() { + let mut t = Lexer::new(r#""#); + let Some(Token::Start(tag)) = t.next() else { panic!("no tag") }; + assert_eq!(tag.attr("href").as_deref(), Some("?a=1&b=2©=3")); + assert_eq!(tag.raw_attr("href"), Some("?a=1&b=2©=3")); + assert_eq!(tag.attr("missing"), None); + assert!(tag.has("checked") && !tag.has("check")); + assert_eq!(tag.attributes().map(|(n, _)| n).collect::>(), ["HREF", "href", "Checked"]); +} + +#[test] +fn a_tag_that_closes_itself_says_so() { + let closes = |html: &str| match Lexer::new(html).next() { + Some(Token::Start(tag)) => tag.self_close, + other => panic!("{other:?}"), + }; + for yes in ["
", "
", "", "", ""] { + assert!(closes(yes), "{yes}"); + } + // A `/` that ends an unquoted value, or stands anywhere but before the `>`, is not it. + for no in ["
", "", "
", "", "
d"), ["T:a < b and c > d"]); + assert_eq!(tokens("1<2<3"), ["T:1<2<3"]); + assert_eq!(tokens("<"), ["T:<"]); + assert_eq!(tokens("x<"), ["T:x<"]); + assert_eq!(tokens("<3 <- b"), ["T:a", "T:b"]); +} + +#[test] +fn comments_and_declarations_vanish() { + assert_eq!(tokens("ab"), ["T:a", "T:b"]); + assert_eq!(tokens("

x"), ["

", "T:x"]); + assert_eq!(tokens("x"), ["T:x"]); + assert_eq!(tokens("abc"), ["T:a", "T:b", "T:c"]); + assert_eq!(tokens("shown"), ["T:shown"]); + assert_eq!(tokens("shown"), ["T:shown"]); + // An unfinished comment swallows the rest. + assert_eq!(tokens("a"); + } else if rest.starts_with(b""); + } else if rest.starts_with(b"` closing its subset (the first `>` when it has none). + let end = match (rest.iter().position(|b| *b == b'['), rest.iter().position(|b| *b == b'>')) { + (Some(o), Some(g)) if o < g => find(i, b"]>"), + _ => find(i, b">"), + }; + let quotes = data.get(i..end).unwrap_or(&[]).iter().filter(|b| matches!(**b, b'"' | b'\'')).count(); + if over(quotes / 2) { + return true; + } + i = end; + } else if rest.starts_with(b""); + } else { + // A start tag: to its `>` outside quotes. + let (mut quote, mut j, mut attrs) = (None, i + 1, 0usize); + while let Some(&c) = data.get(j) { + match quote { + Some(q) if c == q => quote = None, + Some(_) => {} + None if c == b'"' || c == b'\'' => { + quote = Some(c); + attrs += 1; + } + None if c == b'>' => break, + None => {} + } + j += 1; + } + if over(attrs) { + return true; + } + i = j + 1; + } + } + false +} + /// What one pass over the XML text of an SVG finds before any XML reader ([`prescan`]). pub struct Prescan<'s> { /// Whether the elements nest deeper than the cap. The pass stops there. @@ -259,6 +339,40 @@ mod tests { assert!(start.elapsed() < std::time::Duration::from_secs(120), "{:?}", start.elapsed()); } + #[test] + fn an_entity_holding_markup_is_found_and_a_namespace_entity_is_not() { + assert!(entity_holds_markup("\">]>&a;")); + assert!(entity_holds_markup("'>]>")); + assert!(!entity_holds_markup("]>")); + assert!(!entity_holds_markup("]>")); + assert!(!entity_holds_markup("")); + } + + fn wide(svg: &str) -> bool { + too_wide(svg, MAX_ATTRIBUTES, MAX_ATTRIBUTE_WORK) + } + + #[test] + fn an_element_with_thousands_of_attributes_is_too_wide() { + let many = |n: usize| (0..n).map(|i| format!(" a{i}=\"1\"")).collect::(); + assert!(!wide(&format!("", many(4096)))); + assert!(wide(&format!("", many(4097)))); + assert!(!wide(&format!("{}", "".repeat(10_000))), "per element, not per file"); + assert!(too_wide("", 2, usize::MAX) && !too_wide("", 3, usize::MAX)); + assert!(!wide(" '' \"\" "), "quotes outside tags are no attributes"); + } + + #[test] + fn attribute_work_is_bounded_over_the_whole_document_and_its_dtd() { + let many = |n: usize| (0..n).map(|i| format!(" a{i}=\"1\"")).collect::(); + let tag = format!("", many(4000)); + assert!(!wide(&format!("{}", tag.repeat(10)))); + assert!(wide(&format!("{}", tag.repeat(40))), "each element is within the limit, all together are not"); + let dtd = format!("'>]>&e;", many(5000)); + assert!(wide(&dtd), "entities can hold elements"); + assert!(!wide("]>")); + } + #[test] fn declarations_in_comments_and_long_names_cannot_hide_a_large_entity() { let big = "x".repeat(1 << 20); diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index e057b9b1f..fd6ca685e 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -9,6 +9,8 @@ //! and CAD import. //! - [`color`]: CSS colours. //! - [`write`]: a writer for SVG documents, their path data and numbers. +//! - `tree` (feature `tree`): the full parser. usvg at the one version the Craft apps share, +//! re-exported, behind an entry point that runs the checks above before it parses. //! //! Input is treated as hostile throughout: every size, count and depth is bounded, and a file //! past a bound is an error, never a panic or an unbounded allocation. @@ -20,4 +22,6 @@ pub mod guard; pub mod paths; pub mod sniff; pub mod svgz; +#[cfg(feature = "tree")] +pub mod tree; pub mod write; diff --git a/crates/svg/src/paths.rs b/crates/svg/src/paths.rs index d09620e57..e909283fd 100644 --- a/crates/svg/src/paths.rs +++ b/crates/svg/src/paths.rs @@ -72,8 +72,16 @@ pub struct Shape { pub stroke: Option, /// The regions the shape is clipped by, as indices into [`Imported::clips`], outermost first. pub clips: Vec, + /// The name of the innermost Inkscape layer the element is in: a `` with + /// `inkscape:groupmode="layer"`, named by its `inkscape:label`, else its `id`, else empty. + /// `None` outside any layer. At most [`MAX_LAYER_NAME`] characters. + pub layer: Option, } +/// Most characters of a layer name kept in [`Shape::layer`]. +pub const MAX_LAYER_NAME: usize = 256; +const INKSCAPE_NS: &str = "http://www.inkscape.org/namespaces/inkscape"; + /// What [`import`] read. Shapes may lie outside the `width_mm` × `height_mm` viewport. #[derive(Debug, Clone, PartialEq)] pub struct Imported { @@ -102,6 +110,8 @@ struct ImportState { inherited_style: std::collections::HashMap, /// Active `clip-path` regions (indices into the context's list), outermost first. clips: Vec, + /// The innermost Inkscape layer's name ([`Shape::layer`]). + layer: Option>, } impl Default for ImportState { @@ -113,6 +123,7 @@ impl Default for ImportState { visibility_hidden: false, inherited_style: std::collections::HashMap::new(), clips: Vec::new(), + layer: None, } } } @@ -127,7 +138,7 @@ const MAX_SVG_CLIP_PIECES: usize = 100_000; const MAX_SVG_SEGMENTS: usize = 4_000_000; /// Selector tests across the whole document: rules × elements styled, plus each parent, ancestor or /// sibling a combinator walks. -const MAX_CSS_SELECTOR_CHECKS: usize = 5_000_000; +pub(crate) const MAX_CSS_SELECTOR_CHECKS: usize = 5_000_000; /// Reads the drawable geometry of an SVG document, in document order. /// @@ -299,6 +310,10 @@ fn import_node<'a, 'input, K: Kind>( let local = parse_transform(transform).map_err(|e| svg_error(context.path_name, &format!("<{}> transform: {e}", tag)))?; state.transform = compose(inherited.transform, local); } + if tag == "g" && node.attribute((INKSCAPE_NS, "groupmode")) == Some("layer") { + let name = node.attribute((INKSCAPE_NS, "label")).or_else(|| node.attribute("id")).unwrap_or(""); + state.layer = Some(name.chars().take(MAX_LAYER_NAME).collect::().into()); + } context.charge_cascade()?; let style = computed_style(node, &state.inherited_style, &context.css_rules, K::PROPERTIES, &mut context.selector_checks); context.check_selector_budget()?; @@ -406,6 +421,7 @@ fn import_node<'a, 'input, K: Kind>( label: label(node), stroke: stroke_paint(&style), clips: state.clips.clone(), + layer: state.layer.as_deref().map(str::to_string), }); } for child in node.children().filter(|n| n.is_element()) { @@ -849,7 +865,7 @@ type CssPriority = (bool, u32, u32, u32, usize); type CascadeWinners = std::collections::HashMap; #[derive(Clone)] -struct CssRule { +pub(crate) struct CssRule { selectors: Vec, declarations: StyleMap, important: std::collections::HashSet, @@ -985,7 +1001,12 @@ impl SimpleSelector { /// CSS block at-rules whose content never styles geometry; skipped without a warning. const QUIET_AT_RULES: &[&str] = &["font-face", "keyframes", "-webkit-keyframes", "page", "counter-style", "charset", "namespace"]; -fn parse_stylesheets(root: roxmltree::Node<'_, '_>, extra: &[&str], path_name: &str, warnings: &mut Vec) -> Result, Error> { +pub(crate) fn parse_stylesheets( + root: roxmltree::Node<'_, '_>, + extra: &[&str], + path_name: &str, + warnings: &mut Vec, +) -> Result, Error> { let mut rules = Vec::new(); let mut dropped = 0usize; let mut warn = |message: String| push_warning(warnings, &mut dropped, message); @@ -1292,7 +1313,7 @@ fn parse_declarations(raw: &str, extra: &[&str], path_name: &str) -> Result<(Sty Ok((declarations, important)) } -fn computed_style(node: roxmltree::Node<'_, '_>, inherited: &StyleMap, rules: &[CssRule], extra: &[&str], checks: &mut usize) -> StyleMap { +pub(crate) fn computed_style(node: roxmltree::Node<'_, '_>, inherited: &StyleMap, rules: &[CssRule], extra: &[&str], checks: &mut usize) -> StyleMap { let mut result = inherited.clone(); result.remove("display"); let mut winners = CascadeWinners::new(); @@ -2081,4 +2102,29 @@ mod tests { let got = read(r#""#); assert_eq!(got.shapes[0].kind, Tag::Engrave); } + + #[test] + fn inkscape_layers_name_the_shapes_inside_them() { + let read = read( + r#" + + + + + + + + + + "#, + ); + let layers: Vec> = read.shapes.iter().map(|s| s.layer.as_deref()).collect(); + assert_eq!(layers, [None, Some("Cut & score"), Some("Cut & score"), Some("layer2"), Some(""), None, None]); + // A long name is cut, by characters. + let long = format!( + r#""#, + "é".repeat(MAX_LAYER_NAME + 50) + ); + assert_eq!(import::(&long, "test.svg").unwrap().shapes[0].layer.as_ref().map(|n| n.chars().count()), Some(MAX_LAYER_NAME)); + } } diff --git a/crates/svg/src/tree.rs b/crates/svg/src/tree.rs new file mode 100644 index 000000000..6c79c33a7 --- /dev/null +++ b/crates/svg/src/tree.rs @@ -0,0 +1,327 @@ +//! The full SVG parser: usvg, behind one bounded entry point. +//! +//! usvg (re-exported as [`usvg`]) turns an SVG into a tree with styles resolved, `use` expanded, +//! text laid out and units converted. It is the parser every Craft app that reads SVG in full +//! shares, at the one version this crate pins; apps take it from here and not as a dependency of +//! their own, so they also share the checks it needs. usvg trusts its input more than a file +//! from anywhere deserves: it unpacks SVGZ with no limit, expands entities with no total limit, +//! and converts the tree by recursion, a few stack frames an element, so a small hostile file +//! can exhaust memory or overflow the stack (an abort, not an error). +//! +//! [`parse`] is the entry point: the bytes of an SVG or SVGZ file and [`Limits`] in, a +//! [`usvg::Tree`] out. It runs, in order: [`crate::svgz::text`] (bounded unpacking, encodings), +//! [`crate::guard::entities_expand_past`], [`crate::guard::too_wide`] (attributes an element), +//! [`crate::guard::prescan`] (nesting in the text), +//! [`height`] (nesting with references followed, as usvg walks them), then usvg. +//! [`image_resolver`] bounds the SVG documents embedded in `` data URLs the same way. +//! [`draw`] bounds what drawing a tree with resvg allocates. +//! +//! Stack: usvg uses about 15 kB of stack for each level of nesting (measured natively by +//! VectorCraft). [`Limits::depth`] levels, times one more than [`Limits::embedded_depth`], must +//! fit the stack of the thread that calls [`parse`]: the default of 256 needs a thread with +//! 16 MB or so, and a 1 MB stack takes a depth of about 34. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +pub use usvg; + +use crate::paths::{MAX_CSS_SELECTOR_CHECKS, StyleMap, computed_style, parse_stylesheets}; +use crate::{guard, svgz}; + +pub mod draw; + +/// What one import may use. The defaults suit a desktop app that parses on a thread with a +/// large stack (see the module text). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Bytes of the document, unpacked if it is SVGZ. + pub bytes: usize, + /// How deep elements may nest, references followed (the root alone is 1). + pub depth: usize, + /// Bytes the document type's entity references may expand to in all. + pub entity_bytes: usize, + /// Refuse a document type that declares an entity holding markup, instead of counting what + /// it expands to ([`guard::entity_holds_markup`]). + pub refuse_entity_markup: bool, + /// Attributes one element may have ([`guard::too_wide`]). + pub attributes: usize, + /// The sum over all elements of their attribute count squared ([`guard::too_wide`]). + pub attribute_work: usize, + /// Nodes the XML may hold once entities are expanded. + pub xml_nodes: u32, + /// Bytes of all SVG documents embedded in `` data URLs, unpacked, for + /// [`image_resolver`]. + pub embedded_bytes: usize, + /// SVG documents embedded inside one another, for [`image_resolver`]. + pub embedded_depth: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { + bytes: 64 << 20, + depth: 256, + entity_bytes: guard::MAX_ENTITY_EXPANSION, + refuse_entity_markup: false, + attributes: guard::MAX_ATTRIBUTES, + attribute_work: guard::MAX_ATTRIBUTE_WORK, + xml_nodes: 4_000_000, + embedded_bytes: 32 << 20, + embedded_depth: 4, + } + } +} + +/// Why a file was not parsed. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// Too large, a damaged or nested SVGZ, or text in no encoding SVG files use. + #[error(transparent)] + Text(#[from] svgz::Error), + #[error("the SVG's entities expand to too much text")] + Entities, + #[error("the SVG's document type declares an entity holding markup, which isn't supported")] + EntityMarkup, + /// Elements nest deeper than this many levels, references followed. + #[error("the SVG's elements are nested more than {0} levels deep")] + TooDeep(usize), + /// An element has more than this many attributes, or all elements together too many. + #[error("an element of the SVG has more than {0} attributes, or its elements have too many in all")] + TooWide(usize), + /// A style sheet that names other elements (`url(#…)`) and that this crate cannot read as + /// usvg will, so the nesting it makes cannot be measured. + #[error("the SVG's style sheet can't be checked: {0}")] + Stylesheet(String), + #[error("invalid SVG: {0}")] + Xml(String), + /// usvg's own error. + #[error("invalid SVG: {0}")] + Parse(String), +} + +/// The SVG text of the bytes of an SVG or SVGZ file, checked against `limits`: what [`parse`] +/// hands usvg. For a caller that edits the text before it parses ([`parse_text`]). +pub fn text<'a>(bytes: &'a [u8], limits: &Limits) -> Result, Error> { + let text = svgz::text(bytes, limits.bytes)?; + checked(&text, limits)?; + Ok(text) +} + +/// The tree of an SVG or SVGZ file, within `limits`. `options` are usvg's: fonts, the default +/// size, and the image resolver ([`image_resolver`] unless the caller reads linked files). +pub fn parse(bytes: &[u8], limits: &Limits, options: &usvg::Options<'_>) -> Result { + parse_text(&svgz::text(bytes, limits.bytes)?, limits, options) +} + +/// [`parse`] for SVG text the caller already holds. +pub fn parse_text(svg: &str, limits: &Limits, options: &usvg::Options<'_>) -> Result { + let xml = checked(svg, limits)?; + usvg::Tree::from_xmltree(&xml, options).map_err(|e| Error::Parse(e.to_string())) +} + +/// Every check on SVG text, cheapest first; the XML it parses to on the way. +fn checked<'s>(svg: &'s str, limits: &Limits) -> Result, Error> { + if svg.len() > limits.bytes { + return Err(Error::Text(svgz::Error::TooLarge(limits.bytes))); + } + if limits.refuse_entity_markup && guard::entity_holds_markup(svg) { + return Err(Error::EntityMarkup); + } + if guard::entities_expand_past(svg, limits.entity_bytes) { + return Err(Error::Entities); + } + if guard::too_wide(svg, limits.attributes, limits.attribute_work) { + return Err(Error::TooWide(limits.attributes)); + } + if guard::deeper_than(svg, limits.depth) { + return Err(Error::TooDeep(limits.depth)); + } + let options = roxmltree::ParsingOptions { allow_dtd: true, nodes_limit: limits.xml_nodes, ..Default::default() }; + let xml = roxmltree::Document::parse_with_options(svg, options).map_err(|e| Error::Xml(e.to_string()))?; + if height(&xml, limits.depth)?.is_none() { + return Err(Error::TooDeep(limits.depth)); + } + Ok(xml) +} + +/// Properties whose value an element's descendants use too: the paint server they name is +/// converted at each descendant, under everything between. +const INHERITED: [&str; 6] = ["fill", "stroke", "marker", "marker-start", "marker-mid", "marker-end"]; + +/// Properties that name other elements and that the cascade does not track by itself. +const MARKERS: [&str; 4] = ["marker", "marker-start", "marker-mid", "marker-end"]; + +/// The ids of the `url(#id)` references in a property value. +fn urls(value: &str) -> impl Iterator { + value.split("url(").skip(1).filter_map(|rest| { + let id = rest.trim_start().trim_start_matches(['"', '\'']).strip_prefix('#')?; + id.split([')', '"', '\'']).next().map(str::trim).filter(|id| !id.is_empty()) + }) +} + +type XNode<'a, 'i> = roxmltree::Node<'a, 'i>; + +/// How deep the elements of `xml` nest as usvg walks them (the root alone is 1); `None` past +/// `most`. Without recursion. +/// +/// What counts is the tree usvg converts, not the XML alone: a `` holds a copy of what it +/// refers to, and a clip path, mask, pattern, marker or filter is converted where it is used +/// (`clip-path: url(#a)` on an element of a clip path makes a chain as deep as there are clip +/// paths). So each element's depth is the deepest of what it holds and what it refers to, by +/// attribute, `style` and style sheet. A loop of references is not deep: usvg leaves it out. +/// +/// An error when a style sheet names elements and cannot be read here as usvg reads it (a +/// selector or at-rule this crate's cascade does not apply, a sheet for another medium, a sheet +/// past its size or work limits): the nesting such a sheet makes cannot be measured. +pub fn height(xml: &roxmltree::Document<'_>, most: usize) -> Result, Error> { + let elements = || xml.descendants().filter(|n| n.is_element()); + // The first element of an id, as usvg resolves references: a later one of the same id would + // hide a deep target behind a shallow one. + let mut ids: HashMap<&str, XNode> = HashMap::new(); + for n in elements() { + if let Some(id) = n.attribute("id") { + ids.entry(id).or_insert(n); + } + } + let mut warnings = Vec::new(); + let rules = + parse_stylesheets(xml.root_element(), &MARKERS, "", &mut warnings).map_err(|e| Error::Stylesheet(e.0.trim_start_matches(": ").to_string())); + let sheets = || elements().filter(|n| n.tag_name().name() == "style"); + let names_elements = sheets().any(|n| n.text().is_some_and(|t| t.contains("url("))); + let rules = match rules { + Ok(rules) => rules, + // A sheet that names no element adds no nesting, whatever else is in it. + Err(_) if !names_elements => Vec::new(), + Err(e) => return Err(e), + }; + if names_elements { + if let Some(w) = warnings.first() { + return Err(Error::Stylesheet(w.clone())); + } + if sheets().any(|n| n.attribute("media").is_some_and(|m| !matches!(m.trim(), "" | "all" | "screen"))) { + return Err(Error::Stylesheet("a style sheet for another medium names elements".into())); + } + } + let nothing = StyleMap::new(); + let mut checks = 0usize; + // The elements `n` refers to, each with whether `n`'s descendants use it too. + let mut references = |n: XNode, out: &mut Vec<(roxmltree::NodeId, bool)>| -> Result<(), Error> { + for a in n.attributes().filter(|a| a.name() == "href") { + out.extend(a.value().trim().strip_prefix('#').and_then(|id| ids.get(id)).map(|t| (t.id(), false))); + } + for (name, value) in computed_style(n, ¬hing, &rules, &MARKERS, &mut checks) { + let inherited = INHERITED.contains(&name.as_str()); + out.extend(urls(&value).filter_map(|id| ids.get(id)).map(|t| (t.id(), inherited))); + } + if checks > MAX_CSS_SELECTOR_CHECKS { + return Err(Error::Stylesheet("the style sheet is too large for this many elements".into())); + } + Ok(()) + }; + // How deep each element's own tree goes, itself included; 0 while it is being worked out: a + // reference back to it then is a loop, which usvg leaves out. + let mut heights: HashMap = HashMap::new(); + enum Step { + Enter(roxmltree::NodeId), + Leave(roxmltree::NodeId, Vec<(roxmltree::NodeId, bool)>), + } + let mut stack = vec![Step::Enter(xml.root_element().id())]; + while let Some(step) = stack.pop() { + match step { + Step::Enter(id) => { + let Some(n) = xml.get_node(id) else { continue }; + match heights.entry(id) { + Entry::Occupied(_) => continue, + Entry::Vacant(v) => v.insert(0), + }; + let mut refs = vec![]; + references(n, &mut refs)?; + let targets: Vec = refs.iter().map(|(t, _)| *t).collect(); + stack.push(Step::Leave(id, refs)); + stack.extend(n.children().filter(|c| c.is_element()).map(|c| c.id()).chain(targets).map(Step::Enter)); + } + Step::Leave(id, refs) => { + let Some(n) = xml.get_node(id) else { continue }; + let of = |id: roxmltree::NodeId| heights.get(&id).copied().unwrap_or(0); + let held = n.children().filter(|c| c.is_element()).map(|c| of(c.id())).max().unwrap_or(0); + let used = |inherited: bool| refs.iter().filter(|(_, i)| *i == inherited).map(|(t, _)| of(*t)).max().unwrap_or(0); + let height = 1 + held.max(used(false)) + used(true); + if height > most { + return Ok(None); + } + heights.insert(id, height); + } + } + } + Ok(Some(heights.get(&xml.root_element().id()).copied().unwrap_or(0))) +} + +/// What the embedded SVGs of one import have used so far. +struct Used { + bytes: AtomicUsize, + depth: AtomicUsize, +} + +fn raster(data: &[u8]) -> bool { + data.starts_with(b"\x89PNG") + || data.starts_with(&[0xff, 0xd8, 0xff]) + || data.starts_with(b"GIF8") + || (data.len() > 12 && data.get(8..12) == Some(b"WEBP")) +} + +/// An embedded SVG document, if the budgets allow it. +fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<'_>) -> Option { + if used.depth.load(Ordering::Relaxed) >= limits.embedded_depth { + return None; + } + let left = limits.embedded_bytes.saturating_sub(used.bytes.load(Ordering::Relaxed)); + let text = match svgz::text(data, left.min(limits.bytes)) { + Ok(text) => text, + // What a refused document unpacked before it was refused was work too: it uses up what + // is left, so the next image can't repeat it. + Err(_) => { + used.bytes.fetch_add(left, Ordering::Relaxed); + return None; + } + }; + used.bytes.fetch_add(text.len(), Ordering::Relaxed); + let xml = checked(&text, limits).ok()?; + used.depth.fetch_add(1, Ordering::Relaxed); + let tree = usvg::Tree::from_xmltree(&xml, options); + used.depth.fetch_sub(1, Ordering::Relaxed); + tree.ok().map(usvg::ImageKind::SVG) +} + +/// An image resolver for `usvg::Options::image_href_resolver` that reads `` data URLs +/// only: raster images as they are (PNG, JPEG, GIF, WebP), SVG documents (SVGZ too) through the +/// same checks as [`parse`] and within [`Limits::embedded_bytes`] in all and +/// [`Limits::embedded_depth`] inside one another. An image past a limit is left out. Linked +/// files are never read. One resolver is one import's budget: make a new one for each [`parse`]. +pub fn image_resolver(limits: Limits) -> usvg::ImageHrefResolver<'static> { + let used = Arc::new(Used { bytes: AtomicUsize::new(0), depth: AtomicUsize::new(0) }); + usvg::ImageHrefResolver { + resolve_data: Box::new(move |mime, data, options| match mime { + "image/jpg" | "image/jpeg" => Some(usvg::ImageKind::JPEG(data)), + "image/png" => Some(usvg::ImageKind::PNG(data)), + "image/gif" => Some(usvg::ImageKind::GIF(data)), + "image/webp" => Some(usvg::ImageKind::WEBP(data)), + "image/svg+xml" => embedded(&used, &limits, &data, options), + "text/plain" if raster(&data) => match data.first() { + Some(0x89) => Some(usvg::ImageKind::PNG(data)), + Some(0xff) => Some(usvg::ImageKind::JPEG(data)), + Some(b'G') => Some(usvg::ImageKind::GIF(data)), + _ => Some(usvg::ImageKind::WEBP(data)), + }, + "text/plain" => embedded(&used, &limits, &data, options), + _ => None, + }), + resolve_string: Box::new(|_, _| None), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/svg/src/tree/draw.rs b/crates/svg/src/tree/draw.rs new file mode 100644 index 000000000..fed7ac569 --- /dev/null +++ b/crates/svg/src/tree/draw.rs @@ -0,0 +1,431 @@ +//! Hard caps on the memory resvg needs to draw a subtree of a [`usvg::Tree`], checked before it +//! draws. +//! +//! A cap on the target pixmap bounds the target only. While it draws, resvg also allocates, and +//! a failed allocation aborts the process rather than returning an error: +//! - a layer for every isolated group (opacity, blend mode, clip, mask, filter), clamped to 5 × 5 +//! times the target, and one more per link of a clip-path chain, per clip child that has its own +//! clip-path, and per link of a mask-on-mask chain; +//! - for a filter, a result per primitive (all kept until the filter ends) and a clone of the layer. +//! The filter region is NOT clamped: `x`, `y`, `width` and `height` in the file set the size; +//! - a pattern tile of `width × height × scale`; +//! - for an embedded SVG image or an `feImage`, a pixmap of the current layer or filter region with +//! a nested drawing inside. +//! +//! The checks are worst-case products, not a model of resvg's phases. A node is checked against +//! the layers of its ancestors (which are alive while it is drawn) and nothing else, and each +//! shared definition is walked once per size class, so the walk is linear in the file. +//! +//! The allocation counts were read from resvg 0.45.1 (PhotoCraft's `svg/limits.rs`, where this +//! comes from). This crate does not depend on resvg; a caller that draws with another version +//! should treat the byte figures as an estimate with the same shape. + +use std::collections::HashMap; + +use usvg::Transform; + +/// Filter primitives per filter. A result of every primitive is kept; real filters have 1 to 12 +/// (Inkscape's drop shadow has 5), and 64 leaves headroom for generated ones. +const MAX_PRIMITIVES: usize = 64; +/// Links of one clip-path chain, mask-on-mask chain or nested clip children with their own +/// clip-path. Each link keeps a layer-sized buffer alive while the next is applied; real files use +/// one or two, and 16 layers of a 24 MP canvas (1.5 GiB) is the whole budget anyway. +const MAX_LINKS: usize = 16; +/// Patterns drawn inside patterns. Each tile is alive while the inner one is drawn. +const MAX_PATTERN_DEPTH: usize = 8; +/// Embedded SVG images inside embedded SVG images. Each draws on a pixmap of the enclosing +/// layer, which the live-bytes check charges, so deep chains of small images are harmless and +/// chains of big ones stop at the budget long before this. +const MAX_IMAGE_DEPTH: usize = 32; +/// Nested isolated groups, patterns, embedded images and filter images followed. It keeps this +/// walk, and resvg's own recursion, far from a stack overflow; real drawings stay under a few dozen. +const MAX_DEPTH: usize = 200; +/// Nested groups of any kind. usvg expands `` chains up to its own 1024-level limit, possibly +/// two groups per level; resvg recurses three frames per level too, so a walk that stops here is +/// lighter on the stack than the drawing it guards. +const MAX_NEST: usize = 2_100; +/// Nodes the walk visits before it gives up as too complex to check. A node costs a few +/// nanoseconds, so this bounds the walk to well under a second. +const MAX_NODES: usize = 2_000_000; + +/// Why a drawing should not be drawn. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refusal { + /// Too many elements to check, rather than too much memory. + pub complex: bool, + /// Over the memory budget, as opposed to a nesting, chain or element-count cap. + pub memory: bool, + pub message: String, +} + +fn mib(bytes: f64) -> String { + if bytes < 1e15 { format!("about {} MiB", (bytes / 1_048_576.0).ceil()) } else { "an enormous amount of memory".to_string() } +} + +fn memory(what: &str, bytes: f64, budget: f64) -> Refusal { + let limit = budget as u64 >> 20; + Refusal { complex: false, memory: true, message: format!("{what} needs {}, over the {limit} MiB limit", mib(bytes)) } +} + +fn limit(what: &str, value: usize) -> Refusal { + Refusal { complex: false, memory: false, message: format!("{what} (limit {value})") } +} + +/// A pixel count that is never NaN: unknown sizes count as unbounded. +pub fn px(v: f64) -> f64 { + if v.is_nan() { f64::INFINITY } else { v } +} + +/// What is alive where a node is drawn. +#[derive(Clone, Copy)] +struct Cx { + /// Bytes held by the target and the layers of the ancestors. + live: f64, + /// Pixels of the pixmap being drawn on. + layer: f64, + /// Pixels of the largest group layer resvg makes in it (5 × 5 times its first target). + cap: f64, + /// Nested layers (isolated groups, patterns, embedded images, filter images). + depth: usize, + patterns: usize, + images: usize, + /// Nested groups of any kind: resvg and this walk recurse once per level. + nest: usize, +} + +/// What a subtree needs, relative to what is alive where it starts. A shared definition is walked +/// once per transform and size, and every later reference re-checks its profile against where it +/// is used, so nothing is skipped and the walk stays linear. +#[derive(Clone, Copy, Default)] +struct Profile { + /// Most bytes it holds beyond the incoming live bytes. + extra: f64, + /// Most extra levels of nested layers, patterns, embedded images and groups below it. + depth: usize, + patterns: usize, + images: usize, + nest: usize, +} + +impl Profile { + fn max(self, o: Self) -> Self { + Self { + extra: self.extra.max(o.extra), + depth: self.depth.max(o.depth), + patterns: self.patterns.max(o.patterns), + images: self.images.max(o.images), + nest: self.nest.max(o.nest), + } + } + + /// This profile seen from a parent that adds `bytes` and one level of each kind in `levels` + /// (layers, patterns, images, groups). + fn under(self, bytes: f64, levels: [usize; 4]) -> Self { + Self { + extra: self.extra + bytes, + depth: self.depth + levels[0], + patterns: self.patterns + levels[1], + images: self.images + levels[2], + nest: self.nest + levels[3], + } + } +} + +/// A shared definition at one linear transform, layer size and clamp. +type Key = (usize, [u32; 4], u64, u64); + +fn key(ptr: usize, ts: Transform, cx: Cx) -> Key { + (ptr, [ts.sx.to_bits(), ts.kx.to_bits(), ts.ky.to_bits(), ts.sy.to_bits()], cx.layer.to_bits(), cx.cap.to_bits()) +} + +struct Walk { + /// Bytes of RGBA8 buffers alive at once that the drawing may need. + budget: f64, + visited: usize, + shared: HashMap, + clips: HashMap, + masks: HashMap, +} + +/// Check that drawing `nodes` at `ts` onto a `width × height` pixmap keeps the RGBA8 buffers alive +/// at once inside `budget` bytes, given `held` bytes already in use (anything the caller keeps; +/// the target itself is counted here). +pub fn check(nodes: &[usvg::Node], ts: Transform, width: u32, height: u32, held: u64, budget: u64) -> Result<(), Refusal> { + let target = f64::from(width) * f64::from(height); + let cx = Cx { live: held as f64 + target * 4.0, layer: target, cap: 25.0 * target, depth: 0, patterns: 0, images: 0, nest: 0 }; + let mut walk = Walk { budget: budget as f64, visited: 0, shared: HashMap::new(), clips: HashMap::new(), masks: HashMap::new() }; + walk.nodes(nodes, ts, cx).map(|_| ()) +} + +impl Walk { + fn need(&self, live: f64, what: impl FnOnce() -> String) -> Result<(), Refusal> { + if live > self.budget { Err(memory(&what(), live, self.budget)) } else { Ok(()) } + } +} + +impl Walk { + fn nodes(&mut self, nodes: &[usvg::Node], ts: Transform, cx: Cx) -> Result { + let mut profile = Profile::default(); + for n in nodes { + profile = profile.max(self.node(n, ts, cx)?); + } + Ok(profile) + } + + // The recursion through plain groups is the deep one (usvg allows 1,000+ levels), so only small + // functions sit on it; everything with many locals is kept off it with `inline(never)`. + fn node(&mut self, node: &usvg::Node, ts: Transform, cx: Cx) -> Result { + self.visited += 1; + if self.visited > MAX_NODES { + return Err(Refusal { complex: true, memory: false, message: format!("the drawing has more than {MAX_NODES} elements to check") }); + } + match node { + usvg::Node::Group(g) if !g.should_isolate() => self.plain(g, ts, cx), + usvg::Node::Group(g) => self.group(g, ts, cx), + usvg::Node::Text(t) => self.group(t.flattened(), ts, cx), + usvg::Node::Path(p) => self.path(p, ts, cx), + usvg::Node::Image(image) => self.image(image, ts, cx), + } + } + + /// A plain group is no layer. + fn plain(&mut self, g: &usvg::Group, ts: Transform, cx: Cx) -> Result { + if cx.nest >= MAX_NEST { + return Err(limit("groups are nested too deeply", MAX_NEST)); + } + let inside = self.nodes(g.children(), ts.pre_concat(g.transform()), Cx { nest: cx.nest + 1, ..cx })?; + Ok(inside.under(0.0, [0, 0, 0, 1])) + } + + #[inline(never)] + fn path(&mut self, p: &usvg::Path, ts: Transform, cx: Cx) -> Result { + let mut profile = Profile::default(); + if !p.is_visible() { + return Ok(profile); + } + for paint in p.fill().map(|f| f.paint()).into_iter().chain(p.stroke().map(|s| s.paint())) { + if let usvg::Paint::Pattern(pattern) = paint { + profile = profile.max(self.pattern(pattern, ts, cx)?); + } + } + Ok(profile) + } + + /// resvg draws an embedded SVG on a pixmap the size of the current one, with its own 5 × 5 clamp. + #[inline(never)] + fn image(&mut self, image: &usvg::Image, ts: Transform, cx: Cx) -> Result { + let usvg::ImageKind::SVG(tree) = image.kind() else { return Ok(Profile::default()) }; + if cx.images >= MAX_IMAGE_DEPTH { + return Err(limit("embedded SVG images are nested too deeply", MAX_IMAGE_DEPTH)); + } + let bytes = cx.layer * 4.0; + self.need(cx.live + bytes, || "an embedded SVG image".to_string())?; + let nested = Cx { live: cx.live + bytes, cap: 25.0 * cx.layer, depth: cx.depth + 1, images: cx.images + 1, nest: cx.nest + 1, ..cx }; + deeper(nested)?; + let inside = self.nodes(tree.root().children(), ts, nested)?; + Ok(Profile { extra: bytes, ..Profile::default() }.max(inside.under(bytes, [1, 0, 1, 1]))) + } + + /// Walk a definition shared by reference (pattern, mask, filter image) once per transform and + /// size; a repeat only re-checks its profile where it is used now. + fn shared(&mut self, key: Key, cx: Cx, walk: impl FnOnce(&mut Self) -> Result) -> Result { + let Some(p) = self.shared.get(&key).copied() else { + let p = walk(self)?; + self.shared.insert(key, p); + return Ok(p); + }; + self.need(cx.live + p.extra, || "a shared definition used here".to_string())?; + if cx.depth + p.depth > MAX_DEPTH { + return Err(limit("layers are nested too deeply", MAX_DEPTH)); + } + if cx.patterns + p.patterns > MAX_PATTERN_DEPTH { + return Err(limit("patterns are nested too deeply", MAX_PATTERN_DEPTH)); + } + if cx.images + p.images > MAX_IMAGE_DEPTH { + return Err(limit("embedded SVG images are nested too deeply", MAX_IMAGE_DEPTH)); + } + if cx.nest + p.nest > MAX_NEST { + return Err(limit("groups are nested too deeply", MAX_NEST)); + } + Ok(p) + } + + #[inline(never)] + fn group(&mut self, g: &usvg::Group, ts: Transform, cx: Cx) -> Result { + if !g.should_isolate() { + return self.plain(g, ts, cx); + } + let ts = ts.pre_concat(g.transform()); + if cx.nest >= MAX_NEST { + return Err(limit("groups are nested too deeply", MAX_NEST)); + } + let Some(bb) = g.layer_bounding_box().transform(ts) else { return Ok(Profile::default()) }; + let own = px((f64::from(bb.width()).ceil() + 4.0) * (f64::from(bb.height()).ceil() + 4.0)).min(cx.cap); + let inner = Cx { live: cx.live + own * 4.0, layer: own, depth: cx.depth + 1, nest: cx.nest + 1, ..cx }; + deeper(inner)?; + // Filter, clip and mask are applied one after another; each needs its own extra buffers + // beside the group's layer. A clip or mask link is a 4 B/px pixmap and a 1 B/px mask. + let clip = g.clip_path().map_or(Ok(0), |c| self.clip_links(c, 0))?; + let mask = g.mask().map_or(Ok(0), |m| self.mask_links(m, 0))?; + let links = clip.max(mask); + let layers = own * 4.0 + own * 5.0 * links as f64; + self.need(cx.live + layers, || format!("a group with {links} clip or mask layers of {} px", own as u64))?; + let mut profile = Profile { extra: layers, ..Profile::default() }; + for filter in g.filters() { + profile = profile.max(self.filter(filter, ts, cx, own)?); + } + let mut mask_ref = g.mask(); + let mut link = 1.0; + while let Some(mask) = mask_ref { + // The mask content is drawn while this and every earlier link's pixmap and mask are alive. + let bytes = own * 4.0 + own * 5.0 * link; + let content = Cx { live: cx.live + bytes, ..inner }; + let inside = + self.shared(key(std::ptr::from_ref(mask) as usize, ts, content), content, |w| w.nodes(mask.root().children(), ts, content))?; + profile = profile.max(inside.under(bytes, [1, 0, 0, 1])); + mask_ref = mask.mask(); + link += 1.0; + } + let inside = self.nodes(g.children(), ts, inner)?; + Ok(profile.max(inside.under(own * 4.0, [1, 0, 0, 1]))) + } + + /// Layers a clip-path keeps alive: its own, the deepest clip child with a clip-path of its own, + /// or the next link of the chain, whichever is deepest. Nothing is walked twice. + fn clip_links(&mut self, clip: &usvg::ClipPath, depth: usize) -> Result { + let key = std::ptr::from_ref(clip) as usize; + if let Some(n) = self.clips.get(&key) { + return Ok(*n); + } + let too_long = || limit("clip-paths are chained or nested too deeply", MAX_LINKS); + if depth >= MAX_LINKS { + return Err(too_long()); + } + let inside = self.clip_children(clip.root(), depth + 1)?; + let next = clip.clip_path().map_or(Ok(0), |c| self.clip_links(c, depth + 1))?; + let n = 1 + inside.max(next); + if n > MAX_LINKS { + return Err(too_long()); + } + self.clips.insert(key, n); + Ok(n) + } + + /// resvg's `clip_group`: a clip child with its own clip-path is drawn on a layer of its own, + /// kept while its descendants are drawn and its clip is applied. + fn clip_children(&mut self, group: &usvg::Group, depth: usize) -> Result { + let mut deepest = 0; + for child in group.children() { + let inner = match child { + usvg::Node::Group(g) => { + let inside = self.clip_children(g, depth + usize::from(g.clip_path().is_some()))?; + match g.clip_path() { + Some(c) => 1 + inside.max(self.clip_links(c, depth + 1)?), + None => inside, + } + } + usvg::Node::Text(t) => self.clip_children(t.flattened(), depth)?, + _ => 0, + }; + if inner + depth > MAX_LINKS { + return Err(limit("clip-paths are chained or nested too deeply", MAX_LINKS)); + } + deepest = deepest.max(inner); + } + Ok(deepest) + } + + /// Layers a mask chain keeps alive: a mask pixmap per link while the next is applied. + fn mask_links(&mut self, mask: &usvg::Mask, depth: usize) -> Result { + let key = std::ptr::from_ref(mask) as usize; + if let Some(n) = self.masks.get(&key) { + return Ok(*n); + } + if depth >= MAX_LINKS { + return Err(limit("masks are chained too deeply", MAX_LINKS)); + } + let n = 1 + mask.mask().map_or(Ok(0), |m| self.mask_links(m, depth + 1))?; + // A cached tail can make the chain longer than `depth` shows; the cap is on the whole chain. + if n > MAX_LINKS { + return Err(limit("masks are chained too deeply", MAX_LINKS)); + } + self.masks.insert(key, n); + Ok(n) + } + + /// A filter keeps a result per primitive, each as large as the filter region or the layer it + /// filters, whichever is larger (usvg makes the layer the union of all of a group's filter + /// regions, and `SourceGraphic` clones the whole layer). `own` is the size of that layer. + fn filter(&mut self, f: &usvg::filter::Filter, ts: Transform, cx: Cx, own: f64) -> Result { + use usvg::filter::Kind; + let prims = f.primitives().len(); + if prims > MAX_PRIMITIVES { + return Err(limit("a filter has too many primitives", MAX_PRIMITIVES)); + } + let Some(region) = f.rect().transform(ts) else { return Ok(Profile::default()) }; + let region = px(f64::from(region.width()).ceil() * f64::from(region.height()).ceil()); + let slot = region.max(own) * 4.0; + // Buffers a primitive allocates beside its result (resvg 0.45.1 `filter/`): a blur works + // on one copy, an IIR blur (sigma under 2 after scaling) also on f64 scratch; blend, + // composite and displacement map convert two inputs; a drop shadow holds the input, its + // blur, the shadow and the result. + let (sx, sy) = ts.get_scale(); + let transient = |kind: &Kind| match kind { + Kind::GaussianBlur(b) if b.std_dev_x().get() * sx >= 2.0 || b.std_dev_y().get() * sy >= 2.0 => 1.0, + Kind::GaussianBlur(_) => 2.0, + Kind::Blend(_) | Kind::Composite(_) | Kind::DisplacementMap(_) => 2.0, + // A tile of the source graphic converts and tiles two copies. + Kind::Tile(t) if matches!(t.input(), usvg::filter::Input::SourceGraphic) => 2.0, + Kind::DropShadow(_) => 4.0, + _ => 1.0, + }; + let most = f.primitives().iter().map(|p| transient(p.kind())).fold(0.0, f64::max); + let extra = own * 4.0 + slot * (prims as f64 + most); + self.need(cx.live + extra, || format!("a filter with {prims} primitives over a region of {} px", region.min(1e18) as u64))?; + let mut profile = Profile { extra, ..Profile::default() }; + for (i, primitive) in f.primitives().iter().enumerate() { + if let Kind::Image(fe) = primitive.kind() { + // What an feImage draws sees the results kept so far. + let bytes = own * 4.0 + slot * (i + 1) as f64; + let (sx, sy) = ts.get_scale(); + let scaled = Transform::from_scale(sx, sy); + let nested = Cx { live: cx.live + bytes, layer: region, cap: region, depth: cx.depth + 1, nest: cx.nest + 1, ..cx }; + deeper(nested)?; + let inside = + self.shared(key(std::ptr::from_ref(fe) as usize, scaled, nested), nested, |w| w.nodes(fe.root().children(), scaled, nested))?; + profile = profile.max(inside.under(bytes, [1, 0, 0, 1])); + } + } + Ok(profile) + } + + /// A pattern tile is `width × height × scale` pixels, whatever the target. + fn pattern(&mut self, pattern: &usvg::Pattern, ts: Transform, cx: Cx) -> Result { + let (sx, sy) = ts.pre_concat(pattern.transform()).get_scale(); + let rect = pattern.rect(); + let (tw, th) = (f64::from(rect.width() * sx).round(), f64::from(rect.height() * sy).round()); + // resvg draws no tile smaller than a pixel (or not a number). + if !(tw >= 1.0 && th >= 1.0) { + return Ok(Profile::default()); + } + let tile = tw * th; + let bytes = tile * 4.0; + self.need(cx.live + bytes, || format!("a pattern tile of {tw} × {th} px"))?; + if cx.patterns >= MAX_PATTERN_DEPTH { + return Err(limit("patterns are nested too deeply", MAX_PATTERN_DEPTH)); + } + let nested = Cx { live: cx.live + bytes, layer: tile, depth: cx.depth + 1, patterns: cx.patterns + 1, nest: cx.nest + 1, ..cx }; + deeper(nested)?; + let inner_ts = Transform::from_scale(sx, sy); + let inside = self + .shared(key(std::ptr::from_ref(pattern) as usize, inner_ts, nested), nested, |w| w.nodes(pattern.root().children(), inner_ts, nested))?; + Ok(Profile { extra: bytes, ..Profile::default() }.max(inside.under(bytes, [1, 1, 0, 1]))) + } +} + +fn deeper(cx: Cx) -> Result<(), Refusal> { + if cx.depth > MAX_DEPTH { + return Err(limit("layers are nested too deeply", MAX_DEPTH)); + } + Ok(()) +} diff --git a/crates/svg/src/tree/tests.rs b/crates/svg/src/tree/tests.rs new file mode 100644 index 000000000..751e7726b --- /dev/null +++ b/crates/svg/src/tree/tests.rs @@ -0,0 +1,304 @@ +#![allow(clippy::unwrap_used, clippy::panic, clippy::indexing_slicing)] + +use super::*; + +const DEPTH: usize = 256; + +fn svg(body: &str) -> String { + format!(r#"{body}"#) +} + +/// `n` groups in one another around a rectangle. +fn groups(n: usize) -> String { + format!("{}{}", "".repeat(n), "".repeat(n)) +} + +fn deep(svg: &str) -> bool { + height(&roxmltree::Document::parse(svg).unwrap(), DEPTH).unwrap().is_none() +} + +fn options() -> usvg::Options<'static> { + usvg::Options { image_href_resolver: image_resolver(Limits::default()), ..Default::default() } +} + +/// A limit small enough for usvg to convert on a test thread's stack. +fn shallow() -> Limits { + Limits { depth: 24, ..Limits::default() } +} + +fn try_parse(svg: &str, limits: &Limits) -> Result { + parse(svg.as_bytes(), limits, &options()) +} + +/// Every image in the tree, as whether it is an SVG document, nested ones after their parent. +fn images(group: &usvg::Group, out: &mut Vec) { + for node in group.children() { + match node { + usvg::Node::Group(g) => images(g, out), + usvg::Node::Image(image) => match image.kind() { + usvg::ImageKind::SVG(tree) => { + out.push(true); + images(tree.root(), out); + } + _ => out.push(false), + }, + _ => {} + } + } +} + +/// `` showing the SVG text `inner` as a data URL. +fn embed(inner: &str) -> String { + let encoded: String = inner.bytes().map(|b| if b.is_ascii_alphanumeric() { char::from(b).to_string() } else { format!("%{b:02X}") }).collect(); + format!(r#""#) +} + +#[test] +fn an_svg_and_an_svgz_parse_to_the_same_tree() { + let text = svg(""); + let tree = try_parse(&text, &shallow()).unwrap(); + assert_eq!((tree.size().width(), tree.size().height()), (10.0, 10.0)); + assert_eq!(tree.root().children().len(), 1); + let packed = parse(&svgz::compress(text.as_bytes()), &shallow(), &options()).unwrap(); + assert_eq!(packed.root().children().len(), 1); + assert_eq!(super::text(text.as_bytes(), &shallow()).unwrap(), text); + assert_eq!(parse_text(&text, &shallow(), &options()).unwrap().root().children().len(), 1); +} + +#[test] +fn every_limit_refuses_the_file_past_it() { + let text = svg(&groups(4)); + // Bytes, plain and unpacked. + let small = Limits { bytes: text.len() - 1, ..shallow() }; + assert_eq!(try_parse(&text, &small).err(), Some(Error::Text(svgz::Error::TooLarge(text.len() - 1)))); + assert_eq!(parse(&svgz::compress(text.as_bytes()), &small, &options()).err(), Some(Error::Text(svgz::Error::TooLarge(text.len() - 1)))); + assert!(matches!(parse_text(&text, &small, &options()), Err(Error::Text(_)))); + assert!(try_parse(&text, &Limits { bytes: text.len(), ..shallow() }).is_ok()); + // Depth in the text: the root, four groups and the rectangle are six levels. + assert!(try_parse(&text, &Limits { depth: 6, ..shallow() }).is_ok()); + assert_eq!(try_parse(&text, &Limits { depth: 5, ..shallow() }).err(), Some(Error::TooDeep(5))); + // Depth by reference: no element is nested, each holds the next. + let chain: String = (0..20).map(|i| format!("", i + 1)).collect(); + let uses = svg(&format!("{chain}")); + assert!(!guard::deeper_than(&uses, 24)); + assert_eq!(try_parse(&uses, &shallow()).err(), Some(Error::TooDeep(24))); + // Attributes on one element. + let wide = svg(&format!("", (0..40).map(|i| format!(" a{i}='1'")).collect::())); + assert!(try_parse(&wide, &Limits { attributes: 40, ..shallow() }).is_ok()); + assert_eq!(try_parse(&wide, &Limits { attributes: 39, ..shallow() }).err(), Some(Error::TooWide(39))); + assert_eq!(try_parse(&wide, &Limits { attribute_work: 1000, ..shallow() }).err(), Some(Error::TooWide(4096))); + // Entities. + let bomb = format!("]>{}", "x".repeat(1000), svg(&format!("{}", "&a;".repeat(10)))); + assert_eq!(try_parse(&bomb, &Limits { entity_bytes: 9_999, ..shallow() }).err(), Some(Error::Entities)); + assert!(try_parse(&bomb, &Limits { entity_bytes: 10_000, ..shallow() }).is_ok()); + // XML nodes. + assert!(matches!(try_parse(&svg(&"".repeat(100)), &Limits { xml_nodes: 50, ..shallow() }), Err(Error::Xml(_)))); + // Not XML, and XML that is not an SVG. + assert!(matches!(try_parse("", &shallow()), Err(Error::Parse(_)))); + assert!(matches!(parse(&[0xfe, 0xff, 0xd8], &shallow(), &options()), Err(Error::Text(svgz::Error::Encoding)))); +} + +#[test] +fn an_entity_holding_markup_is_refused_only_when_asked() { + let text = format!("\">]>{}", svg("&a;")); + assert_eq!(try_parse(&text, &Limits { refuse_entity_markup: true, ..shallow() }).err(), Some(Error::EntityMarkup)); + let tree = try_parse(&text, &shallow()).unwrap(); + assert_eq!(tree.root().children().len(), 1, "the entity's rectangle is drawn"); + // A namespace entity, as drawing apps write, is not markup. + let names = "]>"; + assert!(try_parse(names, &Limits { refuse_entity_markup: true, ..shallow() }).is_ok()); +} + +#[test] +fn elements_nest_up_to_the_cap() { + let (at, past) = (svg(&groups(DEPTH - 2)), svg(&groups(DEPTH - 1))); + assert!(!deep(&at)); + assert!(deep(&past)); + let ten = svg(&groups(8)); + let xml = roxmltree::Document::parse(&ten).unwrap(); + assert_eq!((height(&xml, 10), height(&xml, 9)), (Ok(Some(10)), Ok(None))); + assert_eq!(height(&roxmltree::Document::parse("").unwrap(), 1), Ok(Some(1))); +} + +#[test] +fn a_chain_of_uses_is_as_deep_as_what_it_copies() { + let chain = |n: usize| { + let defs: String = (0..n).map(|i| format!("", i + 1)).collect(); + svg(&format!("{defs}")) + }; + assert!(!deep(&chain(10))); + assert!(deep(&chain(DEPTH / 2)), "two elements a link"); + assert!(deep(&chain(5000))); +} + +#[test] +fn chains_of_clips_masks_and_patterns_count_by_attribute_style_and_style_sheet() { + let by_attribute = |n: usize| -> String { + (0..n).map(|i| format!("", i + 1)).collect() + }; + let by_style = |n: usize| -> String { + (0..n).map(|i| format!("", i + 1)).collect() + }; + let by_sheet = |n: usize| -> String { + let rules: String = (0..n).map(|i| format!(".p{i} {{ fill: url(#c{}) }}", i + 1)).collect(); + let patterns: String = + (0..n).map(|i| format!("")).collect(); + format!("{patterns}") + }; + let by_marker = + |n: usize| -> String { (0..n).map(|i| format!("", i + 1)).collect() }; + for chain in [&by_attribute as &dyn Fn(usize) -> String, &by_style, &by_sheet, &by_marker] { + let file = |n| { + svg(&format!( + "{}", + chain(n) + )) + }; + assert!(!deep(&file(5))); + assert!(deep(&file(DEPTH))); + } +} + +#[test] +fn many_paint_servers_used_side_by_side_are_not_a_chain() { + // As drawing apps write gradients: a class each, used by objects that aren't inside one another. + let rules: String = (0..300).map(|i| format!(".c{i}{{fill:url(#g{i})}}")).collect(); + let defs: String = (0..300).map(|i| format!("")).collect(); + let art: String = (0..300).map(|i| format!("")).collect(); + assert!(!deep(&svg(&format!("{defs}{art}")))); +} + +#[test] +fn a_reference_follows_the_first_element_of_its_id() { + // A chain of ``s as deep as the cap, each link's id given again later to an empty group: + // usvg follows the first, so the chain is deep. + let chain: String = (1..DEPTH).map(|i| format!("", i - 1)).collect(); + let shallow: String = (1..DEPTH).map(|i| format!("")).collect(); + let top = format!("", DEPTH - 1); + assert!(deep(&svg(&format!("{chain}{shallow}{top}")))); +} + +#[test] +fn a_loop_of_references_is_not_deep() { + assert!(!deep(&svg(""))); +} + +#[test] +fn an_inherited_paint_is_converted_under_everything_between() { + // Neither the pattern nor the art is too deep; the pattern under the art's last object is. + let half = DEPTH / 2; + let pattern = format!("{}", groups(half)); + assert!(!deep(&svg(&format!("{pattern}{}", groups(half / 2))))); + assert!(deep(&svg(&format!("{pattern}{}", groups(half))))); +} + +#[test] +fn a_style_sheet_that_names_elements_and_cannot_be_read_is_refused() { + let sheet = |css: &str, media: &str| { + svg(&format!("{css}")) + }; + let check = |text: &str| height(&roxmltree::Document::parse(text).unwrap(), DEPTH); + // The root, the rectangle, and under it the pattern its fill names. + assert_eq!(check(&sheet(".a{fill:url(#p)}", "")), Ok(Some(3))); + // An at-rule block, a sheet for another medium and a broken rule: read here they would add + // nothing, read by usvg they might. + assert!(matches!(check(&sheet("@media print{.a{fill:url(#p)}}", "")), Err(Error::Stylesheet(_)))); + assert!(matches!(check(&sheet(".a{fill:url(#p)}", " media='print'")), Err(Error::Stylesheet(_)))); + assert!(matches!(check(&sheet(".a{fill:url(#p)", "")), Err(Error::Stylesheet(_)))); + assert!(matches!(try_parse(&sheet("@media print{.a{fill:url(#p)}}", ""), &shallow()), Err(Error::Stylesheet(_)))); + // The same sheets naming no element add no nesting and are usvg's to read. + assert_eq!(check(&sheet("@media print{.a{fill:red}}", "")), Ok(Some(2))); + assert_eq!(check(&sheet(".a{fill:red", "")), Ok(Some(2))); + assert!(try_parse(&sheet(".a{fill:red}", " media='print'"), &shallow()).is_ok()); +} + +#[test] +fn embedded_svgs_are_read_within_their_budgets() { + let inner = svg(""); + let found = |text: &str, limits: Limits| { + let options = usvg::Options { image_href_resolver: image_resolver(limits), ..Default::default() }; + let mut out = vec![]; + images(parse(text.as_bytes(), &limits, &options).unwrap().root(), &mut out); + out + }; + let one = svg(&embed(&inner)); + assert_eq!(found(&one, shallow()), [true]); + // Bytes: one fits, a second does not; what a refused one would have used is spent. + let two = svg(&format!("{}{}", embed(&inner), embed(&inner))); + assert_eq!(found(&two, shallow()), [true, true]); + assert_eq!(found(&two, Limits { embedded_bytes: inner.len() * 2 - 1, ..shallow() }), [true]); + assert_eq!(found(&one, Limits { embedded_bytes: inner.len() - 1, ..shallow() }), [false; 0]); + // Depth: a document in a document in a document. + let three = svg(&embed(&svg(&embed(&inner)))); + assert_eq!(found(&three, shallow()), [true, true]); + assert_eq!(found(&three, Limits { embedded_depth: 1, ..shallow() }), [true]); + assert_eq!(found(&three, Limits { embedded_depth: 0, ..shallow() }), [false; 0]); + // An embedded document goes through the same checks: too deep, it is left out. + let nested = svg(&embed(&svg(&groups(30)))); + assert_eq!(found(&nested, shallow()), [false; 0]); + let wide = svg(&embed(&svg(&format!("", (0..40).map(|i| format!(" a{i}='1'")).collect::())))); + assert_eq!(found(&wide, shallow()), [true]); + assert_eq!(found(&wide, Limits { attributes: 39, ..shallow() }), [false; 0]); + // A linked file is never read. + assert_eq!(found(&svg(r#""#), shallow()), [false; 0]); +} + +mod draw_checks { + use super::*; + + const GIB: u64 = 1 << 30; + + fn check(body: &str, budget: u64) -> Result<(), draw::Refusal> { + let tree = try_parse(&svg(body), &Limits { depth: 40, ..Limits::default() }).unwrap(); + draw::check(tree.root().children(), usvg::Transform::identity(), 100, 100, 0, budget) + } + + #[test] + fn an_ordinary_drawing_fits() { + let body = " + + + "; + assert_eq!(check(body, GIB), Ok(())); + // The target alone is 100 × 100 × 4 bytes. + assert!(check("", 40_000).is_ok()); + assert!(check("", 39_999).is_ok(), "nothing is charged where nothing draws on a layer"); + } + + #[test] + fn a_filter_region_the_file_sets_is_charged_whatever_the_target() { + let body = " + "; + let refusal = check(body, GIB).unwrap_err(); + assert!(refusal.memory && !refusal.complex && refusal.message.contains("filter"), "{refusal:?}"); + } + + #[test] + fn a_pattern_tile_is_charged_at_its_own_size() { + let body = " + "; + let refusal = check(body, GIB).unwrap_err(); + assert!(refusal.memory && refusal.message.contains("pattern tile"), "{refusal:?}"); + let small = " + "; + assert_eq!(check(small, GIB), Ok(())); + } + + #[test] + fn counts_are_capped_apart_from_memory() { + let primitives = + |n: usize| format!("{}", "".repeat(n)); + assert_eq!(check(&primitives(64), GIB), Ok(())); + let refusal = check(&primitives(65), GIB).unwrap_err(); + assert!(!refusal.memory && refusal.message.contains("primitives"), "{refusal:?}"); + let clips = |n: usize| { + let chain: String = + (0..n).map(|i| format!("", i + 1)).collect(); + format!("{chain}") + }; + assert_eq!(check(&clips(15), GIB), Ok(())); + let refusal = check(&clips(16), GIB).unwrap_err(); + assert!(!refusal.memory && refusal.message.contains("clip-paths"), "{refusal:?}"); + } +} diff --git a/crates/text/src/linebreak/knuth_plass.rs b/crates/text/src/linebreak/knuth_plass.rs index 742c3245f..e9de0b485 100644 --- a/crates/text/src/linebreak/knuth_plass.rs +++ b/crates/text/src/linebreak/knuth_plass.rs @@ -4,6 +4,11 @@ use super::{Item, Kind, Line, Params, Sums, clamp_measure, fitness_class}; /// Give up (return `None`) beyond this many active breaks. const MAX_ACTIVE: usize = 4096; +/// Give up (return `None`) after this much work, counted as one for each break considered and one +/// for each active break it is tried against. A paragraph of 400,000 items with 30 active breaks +/// takes some 12,000,000 on a pass; the limit is where a pass runs for seconds, and past it the +/// caller falls back to [`super::greedy`], which keeps every item. +pub(super) const MAX_WORK: u64 = 1 << 27; /// Ratios beyond this are rated as this (an unstretchable line is infinitely loose). const MAX_RATIO: f64 = 10_000.0; /// Demerits of an overfull line accepted because nothing else reaches a break. @@ -37,8 +42,14 @@ struct Candidate { /// One total-fit pass over `items`. `width(k)` is the measure of line `k`; set /// [`Params::uniform_from`] when it varies. Returns `None` when no set of breaks keeps every line -/// within [`Params::tolerance`] (unless [`Params::overfull`]), or past the active-break limit. +/// within [`Params::tolerance`] (unless [`Params::overfull`]), or past the active-break or work limit. pub fn knuth_plass(items: &[Item], width: &dyn Fn(usize) -> f64, p: &Params) -> Option> { + knuth_plass_within(items, width, p, &mut MAX_WORK.clone()) +} + +/// [`knuth_plass`] spending at most `work` (left over on return), so that the passes of one +/// paragraph share a budget. +pub(super) fn knuth_plass_within(items: &[Item], width: &dyn Fn(usize) -> f64, p: &Params, work: &mut u64) -> Option> { let p = &p.sanitized(); let width = |k: usize| clamp_measure(width(k)); let s = Sums::new(items); @@ -57,6 +68,7 @@ pub fn knuth_plass(items: &[Item], width: &dyn Fn(usize) -> f64, p: &Params) -> if !s.is_break(b) { continue; } + *work = work.checked_sub(active.len() as u64 + 1)?; let item = items.get(b); let forced = s.forced(b); let flagged = item.is_some_and(Item::is_flagged); diff --git a/crates/text/src/linebreak/mod.rs b/crates/text/src/linebreak/mod.rs index 9d20b0645..dfdfd9cf3 100644 --- a/crates/text/src/linebreak/mod.rs +++ b/crates/text/src/linebreak/mod.rs @@ -29,6 +29,7 @@ use std::ops::Range; pub use greedy::{greedy, greedy_with}; pub use knuth_plass::knuth_plass; +use knuth_plass::{MAX_WORK, knuth_plass_within}; /// Number of elasticity tiers: word space, letter space, glyph scale. pub const TIERS: usize = 3; @@ -345,11 +346,17 @@ pub struct Breaks { /// [`knuth_plass`] at each of `tolerances` in turn, the last pass also accepting overfull lines; /// [`greedy`] if every pass fails or `tolerances` is empty. The last pass fails only past the -/// active-break limit (see [`Params::uniform_from`]). +/// active-break limit (see [`Params::uniform_from`]) or the passes' shared work limit, which +/// only a paragraph of many hundreds of thousands of items reaches. Nothing is left out then: the +/// greedy breaker lays out every item, in linear time. pub fn break_paragraph(items: &[Item], width: &dyn Fn(usize) -> f64, params: &Params, tolerances: &[f64]) -> Breaks { + break_paragraph_within(items, width, params, tolerances, MAX_WORK) +} + +fn break_paragraph_within(items: &[Item], width: &dyn Fn(usize) -> f64, params: &Params, tolerances: &[f64], mut work: u64) -> Breaks { for (pass, &tolerance) in tolerances.iter().enumerate() { let overfull = params.overfull || pass + 1 == tolerances.len(); - if let Some(lines) = knuth_plass(items, width, &Params { tolerance, overfull, ..*params }) { + if let Some(lines) = knuth_plass_within(items, width, &Params { tolerance, overfull, ..*params }, &mut work) { return Breaks { lines, method: Method::KnuthPlass { pass }, balanced: false }; } } diff --git a/crates/text/src/linebreak/tests.rs b/crates/text/src/linebreak/tests.rs index d8163edde..58483d2aa 100644 --- a/crates/text/src/linebreak/tests.rs +++ b/crates/text/src/linebreak/tests.rs @@ -492,3 +492,22 @@ fn next_start_is_the_first_box_or_forced_break_after_each_item() { assert_eq!(s.next_start(b), scan, "after {b}"); } } + +/// Past its work limit the paragraph is broken greedily, with every item laid out and no error or +/// cut: a limit of a few units stands for the real one, which a hostile paragraph of hundreds of +/// thousands of items would reach (and the test never builds). +#[test] +fn a_paragraph_past_the_work_limit_falls_back_to_greedy_with_every_item() { + let p = vectorcraft(false); + let para = Para::new(COPY, &p, Some(50.0)); + let w = |_| 150.0; + let within = break_paragraph_within(¶.items, &w, &p, &PASSES, MAX_WORK); + assert!(matches!(within.method, Method::KnuthPlass { .. }), "{:?}", within.method); + let limited = break_paragraph_within(¶.items, &w, &p, &PASSES, 20); + assert_eq!(limited.method, Method::Greedy); + assert_eq!(limited.lines, greedy(¶.items, &w, &p)); + assert_covers(¶.items, &limited.lines); + // The work is shared by the passes: what one spends the next doesn't have. + let mut work = 30; + assert!(knuth_plass_within(¶.items, &w, &Params { tolerance: 1.0, ..p }, &mut work).is_none()); +} diff --git a/crates/tga/Cargo.toml b/crates/tga/Cargo.toml new file mode 100644 index 000000000..0c52fef98 --- /dev/null +++ b/crates/tga/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-tga" +description = "Clean-room Truevision Targa (TGA) reader and run-length writer: true-colour, grayscale and colour-mapped pictures, any origin, packets that end with their scan line." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +thiserror = { workspace = true } diff --git a/crates/tga/src/lib.rs b/crates/tga/src/lib.rs new file mode 100644 index 000000000..ac9d21497 --- /dev/null +++ b/crates/tga/src/lib.rs @@ -0,0 +1,374 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! Truevision Targa (`.tga`), read and written from the Truevision TGA File Format Specification 2.0. +//! +//! Reading ([`decode`]): image types 1, 2 and 3 (colour-mapped, true-colour, grayscale) and their +//! run-length encoded forms 9, 10 and 11; 15- and 16-bit (5-5-5, the top bit as alpha when the +//! descriptor says one attribute bit), 24-bit BGR and 32-bit BGRA true-colour, 8-bit grayscale and +//! 16-bit grayscale with alpha, colour maps of 15-, 16-, 24- or 32-bit entries indexed by 8 or 16 +//! bits; any origin corner. Run-length packets may cross scan lines (older writers do it). The +//! result is straight-alpha RGBA8, top row first, with [`Picture::layout`] naming what the file +//! stored. +//! +//! Writing ([`encode`]): 8-bit grayscale, grayscale with alpha, RGB or RGBA, run-length encoded +//! (types 10 and 11), rows stored bottom-up (the bottom-left origin every reader assumes, also +//! those that ignore the origin bits), alpha bits in the descriptor and the TGA 2.0 footer. A +//! packet never crosses a scan line: TGA 2.0 forbids it, and readers that decode a row at a time +//! misread files that do. +//! +//! Input is treated as hostile: the picture size is capped by [`Limits`], and a run-length file +//! must be long enough to hold the pixels its header declares before anything is allocated. + +#[cfg(test)] +mod tests; + +/// Length of the fixed header. +const HEADER: usize = 18; +/// TGA 2.0 files end with this signature (after two 32-bit area offsets). +const SIGNATURE: &[u8] = b"TRUEVISION-XFILE.\0"; +/// The TGA 2.0 footer written: no extension or developer area, then the signature. +const FOOTER: &[u8; 26] = b"\0\0\0\0\0\0\0\0TRUEVISION-XFILE.\0"; +/// Most pixels one packet holds (a 7-bit count, plus one). +const MAX_PACKET: usize = 128; + +/// Why a file could not be read or written. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The header or the pixel data is damaged or cut short. + #[error("Targa: {0}")] + Malformed(&'static str), + /// A Targa image type this reader does not cover. + #[error("unsupported Targa: image type {0}")] + Unsupported(u8), + /// The file declares more than [`Limits`] allow. + #[error("Targa exceeds a limit: {0}")] + LimitExceeded(&'static str), + /// The picture handed to the writer cannot be stored. + #[error("Targa: cannot write: {0}")] + Encode(String), +} + +/// Result of this crate's functions. +pub type Result = std::result::Result; + +/// Caps on what a header may ask the reader to allocate, checked before anything is allocated. +/// `#[non_exhaustive]`: start from [`Limits::default`] and set the fields you change. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub struct Limits { + /// Most pixels (width × height) a picture may have. Default 2^28 (16384 × 16384). + pub max_pixels: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_pixels: 1 << 28 } + } +} + +/// What a picture's pixels are: what a file stored, or what the writer is given. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Layout { + /// One byte a pixel. + Gray, + /// Two bytes a pixel: gray, alpha. + GrayAlpha, + /// Three bytes a pixel. + Rgb, + /// Four bytes a pixel, straight alpha. + Rgba, +} + +impl Layout { + /// Bytes of one pixel. + pub fn channels(self) -> usize { + match self { + Layout::Gray => 1, + Layout::GrayAlpha => 2, + Layout::Rgb => 3, + Layout::Rgba => 4, + } + } +} + +/// A decoded picture. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Picture { + pub width: u32, + pub height: u32, + /// Straight-alpha RGBA8, top row first, whatever the file stored. + pub rgba: Vec, + /// What the file stored (a colour-mapped file reports its map entries' layout). + pub layout: Layout, + /// Whether any pixel is not fully opaque. + pub has_alpha: bool, +} + +/// Whether `bytes` looks like a Targa file: a plausible header and either a TGA 2.0 footer or, +/// for the original format (which has no signature), a Targa file extension on `name`. +pub fn sniff(name: &str, bytes: &[u8]) -> bool { + let header_ok = || { + let Some(h) = bytes.first_chunk::
() else { return false }; + let (map_type, kind, depth) = (h[1], h[2], h[16]); + let (w, ht) = (u16::from_le_bytes([h[12], h[13]]), u16::from_le_bytes([h[14], h[15]])); + map_type <= 1 && matches!(kind, 1 | 2 | 3 | 9 | 10 | 11) && w > 0 && ht > 0 && matches!(depth, 8 | 15 | 16 | 24 | 32) + }; + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()); + let named = matches!(ext.as_deref(), Some("tga" | "targa" | "icb" | "vda" | "vst")); + header_ok() && (named || bytes.ends_with(SIGNATURE)) +} + +/// Pixel layout of the stored values (after the colour-map lookup, for mapped images). +#[derive(Clone, Copy)] +enum Stored { + /// 15/16-bit `ARRRRRGG GGGBBBBB`, little-endian; `alpha`: the top bit is an alpha bit. + Rgb555 { + alpha: bool, + }, + Bgr24, + Bgra32, + Gray8, + GrayAlpha16, +} + +impl Stored { + fn true_colour(depth: u8, attr_bits: u8) -> Option { + Some(match depth { + 15 => Stored::Rgb555 { alpha: false }, + 16 => Stored::Rgb555 { alpha: attr_bits == 1 }, + 24 => Stored::Bgr24, + 32 => Stored::Bgra32, + _ => return None, + }) + } + + fn bytes(self) -> usize { + match self { + Stored::Rgb555 { .. } | Stored::GrayAlpha16 => 2, + Stored::Bgr24 => 3, + Stored::Bgra32 => 4, + Stored::Gray8 => 1, + } + } + + fn layout(self) -> Layout { + match self { + Stored::Rgb555 { alpha: false } | Stored::Bgr24 => Layout::Rgb, + Stored::Rgb555 { alpha: true } | Stored::Bgra32 => Layout::Rgba, + Stored::Gray8 => Layout::Gray, + Stored::GrayAlpha16 => Layout::GrayAlpha, + } + } + + /// RGBA of one stored value (`p` holds exactly [`bytes`](Self::bytes) bytes). + fn rgba(self, p: &[u8]) -> [u8; 4] { + let b = |i: usize| p.get(i).copied().unwrap_or(0); + match self { + Stored::Rgb555 { alpha } => { + let v = u16::from_le_bytes([b(0), b(1)]); + let five = |s: u16| { + let c = ((v >> s) & 31) as u8; + (c << 3) | (c >> 2) + }; + let a = if !alpha || v & 0x8000 != 0 { 255 } else { 0 }; + [five(10), five(5), five(0), a] + } + Stored::Bgr24 => [b(2), b(1), b(0), 255], + Stored::Bgra32 => [b(2), b(1), b(0), b(3)], + Stored::Gray8 => [b(0), b(0), b(0), 255], + Stored::GrayAlpha16 => [b(0), b(0), b(0), b(1)], + } + } +} + +/// Decodes a Targa file to straight-alpha RGBA8, top row first. +pub fn decode(bytes: &[u8], limits: &Limits) -> Result { + let err = Error::Malformed; + let h = bytes.first_chunk::
().ok_or(err("truncated header"))?; + let (id_len, map_type, kind) = (usize::from(h[0]), h[1], h[2]); + let map_first = usize::from(u16::from_le_bytes([h[3], h[4]])); + let map_len = usize::from(u16::from_le_bytes([h[5], h[6]])); + let map_depth = h[7]; + let (w, ht) = (usize::from(u16::from_le_bytes([h[12], h[13]])), usize::from(u16::from_le_bytes([h[14], h[15]]))); + let (depth, descriptor) = (h[16], h[17]); + let attr_bits = descriptor & 0x0F; + let (right_to_left, top_to_bottom) = (descriptor & 0x10 != 0, descriptor & 0x20 != 0); + if w == 0 || ht == 0 { + return Err(err("empty picture")); + } + // Both are 16-bit, so the product fits. + let pixels = w * ht; + if pixels as u64 > limits.max_pixels { + return Err(Error::LimitExceeded("pixel count")); + } + let rle = kind >= 9; + // The stored value layout and, for colour-mapped images, the palette. + let mut palette: Vec<[u8; 4]> = Vec::new(); + let map_entry = if map_type == 1 { + Some(Stored::true_colour(map_depth, if map_depth == 16 { attr_bits.min(1) } else { 0 }).ok_or(err("colour map entry size"))?) + } else { + None + }; + let mut at = HEADER + id_len; + if let Some(l) = map_entry { + let end = at + map_len * l.bytes(); + let map = bytes.get(at..end).ok_or(err("truncated colour map"))?; + palette = map.chunks_exact(l.bytes()).map(|e| l.rgba(e)).collect(); + at = end; + } + let (stored_as, mapped) = match kind & 7 { + 1 => { + if map_type != 1 || !matches!(depth, 8 | 16) { + return Err(err("colour-mapped picture without an 8/16-bit index and a colour map")); + } + (if depth == 8 { Stored::Gray8 } else { Stored::GrayAlpha16 }, true) + } + 2 => (Stored::true_colour(depth, attr_bits).ok_or(err("true-colour pixel depth"))?, false), + 3 => match depth { + 8 => (Stored::Gray8, false), + 16 => (Stored::GrayAlpha16, false), + _ => return Err(err("grayscale pixel depth")), + }, + _ => return Err(Error::Unsupported(kind)), + }; + let data = bytes.get(at..).unwrap_or_default(); + let bpp = stored_as.bytes(); + // The stored values, in file order. + let stored: Vec = if rle { + unpack_rle(data, pixels, bpp)? + } else { + let n = pixels.checked_mul(bpp).ok_or(Error::LimitExceeded("image size"))?; + data.get(..n).ok_or(err("truncated pixel data"))?.to_vec() + }; + let mut rgba = vec![0u8; pixels.checked_mul(4).ok_or(Error::LimitExceeded("image size"))?]; + for (i, v) in stored.chunks_exact(bpp).enumerate().take(pixels) { + let (x, y) = (i % w, i / w); + let x = if right_to_left { w - 1 - x } else { x }; + let y = if top_to_bottom { y } else { ht - 1 - y }; + let px = if mapped { + let byte = |i: usize| v.get(i).copied().unwrap_or(0); + let index = if bpp == 1 { usize::from(byte(0)) } else { usize::from(u16::from_le_bytes([byte(0), byte(1)])) }; + *index.checked_sub(map_first).and_then(|k| palette.get(k)).ok_or(err("colour index outside the colour map"))? + } else { + stored_as.rgba(v) + }; + let o = (y * w + x) * 4; + if let Some(d) = rgba.get_mut(o..o + 4) { + d.copy_from_slice(&px); + } + } + // 32-bit files from writers that leave the attribute bits unset often store zero alpha + // everywhere: such a picture is opaque, not invisible. + let alpha_used = match (stored_as, mapped) { + (Stored::Bgra32, false) => attr_bits != 0 || rgba.as_chunks::<4>().0.iter().any(|p| p[3] != 0), + _ => true, + }; + if !alpha_used { + rgba.as_chunks_mut::<4>().0.iter_mut().for_each(|p| p[3] = 255); + } + let has_alpha = rgba.as_chunks::<4>().0.iter().any(|p| p[3] != 255); + let layout = match (mapped, map_entry) { + (true, Some(entry)) => entry.layout(), + _ => stored_as.layout(), + }; + Ok(Picture { width: w as u32, height: ht as u32, rgba, layout, has_alpha }) +} + +/// Expands run-length packets into `pixels` stored values of `bpp` bytes each. Packets may span +/// scan lines (the TGA 2.0 spec discourages it; older writers do it). +fn unpack_rle(mut data: &[u8], pixels: usize, bpp: usize) -> Result> { + let short = Error::Malformed("truncated run-length data"); + // A two-byte packet expands to at most 128 values: a header asking for more is lying. + let bound = data.len().saturating_mul(64).saturating_add(128); + if pixels > bound { + return Err(short); + } + let total = pixels.checked_mul(bpp).ok_or(Error::LimitExceeded("image size"))?; + let mut out = Vec::with_capacity(total); + while out.len() < total { + let (&head, rest) = data.split_first().ok_or(short.clone())?; + let count = usize::from(head & 0x7F) + 1; + let want = (total - out.len()).min(count * bpp); + if head & 0x80 != 0 { + let v = rest.get(..bpp).ok_or(short.clone())?; + for _ in 0..want / bpp { + out.extend_from_slice(v); + } + data = rest.get(bpp..).unwrap_or_default(); + } else { + let n = count * bpp; + let v = rest.get(..n).ok_or(short.clone())?; + out.extend_from_slice(v.get(..want).unwrap_or(v)); + data = rest.get(n..).unwrap_or_default(); + } + } + Ok(out) +} + +/// Encodes 8-bit pixels (`height` rows of `width × layout.channels()` bytes, top row first) as a +/// run-length encoded Targa. +pub fn encode(width: u32, height: u32, layout: Layout, data: &[u8]) -> Result> { + let (bpp, image_type, alpha_bits) = match layout { + Layout::Gray => (1usize, 11u8, 0u8), + Layout::GrayAlpha => (2, 11, 8), + Layout::Rgb => (3, 10, 0), + Layout::Rgba => (4, 10, 8), + }; + let (Ok(w16), Ok(h16)) = (u16::try_from(width), u16::try_from(height)) else { + return Err(Error::Encode(format!("dimensions exceed 65535x65535: {width}x{height}"))); + }; + let row = usize::from(w16) * bpp; + if data.len() != row * usize::from(h16) { + return Err(Error::Encode("buffer size mismatch".into())); + } + let mut out = Vec::with_capacity(HEADER + data.len() + data.len() / MAX_PACKET + FOOTER.len()); + out.extend_from_slice(&[0, 0, image_type, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + out.extend_from_slice(&w16.to_le_bytes()); + out.extend_from_slice(&h16.to_le_bytes()); + // Bits per pixel; the descriptor holds the alpha bits, origin bits 0 (bottom-left). + out.extend_from_slice(&[(bpp * 8) as u8, alpha_bits]); + let mut px = vec![0u8; row]; + // `row` is 0 only for an empty picture, which has no rows to write. + for line in data.chunks_exact(row.max(1)).rev() { + px.copy_from_slice(line); + // Targa stores colour as BGR. + if bpp >= 3 { + for p in px.chunks_exact_mut(bpp) { + p.swap(0, 2); + } + } + rle_row(&px, bpp, &mut out); + } + out.extend_from_slice(FOOTER); + Ok(out) +} + +/// One scan line as run-length packets that end with it: a run of two or more equal pixels is a +/// run packet, anything else goes out in raw packets. +fn rle_row(row: &[u8], bpp: usize, out: &mut Vec) { + let px: Vec<&[u8]> = row.chunks_exact(bpp).collect(); + let n = px.len(); + let at = |i: usize| px.get(i).copied().unwrap_or_default(); + let mut i = 0; + while i < n { + let mut run = 1; + while i + run < n && run < MAX_PACKET && at(i + run) == at(i) { + run += 1; + } + if run >= 2 { + out.push(0x80 | (run - 1) as u8); + out.extend_from_slice(at(i)); + i += run; + continue; + } + // Raw until two equal pixels start a run, the packet is full or the row ends. The first + // pixel always goes in: it differs from the one after it, or it is the row's last. + let start = i; + while i < n && i - start < MAX_PACKET && !(i > start && i + 1 < n && at(i) == at(i + 1)) { + i += 1; + } + out.push((i - start - 1) as u8); + for p in px.get(start..i).unwrap_or_default() { + out.extend_from_slice(p); + } + } +} diff --git a/crates/tga/src/tests.rs b/crates/tga/src/tests.rs new file mode 100644 index 000000000..06109a179 --- /dev/null +++ b/crates/tga/src/tests.rs @@ -0,0 +1,237 @@ +//! The reader's tests come from FilmCraft's decoder, the writer's from PhotoCraft's encoder. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; + +fn header(kind: u8, w: u16, h: u16, depth: u8, descriptor: u8) -> Vec { + let mut b = vec![0, 0, kind, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + b.extend_from_slice(&w.to_le_bytes()); + b.extend_from_slice(&h.to_le_bytes()); + b.extend_from_slice(&[depth, descriptor]); + b +} + +fn dec(bytes: &[u8]) -> Result { + decode(bytes, &Limits::default()) +} + +#[test] +fn bottom_up_bgr_is_flipped() { + let mut f = header(2, 2, 2, 24, 0); + // Bottom row first: blue, green; then the top row: red, white. + f.extend_from_slice(&[255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255]); + let r = dec(&f).unwrap(); + assert_eq!((r.width, r.height, r.has_alpha, r.layout), (2, 2, false, Layout::Rgb)); + assert_eq!(r.rgba, [255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 255, 255, 0, 255, 0, 255]); +} + +#[test] +fn every_origin_corner() { + // 2 × 2 gray, stored values 1 2 / 3 4 in file order. + for (descriptor, want) in [(0x00, [3, 4, 1, 2]), (0x10, [4, 3, 2, 1]), (0x20, [1, 2, 3, 4]), (0x30, [2, 1, 4, 3])] { + let mut f = header(3, 2, 2, 8, descriptor); + f.extend_from_slice(&[1, 2, 3, 4]); + let r = dec(&f).unwrap(); + assert_eq!(r.rgba.chunks(4).map(|p| p[0]).collect::>(), want, "descriptor {descriptor:#x}"); + assert_eq!(r.layout, Layout::Gray); + } +} + +#[test] +fn rle_runs_and_raw_packets_cross_lines() { + let mut f = header(10, 3, 2, 32, 0x28); + // A run of 4 translucent red, then 2 raw pixels. + f.extend_from_slice(&[0x83, 0, 0, 255, 128, 0x01, 1, 2, 3, 255, 4, 5, 6, 255]); + let r = dec(&f).unwrap(); + assert!(r.has_alpha); + assert_eq!(r.layout, Layout::Rgba); + assert_eq!(&r.rgba[..16], &[255, 0, 0, 128].repeat(4)[..]); + assert_eq!(&r.rgba[16..], &[3, 2, 1, 255, 6, 5, 4, 255]); +} + +#[test] +fn colour_map_and_16_bit_alpha() { + let mut f = header(1, 2, 1, 8, 0x20); + f[1] = 1; // colour map present + f[3..5].copy_from_slice(&1u16.to_le_bytes()); // first entry index 1 + f[5..7].copy_from_slice(&2u16.to_le_bytes()); + f[7] = 24; + f.extend_from_slice(&[10, 20, 30, 40, 50, 60, 2, 1]); + let r = dec(&f).unwrap(); + assert_eq!(r.rgba, [60, 50, 40, 255, 30, 20, 10, 255]); + assert_eq!(r.layout, Layout::Rgb); + f[18 + 6] = 0; // index 0 is below the map's first entry + assert_eq!(dec(&f), Err(Error::Malformed("colour index outside the colour map"))); + + let mut f = header(2, 2, 1, 16, 0x21); + f.extend_from_slice(&0xFC00u16.to_le_bytes()); // opaque full red + f.extend_from_slice(&0x03E0u16.to_le_bytes()); // transparent full green + let r = dec(&f).unwrap(); + assert_eq!(r.rgba, [255, 0, 0, 255, 0, 255, 0, 0]); + + // 16-bit grayscale with alpha. + let mut f = header(3, 1, 1, 16, 0x28); + f.extend_from_slice(&[7, 9]); + let r = dec(&f).unwrap(); + assert_eq!((r.rgba.as_slice(), r.layout, r.has_alpha), (&[7, 7, 7, 9][..], Layout::GrayAlpha, true)); +} + +#[test] +fn zero_alpha_32_bit_without_attribute_bits_is_opaque() { + let mut f = header(2, 1, 1, 32, 0); + f.extend_from_slice(&[1, 2, 3, 0]); + let r = dec(&f).unwrap(); + assert_eq!((r.rgba.as_slice(), r.has_alpha), (&[3, 2, 1, 255][..], false)); +} + +#[test] +fn hostile_headers_fail_without_allocating() { + // 65535 × 65535 run-length encoded from a few bytes, truncated raw data, bad types. + let mut f = header(10, 65535, 65535, 32, 0); + f.extend_from_slice(&[0xFF, 1, 2, 3, 4]); + assert_eq!(dec(&f), Err(Error::LimitExceeded("pixel count"))); + let mut f = header(10, 16384, 16384, 32, 0); + f.extend_from_slice(&[0xFF, 1, 2, 3, 4]); + assert_eq!(dec(&f), Err(Error::Malformed("truncated run-length data"))); + let mut f = header(2, 4, 4, 24, 0); + f.extend_from_slice(&[0; 10]); + assert_eq!(dec(&f), Err(Error::Malformed("truncated pixel data"))); + assert!(dec(&header(2, 1, 1, 7, 0)).is_err()); + assert!(dec(&header(1, 1, 1, 8, 0)).is_err()); + assert_eq!(dec(&header(2, 0, 1, 24, 0)), Err(Error::Malformed("empty picture"))); + assert_eq!(dec(&header(4, 1, 1, 24, 0)), Err(Error::Unsupported(4))); + assert_eq!(dec(&[0; 5]), Err(Error::Malformed("truncated header"))); + for n in 0..40 { + let mut f = header(9, 3, 3, 8, 0); + f[1] = 1; + f[5] = 2; + f[7] = 16; + f.extend_from_slice(&[0x82, 1, 0, 1, 0x01, 0, 0]); + f.truncate(n); + let _ = dec(&f); + } +} + +#[test] +fn the_pixel_limit_is_checked() { + let mut f = header(3, 2, 2, 8, 0); + f.extend_from_slice(&[0; 4]); + assert!(decode(&f, &Limits { max_pixels: 4 }).is_ok()); + assert_eq!(decode(&f, &Limits { max_pixels: 3 }), Err(Error::LimitExceeded("pixel count"))); +} + +#[test] +fn sniffs_by_footer_or_name() { + let mut f = header(2, 1, 1, 24, 0); + f.extend_from_slice(&[0, 0, 0]); + assert!(sniff("x.TGA", &f)); + assert!(!sniff("x.bin", &f)); + f.extend_from_slice(&[0; 8]); + f.extend_from_slice(SIGNATURE); + assert!(sniff("x.bin", &f)); + assert!(!sniff("x.tga", b"\x89PNG\r\n\x1a\n0000000000")); +} + +#[test] +fn run_packets_at_the_128_pixel_boundary() { + for bpp in 1..=4 { + for (pixels, headers) in [(1, vec![0]), (2, vec![0x81]), (127, vec![0xfe]), (128, vec![0xff]), (129, vec![0xff, 0])] { + let pixel: Vec = (1..=bpp as u8).collect(); + let mut encoded = Vec::new(); + rle_row(&pixel.repeat(pixels), bpp, &mut encoded); + let expected: Vec = headers.into_iter().flat_map(|header| std::iter::once(header).chain(pixel.iter().copied())).collect(); + assert_eq!(encoded, expected, "{pixels} pixels, {bpp} bytes per pixel"); + } + } +} + +#[test] +fn raw_packets_at_the_128_pixel_boundary() { + for bpp in 1..=4 { + for pixels in [127usize, 128, 129] { + let row: Vec = (0..pixels).flat_map(|x| vec![x as u8; bpp]).collect(); + let mut encoded = Vec::new(); + rle_row(&row, bpp, &mut encoded); + let mut expected = vec![(pixels.min(128) - 1) as u8]; + expected.extend_from_slice(&row[..pixels.min(128) * bpp]); + if pixels > 128 { + expected.push(0); + expected.extend_from_slice(&row[128 * bpp..]); + } + assert_eq!(encoded, expected, "{pixels} pixels, {bpp} bytes per pixel"); + } + } +} + +#[test] +fn raw_packets_stop_before_a_run_of_complete_pixels() { + // Equal first channels alone do not make an RGBA run; alpha participates too. + let a = [10, 20, 30, 40]; + let b = [10, 20, 30, 41]; + let c = [50, 60, 70, 80]; + let row = [a, b, c, c, a].concat(); + let mut encoded = Vec::new(); + rle_row(&row, 4, &mut encoded); + assert_eq!(encoded, [vec![1], a.to_vec(), b.to_vec(), vec![0x81], c.to_vec(), vec![0], a.to_vec()].concat()); +} + +#[test] +fn dimensions_fit_the_unsigned_16_bit_header() { + for (width, height) in [(65535u32, 1u32), (1, 65535)] { + let file = encode(width, height, Layout::Gray, &vec![0; 65535]).unwrap(); + assert_eq!(&file[12..14], &(width as u16).to_le_bytes()); + assert_eq!(&file[14..16], &(height as u16).to_le_bytes()); + } + for (width, height) in [(65536u32, 1u32), (1, 65536)] { + assert!(matches!(encode(width, height, Layout::Gray, &vec![0; 65536]), Err(Error::Encode(_))), "{width}x{height}"); + } +} + +#[test] +fn wrong_buffer_sizes_are_refused() { + for layout in [Layout::Gray, Layout::GrayAlpha, Layout::Rgb, Layout::Rgba] { + let len = 2 * 2 * layout.channels(); + for bytes in [len - 1, len + 1] { + assert!(matches!(encode(2, 2, layout, &vec![0; bytes]), Err(Error::Encode(_))), "{layout:?}: {bytes} bytes"); + } + } + assert!(encode(0, 0, Layout::Rgb, &[]).is_ok()); +} + +/// What the writer produces, the reader returns: every layout, with rows that hold runs, raw +/// stretches and packets longer than 128 pixels, and no packet crossing a row. +#[test] +fn written_files_read_back() { + for layout in [Layout::Gray, Layout::GrayAlpha, Layout::Rgb, Layout::Rgba] { + let n = layout.channels(); + let (w, h) = (300usize, 3usize); + let data: Vec = + (0..w * h).flat_map(|i| (0..n).map(move |c| if i % w < 140 { 9 + c as u8 } else { (i * 7 + c * 31) as u8 | 1 })).collect(); + let file = encode(w as u32, h as u32, layout, &data).unwrap(); + assert!(file.ends_with(SIGNATURE) && sniff("x.bin", &file)); + // Walk the packets: each row's packets add up to exactly the row. + let mut at = HEADER; + for _ in 0..h { + let mut px = 0; + while px < w { + let count = usize::from(file[at] & 0x7F) + 1; + at += 1 + if file[at] & 0x80 != 0 { n } else { count * n }; + px += count; + } + assert_eq!(px, w, "a packet crossed a row"); + } + assert_eq!(at, file.len() - FOOTER.len()); + let r = dec(&file).unwrap(); + assert_eq!((r.width, r.height, r.layout), (w as u32, h as u32, layout)); + let want: Vec = data + .chunks(n) + .flat_map(|p| match layout { + Layout::Gray => [p[0], p[0], p[0], 255], + Layout::GrayAlpha => [p[0], p[0], p[0], p[1]], + Layout::Rgb => [p[0], p[1], p[2], 255], + Layout::Rgba => [p[0], p[1], p[2], p[3]], + }) + .collect(); + assert_eq!(r.rgba, want, "{layout:?}"); + } +} diff --git a/crates/vcard/Cargo.toml b/crates/vcard/Cargo.toml new file mode 100644 index 000000000..b2673cf02 --- /dev/null +++ b/crates/vcard/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-vcard" +description = "vCard: contacts read from vCard 2.1, 3.0 and 4.0 text (RFC 2426, RFC 6350) and written as vCard 3.0, with labels, groups, legacy character sets and KEY certificates." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +# Character sets of vCard 2.1's CHARSET, and strict base64 for KEY. +craft-mime = { workspace = true } +chrono = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/vcard/README.md b/crates/vcard/README.md new file mode 100644 index 000000000..213478a34 --- /dev/null +++ b/crates/vcard/README.md @@ -0,0 +1,48 @@ +# craft-vcard + +vCard: contacts as vCard text (`.vcf` files, CardDAV address data). + +- `parse(text)` reads vCard 2.1, 3.0 and 4.0, one card or many in a text. `parse_bytes(bytes)` + reads a file: UTF-8, UTF-16 with a byte order mark, and vCard 2.1 values each in their own + `CHARSET` (quoted-printable or raw), decoded by `craft_mime::charset`. +- `write(&[&Contact])` writes vCard 3.0, the version every address book reads. Lines are folded + at 75 octets, values are escaped, and no value can start a new property or card. +- `Contact` is this crate's own plain model: names, organisation, labelled e-mail addresses and + phone numbers, postal addresses, web sites, birthday (`chrono::NaiveDate`), notes, categories, + favourite, `UID` and `KEY`. +- Labels come from `TYPE` in all three versions' spellings and from Apple's `itemN.X-ABLabel` + groups, and are written back the same way. +- `KEY` keeps S/MIME certificates and OpenPGP public keys in every form the three versions have + (base64, `data:` URIs, PEM, ASCII armour); a key given as an address is kept as an address and + never fetched. Anything with the shape of secret key material is dropped. + +## Hostile input + +Nothing panics on any text. What makes no sense is skipped. + +| Limit | Value | +|---|---| +| cards in one text | 100,000 | +| nesting of `BEGIN:VCARD` | 8 | +| unfolded line | 1 MiB | +| parameters on a line | 64 | +| e-mail addresses, phones, addresses, web sites per card | 100 each | +| categories per card | 500 | +| group labels per card | 400 | +| keys per card (`Contact::MAX_KEYS`) | 32 | +| one key (`ContactKey::MAX_BYTES`) | 64 KiB | +| key URI (`ContactKey::MAX_URI`) | 2048 bytes | +| key bytes kept from one text | 64 MiB | + +## What stays in the apps + +Ids, where a contact came from, merging and de-duplication, photos (not read), and the mapping +of `Contact` onto the app's own contact type. + +## Origin + +MailCraft `crates/vcard` at +[a44a450](https://github.com/UCS-Care-Group/mailcraft/commit/a44a45013d1c6396229c40ab60172d1882b368d5), +by Martin Ball and the MailCraft contributors (MIT OR Apache-2.0), with its tests. The model +types are the vCard fields of MailCraft's `Contact`; the birthday is a `chrono::NaiveDate` where +MailCraft has its own date type. diff --git a/crates/vcard/src/key.rs b/crates/vcard/src/key.rs new file mode 100644 index 000000000..3cd5be01a --- /dev/null +++ b/crates/vcard/src/key.rs @@ -0,0 +1,294 @@ +//! `KEY`: an S/MIME certificate or an OpenPGP public key on a card, kept as bytes. +//! +//! Read in every form the versions have: vCard 2.1 (`KEY;X509;ENCODING=BASE64:`), 3.0 +//! (`KEY;ENCODING=b;TYPE=PGP:`, RFC 2426) and 4.0 (`KEY:data:application/pgp-keys;base64,…` or +//! `KEY;MEDIATYPE=application/pgp-keys:https://…`, RFC 6350), and a key written as text (an +//! ASCII-armoured OpenPGP key, a PEM certificate). +//! +//! What a key is follows from its bytes, whatever the card calls it: a certificate is kept as DER +//! with the outline of an X.509 certificate (a PEM one is unwrapped), an OpenPGP key as the +//! packets of a public key, binary or armoured as it came. A card whose label disagrees with the +//! bytes, anything else, and above all secret key material (an armour or PEM label that says +//! PRIVATE or SECRET, an OpenPGP secret-key packet, a PKCS #8 or PKCS #12 structure) is dropped. +//! Nothing is checked beyond that outline, nothing is trusted, and nothing is fetched: an address +//! is kept as an address. Written as vCard 3.0. + +use crate::{ContactKey, KeyKind}; + +use crate::lines::ContentLine; +use crate::text::{base64_bytes, quoted_printable, unescape}; + +/// The schemes an address of a key may have; any other address is dropped. +const SCHEMES: [&str; 5] = ["http", "https", "ldap", "ldaps", "openpgp4fpr"]; +const PEM_BEGIN: &str = "-----BEGIN CERTIFICATE-----"; +const PEM_END: &str = "-----END CERTIFICATE-----"; +const PGP_BEGIN: &str = "-----BEGIN PGP PUBLIC KEY BLOCK-----"; +const PGP_END: &str = "-----END PGP PUBLIC KEY BLOCK-----"; + +/// Most bytes a value may decode to before what it holds is worked out: a PEM certificate or +/// an armoured key is larger than the bytes it is kept as. +const MAX_DECODED: usize = ContactKey::MAX_BYTES.saturating_mul(2); +/// Most characters of a value read for a key: the most it takes to spell [`MAX_DECODED`] bytes +/// (three characters a byte, quoted-printable or percent-encoded), with room for a header. +const MAX_VALUE: usize = MAX_DECODED.saturating_mul(3).saturating_add(1024); + +/// The kind a type or media type names: `X509`, `PGP`, `application/pkix-cert`, +/// `application/pgp-keys` and the spellings writers use for them. +fn kind_named(name: &str) -> Option { + match name.trim().to_ascii_lowercase().as_str() { + "x509" | "x.509" | "x-x509" | "application/pkix-cert" | "application/x-x509-ca-cert" | "application/x-x509-user-cert" => Some(KeyKind::X509), + "pgp" | "x-pgp" | "gpg" | "openpgp" | "application/pgp-keys" | "application/pgp" | "application/x-pgp-keys" => Some(KeyKind::OpenPgp), + _ => None, + } +} + +/// The key of one `KEY` line; `None` for one that holds nothing kept (junk, secret key material, +/// a label the bytes don't bear out, a key too large, an address of another scheme). +pub(crate) fn read(line: &ContentLine) -> Option { + if line.value.len() > MAX_VALUE { + return None; + } + let mut stated = line.types().iter().chain(line.param("MEDIATYPE").map(str::to_string).iter()).find_map(|t| kind_named(t)); + let bytes = match line.param("ENCODING").unwrap_or("").to_ascii_uppercase().as_str() { + "B" | "BASE64" => base64_bytes(&line.value), + "QUOTED-PRINTABLE" | "Q" => quoted_printable(&line.value), + _ => { + let value = unescape(&line.value); + let value = value.trim(); + if starts_with_ci(value, "data:") { + let (named, bytes) = data_uri(value.get(5..).unwrap_or(""))?; + stated = named.or(stated); + bytes + } else if value.starts_with("-----BEGIN") { + value.as_bytes().to_vec() + } else if line.param("VALUE").is_some_and(|v| v.eq_ignore_ascii_case("text")) { + // Text that is neither armour nor PEM is no key (a fingerprint, a note); it is + // never taken for the bytes of one. + return None; + } else { + return address(value, stated); + } + } + }; + if bytes.len() > MAX_DECODED { + return None; + } + key_of(&bytes, stated) +} + +fn starts_with_ci(s: &str, start: &str) -> bool { + s.get(..start.len()).is_some_and(|head| head.eq_ignore_ascii_case(start)) +} + +/// An address of a key, with what the card says is there. +fn address(value: &str, stated: Option) -> Option { + let uri = checked_uri(value)?; + let media_type = match stated { + Some(KeyKind::X509) => ContactKey::X509_MEDIA_TYPE, + Some(KeyKind::OpenPgp) => ContactKey::OPENPGP_MEDIA_TYPE, + _ => "", + }; + Some(ContactKey { kind: KeyKind::Uri, uri, media_type: media_type.into(), ..Default::default() }) +} + +/// The key `bytes` hold, however they were spelled: a certificate as DER, an OpenPGP public key as +/// it came. `None` for anything else, for secret key material, for bytes that are not the kind +/// the card `stated`, and for a key larger than is kept. +pub(crate) fn key_of(bytes: &[u8], stated: Option) -> Option { + let text = std::str::from_utf8(bytes).ok().map(str::trim_start).filter(|t| t.starts_with("-----BEGIN")); + let (kind, data) = match text { + Some(t) if says_secret(t) => return None, + Some(t) if t.starts_with(PEM_BEGIN) => { + let body = t.get(PEM_BEGIN.len()..)?; + let (body, _) = body.split_once(PEM_END)?; + (KeyKind::X509, base64_bytes(body)) + } + Some(t) if t.starts_with(PGP_BEGIN) => { + // Up to the end of the armour; what follows it is not kept. + let end = t.find(PGP_END)?.checked_add(PGP_END.len())?; + let armour = t.get(..end)?; + openpgp_public(&armour_body(armour)?).then_some(())?; + (KeyKind::OpenPgp, armour.as_bytes().to_vec()) + } + Some(_) => return None, + None if is_certificate(bytes) => (KeyKind::X509, bytes.to_vec()), + None if openpgp_public(bytes) => (KeyKind::OpenPgp, bytes.to_vec()), + None => return None, + }; + let fits = !data.is_empty() && data.len() <= ContactKey::MAX_BYTES; + let agrees = stated.is_none_or(|s| s == kind); + let whole = kind != KeyKind::X509 || is_certificate(&data); + (fits && agrees && whole).then(|| ContactKey { kind, data, ..Default::default() }) +} + +/// Whether an armour or PEM label in the text says it holds secret key material +/// (`-----BEGIN PGP PRIVATE KEY BLOCK-----`, `-----BEGIN RSA PRIVATE KEY-----`, +/// `-----BEGIN ENCRYPTED PRIVATE KEY-----`, …), anywhere in it. +fn says_secret(text: &str) -> bool { + text.lines().map(str::trim).filter(|l| l.starts_with("-----")).any(|l| { + let label = l.to_ascii_uppercase(); + label.contains("PRIVATE") || label.contains("SECRET") + }) +} + +/// The bytes of an ASCII armour (RFC 9580 section 6): after the header lines and the blank line +/// that ends them, up to the checksum or the end line. `None` when that isn't base64. +fn armour_body(armour: &str) -> Option> { + let mut lines = armour.lines().skip(1).map(str::trim); + let mut body = String::new(); + // Header lines (`Version: …`, `Version:GnuPG`) end at a blank line; an armour without headers + // begins at once. (A colon is never base64.) + let mut first = lines.next()?; + if first.contains(':') { + first = lines.by_ref().find(|l| l.is_empty())?; + } + for line in std::iter::once(first).chain(lines) { + if line.starts_with('=') || line.starts_with("-----") { + break; + } + body.push_str(line); + } + let compact = body.trim_end_matches('='); + craft_mime::base64::STANDARD_NO_PAD.decode(compact).ok().filter(|b| !b.is_empty()) +} + +/// One DER element: its tag, its contents and what follows it. Only the definite lengths DER +/// allows, of at most four bytes. +fn element(bytes: &[u8]) -> Option<(u8, &[u8], &[u8])> { + let tag = *bytes.first()?; + let first = usize::from(*bytes.get(1)?); + let (length, start) = if first < 0x80 { + (first, 2usize) + } else { + let count = first.checked_sub(0x80).filter(|n| (1..=4).contains(n))?; + let digits = bytes.get(2..2usize.checked_add(count)?)?; + let length = digits.iter().try_fold(0usize, |n, d| n.checked_mul(256)?.checked_add(usize::from(*d)))?; + (length, 2usize.checked_add(count)?) + }; + let end = start.checked_add(length)?; + Some((tag, bytes.get(start..end)?, bytes.get(end..)?)) +} + +/// Whether the bytes have the outline of an X.509 certificate (RFC 5280 section 4.1): one +/// SEQUENCE of the to-be-signed SEQUENCE (beginning with its version or serial number), the +/// signature algorithm's SEQUENCE and the signature's BIT STRING, and nothing after it. A private +/// key (PKCS #1, PKCS #8, encrypted or not) or a PKCS #12 file does not have it. +fn is_certificate(bytes: &[u8]) -> bool { + let shape = || -> Option<()> { + let (0x30, certificate, []) = element(bytes)? else { return None }; + let (0x30, signed, rest) = element(certificate)? else { return None }; + matches!(signed.first(), Some(0xa0 | 0x02)).then_some(())?; + let (0x30, _, rest) = element(rest)? else { return None }; + let (0x03, _, []) = element(rest)? else { return None }; + Some(()) + }; + shape().is_some() +} + +/// Whether the bytes are OpenPGP packets (RFC 9580 section 4.2) that make a public key: a +/// public-key packet first, every packet whole, and no secret-key or secret-subkey packet +/// anywhere. +fn openpgp_public(bytes: &[u8]) -> bool { + let mut at = 0usize; + let mut first = true; + while at < bytes.len() { + let Some((tag, next)) = packet(bytes, at) else { return false }; + if matches!(tag, 5 | 7) || (first && tag != 6) { + return false; + } + first = false; + at = next; + } + !first +} + +/// The tag of the packet at `at` and where the next one begins; `None` for a header that isn't +/// one or a packet that runs past the end. A partial length (only data packets have one) is not a +/// key's. +fn packet(bytes: &[u8], at: usize) -> Option<(u8, usize)> { + let header = *bytes.get(at)?; + if header & 0x80 == 0 { + return None; + } + let byte = |i: usize| bytes.get(at.checked_add(i)?).map(|b| usize::from(*b)); + let big_endian = |from: usize, count: usize| (from..from.checked_add(count)?).try_fold(0usize, |n, i| n.checked_mul(256)?.checked_add(byte(i)?)); + let (tag, length, header_len) = if header & 0x40 == 0 { + // The old format: the tag in bits 5 to 2, the length's size in bits 1 and 0. + let tag = (header >> 2) & 0x0f; + match header & 0x03 { + 0 => (tag, byte(1)?, 2usize), + 1 => (tag, big_endian(1, 2)?, 3), + 2 => (tag, big_endian(1, 4)?, 5), + // An indeterminate length, which only data packets may have: not a key's. + _ => return None, + } + } else { + let tag = header & 0x3f; + match byte(1)? { + n @ 0..=191 => (tag, n, 2usize), + n @ 192..=223 => (tag, n.checked_sub(192)?.checked_mul(256)?.checked_add(byte(2)?)?.checked_add(192)?, 3), + 255 => (tag, big_endian(2, 4)?, 6), + _ => return None, + } + }; + let next = at.checked_add(header_len)?.checked_add(length)?; + (next <= bytes.len()).then_some((tag, next)) +} + +/// The kind its media type names and the bytes of a `data:` URI (after the scheme): +/// `application/pgp-keys;base64,mQIN…` or percent-encoded text. +fn data_uri(rest: &str) -> Option<(Option, Vec)> { + let (head, data) = rest.split_once(',')?; + let mut parts = head.split(';'); + let named = parts.next().and_then(kind_named); + let base64 = parts.any(|p| p.trim().eq_ignore_ascii_case("base64")); + Some((named, if base64 { base64_bytes(data) } else { percent_decoded(data) })) +} + +/// `%41` as `A`; a `%` without two hex digits after it is kept. +fn percent_decoded(s: &str) -> Vec { + let bytes = s.as_bytes(); + let hex = |at: usize| bytes.get(at).and_then(|b| char::from(*b).to_digit(16)).and_then(|d| u8::try_from(d).ok()); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0usize; + while let Some(&b) = bytes.get(i) { + if b == b'%' + && let (Some(high), Some(low)) = (hex(i.saturating_add(1)), hex(i.saturating_add(2))) + { + out.push(high.saturating_mul(16).saturating_add(low)); + i = i.saturating_add(3); + } else { + out.push(b); + i = i.saturating_add(1); + } + } + out +} + +/// The address when it is one a key may be at: a known scheme, no white space, control or +/// format characters (a right-to-left override, a zero-width space) or backslashes, not too long. +pub(crate) fn checked_uri(value: &str) -> Option { + let (scheme, rest) = value.split_once(':')?; + let known = SCHEMES.iter().any(|s| s.eq_ignore_ascii_case(scheme)); + // (A backslash would be read back as an escape.) + let clean = !rest.is_empty() && !value.chars().any(|c| c.is_whitespace() || c.is_control() || crate::text::is_format(c) || c == '\\'); + (known && clean && value.len() <= ContactKey::MAX_URI).then(|| value.to_string()) +} + +/// The `KEY` line of a key, as vCard 3.0 writes it; `None` for a key that would not read back as +/// itself (an unknown kind, bytes that aren't a certificate or a public key, too many of them). +/// +/// An address of a key is not written: vCard 3.0 (RFC 2426 section 3.7.2) lets `KEY` be binary +/// or text only, and an address written as text would be read elsewhere as the key itself. It +/// stays on the contact. +pub(crate) fn line(key: &ContactKey) -> Option { + let kind = match key.kind { + KeyKind::X509 => "X509", + KeyKind::OpenPgp => "PGP", + KeyKind::Uri => return None, + }; + // Only what the reader would keep as this very key: never secret material a mailbox file + // may hold. + (key_of(&key.data, Some(key.kind)).as_ref() == Some(key)) + .then(|| format!("KEY;TYPE={kind};ENCODING=b:{}", craft_mime::base64::STANDARD.encode(&key.data))) +} diff --git a/crates/vcard/src/key_tests.rs b/crates/vcard/src/key_tests.rs new file mode 100644 index 000000000..18bfe2291 --- /dev/null +++ b/crates/vcard/src/key_tests.rs @@ -0,0 +1,417 @@ +//! `KEY`: certificates and OpenPGP public keys read in every version's form, known by their bytes, +//! secret key material never kept, written back as 3.0, capped, and never a panic. + +use crate::{Contact, ContactKey, KeyKind}; +use craft_mime::base64::STANDARD; +use proptest::prelude::*; + +use crate::{parse, write}; + +/// Made-up bytes with the outline of a DER certificate: SEQUENCE { SEQUENCE { INTEGER 7 }, +/// SEQUENCE {}, BIT STRING }. +const DER: &[u8] = &[0x30, 0x0a, 0x30, 0x03, 0x02, 0x01, 0x07, 0x30, 0x00, 0x03, 0x01, 0x00]; +/// Made-up OpenPGP packets: an old-format public-key packet (tag 6) of six bytes. +const PGP: &[u8] = &[0x99, 0x00, 0x06, 0x04, 0x5e, 0x00, 0x00, 0x01, 0x16]; + +/// One DER element, its length in the short or the long form. +fn der(tag: u8, content: &[u8]) -> Vec { + let mut out = vec![tag]; + match content.len() { + n if n < 0x80 => out.push(n as u8), + n if n < 0x100 => out.extend([0x81, n as u8]), + n => out.extend([0x82, (n >> 8) as u8, n as u8]), + } + out.extend(content); + out +} + +/// A certificate's outline whose signature is `signature`. +fn certificate(serial: &[u8], signature: &[u8]) -> Vec { + let signed = der(0x30, &der(0x02, serial)); + der(0x30, &[signed, der(0x30, &[]), der(0x03, signature)].concat()) +} + +/// An ASCII armour of OpenPGP packets, with a header and a checksum line. +fn armoured(packets: &[u8]) -> String { + format!("-----BEGIN PGP PUBLIC KEY BLOCK-----\nComment: made up\n\n{}\n=AAAA\n-----END PGP PUBLIC KEY BLOCK-----", STANDARD.encode(packets)) +} + +fn pem(der: &[u8]) -> String { + format!("-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n", STANDARD.encode(der)) +} + +/// `text` with `\`, `;`, `,` and line breaks escaped as a vCard value. +fn escaped(text: &str) -> String { + crate::text::escape(text) +} + +fn keys(version: &str, properties: &str) -> Vec { + let got = parse(&format!("BEGIN:VCARD\r\nVERSION:{version}\r\nFN:Ada\r\n{properties}\r\nEND:VCARD\r\n")); + assert_eq!(got.len(), 1, "{properties}"); + got.into_iter().next().map(|c| c.keys).unwrap_or_default() +} + +fn x509(data: &[u8]) -> ContactKey { + ContactKey { kind: KeyKind::X509, data: data.to_vec(), ..Default::default() } +} + +fn openpgp(data: &[u8]) -> ContactKey { + ContactKey { kind: KeyKind::OpenPgp, data: data.to_vec(), ..Default::default() } +} + +fn at(uri: &str, media_type: &str) -> ContactKey { + ContactKey { kind: KeyKind::Uri, uri: uri.into(), media_type: media_type.into(), ..Default::default() } +} + +#[test] +fn reads_2_1_keys() { + let (der, pgp) = (STANDARD.encode(DER), STANDARD.encode(PGP)); + let (head, tail) = der.split_at(4); + let got = keys("2.1", &format!("KEY;X509;ENCODING=BASE64:{head}\r\n {tail}\r\n\r\nKEY;PGP;BASE64:{pgp}")); + assert_eq!(got, [x509(DER), openpgp(PGP)]); +} + +#[test] +fn reads_3_0_keys() { + let (der, pgp) = (STANDARD.encode(DER), STANDARD.encode(PGP)); + let (head, tail) = pgp.split_at(5); + let armour = armoured(PGP); + let got = keys( + "3.0", + &format!( + "KEY;ENCODING=b;TYPE=X509:{der}\r\nkey;type=pgp;encoding=B:{head}\r\n {tail}\r\nKEY;TYPE=PGP:{}\r\nKEY;VALUE=uri;TYPE=X509:ldap://ldap.example.org/cn=Ada", + escaped(&format!("{armour}\nWhat follows the armour is not kept")) + ), + ); + assert_eq!(got, [x509(DER), openpgp(PGP), openpgp(armour.as_bytes()), at("ldap://ldap.example.org/cn=Ada", ContactKey::X509_MEDIA_TYPE)]); +} + +#[test] +fn reads_4_0_keys() { + let (der, pgp) = (STANDARD.encode(DER), STANDARD.encode(PGP)); + let got = keys( + "4.0", + &format!( + "KEY:data:application/pgp-keys;base64,{pgp}\r\nKEY:data:application/pkix-cert;base64\\,{der}\r\nKEY:data:application/pgp-keys,%99%00%06%04%5E%00%00%01%16\r\n\ +KEY;MEDIATYPE=application/pgp-keys:https://keys.example.org/ada.asc\r\nKEY;TYPE=work:openpgp4fpr:ABCDEF0123456789ABCDEF0123456789ABCDEF01\r\nKEY:http://example.org/ada.cer" + ), + ); + assert_eq!( + got, + [ + openpgp(PGP), + x509(DER), + // (The same key twice is kept once.) + at("https://keys.example.org/ada.asc", ContactKey::OPENPGP_MEDIA_TYPE), + at("openpgp4fpr:ABCDEF0123456789ABCDEF0123456789ABCDEF01", ""), + at("http://example.org/ada.cer", ""), + ] + ); +} + +#[test] +fn a_key_without_a_type_is_known_by_its_bytes() { + let got = keys( + "3.0", + &format!( + "KEY;ENCODING=b:{}\r\nKEY;ENCODING=b:{}\r\nKEY:{}\r\nKEY:data:,{}\r\nKEY;ENCODING=b:{}", + STANDARD.encode(DER), + STANDARD.encode(PGP), + escaped(&pem(DER)), + armoured(PGP).replace('\n', "%0A"), + STANDARD.encode(b"neither") + ), + ); + assert_eq!(got, [x509(DER), openpgp(PGP), openpgp(armoured(PGP).as_bytes())]); +} + +#[test] +fn secret_key_material_is_never_kept() { + let pkcs8 = der(0x30, &[der(0x02, &[0]), der(0x30, &der(0x06, &[0x2a, 0x86, 0x48])), der(0x04, &[1, 2, 3, 4])].concat()); + let pkcs12 = der(0x30, &[der(0x02, &[3]), der(0x30, &der(0x06, &[0x2a])), der(0x30, &[])].concat()); + let encrypted_pkcs8 = der(0x30, &[der(0x30, &der(0x06, &[0x2a])), der(0x04, &[9, 9])].concat()); + // A public-key packet followed by a secret-subkey packet (old format, tag 7). + let with_secret_subkey = [PGP, &[0x9d, 0x00, 0x01, 0x00]].concat(); + for (what, line) in [ + ("an armoured secret key labelled PGP", format!("KEY;TYPE=PGP:{}", escaped(&armoured(PGP).replace("PUBLIC", "PRIVATE")))), + ( + "a PEM private key labelled X509", + format!("KEY;TYPE=X509:{}", escaped(&format!("-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----", STANDARD.encode(&pkcs8)))), + ), + ("a PEM RSA key", format!("KEY:{}", escaped("-----BEGIN RSA PRIVATE KEY-----\nMIIB\n-----END RSA PRIVATE KEY-----"))), + ( + "a certificate with a key after it", + format!( + "KEY;TYPE=X509:{}", + escaped(&format!("{}-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIB\n-----END ENCRYPTED PRIVATE KEY-----", pem(DER))) + ), + ), + ("a secret-key packet, old format (lQAA)", "KEY;TYPE=PGP;ENCODING=b:lQAA".to_string()), + ("a secret-key packet, new format", format!("KEY;ENCODING=b:{}", STANDARD.encode([0xc5, 0x01, 0x04]))), + ("a secret-subkey packet, new format", format!("KEY;ENCODING=b:{}", STANDARD.encode([PGP, &[0xc7, 0x00]].concat()))), + ("a secret subkey after a public key", format!("KEY;TYPE=PGP;ENCODING=b:{}", STANDARD.encode(&with_secret_subkey))), + ("a secret subkey inside a public armour", format!("KEY;TYPE=PGP:{}", escaped(&armoured(&with_secret_subkey)))), + ("PKCS #8 labelled X509", format!("KEY;TYPE=X509;ENCODING=b:{}", STANDARD.encode(&pkcs8))), + ("PKCS #8 without a type", format!("KEY;ENCODING=b:{}", STANDARD.encode(&pkcs8))), + ("encrypted PKCS #8", format!("KEY:data:application/pkix-cert;base64,{}", STANDARD.encode(&encrypted_pkcs8))), + ("PKCS #12", format!("KEY;TYPE=X509;ENCODING=b:{}", STANDARD.encode(&pkcs12))), + ("PKCS #8 in PEM as a certificate", format!("KEY:{}", escaped(&pem(&pkcs8)))), + ] { + assert!(keys("3.0", &line).is_empty(), "{what}"); + } + // And a mailbox file that holds such bytes never has them written to a card. + let c = + Contact { display_name: "Ada".into(), keys: vec![x509(&pkcs8), openpgp(&with_secret_subkey), openpgp(&[0x95, 0, 0])], ..Default::default() }; + assert!(!write(&[&c]).contains("KEY")); +} + +#[test] +fn text_is_never_taken_for_binary() { + for line in [ + "KEY;VALUE=text:0abc", + "KEY;TYPE=X509;VALUE=text:0\\n\\u{3}", + "KEY;TYPE=X509;ENCODING=QUOTED-PRINTABLE:0hello", + "KEY;TYPE=PGP;VALUE=text:ABCD 1234 EF56", + "KEY;TYPE=PGP:ABCD1234EF56", + // Text that looks like an address is text, not the address of a key. + "KEY;VALUE=text:https://keys.example.org/ada.asc", + "KEY;TYPE=PGP;VALUE=TEXT:openpgp4fpr:ABCDEF01", + ] { + assert!(keys("3.0", line).is_empty(), "{line}"); + } +} + +#[test] +fn an_indeterminate_length_is_no_keys() { + // Old format, tag 6, length type 3 (the rest of the bytes): only data packets may have it. + for header in [0x9b_u8, 0xbb] { + let bytes = [header, 0x04, 0x5e, 0x00, 0x00, 0x01, 0x16]; + assert!(keys("3.0", &format!("KEY;TYPE=PGP;ENCODING=b:{}", STANDARD.encode(bytes))).is_empty(), "{header:#x}"); + assert!(keys("3.0", &format!("KEY;ENCODING=b:{}", STANDARD.encode([PGP, &bytes].concat()))).is_empty(), "{header:#x}"); + } +} + +#[test] +fn armour_headers_without_a_space_are_headers() { + let armour = format!( + "-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion:GnuPG v2\nComment:made up\n\n{}\n=AAAA\n-----END PGP PUBLIC KEY BLOCK-----", + STANDARD.encode(PGP) + ); + assert_eq!(keys("3.0", &format!("KEY;TYPE=PGP:{}", escaped(&armour))), [openpgp(armour.as_bytes())]); +} + +#[test] +fn every_spelling_of_a_certificate_is_kept_as_der_and_the_bytes_say_the_kind() { + let quoted: String = pem(DER).bytes().map(|b| format!("={b:02X}")).collect(); + let percent: String = pem(DER).bytes().map(|b| format!("%{b:02X}")).collect(); + let got = keys( + "3.0", + &format!( + "KEY;TYPE=X509;ENCODING=QUOTED-PRINTABLE:{quoted}\r\nKEY:data:application/pkix-cert,{percent}\r\nKEY;TYPE=X509;ENCODING=b:{}\r\nKEY;ENCODING=b:{}", + STANDARD.encode(pem(DER)), + STANDARD.encode(pem(&certificate(&[8], &[0]))) + ), + ); + // The first three are the same certificate, kept once. + assert_eq!(got, [x509(DER), x509(&certificate(&[8], &[0]))]); + // A label the bytes don't bear out is dropped. + for line in [ + format!("KEY;TYPE=PGP:{}", escaped(&pem(DER))), + format!("KEY;TYPE=PGP;ENCODING=b:{}", STANDARD.encode(DER)), + format!("KEY;TYPE=X509;ENCODING=b:{}", STANDARD.encode(PGP)), + format!("KEY:data:application/pkix-cert;base64,{}", STANDARD.encode(PGP)), + format!("KEY;MEDIATYPE=application/pgp-keys:{}", escaped(&pem(DER))), + ] { + assert!(keys("4.0", &line).is_empty(), "{line}"); + } +} + +#[test] +fn what_is_not_a_key_is_dropped() { + for junk in [ + "KEY;TYPE=PGP;ENCODING=b:!!!", + "KEY;TYPE=PGP;ENCODING=b:", + "KEY;TYPE=X509:", + "KEY:javascript:alert(1)", + "KEY:file:///etc/passwd", + "KEY:cid:part1@example.org", + "KEY;VALUE=uri:https://exa mple.org/key", + "KEY:https:", + "KEY:no scheme at all", + "KEY:data:application/pgp-keys;base64", + "KEY;TYPE=X509:-----BEGIN CERTIFICATE-----\\n!!!\\n-----END CERTIFICATE-----", + "KEY;TYPE=X509:-----BEGIN CERTIFICATE-----\\nMAA=", + "KEY;TYPE=X-SOMETHING;ENCODING=b:AAEC", + // A packet that runs past the end, a partial length, a header that is none. + "KEY;ENCODING=b:mQAJBA==", + "KEY;ENCODING=b:xuAA", + "KEY;ENCODING=b:BgAA", + ] { + assert!(keys("3.0", junk).is_empty(), "{junk}"); + } + let long = format!("KEY:https://example.org/{}", "a".repeat(ContactKey::MAX_URI)); + assert!(keys("4.0", &long).is_empty()); +} + +#[test] +fn an_address_with_format_characters_is_dropped() { + for hidden in ['\u{202e}', '\u{200b}', '\u{2066}', '\u{feff}', '\u{ad}'] { + assert!(keys("4.0", &format!("KEY:https://keys.example.org/{hidden}ada.asc")).is_empty(), "{:?}", hidden); + } + assert_eq!(keys("4.0", "KEY:https://keys.example.org/ada.asc"), [at("https://keys.example.org/ada.asc", "")]); +} + +#[test] +fn the_size_counted_is_the_keys_own() { + // A quoted-printable certificate just under the cap is three times as long written, and kept. + let big = certificate(&[1], &vec![0; ContactKey::MAX_BYTES - 20]); + assert!(big.len() <= ContactKey::MAX_BYTES && big.len() > ContactKey::MAX_BYTES - 32); + let quoted: String = big.iter().map(|b| format!("={b:02X}")).collect(); + assert_eq!(keys("2.1", &format!("KEY;X509;QUOTED-PRINTABLE:{quoted}")), [x509(&big)]); + let percent: String = big.iter().map(|b| format!("%{b:02X}")).collect(); + assert_eq!(keys("4.0", &format!("KEY:data:application/pkix-cert,{percent}")), [x509(&big)]); + // One byte more is not. + let over = certificate(&[1], &vec![0; ContactKey::MAX_BYTES - 20 + (ContactKey::MAX_BYTES - big.len()) + 1]); + assert_eq!(over.len(), ContactKey::MAX_BYTES + 1); + assert!(keys("3.0", &format!("KEY;TYPE=X509;ENCODING=b:{}", STANDARD.encode(&over))).is_empty()); + let quoted: String = over.iter().map(|b| format!("={b:02X}")).collect(); + assert!(keys("2.1", &format!("KEY;X509;QUOTED-PRINTABLE:{quoted}")).is_empty()); +} + +#[test] +fn keys_are_capped_per_card_and_per_text() { + let many: String = (0..Contact::MAX_KEYS + 10) + .map(|i| format!("KEY;TYPE=X509;ENCODING=b:{}\r\n", STANDARD.encode(certificate(&[u8::try_from(i).unwrap()], &[0])))) + .collect(); + assert_eq!(keys("3.0", &many).len(), Contact::MAX_KEYS); + // What one text keeps of keys in all: the cards after the allowance is spent keep none. + let card = |n: u8| format!("BEGIN:VCARD\r\nFN:C{n}\r\nKEY;TYPE=X509;ENCODING=b:{}\r\nEND:VCARD\r\n", STANDARD.encode(certificate(&[n], &[0]))); + let text: String = (0..5).map(card).collect(); + let got = crate::read::parse_keeping(&text, 25); + assert_eq!(got.iter().map(|c| c.keys.len()).collect::>(), [1, 1, 0, 0, 0]); + assert_eq!(parse(&text).iter().map(|c| c.keys.len()).sum::(), 5); +} + +#[test] +fn a_card_of_nothing_but_keys_is_skipped() { + let only = format!( + "BEGIN:VCARD\r\nVERSION:3.0\r\nKEY;TYPE=X509;ENCODING=b:{}\r\nKEY:https://keys.example.org/a.asc\r\nEND:VCARD\r\n", + STANDARD.encode(DER) + ); + assert!(parse(&only).is_empty()); + assert_eq!(parse(&only.replace("VERSION:3.0", "VERSION:3.0\r\nFN:Ada"))[0].keys.len(), 2); +} + +#[test] +fn writes_keys_as_3_0() { + let c = Contact { + display_name: "Ada".into(), + keys: vec![ + x509(DER), + openpgp(PGP), + openpgp(armoured(PGP).as_bytes()), + // Never written: addresses (3.0 has no form for them), nothing in it, bytes that aren't the kind they say. + at("https://keys.example.org/ada.asc", ContactKey::OPENPGP_MEDIA_TYPE), + at("openpgp4fpr:ABCDEF01", ""), + openpgp(&[]), + openpgp(DER), + ContactKey { uri: "https://example.org/a".into(), ..x509(DER) }, + ], + ..Default::default() + }; + let out = write(&[&c]); + let lines: Vec<&str> = out.split("\r\n").filter(|l| l.starts_with("KEY")).collect(); + assert_eq!(lines.len(), 3, "{out}"); + assert_eq!(lines[0], format!("KEY;TYPE=X509;ENCODING=b:{}", STANDARD.encode(DER))); + assert_eq!(lines[1], format!("KEY;TYPE=PGP;ENCODING=b:{}", STANDARD.encode(PGP))); + assert!(lines[2].starts_with("KEY;TYPE=PGP;ENCODING=b:")); + assert!(!out.contains("VALUE=uri") && !out.contains("keys.example.org")); + assert_eq!(parse(&out)[0].keys, c.keys[..3]); +} + +#[test] +fn large_keys_fold_and_read_back() { + let signature: Vec = (0..ContactKey::MAX_BYTES - 32).map(|i| (i % 251) as u8).collect(); + let cert = certificate(&[1], &signature); + let body: Vec = (0..60_000u32).map(|i| (i % 251) as u8).collect(); + let pgp = [&[0x9a, 0x00, 0x00, 0xea, 0x60][..], &body].concat(); + let c = Contact { display_name: "Ada".into(), keys: vec![x509(&cert), openpgp(&pgp)], ..Default::default() }; + let out = write(&[&c]); + assert!(out.split("\r\n").all(|line| line.len() <= 75)); + assert_eq!(parse(&out)[0].keys, c.keys); + assert_eq!(crate::parse_bytes(out.as_bytes())[0].keys, c.keys); +} + +/// A certificate's outline or an OpenPGP public key (binary or armoured), from random bytes. +fn key() -> impl Strategy { + let bytes = || proptest::collection::vec(any::(), 1..200); + let user_ids = proptest::collection::vec(proptest::collection::vec(any::(), 0..60), 0..3); + let packets = (bytes(), user_ids).prop_map(|(body, ids)| { + let mut out = vec![0x99, 0, body.len() as u8]; + out.extend(body); + for id in ids { + // An old-format user ID packet (tag 13) with a one-byte length. + out.extend([0xb4, id.len() as u8]); + out.extend(id); + } + out + }); + prop_oneof![ + (bytes(), bytes()).prop_map(|(serial, signature)| x509(&certificate(&serial[..serial.len().min(100)], &signature))), + packets.clone().prop_map(|p| openpgp(&p)), + packets.prop_map(|p| openpgp(armoured(&p).as_bytes())), + ] +} + +proptest! { + #[test] + fn any_keys_round_trip(list in proptest::collection::vec(key(), 0..6)) { + let mut unique: Vec = Vec::new(); + for k in list { + if !unique.contains(&k) { + unique.push(k); + } + } + let c = Contact { display_name: "Ada".into(), keys: unique, ..Default::default() }; + let back = parse(&write(&[&c])); + prop_assert_eq!(back.len(), 1); + prop_assert_eq!(&back[0].keys, &c.keys); + } + + #[test] + fn arbitrary_key_values_never_panic( + params in proptest::sample::select(vec!["", ";ENCODING=b", ";TYPE=PGP", ";TYPE=X509;ENCODING=BASE64", ";X509;QUOTED-PRINTABLE", ";MEDIATYPE=application/pgp-keys", ";VALUE=text", ";VALUE=uri"]), + head in proptest::sample::select(vec!["", "data:", "data:application/pkix-cert;base64,", "data:,%", "-----BEGIN CERTIFICATE-----", "-----BEGIN PGP PUBLIC KEY BLOCK-----", "https:", "openpgp4fpr:", "0", "\u{99}"]), + value in any::(), + bytes in proptest::collection::vec(any::(), 0..512), + ) { + let text = format!("BEGIN:VCARD\r\nFN:x\r\nKEY{params}:{head}{value}\r\nKEY{params}:{head}{}\r\nEND:VCARD\r\n", STANDARD.encode(&bytes)); + let got = parse(&text); + for c in &got { + prop_assert!(c.keys.iter().all(|k| k.data.len() <= ContactKey::MAX_BYTES && k.uri.len() <= ContactKey::MAX_URI)); + // What was read writes and reads back as itself (addresses are not written to 3.0). + let again = parse(&write(&[c])); + let written: Vec<&ContactKey> = c.keys.iter().filter(|k| k.kind != KeyKind::Uri).collect(); + prop_assert_eq!(again.first().map(|a| a.keys.iter().collect::>()), Some(written)); + } + let mut raw = format!("BEGIN:VCARD\r\nFN:x\r\nKEY{params}:{head}").into_bytes(); + raw.extend(&bytes); + raw.extend(b"\r\nEND:VCARD\r\n"); + let _ = crate::parse_bytes(&raw); + } + + #[test] + fn random_bytes_are_never_kept_as_secret_material(body in proptest::collection::vec(any::(), 0..300)) { + // Whatever follows a secret-key or secret-subkey header, nothing is kept. + for header in [[0x95u8, 0x00], [0x94, 0x00], [0x9d, 0x00], [0xc5, 0x00], [0xc7, 0x00]] { + let mut packet = header.to_vec(); + if let Some(len) = packet.get_mut(1) { + *len = body.len().min(150) as u8; + } + let mut bytes = packet; + bytes.extend(body.iter().take(150)); + let line = format!("KEY;TYPE=PGP;ENCODING=b:{}", STANDARD.encode([PGP, &bytes].concat())); + prop_assert!(keys("3.0", &line).is_empty()); + } + } +} diff --git a/crates/vcard/src/lib.rs b/crates/vcard/src/lib.rs new file mode 100644 index 000000000..f2fc2fd6a --- /dev/null +++ b/crates/vcard/src/lib.rs @@ -0,0 +1,26 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! vCard: contacts as vCard text (`.vcf` files, CardDAV address data). +//! +//! [`parse`] reads vCard 2.1, 3.0 and 4.0, one card or many in a text ([`parse_bytes`] in a file, +//! each value in its own `CHARSET`); [`write()`] writes vCard 3.0, the version every address book +//! reads. Both work on [`Contact`], this crate's own plain model of a card. +//! +//! Input is hostile. Nothing here panics on any text: line lengths and counts are capped, and what +//! makes no sense is skipped. + +mod key; +#[cfg(test)] +mod key_tests; +mod lines; +mod model; +mod read; +#[cfg(test)] +mod tests; +mod text; +mod write; + +pub use model::{Contact, ContactKey, KeyKind, Labeled, PostalAddress}; +pub use read::{parse, parse_bytes}; +pub use write::write; diff --git a/crates/vcard/src/lines.rs b/crates/vcard/src/lines.rs new file mode 100644 index 000000000..7507026ef --- /dev/null +++ b/crates/vcard/src/lines.rs @@ -0,0 +1,429 @@ +//! Content lines: unfolding (and quoted-printable soft line breaks) on the way in, folding on the +//! way out, and the `group.NAME;PARAM=value;PARAM:value` shape in between. + +/// Longest logical line kept, in bytes; the rest of a longer line is dropped. +pub(crate) const MAX_LINE: usize = 1 << 20; +/// Most parameters read from one line, and most values of one parameter. +const MAX_PARAMS: usize = 64; +/// Octets per physical line when writing. +const FOLD_AT: usize = 75; +/// How far into a line the `:` that ends its parameters is looked for. +const MAX_HEAD: usize = 1024; + +/// The longest prefix of `s` of at most `max` bytes that ends on a char boundary. +pub(crate) fn prefix(s: &str, max: usize) -> &str { + if s.len() <= max { + return s; + } + let mut end = max; + while end > 0 && !s.is_char_boundary(end) { + end -= 1; + } + s.get(..end).unwrap_or("") +} + +/// The text of a vCard file from its bytes, each property's value read in the `CHARSET` it names. +/// +/// vCard 2.1 lets a value be raw 8-bit bytes in a character set of its own +/// (`FN;CHARSET=WINDOWS-1250:Gvo\xF0\xE6i\xE8`), so a file is read line by line: a value with +/// bytes above 0x7F is decoded with the `CHARSET` of its property (a folded line goes on with the +/// property above it), and without one it is UTF-8 when it is valid UTF-8, else Windows-1252. Names, +/// parameters and values in ASCII (quoted-printable and base64 among them, decoded later with +/// their charset) are kept as they are. A file that opens with a UTF-16 byte order mark is read as +/// UTF-16 throughout. +pub(crate) fn text_from_bytes(bytes: &[u8]) -> String { + if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) { + return craft_mime::charset::decode(bytes, "utf-16"); + } + let bytes = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes); + if bytes.is_ascii() { + return String::from_utf8_lossy(bytes).into_owned(); + } + let mut out = String::with_capacity(bytes.len()); + // The charset of the property being read, for the folded lines that go on with it. + let mut charset = String::new(); + let mut rest = bytes; + while !rest.is_empty() { + let end = rest.iter().position(|b| matches!(b, b'\r' | b'\n')).unwrap_or(rest.len()); + let skip = match (rest.get(end), rest.get(end.saturating_add(1))) { + (Some(b'\r'), Some(b'\n')) => 2, + (Some(_), _) => 1, + (None, _) => 0, + }; + let line = rest.get(..end).unwrap_or(&[]); + let value = if line.starts_with(b" ") || line.starts_with(b"\t") { + line + } else if let Some(colon) = head_end(line) { + let head = line.get(..colon).unwrap_or(&[]); + charset = charset_of(head); + out.push_str(&String::from_utf8_lossy(head)); + line.get(colon..).unwrap_or(&[]) + } else { + charset.clear(); + line + }; + out.push_str(&value_text(value, &charset)); + // The line break itself, as it was. + out.push_str(&String::from_utf8_lossy(rest.get(end..end.saturating_add(skip)).unwrap_or(&[]))); + rest = rest.get(end.saturating_add(skip)..).unwrap_or(&[]); + } + out +} + +/// Where the `:` that ends a line's name and parameters is: outside quotes, in the first kilobyte. +fn head_end(line: &[u8]) -> Option { + let mut quoted = false; + for (i, b) in line.iter().enumerate().take(MAX_HEAD) { + match b { + b'"' => quoted = !quoted, + b':' if !quoted => return Some(i), + _ => {} + } + } + None +} + +/// The `CHARSET` named among a line's parameters; empty when there is none. +fn charset_of(head: &[u8]) -> String { + let head = String::from_utf8_lossy(head); + let named = head.split(';').skip(1).find_map(|param| { + let (name, value) = param.split_once('=')?; + name.trim().eq_ignore_ascii_case("CHARSET").then(|| value.trim().trim_matches('"').trim().to_string()) + }); + named.unwrap_or_default() +} + +/// A value's bytes as text in `charset`, or guessed without one. ASCII stays as it is; a set that +/// ASCII isn't part of (UTF-16, ISO-2022) can't be raw 8-bit bytes on a line, so it is guessed. +fn value_text(value: &[u8], charset: &str) -> String { + let label = charset.to_ascii_lowercase(); + if value.is_ascii() || label.starts_with("utf-16") || label.contains("2022") { + return craft_mime::charset::guess(value); + } + craft_mime::charset::decode(value, &label) +} + +/// A cursor over the lines of a text. Lines end at CRLF, LF or CR. +#[derive(Clone, Copy)] +pub(crate) struct Lines<'a> { + rest: &'a str, +} + +impl<'a> Lines<'a> { + pub(crate) fn new(text: &'a str) -> Lines<'a> { + Lines { rest: text.strip_prefix('\u{feff}').unwrap_or(text) } + } + + /// The next physical line, without its line break. + fn physical(&mut self) -> Option<&'a str> { + if self.rest.is_empty() { + return None; + } + let bytes = self.rest.as_bytes(); + let end = bytes.iter().position(|b| matches!(b, b'\r' | b'\n')).unwrap_or(bytes.len()); + let skip = match (bytes.get(end), bytes.get(end.saturating_add(1))) { + (Some(b'\r'), Some(b'\n')) => 2, + (Some(_), _) => 1, + (None, _) => 0, + }; + let line = self.rest.get(..end).unwrap_or(""); + self.rest = self.rest.get(end.saturating_add(skip)..).unwrap_or(""); + Some(line) + } + + /// The next logical line, or `None` at the end of the text. + /// + /// A line that starts with a space or a tab continues the one before. vCard 3.0 and 4.0 drop + /// that first character; vCard 2.1 (`v21`) keeps it, since there a line is folded where it has + /// white space anyway. A quoted-printable value that ends in `=` goes on with the next line, + /// whatever that starts with. + pub(crate) fn next_line(&mut self, v21: bool) -> Option { + let mut line = String::new(); + let mut last = self.physical()?; + // Whether `line` holds all that was read; a line past the cap is still read to its end. + let mut whole = push_capped(&mut line, last); + let mut quoted_printable = None; + loop { + if quoted_printable.is_none() { + quoted_printable = says_quoted_printable(&line); + } + let mut ahead = *self; + let Some(next) = ahead.physical() else { break }; + if quoted_printable == Some(true) && last.trim_end().ends_with('=') && !starts_or_ends_a_card(next) { + if whole { + line.truncate(line.trim_end().len()); + line.pop(); + } + whole &= push_capped(&mut line, next); + } else if next.starts_with([' ', '\t']) { + whole &= push_capped(&mut line, if v21 { next } else { next.get(1..).unwrap_or("") }); + } else { + break; + } + last = next; + *self = ahead; + } + Some(line) + } +} + +/// Append as much of `more` as the cap leaves room for; whether that was all of it. +fn push_capped(line: &mut String, more: &str) -> bool { + let piece = prefix(more, MAX_LINE.saturating_sub(line.len())); + line.push_str(piece); + piece.len() == more.len() +} + +/// Whether the parameters of `line` name the quoted-printable encoding; `None` while the `:` that +/// ends them hasn't been seen yet. +fn says_quoted_printable(line: &str) -> Option { + let head = prefix(line, MAX_HEAD); + match head.find(':') { + Some(colon) => Some(head.get(..colon).unwrap_or("").to_ascii_uppercase().contains("QUOTED-PRINTABLE")), + None if line.len() > MAX_HEAD => Some(false), + None => None, + } +} + +/// A soft line break never swallows the line that ends the card. +fn starts_or_ends_a_card(line: &str) -> bool { + let line = line.trim_start(); + let is = |word: &str| line.get(..word.len()).is_some_and(|start| start.eq_ignore_ascii_case(word)); + is("END:") || is("BEGIN:") +} + +/// One property parameter: `TYPE=WORK,VOICE`, `ENCODING=QUOTED-PRINTABLE`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Param { + /// Upper-cased. + pub name: String, + pub values: Vec, +} + +/// One property: `item1.TEL;TYPE=CELL:+1 555 0100`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct ContentLine { + /// The group before the name (`item1`), lower-cased; empty when there is none. + pub group: String, + /// Upper-cased, without the group. + pub name: String, + pub params: Vec, + /// As written: still encoded and escaped. + pub value: String, +} + +impl ContentLine { + /// Parse an unfolded line; `None` for a line without a name or without a `:`. + /// + /// A parameter without a name (vCard 2.1: `TEL;WORK;VOICE:`) is a `TYPE`, or an `ENCODING` when + /// it names one. + pub(crate) fn parse(line: &str) -> Option { + // Every delimiter is ASCII, so the byte positions found here are char boundaries. + let bytes = line.as_bytes(); + let stop = |from: usize, at: &[u8]| { + bytes.get(from..).and_then(|b| b.iter().position(|c| at.contains(c))).map_or(bytes.len(), |i| from.saturating_add(i)) + }; + let mut pos = stop(0, b";:"); + let full = line.get(..pos)?.trim(); + let (group, name) = full.rsplit_once('.').unwrap_or(("", full)); + if name.is_empty() { + return None; + } + let mut params = Vec::new(); + while bytes.get(pos) == Some(&b';') { + let start = pos.saturating_add(1); + pos = stop(start, b"=;:"); + let written = line.get(start..pos)?.trim().to_ascii_uppercase(); + let param = if bytes.get(pos) == Some(&b'=') { + let mut values = Vec::new(); + while matches!(bytes.get(pos), Some(b'=' | b',')) { + let from = pos.saturating_add(1); + let value = if bytes.get(from) == Some(&b'"') { + let open = from.saturating_add(1); + let close = stop(open, b"\""); + // A quote that never closes: the line has no value. + bytes.get(close)?; + pos = stop(close, b",;:"); + line.get(open..close)? + } else { + pos = stop(from, b",;:"); + line.get(from..pos)? + }; + if values.len() < MAX_PARAMS { + values.push(value.trim().to_string()); + } + } + Param { name: written, values } + } else if matches!(written.as_str(), "QUOTED-PRINTABLE" | "BASE64" | "B" | "7BIT" | "8BIT") { + Param { name: "ENCODING".into(), values: vec![written] } + } else { + Param { name: "TYPE".into(), values: vec![written] } + }; + if !param.name.is_empty() && param.values.iter().any(|v| !v.is_empty()) && params.len() < MAX_PARAMS { + params.push(param); + } + } + if bytes.get(pos) != Some(&b':') { + return None; + } + Some(ContentLine { + group: group.trim().to_ascii_lowercase(), + name: name.trim().to_ascii_uppercase(), + params, + value: line.get(pos.saturating_add(1)..)?.to_string(), + }) + } + + /// The first value of the parameter `name` (upper case). + pub(crate) fn param(&self, name: &str) -> Option<&str> { + self.params.iter().find(|p| p.name == name).and_then(|p| p.values.first()).map(String::as_str) + } + + /// Every `TYPE`, upper-cased: `TYPE=work,voice`, `TYPE=work;TYPE=voice`, `TYPE="work,voice"` + /// and the bare `WORK;VOICE` all give `WORK` and `VOICE`. + pub(crate) fn types(&self) -> Vec { + let values = self.params.iter().filter(|p| p.name == "TYPE").flat_map(|p| p.values.iter()); + values.flat_map(|v| v.split(',')).map(|v| v.trim().to_ascii_uppercase()).filter(|v| !v.is_empty()).take(MAX_PARAMS).collect() + } +} + +/// Append `line` to `out` with CRLF, folded so no physical line is longer than 75 octets and no +/// character is split. +pub(crate) fn fold(out: &mut String, line: &str) { + let mut rest = line; + let mut room = FOLD_AT; + while rest.len() > room { + let head = prefix(rest, room); + if head.is_empty() { + break; + } + out.push_str(head); + out.push_str("\r\n "); + rest = rest.get(head.len()..).unwrap_or(""); + // The leading space counts. + room = FOLD_AT - 1; + } + out.push_str(rest); + out.push_str("\r\n"); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lines(text: &str, v21: bool) -> Vec { + let mut cursor = Lines::new(text); + std::iter::from_fn(|| cursor.next_line(v21)).collect() + } + + #[test] + fn unfolds_every_kind_of_line_break() { + assert_eq!(lines("A:1\r\nB:2\nC:3\rD:4", false), ["A:1", "B:2", "C:3", "D:4"]); + assert_eq!(lines("NOTE:Lunch \r\n with Ada\r\n", false), ["NOTE:Lunch with Ada"]); + assert_eq!(lines("NOTE:Lun\n\tch\n twice\n", false), ["NOTE:Lunch twice"]); + assert_eq!(lines("\u{feff}BEGIN:VCARD\r\n\r\nEND:VCARD", false), ["BEGIN:VCARD", "", "END:VCARD"]); + assert!(lines("", false).is_empty()); + } + + #[test] + fn version_2_1_keeps_the_white_space_of_a_fold() { + let text = "NOTE:This is a long\r\n description\r\n\tin three pieces\r\nFN:x"; + assert_eq!(lines(text, true), ["NOTE:This is a long description\tin three pieces", "FN:x"]); + assert_eq!(lines(text, false), ["NOTE:This is a longdescriptionin three pieces", "FN:x"]); + } + + #[test] + fn quoted_printable_soft_breaks_join_lines() { + let text = "NOTE;ENCODING=QUOTED-PRINTABLE:first=0D=0A=\r\nsecond =\r\n third= \r\nfourth\r\nFN:x\r\n"; + assert_eq!(lines(text, true), ["NOTE;ENCODING=QUOTED-PRINTABLE:first=0D=0Asecond thirdfourth", "FN:x"]); + // The bare 2.1 spelling, in lower case. + assert_eq!(lines("note;quoted-printable:a=\nb\nFN:x", false), ["note;quoted-printable:ab", "FN:x"]); + // Without the encoding an `=` at the end is just an `=`. + assert_eq!(lines("NOTE:1+1=\r\nFN:x", false), ["NOTE:1+1=", "FN:x"]); + // The parameters may themselves be folded before the `:` comes. + assert_eq!(lines("NOTE;CHARSET=UTF-8;\r\n ENCODING=QUOTED-PRINTABLE:a=\r\nb", false), ["NOTE;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:ab"]); + // A soft break at the very end of a card doesn't eat the END line, and one at the end of the text is harmless. + assert_eq!(lines("NOTE;QUOTED-PRINTABLE:a=\r\nEND:VCARD\r\n", false), ["NOTE;QUOTED-PRINTABLE:a=", "END:VCARD"]); + assert_eq!(lines("NOTE;QUOTED-PRINTABLE:a=", false), ["NOTE;QUOTED-PRINTABLE:a="]); + } + + #[test] + fn parses_groups_names_parameters_and_values() { + let l = ContentLine::parse("Item1.email;type=INTERNET;Type=pref:nadia@example.org").unwrap(); + assert_eq!((l.group.as_str(), l.name.as_str(), l.value.as_str()), ("item1", "EMAIL", "nadia@example.org")); + assert_eq!(l.types(), ["INTERNET", "PREF"]); + let plain = ContentLine::parse("NOTE:Budget: phase two; hiring").unwrap(); + assert_eq!( + (plain.group.as_str(), plain.name.as_str(), plain.params.len(), plain.value.as_str()), + ("", "NOTE", 0, "Budget: phase two; hiring") + ); + assert_eq!(ContentLine::parse("FN:").unwrap().value, ""); + for bad in ["no colon here", ":value without a name", "item1.:x", ";WORK:x", "TEL;TYPE=\"never closed:1", " ", ""] { + assert_eq!(ContentLine::parse(bad), None, "{bad}"); + } + } + + #[test] + fn types_come_in_every_spelling() { + let types = |line: &str| ContentLine::parse(line).unwrap().types(); + assert_eq!(types("TEL;TYPE=WORK,VOICE:1"), ["WORK", "VOICE"]); + assert_eq!(types("TEL;type=work;type=voice:1"), ["WORK", "VOICE"]); + assert_eq!(types("TEL;WORK;VOICE:1"), ["WORK", "VOICE"]); + assert_eq!(types("TEL;VALUE=uri;TYPE=\"voice,cell\";PREF=1:tel:+1-555-0100"), ["VOICE", "CELL"]); + assert_eq!(types("TEL;TYPE=:1").len(), 0); + assert_eq!(types("TEL:1").len(), 0); + let bare = ContentLine::parse("NOTE;CHARSET=utf-8;QUOTED-PRINTABLE;;X-THING:a").unwrap(); + assert_eq!(bare.param("ENCODING"), Some("QUOTED-PRINTABLE")); + assert_eq!(bare.param("CHARSET"), Some("utf-8")); + assert_eq!(bare.types(), ["X-THING"]); + assert_eq!(ContentLine::parse("PHOTO;BASE64;JPEG:AAAA").unwrap().param("ENCODING"), Some("BASE64")); + } + + #[test] + fn folds_at_75_octets_without_splitting_characters() { + let line = format!("NOTE:{}", "é東🎉x".repeat(40)); + let mut out = String::new(); + fold(&mut out, &line); + let physical: Vec<&str> = out.trim_end_matches("\r\n").split("\r\n").collect(); + assert!(physical.len() > 3); + assert!(physical.iter().all(|l| l.len() <= 75), "{physical:?}"); + assert!(physical.iter().skip(1).all(|l| l.starts_with(' '))); + assert_eq!(lines(&out, false), [line]); + let mut exact = String::new(); + fold(&mut exact, &"x".repeat(76)); + assert_eq!(exact, format!("{}\r\n x\r\n", "x".repeat(75))); + } + + #[test] + fn enormous_lines_are_capped() { + let text = format!("PHOTO;ENCODING=b:{}\r\n {}\r\nFN:after", "A".repeat(MAX_LINE + 5000), "B".repeat(1000)); + let got = lines(&text, false); + assert_eq!(got.len(), 2); + assert!(got[0].len() <= MAX_LINE); + assert_eq!(got[1], "FN:after"); + // A quoted-printable value that never stops. + let endless = format!("NOTE;QUOTED-PRINTABLE:{}", "é=\r\n".repeat(700_000)); + let got = lines(&endless, true); + assert_eq!(got.len(), 1); + assert!(got[0].len() <= MAX_LINE); + assert_eq!(prefix("héllo", 2), "h"); + } + + proptest::proptest! { + #[test] + fn folding_then_unfolding_gives_the_line_back(line in "[^\r\n]{0,400}") { + let mut out = String::new(); + fold(&mut out, &line); + proptest::prop_assert!(out.split("\r\n").all(|l| l.len() <= 75)); + // A byte order mark at the very start of a text isn't part of its first line. + proptest::prop_assert_eq!(lines(&out, false), vec![line.strip_prefix('\u{feff}').unwrap_or(&line).to_string()]); + } + + #[test] + fn any_text_splits_into_lines(text in proptest::prelude::any::(), v21 in proptest::prelude::any::()) { + for line in lines(&text, v21) { + let _ = ContentLine::parse(&line).map(|l| l.types()); + } + } + } +} diff --git a/crates/vcard/src/model.rs b/crates/vcard/src/model.rs new file mode 100644 index 000000000..2fd6b4fa6 --- /dev/null +++ b/crates/vcard/src/model.rs @@ -0,0 +1,127 @@ +//! What a card holds: a contact, as the vCard properties this crate reads and writes. + +use chrono::NaiveDate; + +/// A value with a label (`work`, `home`, `mobile`). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Labeled { + pub label: String, + pub value: String, +} + +impl Labeled { + pub fn new(label: impl Into, value: impl Into) -> Labeled { + Labeled { label: label.into(), value: value.into() } + } +} + +/// A postal address (`ADR`). The street holds the post office box and the extended address too. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PostalAddress { + pub label: String, + pub street: String, + pub city: String, + pub region: String, + pub postal_code: String, + pub country: String, +} + +impl PostalAddress { + /// The address on one line, skipping empty parts. + pub fn one_line(&self) -> String { + let city = [self.city.as_str(), self.region.as_str(), self.postal_code.as_str()] + .into_iter() + .filter(|p| !p.trim().is_empty()) + .collect::>() + .join(" "); + [self.street.as_str(), city.as_str(), self.country.as_str()].into_iter().filter(|p| !p.trim().is_empty()).collect::>().join(", ") + } + + pub fn is_empty(&self) -> bool { + self.one_line().is_empty() + } +} + +/// What a key on a card is. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum KeyKind { + /// An S/MIME certificate (X.509, DER). + #[default] + X509, + /// An OpenPGP public key, binary or ASCII-armoured, as the card had it. + OpenPgp, + /// Where the card says a key is ([`ContactKey::uri`]); never fetched. + Uri, +} + +/// A public key or certificate a card carries (`KEY`). The reader keeps only what has the shape +/// of a certificate or of an OpenPGP public key, never secret key material. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ContactKey { + pub kind: KeyKind, + /// The key's bytes; empty for a [`KeyKind::Uri`]. + pub data: Vec, + /// For a [`KeyKind::Uri`]: the address the card gave (`https:`, `ldap:`, `openpgp4fpr:`). + pub uri: String, + /// For a [`KeyKind::Uri`]: what the card says is there, [`ContactKey::X509_MEDIA_TYPE`] or + /// [`ContactKey::OPENPGP_MEDIA_TYPE`]; empty when it doesn't say. + pub media_type: String, +} + +impl ContactKey { + /// Most bytes of one key kept. + pub const MAX_BYTES: usize = 64 * 1024; + /// Longest address of a key kept, in bytes. + pub const MAX_URI: usize = 2048; + /// The media type of an S/MIME certificate. + pub const X509_MEDIA_TYPE: &str = "application/pkix-cert"; + /// The media type of OpenPGP keys. + pub const OPENPGP_MEDIA_TYPE: &str = "application/pgp-keys"; +} + +/// One card. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Contact { + /// `FN`; when empty, [`Contact::name`] builds one. + pub display_name: String, + pub first: String, + pub middle: String, + pub last: String, + pub nickname: String, + pub company: String, + pub title: String, + pub department: String, + pub emails: Vec, + pub phones: Vec, + pub addresses: Vec, + pub websites: Vec, + pub birthday: Option, + pub notes: String, + pub categories: Vec, + /// `X-FAVORITE` (and the forms other address books write it in). + pub favorite: bool, + /// `KEY`: certificates and OpenPGP public keys, at most [`Contact::MAX_KEYS`]. + pub keys: Vec, + /// `UID`, kept so a written card updates the same contact elsewhere. + pub uid: String, +} + +impl Contact { + /// Most keys kept for one contact. + pub const MAX_KEYS: usize = 32; + + /// The name to show: the display name, else first and last, the company, or the first address. + pub fn name(&self) -> String { + if !self.display_name.trim().is_empty() { + return self.display_name.trim().to_string(); + } + let full = [self.first.trim(), self.middle.trim(), self.last.trim()].into_iter().filter(|p| !p.is_empty()).collect::>().join(" "); + if !full.is_empty() { + return full; + } + if !self.company.trim().is_empty() { + return self.company.trim().to_string(); + } + self.emails.first().map(|e| e.value.clone()).unwrap_or_default() + } +} diff --git a/crates/vcard/src/read.rs b/crates/vcard/src/read.rs new file mode 100644 index 000000000..faa117f45 --- /dev/null +++ b/crates/vcard/src/read.rs @@ -0,0 +1,778 @@ +//! Reading vCards (2.1, 3.0 and 4.0) into contacts. + +use std::collections::HashMap; + +use crate::{Contact, Labeled, PostalAddress}; +use chrono::NaiveDate; + +use crate::lines::{ContentLine, Lines}; +use crate::text::{base64_bytes, component, multi, quoted_printable, single, split, unescape}; + +/// Most cards read from one text. +const MAX_CARDS: usize = 100_000; +/// Most e-mail addresses, phone numbers, postal addresses or web sites kept per card. +const MAX_ITEMS: usize = 100; +const MAX_CATEGORIES: usize = 500; +/// Most group labels (`item1.X-ABLabel`) kept per card. +const MAX_LABELS: usize = 400; +/// Deepest nesting of cards followed (a 2.1 `AGENT` holds a card of its own). +const MAX_DEPTH: usize = 8; +/// Most bytes of keys (`KEY`) kept from one text, all its cards together. +pub(crate) const MAX_KEY_BYTES: usize = 64 << 20; + +/// Parse one or many vCards (2.1, 3.0, 4.0). Never fails: junk gives an empty list, and a card +/// with nothing in it is skipped. Ids are left 0. +/// +/// `FN` gives the display name; without one it stays empty and the model derives a name. A label +/// comes from `TYPE` (`work`, `home`, `other`, and for phones `mobile`, `fax`, `pager`), or from the +/// `X-ABLabel` of the property's group (`item1.X-ABLabel:Family`); it is empty when neither says +/// anything. An S/MIME certificate or OpenPGP public key (`KEY`) is kept as bytes when its bytes +/// have the shape of one, and the address of one as an address, never fetched; secret key +/// material is never kept (`crate::key`). A card with nothing but keys is skipped. Photos, logos, +/// sounds and unknown properties are skipped. +/// +/// Work is bounded: at most 100 000 cards are read, 100 e-mail addresses, phone numbers, postal +/// addresses and web sites per card, 32 keys of at most 64 KiB per card and 64 MiB of keys in all, +/// and what a line holds beyond 1 MiB is dropped. +/// +/// A file's bytes go through [`parse_bytes`], which reads raw 8-bit values in their `CHARSET`. +pub fn parse(text: &str) -> Vec { + parse_keeping(text, MAX_KEY_BYTES) +} + +/// [`parse`], keeping at most `key_room` bytes of keys. +pub(crate) fn parse_keeping(text: &str, mut key_room: usize) -> Vec { + let mut lines = Lines::new(text); + // The cards that are open, outermost first, and the finished ones with the order they began in. + let mut open: Vec = Vec::new(); + let mut done: Vec<(usize, Contact)> = Vec::new(); + let mut begun = 0usize; + while done.len() < MAX_CARDS { + let v21 = open.last().is_some_and(|card| card.v21); + let Some(raw) = lines.next_line(v21) else { break }; + let Some(line) = ContentLine::parse(&raw) else { continue }; + let is_card = line.value.trim().eq_ignore_ascii_case("VCARD"); + match (line.name.as_str(), open.last_mut()) { + ("BEGIN", _) if is_card => { + // A card that never ended ends where too many are open. + if open.len() >= MAX_DEPTH { + done.extend(open.pop().and_then(Card::finish)); + } + open.push(Card { order: begun, ..Default::default() }); + begun = begun.saturating_add(1); + } + ("END", _) if is_card => done.extend(open.pop().and_then(Card::finish)), + ("BEGIN", Some(card)) => card.foreign = card.foreign.saturating_add(1), + ("END", Some(card)) => card.foreign = card.foreign.saturating_sub(1), + (_, Some(card)) if card.foreign == 0 => card.apply(&line, &mut key_room), + _ => {} + } + } + // Cards without an END are still cards. + while let Some(card) = open.pop() { + done.extend(card.finish()); + } + done.sort_by_key(|(order, _)| *order); + done.into_iter().map(|(_, contact)| contact).take(MAX_CARDS).collect() +} + +/// Parse a vCard file as [`parse`] does, from its bytes: a value written as raw 8-bit bytes +/// (vCard 2.1, `FN;CHARSET=WINDOWS-1250:…`) is read in the `CHARSET` of its property, and one +/// without a `CHARSET` as UTF-8 when it is valid UTF-8, else as Windows-1252. +pub fn parse_bytes(bytes: &[u8]) -> Vec { + parse(&crate::lines::text_from_bytes(bytes)) +} + +/// A card being read. +#[derive(Default)] +struct Card { + /// Its place among the cards of the text. + order: usize, + /// `VERSION:2.1`: other folding, no comma lists. + v21: bool, + /// How deep inside a component that isn't a card the reader is. + foreign: u32, + contact: Contact, + named: bool, + /// E-mail addresses, phones and postal addresses, each with the group it was written in. + emails: Vec<(String, Labeled)>, + phones: Vec<(String, Labeled)>, + addresses: Vec<(String, PostalAddress)>, + /// `X-ABLabel` by group. + labels: HashMap, +} + +impl Card { + /// Take in one property; `key_room` is what keys may still take of the text's allowance. + fn apply(&mut self, line: &ContentLine, key_room: &mut usize) { + let v21 = self.v21; + let contact = &mut self.contact; + // One line of text, decoded and unescaped. + let one = |line: &ContentLine| single(&unescape(&decoded(line))); + match line.name.as_str() { + "VERSION" => self.v21 = line.value.trim().starts_with("2."), + "FN" if contact.display_name.is_empty() => contact.display_name = one(line), + "N" if !self.named => { + self.named = true; + let value = decoded(line); + let parts = split(&value, ';', 8); + let part = |i: usize| parts.get(i).map(|p| component(p, " ", v21)).unwrap_or_default(); + (contact.last, contact.first, contact.middle) = (part(0), part(1), part(2)); + } + "NICKNAME" if contact.nickname.is_empty() => contact.nickname = one(line), + "ORG" if contact.company.is_empty() && contact.department.is_empty() => { + let value = decoded(line); + let parts = split(&value, ';', 16); + contact.company = parts.first().map(|p| component(p, ", ", v21)).unwrap_or_default(); + contact.department = parts.iter().skip(1).map(|p| component(p, ", ", v21)).filter(|p| !p.is_empty()).collect::>().join(", "); + } + "TITLE" if contact.title.is_empty() => contact.title = one(line), + "EMAIL" if self.emails.len() < MAX_ITEMS => { + let value = without_scheme(&one(line), "mailto:"); + if !value.is_empty() { + self.emails.push((line.group.clone(), Labeled::new(place_label(&line.types()), value))); + } + } + "TEL" if self.phones.len() < MAX_ITEMS => { + let value = without_scheme(&one(line), "tel:"); + if !value.is_empty() { + self.phones.push((line.group.clone(), Labeled::new(phone_label(&line.types()), value))); + } + } + "ADR" if self.addresses.len() < MAX_ITEMS => { + let value = decoded(line); + let parts = split(&value, ';', 8); + let part = |i: usize| parts.get(i).map(|p| component(p, ", ", v21)).unwrap_or_default(); + // Post office box, extended address, street: the lines above the city. + let street = [part(0), part(1), part(2)].into_iter().filter(|p| !p.is_empty()).collect::>().join(", "); + let address = PostalAddress { + label: place_label(&line.types()).into(), + street, + city: part(3), + region: part(4), + postal_code: part(5), + country: part(6), + }; + if !address.is_empty() { + self.addresses.push((line.group.clone(), address)); + } + } + "URL" if contact.websites.len() < MAX_ITEMS => { + let value = one(line); + if !value.is_empty() { + contact.websites.push(value); + } + } + "BDAY" if contact.birthday.is_none() => contact.birthday = birthday(&line.value), + "NOTE" => { + let note = multi(&unescape(&decoded(line))); + if !note.is_empty() { + if !contact.notes.is_empty() { + contact.notes.push('\n'); + } + contact.notes.push_str(¬e); + } + } + "CATEGORIES" => { + let value = decoded(line); + let room = MAX_CATEGORIES.saturating_sub(contact.categories.len()); + contact + .categories + .extend(split(&value, ',', MAX_CATEGORIES).into_iter().map(|c| single(&unescape(c))).filter(|c| !c.is_empty()).take(room)); + } + "UID" if contact.uid.is_empty() => contact.uid = one(line), + "KEY" if contact.keys.len() < Contact::MAX_KEYS && *key_room > 0 => { + if let Some(key) = crate::key::read(line) { + let cost = key.data.len().saturating_add(key.uri.len()); + if cost <= *key_room && !contact.keys.contains(&key) { + *key_room = key_room.saturating_sub(cost); + contact.keys.push(key); + } + } + } + "X-FAVORITE" | "X-MAILCRAFT-FAVORITE" => { + contact.favorite |= matches!(line.value.trim().to_ascii_uppercase().as_str(), "TRUE" | "YES" | "1") + } + "X-ABLABEL" if !line.group.is_empty() && self.labels.len() < MAX_LABELS => { + let label = one(line); + // The built-in labels of the program that invented this are wrapped: `_$!!$_`. + let label = label.strip_prefix("_$!<").and_then(|l| l.strip_suffix(">!$_")).map(str::to_lowercase).unwrap_or(label); + self.labels.entry(line.group.clone()).or_insert(label); + } + _ => {} + } + } + + /// The contact with the place it began at; `None` for a card with nothing in it. + fn finish(self) -> Option<(usize, Contact)> { + let Card { order, mut contact, emails, phones, addresses, labels, .. } = self; + // A label given to a group says more than the property's type. + let label = |group: &str, own: String| labels.get(group).filter(|_| !group.is_empty()).cloned().unwrap_or(own); + contact.emails = emails.into_iter().map(|(group, e)| Labeled { label: label(&group, e.label), value: e.value }).collect(); + contact.phones = phones.into_iter().map(|(group, p)| Labeled { label: label(&group, p.label), value: p.value }).collect(); + contact.addresses = addresses.into_iter().map(|(group, a)| PostalAddress { label: label(&group, a.label.clone()), ..a }).collect(); + // Keys alone make no contact: a card of nothing but keys is skipped as an empty one is. + let keys = std::mem::take(&mut contact.keys); + let empty = contact == Contact::default(); + contact.keys = keys; + (!empty).then_some((order, contact)) + } +} + +/// The value with its `ENCODING` (quoted-printable or base64) and `CHARSET` undone; still escaped. +fn decoded(line: &ContentLine) -> String { + let bytes = match line.param("ENCODING").unwrap_or("").to_ascii_uppercase().as_str() { + "QUOTED-PRINTABLE" | "Q" => quoted_printable(&line.value), + "BASE64" | "B" => base64_bytes(&line.value), + _ => return line.value.clone(), + }; + craft_mime::charset::decode(&bytes, line.param("CHARSET").unwrap_or("")) +} + +/// `tel:+1-555-0100` and `mailto:a@example.org` (vCard 4.0 URIs) without the scheme. +fn without_scheme(value: &str, scheme: &str) -> String { + match value.get(..scheme.len()) { + Some(start) if start.eq_ignore_ascii_case(scheme) => value.get(scheme.len()..).unwrap_or("").trim().to_string(), + _ => value.to_string(), + } +} + +/// The label of an e-mail or postal address. +fn place_label(types: &[String]) -> &'static str { + let has = |t: &str| types.iter().any(|x| x == t); + if has("WORK") { + "work" + } else if has("HOME") { + "home" + } else if has("OTHER") { + "other" + } else { + "" + } +} + +/// The label of a phone number: what kind of device it is says more than where it stands. +fn phone_label(types: &[String]) -> &'static str { + let has = |t: &str| types.iter().any(|x| x == t); + if has("CELL") || has("MOBILE") || has("IPHONE") { + "mobile" + } else if has("FAX") { + "fax" + } else if has("PAGER") { + "pager" + } else { + place_label(types) + } +} + +/// `1985-04-12`, `19850412`, or either with a time after it; `None` without a year (`--0412`). +fn birthday(value: &str) -> Option { + parse_iso(value.trim().split(['T', 't', ' ']).next()?) +} + +/// A date from `YYYY-MM-DD` or `YYYYMMDD`, years 1 to 9999. +fn parse_iso(s: &str) -> Option { + let s = s.trim(); + let digits: String = s.chars().filter(char::is_ascii_digit).collect(); + if digits.len() != 8 || s.chars().any(|c| !c.is_ascii_digit() && c != '-') { + return None; + } + let year: i32 = digits.get(0..4)?.parse().ok()?; + if year < 1 { + return None; + } + NaiveDate::from_ymd_opt(year, digits.get(4..6)?.parse().ok()?, digits.get(6..8)?.parse().ok()?) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() + } + + /// One contact from the properties of a 3.0 card. + fn card(properties: &str) -> Contact { + let got = parse(&format!("BEGIN:VCARD\r\nVERSION:3.0\r\n{properties}\r\nEND:VCARD\r\n")); + assert_eq!(got.len(), 1, "{properties}"); + got.into_iter().next().unwrap() + } + + /// A vCard 2.1 card as old phones and mail programs write them: bare type parameters, + /// quoted-printable with soft line breaks, a charset. + const V21: &str = "BEGIN:VCARD\r\n\ +VERSION:2.1\r\n\ +N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:M=C3=BCller;J=C3=BCrgen;;Dr.;\r\n\ +FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:Dr. J=C3=BCrgen M=C3=BCller\r\n\ +ORG:Beispiel Werke, GmbH;Entwicklung\r\n\ +TITLE;CHARSET=ISO-8859-1;ENCODING=QUOTED-PRINTABLE:Gesch=E4ftsf=FChrer\r\n\ +TEL;WORK;VOICE:+49 30 5550100\r\n\ +TEL;CELL:+49 170 5550101\r\n\ +TEL;WORK;FAX:+49 30 5550199\r\n\ +TEL;PAGER:+49 30 5550177\r\n\ +EMAIL;PREF;INTERNET:juergen.mueller@example.org\r\n\ +EMAIL;INTERNET;HOME:jm@privat.example.org\r\n\ +ADR;HOME;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:;;Gartenstra=C3=9Fe 12;K=C3=B6ln;NW;50667;Deutschland\r\n\ +LABEL;HOME;ENCODING=QUOTED-PRINTABLE:Gartenstra=C3=9Fe 12=0D=0A50667 K=C3=B6ln\r\n\ +NOTE;ENCODING=QUOTED-PRINTABLE:Erste Zeile=0D=0AZweite Zeile, mit einem sehr langen Text der =\r\n\ +umbrochen wird=3B und noch einmal =\r\n\ +umbrochen.\r\n\ +URL;WORK:http://example.org/~jm\r\n\ +BDAY:19720314\r\n\ +REV:20260901T101500Z\r\n\ +END:VCARD\r\n"; + + #[test] + fn reads_a_2_1_card() { + let got = parse(V21); + assert_eq!(got.len(), 1); + assert_eq!( + got[0], + Contact { + display_name: "Dr. Jürgen Müller".into(), + first: "Jürgen".into(), + last: "Müller".into(), + company: "Beispiel Werke, GmbH".into(), + department: "Entwicklung".into(), + title: "Geschäftsführer".into(), + emails: vec![Labeled::new("", "juergen.mueller@example.org"), Labeled::new("home", "jm@privat.example.org")], + phones: vec![ + Labeled::new("work", "+49 30 5550100"), + Labeled::new("mobile", "+49 170 5550101"), + Labeled::new("fax", "+49 30 5550199"), + Labeled::new("pager", "+49 30 5550177") + ], + addresses: vec![PostalAddress { + label: "home".into(), + street: "Gartenstraße 12".into(), + city: "Köln".into(), + region: "NW".into(), + postal_code: "50667".into(), + country: "Deutschland".into() + }], + websites: vec!["http://example.org/~jm".into()], + birthday: Some(d(1972, 3, 14)), + notes: "Erste Zeile\nZweite Zeile, mit einem sehr langen Text der umbrochen wird; und noch einmal umbrochen.".into(), + ..Default::default() + } + ); + } + + /// A vCard 3.0 card as address books export them: grouped properties with custom labels, a + /// photo, folded lines. + const V30: &str = "BEGIN:VCARD\r\n\ +VERSION:3.0\r\n\ +PRODID:-//Example//Contacts 12.0//EN\r\n\ +N:Okafor;Nadia;Chidi,Rose;Dr.;\r\n\ +FN:Dr. Nadia Okafor\r\n\ +NICKNAME:Nadi\r\n\ +ORG:Example Research\\, Inc.;Field Lab;Unit 7\r\n\ +TITLE:Lead Scientist\r\n\ +item1.EMAIL;type=INTERNET;type=WORK;type=pref:nadia.okafor@example.org\r\n\ +item2.EMAIL;type=INTERNET:nadia@family.example.org\r\n\ +item2.X-ABLabel:Family\r\n\ +TEL;type=CELL;type=VOICE;type=pref:+1 (555) 010-0142\r\n\ +item3.TEL:+1 555 010 0143\r\n\ +item3.X-ABLabel:_$!!$_\r\n\ +TEL;TYPE=WORK,FAX:+1 555 010 0144\r\n\ +item4.ADR;type=WORK;type=pref:;Suite 300;41 Harbor Road;Riverton;CA;94000;USA\r\n\ +item4.X-ABADR:us\r\n\ +item5.URL;type=pref:https\\://example.org/~nadia\r\n\ +item5.X-ABLabel:_$!!$_\r\n\ +BDAY:1985-04-12\r\n\ +NOTE:Met at the 2024 symposium.\\nPrefers e-mail\\, not calls; see the long thread about the field s\r\n tation.\r\n\ +CATEGORIES:Research,Field Team\\, West\r\n\ +PHOTO;ENCODING=b;TYPE=JPEG:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1\r\n Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1u\r\n b3BxcnN0dXZ3eHl6e3x9fn8=\r\n\ +UID:7f1c2f6e-0001-4a5b-9c3d-000000000042\r\n\ +X-FAVORITE:TRUE\r\n\ +REV:2026-09-01T10:15:00Z\r\n\ +END:VCARD\r\n"; + + #[test] + fn reads_a_3_0_card_with_grouped_properties() { + let got = parse(V30); + assert_eq!(got.len(), 1); + assert_eq!( + got[0], + Contact { + display_name: "Dr. Nadia Okafor".into(), + first: "Nadia".into(), + middle: "Chidi Rose".into(), + last: "Okafor".into(), + nickname: "Nadi".into(), + company: "Example Research, Inc.".into(), + department: "Field Lab, Unit 7".into(), + title: "Lead Scientist".into(), + emails: vec![Labeled::new("work", "nadia.okafor@example.org"), Labeled::new("Family", "nadia@family.example.org")], + phones: vec![ + Labeled::new("mobile", "+1 (555) 010-0142"), + Labeled::new("other", "+1 555 010 0143"), + Labeled::new("fax", "+1 555 010 0144") + ], + addresses: vec![PostalAddress { + label: "work".into(), + street: "Suite 300, 41 Harbor Road".into(), + city: "Riverton".into(), + region: "CA".into(), + postal_code: "94000".into(), + country: "USA".into() + }], + websites: vec!["https://example.org/~nadia".into()], + birthday: Some(d(1985, 4, 12)), + notes: "Met at the 2024 symposium.\nPrefers e-mail, not calls; see the long thread about the field station.".into(), + categories: vec!["Research".into(), "Field Team, West".into()], + favorite: true, + uid: "7f1c2f6e-0001-4a5b-9c3d-000000000042".into(), + ..Default::default() + } + ); + } + + /// A vCard 4.0 card: URIs for phones, quoted type lists, no `N` needed. + const V40: &str = "BEGIN:VCARD\r\n\ +VERSION:4.0\r\n\ +KIND:individual\r\n\ +FN:Mei Tanaka\r\n\ +N:Tanaka;Mei;;;\r\n\ +EMAIL;TYPE=work;PREF=1:mei.tanaka@example.org\r\n\ +EMAIL;TYPE=home:mailto:mei@home.example.org\r\n\ +TEL;VALUE=uri;TYPE=\"voice,cell\";PREF=1:tel:+81-90-5550-0101\r\n\ +TEL;VALUE=uri;TYPE=work:tel:+81-3-5550-0102;ext=12\r\n\ +ADR;TYPE=home;LABEL=\"1-2-3 Sakura\\nMinato, Tokyo\":;;1-2-3 Sakura;Minato;Tokyo;105-0000;Japan\r\n\ +BDAY:19910704T080000Z\r\n\ +ANNIVERSARY:20150620\r\n\ +GENDER:F\r\n\ +LANG;PREF=1:ja\r\n\ +URL:https://example.org/mei\r\n\ +URL;TYPE=work:https://design.example.org/team/mei\r\n\ +NOTE:Speaks Japanese\\, English.\r\n\ +NOTE:Second note.\r\n\ +CATEGORIES:Design,Tokyo office\r\n\ +CATEGORIES:Speakers\r\n\ +UID:urn:uuid:0d5c7e0a-0000-4000-8000-0000000000a1\r\n\ +X-MAILCRAFT-FAVORITE:true\r\n\ +END:VCARD\r\n"; + + #[test] + fn reads_a_4_0_card() { + let got = parse(V40); + assert_eq!(got.len(), 1); + assert_eq!( + got[0], + Contact { + display_name: "Mei Tanaka".into(), + first: "Mei".into(), + last: "Tanaka".into(), + emails: vec![Labeled::new("work", "mei.tanaka@example.org"), Labeled::new("home", "mei@home.example.org")], + phones: vec![Labeled::new("mobile", "+81-90-5550-0101"), Labeled::new("work", "+81-3-5550-0102;ext=12")], + addresses: vec![PostalAddress { + label: "home".into(), + street: "1-2-3 Sakura".into(), + city: "Minato".into(), + region: "Tokyo".into(), + postal_code: "105-0000".into(), + country: "Japan".into() + }], + websites: vec!["https://example.org/mei".into(), "https://design.example.org/team/mei".into()], + birthday: Some(d(1991, 7, 4)), + notes: "Speaks Japanese, English.\nSecond note.".into(), + categories: vec!["Design".into(), "Tokyo office".into(), "Speakers".into()], + favorite: true, + uid: "urn:uuid:0d5c7e0a-0000-4000-8000-0000000000a1".into(), + ..Default::default() + } + ); + } + + #[test] + fn reads_many_cards_in_order() { + let text = format!("{V21}\r\n{V30}junk between cards\r\n{V40}"); + let names: Vec = parse(&text).into_iter().map(|c| c.display_name).collect(); + assert_eq!(names, ["Dr. Jürgen Müller", "Dr. Nadia Okafor", "Mei Tanaka"]); + // LF only, lower case, no VERSION. + let plain = parse("begin:vcard\nfn:Ada Lovelace\nemail:ada@example.org\nend:vcard\nBEGIN:VCARD\nFN:Grace Hopper\nEND:VCARD\n"); + assert_eq!(plain.len(), 2); + assert_eq!((plain[0].display_name.as_str(), plain[0].emails[0].value.as_str()), ("Ada Lovelace", "ada@example.org")); + } + + #[test] + fn a_missing_name_leaves_the_display_name_empty() { + let c = card("N:Lovelace;Ada;;;\nEMAIL:ada@example.org"); + assert_eq!(c.display_name, ""); + assert_eq!(c.name(), "Ada Lovelace"); + let org = card("ORG:Analytical Engines Ltd"); + assert_eq!((org.display_name.as_str(), org.name().as_str()), ("", "Analytical Engines Ltd")); + // The first FN, N and so on count. + let twice = card("FN:First\nFN:Second\nN:A;B\nN:C;D\nTITLE:One\nTITLE:Two\nUID:1\nUID:2\nBDAY:2000-01-02\nBDAY:1999-01-02"); + assert_eq!( + (twice.display_name.as_str(), twice.last.as_str(), twice.title.as_str(), twice.uid.as_str(), twice.birthday), + ("First", "A", "One", "1", Some(d(2000, 1, 2))) + ); + } + + #[test] + fn labels_come_from_types_and_groups() { + let c = card( + "EMAIL;TYPE=INTERNET,OTHER:o@example.org\nEMAIL;TYPE=x-custom:x@example.org\nEMAIL;TYPE=HOME,WORK:hw@example.org\n\ +TEL;TYPE=HOME,VOICE:1\nTEL;TYPE=WORK,CELL:2\nTEL;TYPE=iPhone:3\nTEL;TYPE=HOME;TYPE=FAX:4\nTEL;TYPE=OTHER:5\nTEL;TYPE=VOICE:6\nTEL:7\n\ +Item7.TEL;TYPE=CELL:8\nITEM7.X-ABLabel:Car\nitem8.TEL:9\nitem8.X-ABLabel:_$!!$_\nitem8.X-ABLabel:Ignored\nX-ABLabel:No group\nitem9.X-ABLabel:Nothing to label\n\ +ADR;TYPE=dom,postal,parcel:;;1 Main St;Riverton\nitem2.ADR:;;2 Side St\nitem2.X-ABLabel:Cabin", + ); + let labels = |list: &[Labeled]| list.iter().map(|l| l.label.clone()).collect::>(); + assert_eq!(labels(&c.emails), ["other", "", "work"]); + assert_eq!(labels(&c.phones), ["home", "mobile", "mobile", "fax", "other", "", "", "Car", "mobile"]); + assert_eq!( + c.addresses.iter().map(|a| (a.label.as_str(), a.street.as_str())).collect::>(), + [("", "1 Main St"), ("Cabin", "2 Side St")] + ); + } + + #[test] + fn names_and_organisations_split_on_unescaped_separators() { + let c = card("N:van der Berg\\; Jr.;Anna\\,Maria;Q.,R.;;\nORG:Semi\\;colon & Co;R\\&D;;Lab 2\nNICKNAME:Annie\\, Am"); + assert_eq!((c.last.as_str(), c.first.as_str(), c.middle.as_str()), ("van der Berg; Jr.", "Anna,Maria", "Q. R.")); + assert_eq!((c.company.as_str(), c.department.as_str()), ("Semi;colon & Co", "R\\&D, Lab 2")); + assert_eq!(c.nickname, "Annie, Am"); + // Fewer parts than the format has, and none at all. + assert_eq!(card("N:Lovelace").last, "Lovelace"); + assert_eq!(card("N:;;;;\nFN:x").first, ""); + assert_eq!(card("ORG:;Only a department").department, "Only a department"); + // In 2.1 a comma is a comma. + let old = parse("BEGIN:VCARD\nVERSION:2.1\nN:Smith, Jr.;John\nADR:;;1 Main St, Apt 4;Riverton\nEND:VCARD\n").remove(0); + assert_eq!((old.last.as_str(), old.addresses[0].street.as_str()), ("Smith, Jr.", "1 Main St, Apt 4")); + } + + #[test] + fn addresses_join_the_lines_above_the_city() { + let c = + card("ADR:PO Box 9;Floor 2;41 Harbor Road,Building C;Riverton;CA;94000;USA\nADR:;;;;;;\nADR;TYPE=HOME:;;;;;;Japan\nADR:;;Just a street"); + assert_eq!(c.addresses.len(), 3); + assert_eq!(c.addresses[0].street, "PO Box 9, Floor 2, 41 Harbor Road, Building C"); + assert_eq!(c.addresses[0].one_line(), "PO Box 9, Floor 2, 41 Harbor Road, Building C, Riverton CA 94000, USA"); + assert_eq!((c.addresses[1].label.as_str(), c.addresses[1].country.as_str()), ("home", "Japan")); + assert_eq!(c.addresses[2].street, "Just a street"); + } + + #[test] + fn birthdays_in_every_form() { + for (text, want) in [ + ("1985-04-12", Some(d(1985, 4, 12))), + ("19850412", Some(d(1985, 4, 12))), + ("1985-04-12T10:30:00Z", Some(d(1985, 4, 12))), + ("19850412T103000", Some(d(1985, 4, 12))), + (" 1985-04-12 10:30 ", Some(d(1985, 4, 12))), + ("--0412", None), + ("1985-02-30", None), + ("spring", None), + ("", None), + ] { + assert_eq!(birthday(text), want, "{text}"); + } + assert_eq!(card("FN:x\nBDAY;VALUE=date:2000-02-29").birthday, Some(d(2000, 2, 29))); + // A later valid one counts when the first is junk. + assert_eq!(card("FN:x\nBDAY:--0412\nBDAY:1985-04-12").birthday, Some(d(1985, 4, 12))); + } + + #[test] + fn favorites_and_single_line_fields() { + for (line, want) in [ + ("X-FAVORITE:TRUE", true), + ("X-MAILCRAFT-FAVORITE:true", true), + ("X-FAVORITE:1", true), + ("X-FAVORITE: yes ", true), + ("X-FAVORITE:FALSE", false), + ("X-FAVORITE:", false), + ] { + assert_eq!(card(&format!("FN:x\n{line}")).favorite, want, "{line}"); + } + assert!(card("FN:x\nX-FAVORITE:TRUE\nX-FAVORITE:FALSE").favorite); + // Line breaks have no place in a name, an address or a number. + let c = + card("FN: Ada\\nLovelace \nEMAIL: ada@example.org \nTEL:+1 555\\n0100\nURL: https://example.org \nUID: abc \nCATEGORIES: a , ,b\\nc "); + assert_eq!(c.display_name, "Ada Lovelace"); + assert_eq!( + (c.emails[0].value.as_str(), c.phones[0].value.as_str(), c.websites[0].as_str(), c.uid.as_str()), + ("ada@example.org", "+1 555 0100", "https://example.org", "abc") + ); + assert_eq!(c.categories, ["a", "b c"]); + // Empty values are not entries. + let empty = card("FN:x\nEMAIL:\nEMAIL;TYPE=WORK: \nTEL:\nURL:\nNOTE:\nCATEGORIES:,,"); + assert!( + empty.emails.is_empty() && empty.phones.is_empty() && empty.websites.is_empty() && empty.categories.is_empty() && empty.notes.is_empty() + ); + } + + #[test] + fn base64_text_and_unknown_encodings() { + // "Hello, world" as an old 2.1 writer and a 3.0 writer encode it. + assert_eq!(card("NOTE;ENCODING=BASE64:SGVsbG8sIHdvcmxk").notes, "Hello, world"); + assert_eq!(card("NOTE;ENCODING=b:SGVsbG8s\n IHdvcmxk").notes, "Hello, world"); + assert_eq!(card("NOTE;ENCODING=8BIT:as it is").notes, "as it is"); + assert_eq!(card("FN:x\nNOTE;ENCODING=b:!!!").notes, ""); + // Quoted-printable in a named Western charset, and in none. + assert_eq!(card("FN;CHARSET=windows-1252;ENCODING=QUOTED-PRINTABLE:Zo=EB =96 caf=E9").display_name, "Zoë – café"); + assert_eq!(card("FN;QUOTED-PRINTABLE:Zo=EB").display_name, "Zoë"); + assert_eq!(card("FN;QUOTED-PRINTABLE:Zo=C3=AB").display_name, "Zoë"); + } + + #[test] + fn central_european_charsets() { + // A 2.1 card from a Central European phone or mail program, in Windows-1250 and in + // ISO-8859-2, was read as Windows-1252 or UTF-8. + let cards = parse( + "BEGIN:VCARD\r\n\ +VERSION:2.1\r\n\ +N;CHARSET=windows-1250;ENCODING=QUOTED-PRINTABLE:=8Eagar;=D0ur=F0ica;;;\r\n\ +FN;CHARSET=windows-1250;ENCODING=QUOTED-PRINTABLE:=D0ur=F0ica =8Eagar\r\n\ +ORG;CHARSET=windows-1250;ENCODING=QUOTED-PRINTABLE:Gvo=9E=F0e d.o.o.\r\n\ +NOTE;CHARSET=windows-1250;ENCODING=QUOTED-PRINTABLE:We=92ve met =96 twice, in =8Aibenik =\r\n\ +and =C8akovec.\r\n\ +EMAIL;INTERNET:durdica@example.org\r\n\ +END:VCARD\r\n\ +BEGIN:VCARD\r\n\ +VERSION:2.1\r\n\ +N;CHARSET=ISO-8859-2;ENCODING=QUOTED-PRINTABLE:Kova=E8i=E6;=AEeljko;;;\r\n\ +FN;CHARSET=ISO-8859-2;ENCODING=QUOTED-PRINTABLE:=AEeljko Kova=E8i=E6\r\n\ +TITLE;CHARSET=iso-8859-2;ENCODING=QUOTED-PRINTABLE:Gvo=BE=F0e i =B9ljunak\r\n\ +EMAIL;INTERNET:zeljko@example.org\r\n\ +END:VCARD\r\n", + ); + assert_eq!(cards.len(), 2); + let (first, second) = (&cards[0], &cards[1]); + assert_eq!((first.display_name.as_str(), first.first.as_str(), first.last.as_str()), ("Đurđica Žagar", "Đurđica", "Žagar")); + assert_eq!(first.company, "Gvožđe d.o.o."); + assert_eq!(first.notes, "We’ve met – twice, in Šibenik and Čakovec."); + assert_eq!((second.display_name.as_str(), second.first.as_str(), second.last.as_str()), ("Željko Kovačić", "Željko", "Kovačić")); + assert_eq!(second.title, "Gvožđe i šljunak"); + // A set no standard names is read as UTF-8, as mail is. + assert_eq!(card("FN;CHARSET=x-unknown;ENCODING=QUOTED-PRINTABLE:Zo=C3=AB").display_name, "Zoë"); + } + + #[test] + fn raw_8_bit_values_are_read_in_their_charset() { + // Raw Windows-1250 bytes (not quoted-printable) were read as UTF-8 before the charset + // was looked at, and đ ć č Š became U+FFFD. + let cards = parse_bytes( + b"BEGIN:VCARD\r\nVERSION:2.1\r\n\ +N;CHARSET=WINDOWS-1250:Gvo\xf0\xe6i\xe8;Ivana;;;\r\n\ +FN;CHARSET=WINDOWS-1250:Ivana Gvo\xf0\xe6i\xe8\r\n\ +ORG;CHARSET=WINDOWS-1250:\x8akola \xe8e\x9a\xe6e\r\n\ +NOTE;CHARSET=\"iso-8859-2\":Gvo\xbe\xf0e\r\n \xae\xb9\xe8\xe6\r\n\ +TITLE;CHARSET=windows-1250;ENCODING=QUOTED-PRINTABLE:=8Aef\r\n\ +X-SOMETHING:\xff\r\n\ +EMAIL;INTERNET:ivana@example.org\r\n\ +END:VCARD\r\n", + ); + assert_eq!(cards.len(), 1); + let c = &cards[0]; + assert_eq!((c.display_name.as_str(), c.last.as_str(), c.first.as_str()), ("Ivana Gvođćič", "Gvođćič", "Ivana")); + assert_eq!(c.company, "Škola češće"); + // A folded line goes on in the charset of the property it continues (2.1 keeps the space). + assert_eq!(c.notes, "Gvožđe Žščć"); + assert_eq!(c.title, "Šef"); + assert_eq!(c.emails[0].value, "ivana@example.org"); + // Without a charset: UTF-8 when it is UTF-8, else Windows-1252; in UTF-8 nothing changes. + assert_eq!(parse_bytes(b"BEGIN:VCARD\nFN:Zo\xc3\xab\nEND:VCARD")[0].display_name, "Zoë"); + assert_eq!(parse_bytes(b"BEGIN:VCARD\nFN:Zo\xeb \x96 caf\xe9\nEND:VCARD")[0].display_name, "Zoë – café"); + assert_eq!(parse_bytes("\u{feff}BEGIN:VCARD\r\nFN;CHARSET=UTF-8:Đurđica\r\nEND:VCARD".as_bytes())[0].display_name, "Đurđica"); + // A file in UTF-16 with its byte order mark. + let utf16: Vec = "\u{feff}BEGIN:VCARD\r\nFN:Željko\r\nEND:VCARD\r\n".encode_utf16().flat_map(u16::to_le_bytes).collect(); + assert_eq!(parse_bytes(&utf16)[0].display_name, "Željko"); + // Bytes and text give the same cards. + let text = crate::write(&cards.iter().collect::>()); + assert_eq!(parse_bytes(text.as_bytes()), parse(&text)); + } + + #[test] + fn skipped_properties_cost_nothing() { + let photo = "A".repeat(3 << 20); + let c = card(&format!( + "FN:Ada\nPHOTO;ENCODING=b;TYPE=JPEG:{photo}\nLOGO;VALUE=uri:https://example.org/logo.png\nSOUND;ENCODING=QUOTED-PRINTABLE:=41=42\nKEY;TYPE=PGP:{photo}\nX-UNKNOWN;ENCODING=b:{photo}\nTITLE:After" + )); + assert_eq!((c.display_name.as_str(), c.title.as_str()), ("Ada", "After")); + assert_eq!(c, Contact { display_name: "Ada".into(), title: "After".into(), ..Default::default() }); + } + + #[test] + fn junk_gives_an_empty_list() { + for junk in [ + "", + "\r\n\r\n", + "hello", + "BEGIN", + "BEGIN:", + "END:VCARD", + "BEGIN:VCARD", + "BEGIN:VCARD\nEND:VCARD", + "BEGIN:VCARD\nVERSION:3.0\nN:;;;;\nFN:\nEND:VCARD", + "FN:Nobody\nEMAIL:n@example.org", + "\u{0}\u{1}\u{2}\u{fffd}PK\u{3}\u{4}", + "::::;;;;====", + "BEGIN:VCALENDAR\nBEGIN:VEVENT\nSUMMARY:x\nEND:VEVENT\nEND:VCALENDAR", + ] { + assert!(parse(junk).is_empty(), "{junk:?}"); + } + let binary: String = (0u32..2000).filter_map(|i| char::from_u32(i.wrapping_mul(2_654_435_761) % 0x11_0000)).collect(); + assert!(parse(&binary).is_empty()); + } + + #[test] + fn a_missing_end_loses_nothing() { + // The text stops in the middle of the second card. + let cut = parse("BEGIN:VCARD\nFN:Ada\nEND:VCARD\nBEGIN:VCARD\nFN:Grace\nEMAIL:grace@exam"); + assert_eq!(cut.iter().map(|c| c.display_name.as_str()).collect::>(), ["Ada", "Grace"]); + assert_eq!(cut[1].emails[0].value, "grace@exam"); + // A card that never ends, and two that do: each keeps its own lines, in the order they began. + let run_on = parse("BEGIN:VCARD\nFN:Ada\nBEGIN:VCARD\nFN:Grace\nTITLE:Admiral\nEND:VCARD\nBEGIN:VCARD\nFN:Mei\nEND:VCARD\n"); + assert_eq!( + run_on.iter().map(|c| (c.display_name.as_str(), c.title.as_str())).collect::>(), + [("Ada", ""), ("Grace", "Admiral"), ("Mei", "")] + ); + } + + #[test] + fn nested_cards_and_foreign_components_are_contained() { + // A 2.1 AGENT holds a whole card; the outer card goes on after it. + let agent = parse( + "BEGIN:VCARD\nVERSION:2.1\nFN:Nadia Okafor\nAGENT:\nBEGIN:VCARD\nVERSION:2.1\nFN:Tomas Lindqvist\nTEL;WORK:+1 555 0100\nEND:VCARD\nTITLE:Director\nEND:VCARD\n", + ); + assert_eq!(agent.len(), 2); + assert_eq!((agent[0].display_name.as_str(), agent[0].title.as_str(), agent[0].phones.len()), ("Nadia Okafor", "Director", 0)); + assert_eq!((agent[1].display_name.as_str(), agent[1].title.as_str(), agent[1].phones.len()), ("Tomas Lindqvist", "", 1)); + // Something that isn't a card keeps its lines to itself, ended or not. + let foreign = parse( + "BEGIN:VCARD\nFN:Ada\nBEGIN:X-EXTRA\nTITLE:Inner\nBEGIN:X-DEEPER\nNOTE:Inner\nEND:X-DEEPER\nEND:X-EXTRA\nTITLE:Outer\nBEGIN:X-OPEN\nNOTE:Inner\nEND:VCARD\n", + ); + assert_eq!(foreign, [Contact { display_name: "Ada".into(), title: "Outer".into(), ..Default::default() }]); + // Stray ENDs, and nesting deeper than is followed: every card still comes out once. + assert!(parse("END:VCARD\nEND:VCARD\nEND:X\n").is_empty()); + let deep: String = (0..50).map(|i| format!("BEGIN:VCARD\nFN:Card {i}\n")).collect(); + let got = parse(&deep); + assert_eq!(got.len(), 50); + assert_eq!(got.iter().map(|c| c.display_name.clone()).collect::>(), (0..50).map(|i| format!("Card {i}")).collect::>()); + } + + #[test] + fn sizes_and_counts_are_capped() { + let note = "é".repeat(1 << 20); + let c = card(&format!("FN:{}\nNOTE:{note}", "x".repeat(3 << 20))); + assert!(c.display_name.len() <= 1 << 20 && c.display_name.len() > 1_000_000); + assert!(c.notes.len() <= 1 << 20); + let crowded = card(&format!( + "FN:x\n{}{}{}{}CATEGORIES:{}\n{}", + "EMAIL:someone@example.org\n".repeat(MAX_ITEMS + 20), + "TEL:+1 555 0100\n".repeat(MAX_ITEMS + 20), + "ADR:;;1 Main St\n".repeat(MAX_ITEMS + 20), + "URL:https://example.org\n".repeat(MAX_ITEMS + 20), + "a,".repeat(MAX_CATEGORIES + 20), + (0..MAX_LABELS + 20).map(|i| format!("g{i}.X-ABLabel:L{i}\n")).collect::(), + )); + assert_eq!( + (crowded.emails.len(), crowded.phones.len(), crowded.addresses.len(), crowded.websites.len(), crowded.categories.len()), + (MAX_ITEMS, MAX_ITEMS, MAX_ITEMS, MAX_ITEMS, MAX_CATEGORIES) + ); + let many = "BEGIN:VCARD\nFN:x\nEND:VCARD\n".repeat(MAX_CARDS + 10); + assert_eq!(parse(&many).len(), MAX_CARDS); + } +} diff --git a/crates/vcard/src/tests.rs b/crates/vcard/src/tests.rs new file mode 100644 index 000000000..22ee050a0 --- /dev/null +++ b/crates/vcard/src/tests.rs @@ -0,0 +1,391 @@ +//! Whole-crate properties: what is written reads back the same, and no text makes the reader panic. + +use crate::{Contact, Labeled, PostalAddress}; +use chrono::NaiveDate; +use proptest::prelude::*; + +use crate::{parse, write}; + +/// What reading back gives for a written contact: the name the card was written under. +fn as_read(c: &Contact) -> Contact { + Contact { display_name: c.name(), ..c.clone() } +} + +fn round_trip(contacts: &[Contact]) -> Vec { + parse(&write(&contacts.iter().collect::>())) +} + +fn sample_contacts() -> Vec { + let nadia = Contact { + display_name: "Dr. Nadia Okafor".into(), + first: "Nadia".into(), + middle: "Chidi Rose".into(), + last: "Okafor".into(), + nickname: "Nadi, \"the planner\"".into(), + company: "Example Research, Inc.".into(), + title: "Lead Scientist; Field".into(), + department: "Field Lab \\ Unit 7".into(), + emails: vec![ + Labeled::new("work", "nadia.okafor@example.org"), + Labeled::new("", "nadia@example.org"), + Labeled::new("Family", "nadia@family.example.org"), + Labeled::new("mobile", "nadia@phone.example.org"), + ], + phones: vec![ + Labeled::new("mobile", "+1 (555) 010-0142"), + Labeled::new("work", "+1 555 010 0143"), + Labeled::new("home", "+1 555 010 0144"), + Labeled::new("fax", "+1 555 010 0145"), + Labeled::new("pager", "+1 555 010 0146"), + Labeled::new("other", "+1 555 010 0147"), + Labeled::new("", "+1 555 010 0148"), + Labeled::new("Car; old, blue", "+1 555 010 0149"), + ], + addresses: vec![ + PostalAddress { + label: "work".into(), + street: "Suite 300, 41 Harbor Road".into(), + city: "Riverton".into(), + region: "CA".into(), + postal_code: "94000".into(), + country: "USA".into(), + }, + PostalAddress { label: "home".into(), street: "7; Rue de l'Étang".into(), city: "Saint-Rémy".into(), ..Default::default() }, + PostalAddress { label: "Cabin".into(), country: "Norway".into(), ..Default::default() }, + PostalAddress { postal_code: "12345".into(), ..Default::default() }, + ], + websites: vec!["https://example.org/~nadia?a=1,2;b=3".into(), "example.org".into()], + birthday: NaiveDate::from_ymd_opt(1985, 4, 12), + notes: "Met at the 2024 symposium.\nPrefers e-mail, not calls; never on Fridays.\n\n\tC:\\notes\\nadia.txt\n".into(), + categories: vec!["Research".into(), "Field Team, West".into()], + favorite: true, + uid: "7f1c2f6e-0001-4a5b-9c3d-000000000042".into(), + ..Default::default() + }; + let unnamed = + Contact { first: "Jürgen".into(), last: "Müller".into(), phones: vec![Labeled::new("mobile", "+49 170 5550101")], ..Default::default() }; + let company = + Contact { company: "東京デザイン株式会社".into(), websites: vec!["https://design.example.org".into()], ..Default::default() }; + let address_only = Contact { emails: vec![Labeled::new("other", "someone@example.org")], ..Default::default() }; + let bare = Contact { favorite: true, ..Default::default() }; + let emoji = Contact { + display_name: "Zoë 🎉 “Zed” Ødegård".into(), + notes: " leading and trailing spaces stay ".into(), + birthday: NaiveDate::from_ymd_opt(2000, 2, 29), + ..Default::default() + }; + vec![nadia, unnamed, company, address_only, bare, emoji] +} + +#[test] +fn sample_contacts_round_trip() { + let contacts = sample_contacts(); + let back = round_trip(&contacts); + assert_eq!(back, contacts.iter().map(as_read).collect::>()); + assert_eq!(back[1].display_name, "Jürgen Müller"); + assert_eq!(back[3].display_name, "someone@example.org"); + assert_eq!(back[4].display_name, ""); + // What was read writes the same text again. + let text = write(&back.iter().collect::>()); + assert_eq!(parse(&text), back); + assert_eq!(write(&parse(&text).iter().collect::>()), text); +} + +#[test] +fn an_empty_contact_does_not_come_back() { + assert!(round_trip(&[Contact::default(), Contact::default()]).is_empty()); + // Entries with nothing in them are left out. + let hollow = Contact { + display_name: "Ada".into(), + emails: vec![Labeled::new("work", ""), Labeled::new("home", "ada@example.org")], + phones: vec![Labeled::new("mobile", " ")], + addresses: vec![PostalAddress { label: "home".into(), ..Default::default() }], + websites: vec![String::new()], + categories: vec![" ".into()], + ..Default::default() + }; + let back = round_trip(std::slice::from_ref(&hollow)); + assert_eq!(back, [Contact { display_name: "Ada".into(), emails: vec![Labeled::new("home", "ada@example.org")], ..Default::default() }]); +} + +#[test] +fn cards_from_other_programs_survive_a_round_trip() { + // A 2.1 card read, written as 3.0 and read again says the same. + let old = "BEGIN:VCARD\r\nVERSION:2.1\r\nN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:M=C3=BCller;J=C3=BCrgen\r\nTEL;WORK;VOICE:+49 30 5550100\r\nTEL;CELL:+49 170 5550101\r\n\ +EMAIL;PREF;INTERNET:jm@example.org\r\nADR;HOME:;;Gartenweg 12, Hinterhaus;Berlin;;10115;Deutschland\r\nNOTE;ENCODING=QUOTED-PRINTABLE:Zeile eins=0D=0AZeile =\r\nzwei\r\nEND:VCARD\r\n"; + let first = parse(old); + assert_eq!(first.len(), 1); + assert_eq!(first[0].notes, "Zeile eins\nZeile zwei"); + assert_eq!(first[0].addresses[0].street, "Gartenweg 12, Hinterhaus"); + assert_eq!(round_trip(&first), first.iter().map(as_read).collect::>()); +} + +/// One line of text as a contact field holds it: printable, trimmed. +fn line() -> impl Strategy { + prop_oneof!["(\\PC|[;,\\\\:\"^=.]){0,24}", "[ -~]{0,60}", Just(String::new())].prop_map(|s| s.trim().to_string()) +} + +/// A line with something in it: an empty one gets a character. +fn filled_line() -> impl Strategy { + (line(), "[!-~]").prop_map(|(line, fallback)| if line.is_empty() { fallback } else { line }) +} + +fn label(known: &'static [&'static str]) -> impl Strategy { + prop_oneof![proptest::sample::select(known).prop_map(str::to_string), Just(String::new()), line()] +} + +fn date() -> impl Strategy { + (1i32..=9999, 1u32..=12, 1u32..=28).prop_map(|(y, m, day)| NaiveDate::from_ymd_opt(y, m, day).unwrap_or_default()) +} + +fn address() -> impl Strategy { + // One part, any of them, always says something. + (label(&["work", "home", "other"]), [line(), line(), line(), line(), line()], 0usize..5, filled_line()).prop_map( + |(label, mut parts, filled, text)| { + parts[filled] = text; + let [street, city, region, postal_code, country] = parts; + PostalAddress { label, street, city, region, postal_code, country } + }, + ) +} + +fn contact() -> impl Strategy { + let names = (line(), line(), line(), line(), line(), line(), line(), line()); + let emails = proptest::collection::vec((label(&["work", "home", "other"]), filled_line()), 0..4); + let phones = proptest::collection::vec((label(&["mobile", "work", "home", "fax", "pager", "other"]), filled_line()), 0..4); + let lists = ( + emails, + phones, + proptest::collection::vec(address(), 0..3), + proptest::collection::vec(filled_line(), 0..3), + proptest::collection::vec(filled_line(), 0..3), + ); + let rest = (proptest::option::of(date()), "(\\PC|[\n\t;,\\\\:]){0,120}", any::(), line()); + (names, lists, rest).prop_map(|(names, lists, rest)| { + let (display_name, first, middle, last, nickname, company, title, department) = names; + let (emails, phones, addresses, websites, categories) = lists; + let (birthday, notes, favorite, uid) = rest; + let labeled = |list: Vec<(String, String)>| list.into_iter().map(|(label, value)| Labeled { label, value }).collect(); + Contact { + display_name, + first, + middle, + last, + nickname, + company, + title, + department, + emails: labeled(emails), + phones: labeled(phones), + addresses, + websites, + birthday, + notes, + categories, + favorite, + uid, + ..Default::default() + } + }) +} + +/// Text that looks like a card without being one. +fn soup() -> impl Strategy { + let piece = prop_oneof![ + proptest::sample::select(vec![ + "BEGIN:VCARD", + "END:VCARD", + "BEGIN:", + "END:", + "BEGIN:X", + "END:X", + "VERSION:2.1", + "VERSION:3.0", + "VERSION:4.0", + "FN", + "N", + "NICKNAME", + "ORG", + "TITLE", + "EMAIL", + "TEL", + "ADR", + "URL", + "BDAY", + "NOTE", + "CATEGORIES", + "UID", + "PHOTO", + "X-ABLabel", + "X-FAVORITE", + "item1.", + "item2.", + ".", + ":", + ";", + ",", + "=", + "\"", + "\\", + "\r\n", + "\n", + "\r\n ", + "\n\t", + " ", + "=\r\n", + "=\n", + "=C3=A9", + "=C3", + "=ZZ", + "\\n", + "\\;", + "\\,", + ";TYPE=WORK,VOICE", + ";TYPE=\"cell,pref\"", + ";HOME", + ";CELL", + ";ENCODING=QUOTED-PRINTABLE", + ";QUOTED-PRINTABLE", + ";ENCODING=b", + ";BASE64", + ";CHARSET=ISO-8859-1", + ";CHARSET=UTF-8", + ";CHARSET=x", + "mailto:", + "tel:", + "a@example.org", + "+1 555 0100", + "1985-04-12", + "19850412T101010Z", + "--0412", + "0000-00-00", + "TRUE", + "SGVsbG8=", + "_$!!$_", + "_$!<", + ]) + .prop_map(str::to_string), + "\\PC{0,6}", + any::(), + ]; + proptest::collection::vec(piece, 0..60).prop_map(|pieces| pieces.concat()) +} + +fn valid_text() -> String { + write(&sample_contacts().iter().collect::>()) +} + +/// Whatever the reader gives must also be writable and readable again. +fn survives(text: &str) -> Vec { + let contacts = parse(text); + let again = write(&contacts.iter().collect::>()); + let _ = parse(&again); + contacts +} + +proptest! { + #[test] + fn any_contact_round_trips(contacts in proptest::collection::vec(contact(), 0..4)) { + let back = round_trip(&contacts); + // A contact with nothing in it isn't written back as one. + let want: Vec = contacts.iter().map(as_read).filter(|c| *c != Contact::default()).collect(); + prop_assert_eq!(back, want); + } + + #[test] + fn any_notes_and_names_round_trip(notes in "(\\PC|[\n\t]){0,400}", name in "\\PC{0,200}", street in "\\PC{0,100}") { + let name = name.trim().to_string(); + let street = street.trim().to_string(); + let c = Contact { display_name: name.clone(), last: name.clone(), company: name.clone(), notes, addresses: vec![PostalAddress { street, city: "Riverton".into(), ..Default::default() }], uid: "u".into(), ..Default::default() }; + prop_assert_eq!(round_trip(std::slice::from_ref(&c)), vec![as_read(&c)]); + } + + #[test] + fn text_with_control_characters_reads_back_clean_and_stable(name in any::(), notes in any::(), label in any::(), value in any::(), category in any::()) { + let c = Contact { + display_name: name.clone(), + first: name, + notes, + emails: vec![Labeled::new(label.clone(), value.clone())], + phones: vec![Labeled::new(label.clone(), value.clone())], + addresses: vec![PostalAddress { label, street: value.clone(), ..Default::default() }], + websites: vec![value], + categories: vec![category], + uid: "u".into(), + ..Default::default() + }; + let once = round_trip(std::slice::from_ref(&c)); + prop_assert_eq!(once.len(), 1); + // The first pass cleans (control characters, stray spaces); after that nothing changes but a + // display name that was empty. + prop_assert_eq!(round_trip(&once), once.iter().map(as_read).collect::>()); + prop_assert!(!once[0].display_name.contains(['\r', '\n']) && !once[0].notes.contains('\r')); + } + + #[test] + fn arbitrary_text_never_panics(text in any::()) { + survives(&text); + } + + #[test] + fn arbitrary_bytes_never_panic(bytes in proptest::collection::vec(any::(), 0..2048)) { + let contacts = crate::parse_bytes(&bytes); + let _ = parse(&write(&contacts.iter().collect::>())); + } + + #[test] + fn card_shaped_bytes_never_panic(text in soup(), high in proptest::collection::vec((any::(), 0x80u8..=0xFF), 0..12), charset in proptest::sample::select(vec!["", "windows-1250", "UTF-8", "utf-16", "iso-2022-jp", "shift_jis", "x-unknown"])) { + // Card-shaped text with a charset named and raw 8-bit bytes dropped in. + let mut bytes = text.replace("FN:", &format!("FN;CHARSET={charset}:")).into_bytes(); + for (at, byte) in high { + if !bytes.is_empty() { + let i = at.index(bytes.len()); + bytes.insert(i, byte); + } + } + let _ = crate::parse_bytes(&bytes); + } + + #[test] + fn utf8_bytes_read_as_the_text_does(text in soup()) { + // (A value in UTF-8 that says it is Latin-1 is read as Latin-1 from bytes.) + let text = text.replace("ISO-8859-1", "UTF-8"); + prop_assert_eq!(crate::parse_bytes(text.as_bytes()), parse(&text)); + } + + #[test] + fn card_shaped_junk_never_panics(text in soup()) { + survives(&text); + } + + #[test] + fn a_damaged_card_never_panics(cuts in proptest::collection::vec((any::(), 0usize..40, 0u8..5, "\\PC{0,8}|[\r\n:;,=\"\\\\ .]{1,4}"), 1..6)) { + let mut chars: Vec = valid_text().chars().collect(); + for (index, length, kind, junk) in cuts { + let from = index.index(chars.len().max(1)).min(chars.len()); + let to = from.saturating_add(length).min(chars.len()); + match kind { + // Cut a piece out, overwrite it, insert junk, double a piece, or stop the text there. + 0 => drop(chars.drain(from..to)), + 1 => drop(chars.splice(from..to, junk.chars())), + 2 => drop(chars.splice(from..from, junk.chars())), + 3 => { + let piece: Vec = chars[from..to].to_vec(); + drop(chars.splice(from..from, piece)); + } + _ => chars.truncate(from), + } + } + let damaged: String = chars.into_iter().collect(); + prop_assert!(survives(&damaged).len() <= 64); + } +} + +#[test] +fn a_card_cut_anywhere_never_panics() { + let text = valid_text(); + for (cut, _) in text.char_indices().step_by(5) { + survives(&text[..cut]); + survives(&text[cut..]); + } +} diff --git a/crates/vcard/src/text.rs b/crates/vcard/src/text.rs new file mode 100644 index 000000000..a82228b38 --- /dev/null +++ b/crates/vcard/src/text.rs @@ -0,0 +1,239 @@ +//! Text values: cleaning, escaping, splitting, and the 2.1 encodings (quoted-printable, base64; +//! a `CHARSET` is read by `craft_mime::charset`, as mail is). + +/// A one-line field: line breaks and other control characters become spaces, and the ends are +/// trimmed. +pub(crate) fn single(s: &str) -> String { + let spaced: String = s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); + spaced.trim().to_string() +} + +/// Text of several lines: `\r\n` and `\r` become `\n`; other control characters except tab are +/// dropped. +pub(crate) fn multi(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut after_cr = false; + for c in s.chars() { + let cr = c == '\r'; + match c { + '\n' if after_cr => {} + '\r' | '\n' => out.push('\n'), + '\t' => out.push(c), + c if c.is_control() => {} + c => out.push(c), + } + after_cr = cr; + } + out +} + +/// A value ready to write: `\`, `;`, `,` and line breaks escaped. +pub(crate) fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len().saturating_add(8)); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + ';' => out.push_str("\\;"), + ',' => out.push_str("\\,"), + '\n' => out.push_str("\\n"), + '\r' => {} + c => out.push(c), + } + } + out +} + +/// Undo [`escape`]: `\n` and `\N` are line breaks, `\\`, `\;`, `\,` (and the `\:` some writers +/// add) their second character; any other backslash is kept. +pub(crate) fn unescape(s: &str) -> String { + if !s.contains('\\') { + return s.to_string(); + } + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n' | 'N') => out.push('\n'), + Some(x @ ('\\' | ';' | ',' | ':')) => out.push(x), + Some(x) => { + out.push('\\'); + out.push(x); + } + None => out.push('\\'), + } + } + out +} + +/// The first `max` pieces of `s`, split on its unescaped `separator`s; the pieces are still +/// escaped. +pub(crate) fn split(s: &str, separator: char, max: usize) -> Vec<&str> { + let mut out = Vec::new(); + let (mut start, mut escaped) = (0usize, false); + for (i, c) in s.char_indices() { + if out.len() >= max { + return out; + } + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == separator { + out.push(s.get(start..i).unwrap_or("")); + start = i.saturating_add(c.len_utf8()); + } + } + if out.len() < max { + out.push(s.get(start..).unwrap_or("")); + } + out +} + +/// One component of a structured value (a name part, a street) as one line of text. vCard 3.0 and +/// 4.0 let a component list several values with commas, which are joined with `joiner`; in 2.1 +/// (`v21`) a comma is just a comma. +pub(crate) fn component(piece: &str, joiner: &str, v21: bool) -> String { + let values = if v21 { vec![piece] } else { split(piece, ',', 32) }; + match values.as_slice() { + [one] => single(&unescape(one)), + many => many.iter().map(|v| single(&unescape(v))).filter(|v| !v.is_empty()).collect::>().join(joiner), + } +} + +/// The bytes of a quoted-printable value (`=C3=A9`); soft line breaks are already gone, and a `=` +/// that isn't followed by two hex digits is kept. +pub(crate) fn quoted_printable(s: &str) -> Vec { + let bytes = s.as_bytes(); + let hex = |at: usize| bytes.get(at).and_then(|b| char::from(*b).to_digit(16)).and_then(|d| u8::try_from(d).ok()); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0usize; + while let Some(&b) = bytes.get(i) { + if b == b'=' + && let (Some(high), Some(low)) = (hex(i.saturating_add(1)), hex(i.saturating_add(2))) + { + out.push(high.saturating_mul(16).saturating_add(low)); + i = i.saturating_add(3); + } else { + out.push(b); + i = i.saturating_add(1); + } + } + out +} + +/// The bytes of a base64 value, white space and padding or not; empty for junk. +pub(crate) fn base64_bytes(s: &str) -> Vec { + let compact: String = s.chars().filter(|c| !c.is_whitespace()).collect(); + craft_mime::base64::STANDARD_NO_PAD.decode(compact.trim_end_matches('=')).unwrap_or_default() +} + +/// Whether `c` is one of Unicode's format characters (general category Cf, Unicode 17.0): +/// bidirectional marks, zero-width marks and joiners, the byte-order mark, the soft hyphen, tags +/// and the rest. They show nothing and can turn the text around them. +pub(crate) fn is_format(c: char) -> bool { + matches!( + c, + '\u{00ad}' + | '\u{0600}'..='\u{0605}' + | '\u{061c}' + | '\u{06dd}' + | '\u{070f}' + | '\u{0890}'..='\u{0891}' + | '\u{08e2}' + | '\u{180e}' + | '\u{200b}'..='\u{200f}' + | '\u{202a}'..='\u{202e}' + | '\u{2060}'..='\u{2064}' + | '\u{2066}'..='\u{206f}' + | '\u{feff}' + | '\u{fff9}'..='\u{fffb}' + | '\u{110bd}' + | '\u{110cd}' + | '\u{13430}'..='\u{1343f}' + | '\u{1bca0}'..='\u{1bca3}' + | '\u{1d173}'..='\u{1d17a}' + | '\u{e0001}' + | '\u{e0020}'..='\u{e007f}' + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cleans_one_line_and_many_line_text() { + assert_eq!(single(" Ada\r\nLovelace\t\u{0}x "), "Ada Lovelace x"); + assert_eq!(single("\n\u{85}\u{7f} "), ""); + assert_eq!(multi("a\r\nb\rc\n\nd\u{0}\u{7f}\te "), "a\nb\nc\n\nd\te "); + assert_eq!(multi(""), ""); + } + + #[test] + fn escapes_and_unescapes() { + assert_eq!(escape("Research, Inc.; Lab \\ 7\nSecond\r\n"), "Research\\, Inc.\\; Lab \\\\ 7\\nSecond\\n"); + assert_eq!(unescape("Research\\, Inc.\\; Lab \\\\ 7\\nSecond\\NThird"), "Research, Inc.; Lab \\ 7\nSecond\nThird"); + assert_eq!(unescape("http\\://example.org C:\\Users\\x tail\\"), "http://example.org C:\\Users\\x tail\\"); + assert_eq!(unescape("plain"), "plain"); + } + + #[test] + fn splits_on_unescaped_separators() { + assert_eq!(split("Okafor;Nadia;;Dr.;", ';', 9), ["Okafor", "Nadia", "", "Dr.", ""]); + assert_eq!(split("a\\;b;c\\\\;d", ';', 9), ["a\\;b", "c\\\\", "d"]); + assert_eq!(split("a,b,c", ',', 2), ["a", "b"]); + assert_eq!(split("", ';', 9), [""]); + assert!(split("a;b", ';', 0).is_empty()); + assert_eq!(split("é;東;🎉", ';', 9), ["é", "東", "🎉"]); + } + + #[test] + fn components_join_their_lists() { + assert_eq!(component("Quinlan,Paul", " ", false), "Quinlan Paul"); + assert_eq!(component("Quinlan\\,Paul", " ", false), "Quinlan,Paul"); + assert_eq!(component(" 41 Harbor Road , Suite 300,, ", ", ", false), "41 Harbor Road, Suite 300"); + assert_eq!(component("Smith, Jr.", " ", true), "Smith, Jr."); + assert_eq!(component(" one\\nline ", " ", false), "one line"); + assert_eq!(component("", ", ", false), ""); + } + + #[test] + fn decodes_quoted_printable() { + assert_eq!(quoted_printable("J=C3=BCrgen M=c3=bcller"), "Jürgen Müller".as_bytes()); + assert_eq!(quoted_printable("a=3Db=0D=0Ac"), b"a=b\r\nc"); + // What isn't an escape stays. + assert_eq!(quoted_printable("1+1=2 =ZZ =4"), b"1+1=2 =ZZ =4"); + assert_eq!(quoted_printable("="), b"="); + assert_eq!(quoted_printable("é=41"), "éA".as_bytes()); + } + + #[test] + fn decodes_base64() { + assert_eq!(base64_bytes("SGVsbG8sIHdvcmxk"), b"Hello, world"); + assert_eq!(base64_bytes(" SGVs\r\n bG8=\n"), b"Hello"); + assert_eq!(base64_bytes("SGVsbG8"), b"Hello"); + assert!(base64_bytes("not base64!").is_empty()); + assert!(base64_bytes("").is_empty()); + } + + proptest::proptest! { + #[test] + fn clean_text_survives_escaping(s in "(\\PC|[\n\t;,\\\\:]){0,80}") { + proptest::prop_assert_eq!(unescape(&escape(&s)), s.clone()); + // And as one piece of a structured value or a list. + proptest::prop_assert_eq!(split(&format!("{};x", escape(&s)), ';', 9).first().map(|p| unescape(p)), Some(s.clone())); + proptest::prop_assert_eq!(split(&format!("{},x", escape(&s)), ',', 9).first().map(|p| unescape(p)), Some(s)); + } + + #[test] + fn text_helpers_never_panic(s in proptest::prelude::any::(), max in 0usize..5) { + let _ = (single(&s), multi(&s), unescape(&s), split(&s, ';', max), component(&s, ", ", false), quoted_printable(&s), base64_bytes(&s)); + proptest::prop_assert!(!escape(&multi(&s)).contains(['\r', '\n'])); + proptest::prop_assert!(!single(&s).contains(['\r', '\n'])); + } + } +} diff --git a/crates/vcard/src/write.rs b/crates/vcard/src/write.rs new file mode 100644 index 000000000..3d601eca3 --- /dev/null +++ b/crates/vcard/src/write.rs @@ -0,0 +1,326 @@ +//! Writing contacts as vCard 3.0. + +use crate::Contact; +use chrono::{Datelike, NaiveDate}; + +use crate::lines::fold; +use crate::text::{escape, multi, single}; + +/// Write vCard 3.0 cards, CRLF line endings, lines folded at 75 octets on char boundaries. +/// +/// `FN` is the contact's [`name`](Contact::name). Values are escaped. Every field but the notes is +/// one line: its line breaks and other control characters become spaces. A label the format has a +/// `TYPE` for (`work`, `home`, `other`; for phones also `mobile`, `fax`, `pager`) is written as +/// that type; any other label is written as the `X-ABLabel` of a group (`item1.TEL` + +/// `item1.X-ABLabel:Car`), which is how address books exchange custom labels. E-mail addresses, +/// phone numbers, postal addresses and web sites with nothing in them are left out. Keys are +/// written as `KEY;TYPE=X509;ENCODING=b:` and `KEY;TYPE=PGP;ENCODING=b:`; one that would not read +/// back as itself is left out, and so is the address of a key, which vCard 3.0 has no form for. +pub fn write(contacts: &[&Contact]) -> String { + let mut out = String::new(); + for contact in contacts { + card(&mut out, contact); + } + out +} + +/// A one-line field, escaped. +fn field(s: &str) -> String { + escape(&single(s)) +} + +/// `NAME:value` when there is a value. +fn optional(out: &mut String, name: &str, value: &str) { + let value = field(value); + if !value.is_empty() { + fold(out, &format!("{name}:{value}")); + } +} + +/// The `TYPE` of an e-mail or postal address label, when the format has one for it. +fn place_type(label: &str) -> Option<&'static str> { + match label { + "work" => Some("WORK"), + "home" => Some("HOME"), + "other" => Some("OTHER"), + _ => None, + } +} + +fn phone_type(label: &str) -> Option<&'static str> { + match label { + "mobile" => Some("CELL"), + "fax" => Some("FAX"), + "pager" => Some("PAGER"), + _ => place_type(label), + } +} + +/// One labelled property. `kind` is the type the property always has (`INTERNET`), `known` the +/// type its label stands for; a label without one goes into an `X-ABLabel` of the same group. +fn labeled(out: &mut String, groups: &mut u32, name: &str, kind: Option<&str>, known: Option<&str>, label: &str, value: &str) { + let types: Vec<&str> = kind.into_iter().chain(known).collect(); + let params = if types.is_empty() { String::new() } else { format!(";TYPE={}", types.join(",")) }; + let custom = if known.is_some() { String::new() } else { field(label) }; + if custom.is_empty() { + fold(out, &format!("{name}{params}:{value}")); + } else { + *groups = groups.saturating_add(1); + fold(out, &format!("item{groups}.{name}{params}:{value}")); + fold(out, &format!("item{groups}.X-ABLabel:{custom}")); + } +} + +fn card(out: &mut String, c: &Contact) { + fold(out, "BEGIN:VCARD"); + fold(out, "VERSION:3.0"); + fold(out, &format!("N:{};{};{};;", field(&c.last), field(&c.first), field(&c.middle))); + fold(out, &format!("FN:{}", field(&c.name()))); + optional(out, "NICKNAME", &c.nickname); + let (company, department) = (field(&c.company), field(&c.department)); + if !department.is_empty() { + fold(out, &format!("ORG:{company};{department}")); + } else if !company.is_empty() { + fold(out, &format!("ORG:{company}")); + } + optional(out, "TITLE", &c.title); + let mut groups = 0u32; + for email in &c.emails { + let value = field(&email.value); + if !value.is_empty() { + labeled(out, &mut groups, "EMAIL", Some("INTERNET"), place_type(&email.label), &email.label, &value); + } + } + for phone in &c.phones { + let value = field(&phone.value); + if !value.is_empty() { + labeled(out, &mut groups, "TEL", None, phone_type(&phone.label), &phone.label, &value); + } + } + for address in c.addresses.iter().filter(|a| !a.is_empty()) { + // Post office box and extended address stay empty: the model keeps them in the street. + let value = format!( + ";;{};{};{};{};{}", + field(&address.street), + field(&address.city), + field(&address.region), + field(&address.postal_code), + field(&address.country) + ); + labeled(out, &mut groups, "ADR", None, place_type(&address.label), &address.label, &value); + } + for site in &c.websites { + optional(out, "URL", site); + } + if let Some(day) = c.birthday { + // A date that exists, whatever the fields say. + // A year a card can say (1 to 9999), whatever the date's is. + let year = day.year().clamp(1, 9999); + let day = day.with_year(year).or_else(|| NaiveDate::from_ymd_opt(year, day.month(), 28)).unwrap_or_default(); + fold(out, &format!("BDAY:{}", day.format("%Y-%m-%d"))); + } + let notes = escape(&multi(&c.notes)); + if !notes.is_empty() { + fold(out, &format!("NOTE:{notes}")); + } + let categories: Vec = c.categories.iter().map(|name| field(name)).filter(|name| !name.is_empty()).collect(); + if !categories.is_empty() { + fold(out, &format!("CATEGORIES:{}", categories.join(","))); + } + for key in c.keys.iter().filter_map(crate::key::line).take(Contact::MAX_KEYS) { + fold(out, &key); + } + optional(out, "UID", &c.uid); + if c.favorite { + fold(out, "X-MAILCRAFT-FAVORITE:TRUE"); + } + fold(out, "END:VCARD"); +} + +#[cfg(test)] +mod tests { + use crate::{Labeled, PostalAddress}; + + use super::*; + + fn lines(c: &Contact) -> Vec { + let out = write(&[c]); + assert!(out.ends_with("END:VCARD\r\n")); + let mut cursor = crate::lines::Lines::new(&out); + std::iter::from_fn(|| cursor.next_line(false)).collect() + } + + fn nadia() -> Contact { + Contact { + display_name: "Dr. Nadia Okafor".into(), + first: "Nadia".into(), + middle: "Chidi".into(), + last: "Okafor".into(), + nickname: "Nadi".into(), + company: "Example Research, Inc.".into(), + title: "Lead Scientist; Field".into(), + department: "Field Lab".into(), + emails: vec![ + Labeled::new("work", "nadia.okafor@example.org"), + Labeled::new("", "nadia@example.org"), + Labeled::new("Family", "nadia@family.example.org"), + Labeled::new("home", " "), + ], + phones: vec![ + Labeled::new("mobile", "+1 (555) 010-0142"), + Labeled::new("fax", "+1 555 010 0144"), + Labeled::new("Car, old", "+1 555 010 0145"), + Labeled::new("", "+1 555 010 0146"), + ], + addresses: vec![ + PostalAddress { + label: "work".into(), + street: "Suite 300, 41 Harbor Road".into(), + city: "Riverton".into(), + region: "CA".into(), + postal_code: "94000".into(), + country: "USA".into(), + }, + PostalAddress { label: "home".into(), ..Default::default() }, + PostalAddress { label: "Cabin".into(), city: "Pinewood".into(), ..Default::default() }, + ], + websites: vec!["https://example.org/~nadia".into(), "".into()], + birthday: NaiveDate::from_ymd_opt(1985, 4, 12), + notes: "Met at the 2024 symposium.\r\nPrefers e-mail, not calls.".into(), + categories: vec!["Research".into(), "Field Team, West".into(), " ".into()], + favorite: true, + uid: "7f1c2f6e-0001-4a5b-9c3d-000000000042".into(), + ..Default::default() + } + } + + #[test] + fn writes_a_whole_card() { + assert_eq!( + lines(&nadia()), + [ + "BEGIN:VCARD", + "VERSION:3.0", + "N:Okafor;Nadia;Chidi;;", + "FN:Dr. Nadia Okafor", + "NICKNAME:Nadi", + "ORG:Example Research\\, Inc.;Field Lab", + "TITLE:Lead Scientist\\; Field", + "EMAIL;TYPE=INTERNET,WORK:nadia.okafor@example.org", + "EMAIL;TYPE=INTERNET:nadia@example.org", + "item1.EMAIL;TYPE=INTERNET:nadia@family.example.org", + "item1.X-ABLabel:Family", + "TEL;TYPE=CELL:+1 (555) 010-0142", + "TEL;TYPE=FAX:+1 555 010 0144", + "item2.TEL:+1 555 010 0145", + "item2.X-ABLabel:Car\\, old", + "TEL:+1 555 010 0146", + "ADR;TYPE=WORK:;;Suite 300\\, 41 Harbor Road;Riverton;CA;94000;USA", + "item3.ADR:;;;Pinewood;;;", + "item3.X-ABLabel:Cabin", + "URL:https://example.org/~nadia", + "BDAY:1985-04-12", + "NOTE:Met at the 2024 symposium.\\nPrefers e-mail\\, not calls.", + "CATEGORIES:Research,Field Team\\, West", + "UID:7f1c2f6e-0001-4a5b-9c3d-000000000042", + "X-MAILCRAFT-FAVORITE:TRUE", + "END:VCARD", + ] + ); + } + + #[test] + fn an_empty_contact_is_still_a_card() { + assert_eq!(write(&[&Contact::default()]), "BEGIN:VCARD\r\nVERSION:3.0\r\nN:;;;;\r\nFN:\r\nEND:VCARD\r\n"); + assert_eq!(write(&[]), ""); + } + + #[test] + fn the_formatted_name_falls_back_as_the_model_does() { + let named = Contact { first: "Ada".into(), last: "Lovelace".into(), ..Default::default() }; + assert!(lines(&named).contains(&"FN:Ada Lovelace".to_string())); + let company = Contact { company: "Analytical Engines Ltd".into(), ..Default::default() }; + assert_eq!(lines(&company).get(2..5).unwrap(), ["N:;;;;", "FN:Analytical Engines Ltd", "ORG:Analytical Engines Ltd"]); + let mail = Contact { emails: vec![Labeled::new("home", "x@example.org")], department: "Only a department".into(), ..Default::default() }; + assert_eq!(lines(&mail).get(3..6).unwrap(), ["FN:x@example.org", "ORG:;Only a department", "EMAIL;TYPE=INTERNET,HOME:x@example.org"]); + } + + #[test] + fn every_known_label_is_a_type() { + let c = Contact { + emails: ["work", "home", "other", "mobile", "Work"].map(|l| Labeled::new(l, "a@example.org")).to_vec(), + phones: ["mobile", "work", "home", "fax", "pager", "other", "HOME"].map(|l| Labeled::new(l, "1")).to_vec(), + ..Default::default() + }; + let got = lines(&c); + assert_eq!( + got.get(4..20).unwrap(), + [ + "EMAIL;TYPE=INTERNET,WORK:a@example.org", + "EMAIL;TYPE=INTERNET,HOME:a@example.org", + "EMAIL;TYPE=INTERNET,OTHER:a@example.org", + "item1.EMAIL;TYPE=INTERNET:a@example.org", + "item1.X-ABLabel:mobile", + "item2.EMAIL;TYPE=INTERNET:a@example.org", + "item2.X-ABLabel:Work", + "TEL;TYPE=CELL:1", + "TEL;TYPE=WORK:1", + "TEL;TYPE=HOME:1", + "TEL;TYPE=FAX:1", + "TEL;TYPE=PAGER:1", + "TEL;TYPE=OTHER:1", + "item3.TEL:1", + "item3.X-ABLabel:HOME", + "END:VCARD", + ] + ); + } + + #[test] + fn lines_end_in_crlf_and_stay_within_75_octets() { + let mut c = nadia(); + c.notes = "Ünïcödé — 東京 🎉 ".repeat(60); + c.display_name = "é".repeat(200); + let out = write(&[&c, &c]); + assert_eq!(out.matches("BEGIN:VCARD\r\n").count(), 2); + assert!(!out.replace("\r\n", "").contains(['\r', '\n'])); + assert!(out.split("\r\n").all(|line| line.len() <= 75), "{out}"); + assert!(out.contains("\r\n ")); + } + + #[test] + fn text_cannot_inject_lines() { + let c = Contact { + display_name: "Ada\r\nEND:VCARD\r\nBEGIN:VCARD".into(), + first: "A\nTEL:666".into(), + nickname: "x\rEMAIL:evil@example.org".into(), + emails: vec![Labeled::new("work\r\nTEL:1", "a@example.org\r\nTEL:2")], + notes: "one\r\nEND:VCARD\rtwo\u{0}".into(), + categories: vec!["a\nb".into()], + uid: "u\nUID:2".into(), + ..Default::default() + }; + let got = lines(&c); + assert_eq!(got.iter().filter(|l| l.starts_with("BEGIN:") || l.starts_with("END:")).count(), 2, "{got:?}"); + assert!(!got.iter().any(|l| l.starts_with("TEL")), "{got:?}"); + assert_eq!(got.iter().filter(|l| l.starts_with("UID") || l.contains("EMAIL")).count(), 3, "{got:?}"); + assert!(got.contains(&"FN:Ada END:VCARD BEGIN:VCARD".to_string())); + assert!(got.contains(&"NOTE:one\\nEND:VCARD\\ntwo".to_string())); + assert!(got.contains(&"item1.X-ABLabel:work TEL:1".to_string())); + } + + #[test] + fn hostile_birthdays_are_written_as_real_dates() { + for hostile in [ + NaiveDate::MIN, + NaiveDate::MAX, + NaiveDate::from_ymd_opt(0, 1, 1).unwrap(), + NaiveDate::from_ymd_opt(-4, 2, 29).unwrap(), + NaiveDate::from_ymd_opt(10_000, 2, 29).unwrap(), + ] { + let c = Contact { birthday: Some(hostile), ..Default::default() }; + let back = crate::parse(&write(&[&c])); + assert!(back[0].birthday.is_some(), "{hostile:?}"); + } + } +} diff --git a/crates/xcf/Cargo.toml b/crates/xcf/Cargo.toml new file mode 100644 index 000000000..ffaff8abb --- /dev/null +++ b/crates/xcf/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "craft-xcf" +description = "GIMP XCF images (.xcf, .xcf.gz): the header, properties, parasites, layers with their item paths, channels, and tiled pixels (uncompressed, RLE, zlib) at every precision, read with bounded sizes." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +thiserror = { workspace = true } diff --git a/crates/xcf/README.md b/crates/xcf/README.md new file mode 100644 index 000000000..bec85dc68 --- /dev/null +++ b/crates/xcf/README.md @@ -0,0 +1,40 @@ +# craft-xcf + +GIMP XCF images (`.xcf`, `.xcf.gz`), read. Written from the public specification +(, versions 0 to 26) and from files GIMP 3.2 +writes; no GIMP code is used. + +- `is_xcf`, `is_gzipped_xcf`, `gunzip`: recognise a file and inflate a compressed one. +- `Xcf::parse`: the header, the image properties and every layer structure, as an `Image`: + version, canvas, base type, `Precision`, `Compression`, colormap, resolution, guides, the ICC + profile and comment parasites, the path count, and each `Layer` with its properties as GIMP + wrote them (mode, opacity, offsets, locks, colour tag, composite mode and spaces, group flag, + item path, text / vector / link flags, effect count). No pixel is decoded. +- `Xcf::layer_pixels`, `Xcf::layer_mask`, `Xcf::channel`: one drawable's pixels as normalised + `f32` samples (`Pixels`), from uncompressed, RLE or zlib tiles at every precision (8, 16 and + 32-bit integer; 16, 32 and 64-bit float). Indexed pixels are expanded through the colormap. + Each call takes its samples from a byte budget the caller owns, and a `keep_going` callback. +- `Image::tree`: the layers arranged by their item paths, with the ones whose path leads nowhere + or nests too deep reported. + +The reader repairs what GIMP writes wrongly: the length words of `PROP_COLORMAP`, +`PROP_USER_UNIT` and `PROP_LINK_LAYER` are measured, not trusted. + +Layer modes, colour tags and composite settings stay numbers: what they mean to an application +is not decided here. Paths, layer effects and text or vector layer data are not read (their +presence is reported). There is no writer. + +## Limits + +| Limit | Value | +| --- | --- | +| Canvas or drawable side | 300,000 px (`MAX_SIDE`) | +| Canvas area | 1 GiB at 16 bytes per pixel (`MAX_PIXEL_BYTES`) | +| Decoded pixels | the caller's budget, charged 4 bytes a sample before allocation | +| Layers | 8192 (`MAX_LAYERS`); channels 1024 (`MAX_CHANNELS`) | +| Layer effects on one layer | 1024 | +| Properties in one list | 4096; a payload 64 MiB (`MAX_PAYLOAD`) | +| A string | 1 MiB (`MAX_STRING`) | +| Copied layer and channel names and item paths | 32 MiB in all (`MAX_METADATA_BYTES`) | +| Group nesting in `Image::tree` | 64 (`MAX_DEPTH`) | +| A gzipped file, inflated | 1 GiB (`MAX_INFLATED`) | diff --git a/crates/xcf/src/lib.rs b/crates/xcf/src/lib.rs new file mode 100644 index 000000000..fa226d1f1 --- /dev/null +++ b/crates/xcf/src/lib.rs @@ -0,0 +1,923 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! GIMP XCF (`.xcf`, `.xcf.gz`), read. Layout from the public specification +//! (, versions 0 to 26): a header, image +//! properties, then pointers to layer, channel and path structures; each drawable's pixels sit in +//! 64×64 tiles, uncompressed, RLE-coded or zlib-coded. Written from the specification and from +//! files GIMP 3.2 writes; no GIMP code. +//! +//! - [`Xcf::parse`] reads the header, the image properties and every layer's structure into an +//! [`Image`]: no pixel is decoded. +//! - [`Xcf::layer_pixels`], [`Xcf::layer_mask`] and [`Xcf::channel`] decode one drawable each +//! into [`Pixels`] (normalised `f32` samples), charging a byte budget the caller owns. +//! - [`Image::tree`] arranges the layers by their item paths. +//! - [`is_xcf`], [`is_gzipped_xcf`] and [`gunzip`] recognise and inflate files. +//! +//! Layer modes, colour tags and composite settings are kept as the numbers GIMP wrote; what +//! they mean to an application is the application's to decide. + +#[cfg(test)] +mod tests; +mod tiles; + +use std::cell::Cell; +use std::collections::HashMap; +use std::io::Read; + +/// Why an XCF file was not read. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The file is not XCF, is damaged, or exceeds a limit. + #[error("invalid XCF file: {0}")] + Invalid(String), + /// The caller's `keep_going` returned `false`. + #[error("cancelled")] + Cancelled, +} + +pub type Result = std::result::Result; + +fn invalid(message: impl Into) -> Error { + Error::Invalid(message.into()) +} + +const MAGIC: &[u8] = b"gimp xcf "; +/// Canvas and drawable side limit. +pub const MAX_SIDE: u32 = 300_000; +/// The canvas may hold at most this many bytes at 16 bytes per pixel (RGBA `f32`). Also the +/// budget a caller would usually give the decoders. +pub const MAX_PIXEL_BYTES: usize = 1 << 30; +/// Layers and groups in one image. +pub const MAX_LAYERS: usize = 8192; +/// Extra channels in one image. +pub const MAX_CHANNELS: usize = 1024; +/// Group nesting [`Image::tree`] builds. +pub const MAX_DEPTH: usize = 64; +/// Total copied layer and channel metadata (names and item paths). A single reused record with a large +/// name is bounded by [`MAX_STRING`], but repeated layer offsets referencing it must not multiply +/// into unbounded retained metadata. +pub const MAX_METADATA_BYTES: usize = 32 << 20; +/// A string field (layer names, parasite names). +pub const MAX_STRING: usize = 1 << 20; +/// A property payload. +pub const MAX_PAYLOAD: usize = 64 << 20; +/// The largest file a gzipped XCF may inflate to. +pub const MAX_INFLATED: usize = 1 << 30; +/// Highest version this reader was written against; newer files still open (unknown properties +/// are skipped by their length). +pub const KNOWN_VERSION: u32 = 26; +/// The side of a pixel tile. +pub const TILE: u32 = 64; + +/// `true` for an XCF file (by its signature). +pub fn is_xcf(bytes: &[u8]) -> bool { + bytes.starts_with(MAGIC) +} + +/// `true` for a gzip stream named `.xcf.gz` / `.xcfgz` (GIMP writes and reads compressed XCF). +pub fn is_gzipped_xcf(name: &str, bytes: &[u8]) -> bool { + let lower = name.rsplit(['/', '\\']).next().unwrap_or(name).to_ascii_lowercase(); + bytes.starts_with(&[0x1f, 0x8b]) && (lower.ends_with(".xcf.gz") || lower.ends_with(".xcfgz")) +} + +/// Inflates a gzipped XCF, refusing one that inflates past [`MAX_INFLATED`]. +pub fn gunzip(bytes: &[u8]) -> Result> { + let mut out = Vec::new(); + let mut dec = flate2::read::GzDecoder::new(bytes).take(MAX_INFLATED as u64 + 1); + dec.read_to_end(&mut out).map_err(|e| invalid(format!("gzip: {e}")))?; + if out.len() > MAX_INFLATED { + return Err(invalid("the compressed file inflates past the 1 GiB limit")); + } + Ok(out) +} + +/// How samples are stored. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Precision { + /// Bytes per sample: 1, 2, 4 or 8. + pub bytes: usize, + /// Floating point (16, 32 or 64 bit) rather than unsigned integer. + pub float: bool, + /// The values are linear light; otherwise gamma-encoded (the profile's own curve). + pub linear: bool, +} + +impl Precision { + /// 8-bit gamma integer: every file before version 4. + pub const GAMMA8: Precision = Precision { bytes: 1, float: false, linear: false }; + + /// The precision a header's code means in a file of `version` (the codes changed twice). + pub fn from_header(version: u32, code: u32) -> Result { + let p = |bytes, float, linear| Ok(Precision { bytes, float, linear }); + match version { + 0..=3 => Ok(Self::GAMMA8), + 4 => match code { + 0 => p(1, false, false), + 1 => p(2, false, false), + 2 => p(4, false, true), + 3 => p(2, true, true), + 4 => p(4, true, true), + c => Err(invalid(format!("unknown precision {c} in an XCF version 4 file"))), + }, + 5 | 6 => match code { + 100 => p(1, false, true), + 150 => p(1, false, false), + 200 => p(2, false, true), + 250 => p(2, false, false), + 300 => p(4, false, true), + 350 => p(4, false, false), + 400 => p(2, true, true), + 450 => p(2, true, false), + 500 => p(4, true, true), + 550 => p(4, true, false), + c => Err(invalid(format!("unknown precision {c} in an XCF version {version} file"))), + }, + _ => match code { + 100 => p(1, false, true), + 150 => p(1, false, false), + 200 => p(2, false, true), + 250 => p(2, false, false), + 300 => p(4, false, true), + 350 => p(4, false, false), + 500 => p(2, true, true), + 550 => p(2, true, false), + 600 => p(4, true, true), + 650 => p(4, true, false), + 700 => p(8, true, true), + 750 => p(8, true, false), + c => Err(invalid(format!("unknown precision {c}"))), + }, + } + } + + /// One sample, big-endian, as a normalised float (integers map to 0..1). + pub fn sample(self, b: &[u8]) -> f32 { + match (self.float, self.bytes, b) { + (false, 1, [v]) => f32::from(*v) / 255.0, + (false, 2, [a, b]) => f32::from(u16::from_be_bytes([*a, *b])) / 65535.0, + (false, 4, [a, b, c, d]) => (u32::from_be_bytes([*a, *b, *c, *d]) as f64 / f64::from(u32::MAX)) as f32, + (true, 2, [a, b]) => half_to_f32(u16::from_be_bytes([*a, *b])), + (true, 4, [a, b, c, d]) => f32::from_be_bytes([*a, *b, *c, *d]), + (true, 8, [a, b, c, d, e, f, g, h]) => f64::from_be_bytes([*a, *b, *c, *d, *e, *f, *g, *h]) as f32, + _ => 0.0, + } + } +} + +/// An IEEE 754 binary16 value as `f32` (exact: every half is representable). +fn half_to_f32(h: u16) -> f32 { + let sign = u32::from(h >> 15) << 31; + let exp = u32::from(h >> 10) & 0x1f; + let frac = u32::from(h) & 0x3ff; + let bits = match (exp, frac) { + (0, 0) => 0, + (0, f) => { + // Subnormal: shift the leading one up to the implicit position. + let shift = f.leading_zeros() - 21; + ((113 - shift) << 23) | ((f << shift) & 0x3ff) << 13 + } + (31, f) => 0x7f80_0000 | f << 13, + (e, f) => ((e + 112) << 23) | f << 13, + }; + f32::from_bits(sign | bits) +} + +/// How tiles are stored (`PROP_COMPRESSION`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Compression { + None, + Rle, + Zlib, +} + +/// The image's colour model (the header's base type). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BaseType { + Rgb, + Gray, + /// One colormap index per pixel. [`Pixels`] of an indexed image are expanded to RGB. + Indexed, +} + +/// Big-endian reads with bounds checks; every failure is an error, never a panic. +#[derive(Clone, Copy)] +struct Cursor<'a> { + b: &'a [u8], + pos: usize, + /// XCF 11 and later store pointers as 64-bit. + wide: bool, +} + +impl<'a> Cursor<'a> { + fn at(&self, pos: usize) -> Cursor<'a> { + Cursor { b: self.b, pos, wide: self.wide } + } + + fn take(&mut self, n: usize) -> Result<&'a [u8]> { + let end = self.pos.checked_add(n).ok_or_else(|| invalid("offset overflow"))?; + let s = self.b.get(self.pos..end).ok_or_else(|| invalid(format!("the file ends early (wanted {n} bytes at {})", self.pos)))?; + self.pos = end; + Ok(s) + } + + fn u32(&mut self) -> Result { + Ok(be_u32(self.take(4)?).unwrap_or(0)) + } + + fn ptr(&mut self) -> Result { + if self.wide { + let s = self.take(8)?; + let v = s.first_chunk::<8>().map(|b| u64::from_be_bytes(*b)).unwrap_or(0); + usize::try_from(v).map_err(|_| invalid("pointer does not fit in memory")) + } else { + self.u32().map(|v| v as usize) + } + } + + /// A STRING: `n+1` then `n` bytes and a NUL (0 for the empty string). + fn string(&mut self) -> Result { + Ok(String::from_utf8_lossy(self.string_bytes()?).into_owned()) + } + + /// The same bounded STRING read without allocating or decoding an unused field. + fn string_bytes(&mut self) -> Result<&'a [u8]> { + let n = self.u32()? as usize; + if n > MAX_STRING { + return Err(invalid(format!("a string of {n} bytes exceeds the limit"))); + } + let s = self.take(n)?; + Ok(s.strip_suffix(&[0]).unwrap_or(s)) + } + + fn skip(&mut self, n: usize) -> Result<()> { + self.take(n).map(|_| ()) + } +} + +/// One property record: its type and payload. +struct Prop<'a> { + kind: u32, + data: &'a [u8], +} + +/// Reads a property list, measuring known payloads whose length words GIMP writes incorrectly. +/// Ends at PROP_END (type 0). +fn props<'a>(c: &mut Cursor<'a>) -> Result>> { + let mut out = Vec::new(); + loop { + let kind = c.u32()?; + let len = c.u32()? as usize; + if kind == 0 { + return Ok(out); + } + // PROP_COLORMAP's length word was wrong in some releases (n+4 for 3n+4 bytes); its real + // size follows from the count. PROP_USER_UNIT's length is wrong in every release. + // PROP_LINK_LAYER's length can be four bytes short; read all its fields. + let len = match kind { + 1 => { + let n = c.at(c.pos).u32()? as usize; + 4usize.checked_add(n.checked_mul(3).ok_or_else(|| invalid("colormap overflow"))?).ok_or_else(|| invalid("colormap overflow"))? + } + 24 => user_unit_len(c)?, + 48 => link_layer_len(c)?, + _ => len, + }; + if len > MAX_PAYLOAD { + return Err(invalid(format!("property {kind} declares {len} bytes"))); + } + let data = c.take(len)?; + out.push(Prop { kind, data }); + if out.len() > 4096 { + return Err(invalid("too many properties")); + } + } +} + +/// A PROP_LINK_LAYER payload: flags, a path STRING, then the source width and height. +/// The dimensions are present for raster links too, where their values are unused. +fn link_layer_len(c: &Cursor<'_>) -> Result { + let mut p = c.at(c.pos); + p.skip(4)?; + p.string_bytes()?; + p.skip(8)?; + Ok(p.pos - c.pos) +} + +/// The real size of a PROP_USER_UNIT payload: a float, a count and three (XCF 21+) or five +/// strings. Measured without consuming. +fn user_unit_len(c: &Cursor<'_>) -> Result { + let mut p = c.at(c.pos); + p.skip(8)?; + for _ in 0..3 { + p.string_bytes()?; + } + // The two name forms of older files, when present: another string pair before the next + // property. Decide by whether a plausible property header follows. + let three = p.pos - c.pos; + if p.at(p.pos).u32().map(|k| k <= 64).unwrap_or(false) { + return Ok(three); + } + p.string_bytes()?; + p.string_bytes()?; + Ok(p.pos - c.pos) +} + +fn be_u32(b: &[u8]) -> Option { + b.first_chunk::<4>().map(|s| u32::from_be_bytes(*s)) +} + +fn be_i32(b: &[u8]) -> Option { + be_u32(b).map(|v| v as i32) +} + +fn be_f32(b: &[u8]) -> Option { + be_u32(b).map(f32::from_bits) +} + +/// The parasites of a PROP_PARASITES payload as (name, data), in first-seen order; a later +/// duplicate's data wins. A record cut short ends the list. +fn parasites(data: &[u8]) -> Vec<(String, &[u8])> { + let mut c = Cursor { b: data, pos: 0, wide: false }; + let mut out: Vec<(String, &[u8])> = Vec::new(); + // Name to output slot, so a payload of many distinct names is not rescanned per record. + let mut index: HashMap = HashMap::new(); + while c.pos < data.len() { + let Ok(name) = c.string() else { break }; + let (Ok(_flags), Ok(len)) = (c.u32(), c.u32()) else { break }; + let Ok(payload) = c.take(len as usize) else { break }; + match index.get(&name).and_then(|&i| out.get_mut(i)) { + Some(slot) => slot.1 = payload, + None => { + index.insert(name.clone(), out.len()); + out.push((name, payload)); + } + } + } + out +} + +/// A guide's direction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Orientation { + /// A horizontal line: `position` is a y coordinate. + Horizontal, + /// A vertical line: `position` is an x coordinate. + Vertical, +} + +/// A guide (`PROP_GUIDES`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Guide { + pub position: i32, + pub orientation: Orientation, +} + +/// A layer structure, with its properties as GIMP wrote them. +#[derive(Debug, Clone, PartialEq)] +pub struct Layer { + /// The size its pixels are declared to have. + pub width: u32, + pub height: u32, + /// The layer type: 0 RGB, 1 RGBA, 2 gray, 3 gray + alpha, 4 indexed, 5 indexed + alpha. + pub layer_type: u32, + pub name: String, + /// `PROP_FLOATING_SELECTION`: the layer is a floating selection, not part of the stack. + pub floating_selection: bool, + /// 0 to 1: `PROP_FLOAT_OPACITY` when present (it wins whatever the order), else + /// `PROP_OPACITY` / 255. + pub opacity: f32, + /// `PROP_MODE`: GIMP's layer mode number (0 to 22 legacy, 23 and up since 2.10; 61 is + /// pass-through). + pub mode: u32, + pub visible: bool, + /// `PROP_LOCK_ALPHA`. + pub lock_alpha: bool, + /// `PROP_LOCK_CONTENT`. + pub lock_content: bool, + /// `PROP_LOCK_POSITION`. + pub lock_position: bool, + /// `PROP_APPLY_MASK`: the layer mask is in effect. `true` when the property is absent. + pub apply_mask: bool, + /// `PROP_OFFSETS`: where the layer's (and its mask's) top-left pixel sits on the canvas. + pub x: i32, + pub y: i32, + /// `PROP_TEXT_LAYER_FLAGS` or a `gimp-text-layer` parasite: a text layer (its pixels are the + /// rendered text). + pub text: bool, + /// `PROP_VECTOR_LAYER`. + pub vector: bool, + /// `PROP_LINK_LAYER`. + pub link: bool, + /// `PROP_GROUP_ITEM`: a group; its members follow it with longer item paths. + pub group: bool, + /// `PROP_GROUP_ITEM_FLAGS` bit 0. `true` when the property is absent. + pub expanded: bool, + /// `PROP_ITEM_PATH`: the layer's index at each level of the tree; empty at the top level of + /// a file without groups. See [`Image::tree`]. + pub item_path: Vec, + /// `PROP_COLOR_TAG`: 0 none, 1 blue, 2 green, 3 yellow, 4 orange, 5 brown, 6 red, 7 violet, + /// 8 gray. + pub color_tag: u32, + /// `PROP_COMPOSITE_MODE`: 0 or ±1 union, ±2 clip to backdrop, ±3 clip to layer, + /// ±4 intersection (negative: GIMP's automatic choice). + pub composite_mode: i32, + /// `PROP_COMPOSITE_SPACE`: ±1 linear, ±2 perceptual. + pub composite_space: i32, + /// `PROP_BLEND_SPACE`: ±1 linear, ±2 perceptual. + pub blend_space: i32, + /// The layer has a `gimphoto-clipped` parasite (a clipping-mask convention). + pub clipped: bool, + /// Non-destructive layer effects (version 20 and later); they are not read. + pub effects: usize, + hierarchy: usize, + mask: usize, +} + +impl Layer { + /// Does the layer type carry an alpha channel? + pub fn has_alpha(&self) -> bool { + matches!(self.layer_type, 1 | 3 | 5) + } + /// Does the layer point at pixels? Groups usually do not. + pub fn has_pixels(&self) -> bool { + self.hierarchy != 0 + } + /// Does the layer have a mask? + pub fn has_mask(&self) -> bool { + self.mask != 0 + } +} + +/// A channel structure: a layer mask, the selection or an extra channel. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Channel { + pub name: String, + /// `PROP_SELECTION`: this channel is the image's selection. + pub selection: bool, +} + +/// Pixel data of a drawable: `channels` normalised samples per pixel, row-major. A layer has 1 +/// (gray), 2 (gray, alpha), 3 (RGB) or 4 (RGBA) channels; a channel has 1. Indexed pixels are +/// expanded to RGB through the colormap. +#[derive(Debug, Clone, PartialEq)] +pub struct Pixels { + pub width: u32, + pub height: u32, + pub channels: usize, + pub data: Vec, +} + +/// A layer in [`Image::tree`]. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct TreeNode { + /// Index into [`Image::layers`]. + pub layer: usize, + /// The group's members, topmost first. + pub children: Vec, +} + +/// The layers arranged by their item paths. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Tree { + /// The top level, topmost first. + pub roots: Vec, + /// Layers (by index) nested deeper than [`MAX_DEPTH`], moved to the top level. + pub too_deep: Vec, + /// Layers (by index) whose item path leads to no group, put at the top level. + pub misplaced: Vec, +} + +/// The header and structure of an XCF file. +#[derive(Debug, Clone, PartialEq)] +pub struct Image { + /// The file version: 0 to [`KNOWN_VERSION`], or newer. + pub version: u32, + /// Canvas size, 1 to [`MAX_SIDE`]. + pub width: u32, + pub height: u32, + pub base_type: BaseType, + pub precision: Precision, + pub compression: Compression, + /// `PROP_COLORMAP`: at most 256 RGB entries. + pub colormap: Vec<[u8; 3]>, + /// `PROP_RESOLUTION`: horizontal and vertical pixels per inch, as stored. + pub resolution: Option<(f32, f32)>, + /// `PROP_GUIDES`. Files before version 15 could hold stray negative guides; those are + /// left out, as are guides of an unknown orientation. + pub guides: Vec, + /// The `icc-profile` parasite, when not empty. + pub icc_profile: Option>, + /// The `gimp-comment` parasite. + pub comment: Option, + /// Paths the file holds (they are not read). + pub path_count: usize, + /// Every layer structure in file order, topmost first, floating selections included. + pub layers: Vec, + /// The number of channel structures (the selection and the extras); read each with + /// [`Xcf::channel`]. + pub channel_count: usize, +} + +impl Image { + /// Arranges the layers by their item paths, skipping floating selections. A layer without a + /// path sits at the top level in file order; one whose path leads to no group (at any + /// depth) is put at the top level, so later siblings keep their indices. + pub fn tree(&self) -> Tree { + let mut tree = Tree::default(); + let stack = self.layers.iter().enumerate().filter(|(_, l)| !l.floating_selection); + for (position, (index, layer)) in stack.enumerate() { + // Default path: the item's position at the top level, as a file without groups has it. + let default = [position as u32]; + let mut path: &[u32] = if layer.item_path.is_empty() { &default } else { &layer.item_path }; + if path.len() > MAX_DEPTH { + tree.too_deep.push(index); + path = path.get(..1).unwrap_or(path); + } + let (parents, _) = path.split_at(path.len().saturating_sub(1)); + let mut probe = &tree.roots; + let reachable = parents.iter().all(|&i| match probe.get(i as usize) { + Some(n) if self.layers.get(n.layer).is_some_and(|l| l.group) => { + probe = &n.children; + true + } + _ => false, + }); + let group = if reachable { parents } else { &[] }; + if !reachable { + tree.misplaced.push(index); + } + if let Some(level) = group.iter().try_fold(&mut tree.roots, |level, &i| level.get_mut(i as usize).map(|n| &mut n.children)) { + level.push(TreeNode { layer: index, children: Vec::new() }); + } + } + tree + } +} + +/// A parsed XCF file: its [`Image`] and the pixels behind it. +pub struct Xcf<'a> { + c: Cursor<'a>, + image: Image, + channels: Vec, + /// What is left of [`MAX_METADATA_BYTES`] after the layers; channel names are charged too. + meta_budget: Cell, +} + +impl<'a> Xcf<'a> { + /// Reads the header, the image properties and every layer structure of an XCF file + /// (already inflated when it was gzipped). + pub fn parse(bytes: &'a [u8]) -> Result> { + if !is_xcf(bytes) { + return Err(invalid("not an XCF file")); + } + let mut c = Cursor { b: bytes, pos: MAGIC.len(), wide: false }; + let version = match c.take(5)? { + b"file\0" => 0, + [b'v', a, b, d, 0] if a.is_ascii_digit() && b.is_ascii_digit() && d.is_ascii_digit() => { + u32::from(a - b'0') * 100 + u32::from(b - b'0') * 10 + u32::from(d - b'0') + } + _ => return Err(invalid("unknown XCF version tag")), + }; + c.wide = version >= 11; + let (width, height, base_type) = (c.u32()?, c.u32()?, c.u32()?); + if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE { + return Err(invalid(format!("canvas {width}x{height} must be 1 to {MAX_SIDE} pixels a side"))); + } + if (width as usize).saturating_mul(height as usize).saturating_mul(16) > MAX_PIXEL_BYTES { + return Err(invalid("the canvas exceeds the 1 GiB pixel limit")); + } + let precision = if version >= 4 { Precision::from_header(version, c.u32()?)? } else { Precision::GAMMA8 }; + let base_type = match base_type { + 0 => BaseType::Rgb, + 1 => BaseType::Gray, + 2 => BaseType::Indexed, + t => return Err(invalid(format!("unknown image type {t}"))), + }; + let mut image = Image { + version, + width, + height, + base_type, + precision, + compression: Compression::None, + colormap: Vec::new(), + resolution: None, + guides: Vec::new(), + icc_profile: None, + comment: None, + path_count: 0, + layers: Vec::new(), + channel_count: 0, + }; + image_props(&mut c, &mut image)?; + + let pointers = |c: &mut Cursor<'_>, max: usize, what: &str| -> Result> { + let mut out = Vec::new(); + loop { + let p = c.ptr()?; + if p == 0 { + return Ok(out); + } + out.push(p); + if out.len() > max { + return Err(invalid(format!("more than {max} {what}"))); + } + } + }; + let layer_ptrs = pointers(&mut c, MAX_LAYERS, "layers")?; + let channels = pointers(&mut c, MAX_CHANNELS, "channels")?; + if version >= 18 { + let mut n = 0; + while c.ptr().ok().is_some_and(|p| p != 0) { + n += 1; + if n > MAX_CHANNELS { + break; + } + } + image.path_count += n; + } + image.channel_count = channels.len(); + let c = c.at(0); + let mut meta_budget = MAX_METADATA_BYTES; + for ptr in layer_ptrs { + let layer = layer(c.at(ptr), &image, &mut meta_budget)?; + image.layers.push(layer); + } + Ok(Xcf { c, image, channels, meta_budget: Cell::new(meta_budget) }) + } + + /// The file's header and structure. + pub fn image(&self) -> &Image { + &self.image + } + + /// Decodes the pixels of layer `index` of [`Image::layers`]; `None` for a layer that has + /// none (a group). The decoded samples (4 bytes each) are taken from `budget` before + /// anything is allocated. `keep_going` is asked every 64 tiles. + pub fn layer_pixels(&self, index: usize, budget: &mut usize, keep_going: &dyn Fn() -> bool) -> Result> { + let layer = self.image.layers.get(index).ok_or_else(|| invalid("no such layer"))?; + if layer.hierarchy == 0 { + return Ok(None); + } + let color = if self.image.base_type == BaseType::Rgb { 3 } else { 1 }; + let source_channels = color + usize::from(layer.has_alpha()); + let indexed = self.image.base_type == BaseType::Indexed; + let px = self.hierarchy(layer.hierarchy, source_channels, indexed, budget, keep_going)?; + if (px.width, px.height) != (layer.width, layer.height) { + let (name, lw, lh) = (&layer.name, layer.width, layer.height); + return Err(invalid(format!("layer '{name}' pixels are {}x{} where {lw}x{lh} were declared", px.width, px.height))); + } + Ok(Some(px)) + } + + /// Decodes the mask of layer `index`: one channel, placed at the layer's offset. `None` + /// for a layer without one. + pub fn layer_mask(&self, index: usize, budget: &mut usize, keep_going: &dyn Fn() -> bool) -> Result> { + let layer = self.image.layers.get(index).ok_or_else(|| invalid("no such layer"))?; + if layer.mask == 0 { + return Ok(None); + } + self.channel_at(layer.mask, budget, keep_going).map(Some) + } + + /// Decodes channel `index` (below [`Image::channel_count`]): the selection or an extra + /// channel, the size of the canvas. + pub fn channel(&self, index: usize, budget: &mut usize, keep_going: &dyn Fn() -> bool) -> Result<(Channel, Pixels)> { + let ptr = *self.channels.get(index).ok_or_else(|| invalid("no such channel"))?; + self.channel_at(ptr, budget, keep_going) + } + + fn channel_at(&self, ptr: usize, budget: &mut usize, keep_going: &dyn Fn() -> bool) -> Result<(Channel, Pixels)> { + let mut c = self.c.at(ptr); + let (_w, _h) = (c.u32()?, c.u32()?); + let name = c.string()?; + // As for layers: repeated channel pointers must not retain unbounded copies of one name. + self.meta_budget.set(self.meta_budget.get().checked_sub(name.len()).ok_or_else(|| invalid("channel metadata exceeds the budget"))?); + let selection = props(&mut c)?.iter().any(|p| p.kind == 4); + let hptr = c.ptr()?; + // Channels are always one plain sample per pixel, even in indexed images. + let px = self.hierarchy(hptr, 1, false, budget, keep_going)?; + Ok((Channel { name, selection }, px)) + } + + /// Reads a hierarchy: the first level's tiles into floats, `source_channels` as stored + /// (indexed pixels expand to RGB here). + fn hierarchy(&self, hptr: usize, source_channels: usize, indexed: bool, budget: &mut usize, keep_going: &dyn Fn() -> bool) -> Result { + let precision = self.image.precision; + let mut c = self.c.at(hptr); + let (w, h, bpp) = (c.u32()?, c.u32()?, c.u32()? as usize); + if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { + return Err(invalid(format!("drawable size {w}x{h} is out of range"))); + } + let expected_bpp = source_channels.checked_mul(precision.bytes).ok_or_else(|| invalid("bpp overflow"))?; + if bpp != expected_bpp { + return Err(invalid(format!("{bpp} bytes per pixel where {expected_bpp} were expected"))); + } + let channels = if indexed { source_channels + 2 } else { source_channels }; + let count = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(channels)).ok_or_else(|| invalid("drawable overflow"))?; + let bytes = count.checked_mul(4).ok_or_else(|| invalid("drawable overflow"))?; + *budget = budget.checked_sub(bytes).ok_or_else(|| invalid("the layers exceed the pixel limit"))?; + let lptr = c.ptr()?; + let mut l = self.c.at(lptr); + if (l.u32()?, l.u32()?) != (w, h) { + return Err(invalid("the level does not match its hierarchy")); + } + let across = w.div_ceil(TILE) as usize; + let down = h.div_ceil(TILE) as usize; + let mut tiles = Vec::with_capacity(across * down); + for _ in 0..across * down { + let p = l.ptr()?; + if p == 0 { + return Err(invalid("the tile list ends before every tile")); + } + tiles.push(p); + } + let mut data = vec![0.0f32; count]; + let stride = w as usize * channels; + let side = TILE as usize; + for (i, &at) in tiles.iter().enumerate() { + if i % 64 == 0 && !keep_going() { + return Err(Error::Cancelled); + } + let (tx, ty) = (i % across, i / across); + let (tw, th) = ((w as usize - tx * side).min(side), (h as usize - ty * side).min(side)); + let end = tiles.get(i + 1).copied().filter(|&n| n > at).unwrap_or(self.c.b.len()); + let input = self.c.b.get(at..end.min(self.c.b.len())).ok_or_else(|| invalid("a tile pointer is outside the file"))?; + let raw = tiles::decode(input, self.image.compression, bpp, tw * th)?; + for (py, row) in raw.chunks_exact(tw * bpp).enumerate() { + let start = (ty * side + py) * stride + tx * side * channels; + let Some(out) = data.get_mut(start..start + tw * channels) else { continue }; + for (pixel, dst) in row.chunks_exact(bpp).zip(out.chunks_exact_mut(channels)) { + if indexed { + let idx = pixel.first().copied().unwrap_or(0); + let rgb = self.image.colormap.get(usize::from(idx)).copied().unwrap_or([idx; 3]); + let alpha = pixel.get(1).copied(); + for (d, v) in dst.iter_mut().zip(rgb.into_iter().chain(alpha)) { + *d = f32::from(v) / 255.0; + } + } else { + for (d, s) in dst.iter_mut().zip(pixel.chunks_exact(precision.bytes)) { + *d = precision.sample(s); + } + } + } + } + } + Ok(Pixels { width: w, height: h, channels, data }) + } +} + +fn image_props(c: &mut Cursor<'_>, image: &mut Image) -> Result<()> { + for p in &props(c)? { + match p.kind { + 1 => { + let n = be_u32(p.data).unwrap_or(0) as usize; + image.colormap = p.data.get(4..).unwrap_or(&[]).as_chunks::<3>().0.iter().take(n.min(256)).copied().collect(); + } + 17 => { + image.compression = match p.data.first() { + Some(0) => Compression::None, + Some(1) => Compression::Rle, + Some(2) => Compression::Zlib, + Some(k) => return Err(invalid(format!("unknown compression {k}"))), + None => return Err(invalid("empty compression property")), + } + } + 18 => { + for g in p.data.as_chunks::<5>().0 { + let position = i32::from_be_bytes([g[0], g[1], g[2], g[3]]); + let orientation = match g[4] { + 1 => Orientation::Horizontal, + 2 => Orientation::Vertical, + _ => continue, + }; + if position >= 0 || image.version >= 15 { + image.guides.push(Guide { position, orientation }); + } + } + } + 19 => { + if let (Some(x), Some(y)) = (be_f32(p.data), p.data.get(4..).and_then(be_f32)) { + image.resolution = Some((x, y)); + } + } + 21 => { + for (name, data) in parasites(p.data) { + match name.as_str() { + "icc-profile" if !data.is_empty() => image.icc_profile = Some(data.to_vec()), + "gimp-comment" => image.comment = Some(String::from_utf8_lossy(data).trim_end_matches('\0').to_string()), + _ => {} + } + } + } + 23 => image.path_count += be_u32(p.data.get(4..).unwrap_or(&[])).unwrap_or(0) as usize, + 25 => image.path_count += be_u32(p.data.get(8..).unwrap_or(&[])).unwrap_or(0) as usize, + _ => {} + } + } + Ok(()) +} + +/// Reads a layer structure at `c`. +fn layer(mut c: Cursor<'_>, image: &Image, meta_budget: &mut usize) -> Result { + let (width, height, layer_type) = (c.u32()?, c.u32()?, c.u32()?); + let name = c.string()?; + // Charge the owned name against the image-wide metadata budget: repeated layer offsets + // referencing one large name must not retain unbounded copies. + *meta_budget = meta_budget.checked_sub(name.len()).ok_or_else(|| invalid("layer metadata exceeds the budget"))?; + let lprops = props(&mut c)?; + let hierarchy = c.ptr()?; + let mask = c.ptr()?; + let mut effects = 0usize; + if image.version >= 20 { + while c.ptr()? != 0 { + effects += 1; + if effects > 1024 { + return Err(invalid("too many layer effects")); + } + } + } + let type_rgb = match layer_type { + 0 | 1 => true, + 2..=5 => false, + k => return Err(invalid(format!("unknown layer type {k} on '{name}'"))), + }; + if type_rgb != (image.base_type != BaseType::Gray) && image.base_type != BaseType::Indexed { + return Err(invalid(format!("layer '{name}' does not match the image's colour model"))); + } + let mut l = Layer { + width, + height, + layer_type, + name, + floating_selection: false, + opacity: 1.0, + mode: 0, + visible: true, + lock_alpha: false, + lock_content: false, + lock_position: false, + apply_mask: true, + x: 0, + y: 0, + text: false, + vector: false, + link: false, + group: false, + expanded: true, + item_path: Vec::new(), + color_tag: 0, + composite_mode: 0, + composite_space: 0, + blend_space: 0, + clipped: false, + effects, + hierarchy, + mask, + }; + // PROP_FLOAT_OPACITY wins over PROP_OPACITY whatever their order in the file. + let mut float_opacity = None; + for p in &lprops { + let v = be_u32(p.data).unwrap_or(0); + match p.kind { + 5 => l.floating_selection = true, + 6 => l.opacity = (v.min(255) as f32) / 255.0, + 33 => float_opacity = be_f32(p.data).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0)).or(float_opacity), + 7 => l.mode = v, + 8 => l.visible = v != 0, + 10 => l.lock_alpha = v != 0, + 11 => l.apply_mask = v != 0, + 15 => { + l.x = be_i32(p.data).unwrap_or(0); + l.y = p.data.get(4..).and_then(be_i32).unwrap_or(0); + } + 26 => l.text = true, + 28 => l.lock_content = v != 0, + 29 => l.group = true, + 30 => { + l.item_path = p.data.as_chunks::<4>().0.iter().map(|s| u32::from_be_bytes(*s)).collect(); + *meta_budget = + meta_budget.checked_sub(l.item_path.len().saturating_mul(4)).ok_or_else(|| invalid("layer metadata exceeds the budget"))?; + } + 31 => l.expanded = v & 1 != 0, + 32 => l.lock_position = v != 0, + 34 => l.color_tag = v, + 35 => l.composite_mode = be_i32(p.data).unwrap_or(0), + 36 => l.composite_space = be_i32(p.data).unwrap_or(0), + 37 => l.blend_space = be_i32(p.data).unwrap_or(0), + 47 => l.vector = true, + 48 => l.link = true, + 21 => { + for (pname, _) in parasites(p.data) { + match pname.as_str() { + "gimphoto-clipped" => l.clipped = true, + "gimp-text-layer" => l.text = true, + _ => {} + } + } + } + _ => {} + } + } + l.opacity = float_opacity.unwrap_or(l.opacity); + Ok(l) +} diff --git a/crates/xcf/src/tests.rs b/crates/xcf/src/tests.rs new file mode 100644 index 000000000..5ec45620c --- /dev/null +++ b/crates/xcf/src/tests.rs @@ -0,0 +1,1120 @@ +//! Synthetic XCF files (written here, from the specification) for the reader: structure, +//! every compression, precisions, groups, masks, channels, limits and malformed input. + +use super::tiles::rle_decode; +use super::*; + +/// A small XCF writer for tests: version 11+ layout (64-bit pointers) by default. +pub(super) struct W { + pub out: Vec, + pub wide: bool, +} + +impl W { + pub fn new(version: u32) -> Self { + let mut w = W { out: Vec::new(), wide: version >= 11 }; + w.out.extend_from_slice(b"gimp xcf "); + if version == 0 { + w.out.extend_from_slice(b"file\0"); + } else { + w.out.extend_from_slice(format!("v{version:03}\0").as_bytes()); + } + w + } + pub fn u32(&mut self, v: u32) { + self.out.extend_from_slice(&v.to_be_bytes()); + } + pub fn ptr(&mut self, v: usize) { + if self.wide { + self.out.extend_from_slice(&(v as u64).to_be_bytes()); + } else { + self.u32(v as u32); + } + } + pub fn string(&mut self, s: &str) { + if s.is_empty() { + self.u32(0); + } else { + self.u32(s.len() as u32 + 1); + self.out.extend_from_slice(s.as_bytes()); + self.out.push(0); + } + } + pub fn prop(&mut self, kind: u32, payload: &[u8]) { + self.u32(kind); + self.u32(payload.len() as u32); + self.out.extend_from_slice(payload); + } + pub fn prop_u32(&mut self, kind: u32, v: u32) { + self.prop(kind, &v.to_be_bytes()); + } + pub fn end(&mut self) { + self.u32(0); + self.u32(0); + } + /// Reserves a pointer slot, returning where to patch it. + pub fn slot(&mut self) -> usize { + let at = self.out.len(); + self.ptr(0); + at + } + pub fn patch(&mut self, slot: usize, target: usize) { + if self.wide { + self.out[slot..slot + 8].copy_from_slice(&(target as u64).to_be_bytes()); + } else { + self.out[slot..slot + 4].copy_from_slice(&(target as u32).to_be_bytes()); + } + } +} + +/// RLE-encodes one tile of `bpp`-byte pixels, plane by plane, with runs and literals. +pub(super) fn rle(pixels: &[u8], bpp: usize) -> Vec { + let n = pixels.len() / bpp; + let mut out = Vec::new(); + for b in 0..bpp { + let plane: Vec = (0..n).map(|i| pixels[i * bpp + b]).collect(); + let mut i = 0; + while i < n { + let v = plane[i]; + let mut run = 1; + while i + run < n && plane[i + run] == v && run < 65535 { + run += 1; + } + if run >= 2 { + if run <= 127 { + out.push((run - 1) as u8); + } else { + out.push(127); + out.push((run / 256) as u8); + out.push((run % 256) as u8); + } + out.push(v); + i += run; + } else { + let start = i; + while i < n && (i + 1 >= n || plane[i + 1] != plane[i]) && i - start < 127 { + i += 1; + } + let len = i - start; + out.push((256 - len) as u8); + out.extend_from_slice(&plane[start..i]); + } + } + } + out +} + +/// Writes a hierarchy for `w`×`h` pixels of `bpp` bytes (`data` row-major), returning its offset. +pub(super) fn hierarchy(w: &mut W, width: u32, height: u32, bpp: usize, data: &[u8], compression: Compression) -> usize { + let at = w.out.len(); + w.u32(width); + w.u32(height); + w.u32(bpp as u32); + let level_slot = w.slot(); + w.ptr(0); + let level = w.out.len(); + w.patch(level_slot, level); + w.u32(width); + w.u32(height); + let across = width.div_ceil(TILE) as usize; + let down = height.div_ceil(TILE) as usize; + let slots: Vec = (0..across * down).map(|_| w.slot()).collect(); + w.ptr(0); + for (i, slot) in slots.into_iter().enumerate() { + let (tx, ty) = ((i % across) as u32, (i / across) as u32); + let (tw, th) = ((width - tx * TILE).min(TILE), (height - ty * TILE).min(TILE)); + let mut tile = Vec::new(); + for py in 0..th { + for px in 0..tw { + let src = ((ty * TILE + py) as usize * width as usize + (tx * TILE + px) as usize) * bpp; + tile.extend_from_slice(&data[src..src + bpp]); + } + } + let encoded = match compression { + Compression::None => tile, + Compression::Rle => rle(&tile, bpp), + Compression::Zlib => { + use std::io::Write; + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + e.write_all(&tile).unwrap(); + e.finish().unwrap() + } + }; + let here = w.out.len(); + w.patch(slot, here); + w.out.extend_from_slice(&encoded); + } + at +} + +/// A layer to write. +pub(super) struct TestLayer { + pub name: &'static str, + pub width: u32, + pub height: u32, + pub kind: u32, + pub x: i32, + pub y: i32, + pub opacity: f32, + pub visible: bool, + pub mode: u32, + pub props: Vec<(u32, Vec)>, + pub data: Vec, + pub mask: Option>, + pub apply_mask: bool, +} + +impl TestLayer { + pub fn rgba(name: &'static str, width: u32, height: u32, data: Vec) -> Self { + TestLayer { + name, + width, + height, + kind: 1, + x: 0, + y: 0, + opacity: 1.0, + visible: true, + mode: 28, + props: Vec::new(), + data, + mask: None, + apply_mask: true, + } + } +} + +pub(super) struct TestImage { + pub version: u32, + pub width: u32, + pub height: u32, + pub base_type: u32, + pub precision: u32, + pub compression: Compression, + pub image_props: Vec<(u32, Vec)>, + pub layers: Vec, + pub channels: Vec<(&'static str, Vec, bool)>, +} + +impl TestImage { + pub fn rgb8(width: u32, height: u32) -> Self { + TestImage { + version: 11, + width, + height, + base_type: 0, + precision: 150, + compression: Compression::Rle, + image_props: Vec::new(), + layers: Vec::new(), + channels: Vec::new(), + } + } + + pub fn write(&self) -> Vec { + let mut w = W::new(self.version); + w.u32(self.width); + w.u32(self.height); + w.u32(self.base_type); + if self.version >= 4 { + w.u32(self.precision); + } + let comp = match self.compression { + Compression::None => 0u8, + Compression::Rle => 1, + Compression::Zlib => 2, + }; + w.prop(17, &[comp]); + for (k, v) in &self.image_props { + w.prop(*k, v); + } + w.end(); + let layer_slots: Vec = self.layers.iter().map(|_| w.slot()).collect(); + w.ptr(0); + let channel_slots: Vec = self.channels.iter().map(|_| w.slot()).collect(); + w.ptr(0); + if self.version >= 18 { + w.ptr(0); + } + let bytes = match self.precision { + 100 | 150 => 1, + 200 | 250 | 500 | 550 => 2, + 300 | 350 | 600 | 650 => 4, + _ => 8, + }; + for (layer, slot) in self.layers.iter().zip(layer_slots) { + let at = w.out.len(); + w.patch(slot, at); + w.u32(layer.width); + w.u32(layer.height); + w.u32(layer.kind); + w.string(layer.name); + w.prop_u32(6, (layer.opacity * 255.0).round() as u32); + w.prop(33, &layer.opacity.to_be_bytes()); + w.prop_u32(8, u32::from(layer.visible)); + w.prop_u32(7, layer.mode); + let mut off = Vec::new(); + off.extend_from_slice(&layer.x.to_be_bytes()); + off.extend_from_slice(&layer.y.to_be_bytes()); + w.prop(15, &off); + if layer.mask.is_some() { + w.prop_u32(11, u32::from(layer.apply_mask)); + } + for (k, v) in &layer.props { + w.prop(*k, v); + } + w.end(); + let hslot = w.slot(); + let mslot = w.slot(); + if self.version >= 20 { + w.ptr(0); + } + let channels = match layer.kind { + 0 => 3, + 1 => 4, + 2 | 4 => 1, + _ => 2, + }; + if !layer.data.is_empty() { + let h = hierarchy(&mut w, layer.width, layer.height, channels * bytes, &layer.data, self.compression); + w.patch(hslot, h); + } + if let Some(mask) = &layer.mask { + let at = w.out.len(); + w.patch(mslot, at); + w.u32(layer.width); + w.u32(layer.height); + w.string("mask"); + w.end(); + let hs = w.slot(); + let h = hierarchy(&mut w, layer.width, layer.height, bytes, mask, self.compression); + w.patch(hs, h); + } + } + for ((name, data, selection), slot) in self.channels.iter().zip(channel_slots) { + let at = w.out.len(); + w.patch(slot, at); + w.u32(self.width); + w.u32(self.height); + w.string(name); + if *selection { + w.prop(4, &[]); + } + w.end(); + let hs = w.slot(); + let h = hierarchy(&mut w, self.width, self.height, bytes, data, self.compression); + w.patch(hs, h); + } + w.out + } +} + +const GO: &dyn Fn() -> bool = &|| true; + +fn open(bytes: &[u8]) -> Result> { + Xcf::parse(bytes) +} + +/// Parses and decodes everything, as an application would. +fn read_all(bytes: &[u8]) -> Result { + let xcf = Xcf::parse(bytes)?; + let mut budget = MAX_PIXEL_BYTES; + let mut samples = 0; + for i in 0..xcf.image().layers.len() { + samples += xcf.layer_pixels(i, &mut budget, GO)?.map_or(0, |p| p.data.len()); + samples += xcf.layer_mask(i, &mut budget, GO)?.map_or(0, |(_, p)| p.data.len()); + } + for i in 0..xcf.image().channel_count { + samples += xcf.channel(i, &mut budget, GO)?.1.data.len(); + } + xcf.image().tree(); + Ok(samples) +} + +fn rgba(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec { + let f = &f; + (0..h).flat_map(|y| (0..w).flat_map(move |x| f(x, y))).collect() +} + +fn pixels(xcf: &Xcf<'_>, layer: usize) -> Pixels { + xcf.layer_pixels(layer, &mut MAX_PIXEL_BYTES.clone(), GO).unwrap().unwrap() +} + +/// The samples of pixel (x, y), in the drawable's own coordinates. +fn at(px: &Pixels, x: u32, y: u32) -> &[f32] { + let i = (y * px.width + x) as usize * px.channels; + &px.data[i..i + px.channels] +} + +fn path(indices: &[u32]) -> (u32, Vec) { + (30, indices.iter().flat_map(|v| v.to_be_bytes()).collect()) +} + +fn names(image: &Image, nodes: &[TreeNode]) -> Vec { + nodes.iter().map(|n| image.layers[n.layer].name.clone()).collect() +} + +#[test] +fn a_layer_decodes_with_every_compression() { + for compression in [Compression::None, Compression::Rle, Compression::Zlib] { + let mut img = TestImage::rgb8(70, 66); + img.compression = compression; + img.layers.push(TestLayer::rgba("A", 70, 66, rgba(70, 66, |x, y| [x as u8 * 3, y as u8 * 2, (x + y) as u8, 255 - x as u8]))); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + let image = xcf.image(); + assert_eq!((image.width, image.height, image.version, image.compression), (70, 66, 11, compression)); + assert_eq!((image.base_type, image.precision), (BaseType::Rgb, Precision::GAMMA8)); + assert_eq!(image.layers.len(), 1, "{compression:?}"); + let px = pixels(&xcf, 0); + assert_eq!((px.width, px.height, px.channels), (70, 66, 4)); + for (x, y) in [(0, 0), (63, 0), (64, 0), (69, 65), (10, 64)] { + let want = [x as f32 * 3.0, y as f32 * 2.0, (x + y) as f32, 255.0 - x as f32].map(|v| v / 255.0); + assert_eq!(at(&px, x, y), want, "{compression:?} at {x},{y}"); + } + } +} + +#[test] +fn every_truncation_errors_never_panics() { + let mut img = TestImage::rgb8(20, 20); + let mut l = TestLayer::rgba("A", 20, 20, rgba(20, 20, |x, y| [x as u8, y as u8, 0, 255])); + l.mask = Some(vec![9; 400]); + img.layers.push(l); + img.channels.push(("Extra", vec![3; 400], false)); + let bytes = img.write(); + for cut in 0..bytes.len() { + assert!(read_all(&bytes[..cut]).is_err(), "cut at {cut}"); + } + assert_eq!(read_all(&bytes), Ok(1600 + 400 + 400)); +} + +#[test] +fn corrupted_files_never_panic() { + let mut img = TestImage::rgb8(70, 20); + let mut group = TestLayer::rgba("Group", 1, 1, Vec::new()); + group.props = vec![(29, vec![])]; + img.layers.push(group); + let mut l = TestLayer::rgba("A", 70, 20, rgba(70, 20, |x, y| [x as u8, y as u8, 0, 255])); + l.props = vec![path(&[0, 0])]; + l.mask = Some(vec![9; 1400]); + img.layers.push(l); + img.channels.push(("Sel", vec![3; 1400], true)); + for compression in [Compression::None, Compression::Rle, Compression::Zlib] { + img.compression = compression; + let bytes = img.write(); + assert!(read_all(&bytes).is_ok()); + let mut state = 0x9e37_79b9_u32; + for _ in 0..2000 { + let mut b = bytes.clone(); + for _ in 0..3 { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + let i = state as usize % b.len(); + b[i] ^= (state >> 24) as u8 | 1; + } + let _ = read_all(&b); + } + } +} + +#[test] +fn properties_offsets_opacity_mode_visibility_locks_and_tags() { + let mut img = TestImage::rgb8(30, 20); + let mut l = TestLayer::rgba("Top", 10, 8, rgba(10, 8, |x, y| [x as u8 * 20, y as u8 * 30, 0, 200])); + l.x = -3; + l.y = 15; + l.opacity = 0.4; + l.visible = false; + l.mode = 30; // Multiply + let one = 1u32.to_be_bytes().to_vec(); + l.props = vec![ + (10, one.clone()), + (28, one.clone()), + (32, one.clone()), + (34, 2u32.to_be_bytes().to_vec()), + (35, (-2i32).to_be_bytes().to_vec()), + (36, 1i32.to_be_bytes().to_vec()), + (37, (-1i32).to_be_bytes().to_vec()), + ]; + img.layers.push(l); + img.layers.push(TestLayer::rgba("Bottom", 30, 20, rgba(30, 20, |_, _| [9, 9, 9, 255]))); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + let layers = &xcf.image().layers; + assert_eq!(layers.iter().map(|l| l.name.as_str()).collect::>(), ["Top", "Bottom"], "file order: topmost first"); + let top = &layers[0]; + assert_eq!((top.mode, top.opacity, top.visible, top.x, top.y), (30, 0.4, false, -3, 15)); + assert!(top.lock_alpha && top.lock_content && top.lock_position); + assert_eq!((top.color_tag, top.composite_mode, top.composite_space, top.blend_space), (2, -2, 1, -1)); + assert!(top.has_alpha() && top.has_pixels() && !top.has_mask() && top.apply_mask && top.expanded); + assert!(!(top.group || top.text || top.vector || top.link || top.clipped || top.floating_selection)); + assert_eq!((top.width, top.height, top.layer_type, top.effects), (10, 8, 1, 0)); + // The layer's own pixel (5, 2); the offset is the caller's to apply. + assert_eq!(at(&pixels(&xcf, 0), 5, 2), [100.0 / 255.0, 60.0 / 255.0, 0.0, 200.0 / 255.0]); + let bottom = &layers[1]; + assert_eq!((bottom.mode, bottom.opacity, bottom.visible, bottom.color_tag), (28, 1.0, true, 0)); + assert!(!bottom.lock_alpha && !bottom.lock_content && !bottom.lock_position); +} + +#[test] +fn groups_follow_item_paths() { + // File order: Top, Group (0), child A [1,0], Nested group [1,1], nested child [1,1,0], Bottom. + let mut img = TestImage::rgb8(16, 16); + let px = |v: u8| rgba(4, 4, move |_, _| [v, v, v, 255]); + img.layers.push(TestLayer::rgba("Top", 4, 4, px(1))); + let mut group = TestLayer::rgba("Group", 1, 1, Vec::new()); + group.props = vec![(29, vec![]), (31, 0u32.to_be_bytes().to_vec())]; + img.layers.push(group); + let mut a = TestLayer::rgba("A", 4, 4, px(2)); + a.props = vec![path(&[1, 0])]; + img.layers.push(a); + let mut nested = TestLayer::rgba("Nested", 1, 1, Vec::new()); + nested.props = vec![(29, vec![]), path(&[1, 1])]; + nested.mode = 61; // Pass through + img.layers.push(nested); + let mut b = TestLayer::rgba("B", 4, 4, px(3)); + b.props = vec![path(&[1, 1, 0])]; + img.layers.push(b); + img.layers.push(TestLayer::rgba("Bottom", 16, 16, rgba(16, 16, |_, _| [0, 0, 0, 255]))); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + let image = xcf.image(); + let tree = image.tree(); + assert!(tree.misplaced.is_empty() && tree.too_deep.is_empty()); + assert_eq!(names(image, &tree.roots), ["Top", "Group", "Bottom"]); + let g = &image.layers[tree.roots[1].layer]; + assert!(g.group && !g.expanded && !g.has_pixels() && g.mode == 28); + assert_eq!(xcf.layer_pixels(tree.roots[1].layer, &mut 0, GO), Ok(None), "a group has no pixels and costs nothing"); + let children = &tree.roots[1].children; + assert_eq!(names(image, children), ["A", "Nested"], "topmost first inside the group too"); + assert_eq!((image.layers[children[1].layer].mode, image.layers[children[1].layer].item_path.as_slice()), (61, &[1, 1][..])); + assert_eq!(names(image, &children[1].children), ["B"]); + assert_eq!(at(&pixels(&xcf, children[0].layer), 0, 0)[0], 2.0 / 255.0); +} + +#[test] +fn a_path_into_nothing_lands_at_the_top_level() { + let mut img = TestImage::rgb8(8, 8); + let mut stray = TestLayer::rgba("Stray", 2, 2, rgba(2, 2, |_, _| [5, 5, 5, 255])); + stray.props = vec![path(&[7, 0])]; + img.layers.push(stray); + img.layers.push(TestLayer::rgba("Bottom", 8, 8, rgba(8, 8, |_, _| [0, 0, 0, 255]))); + let bytes = img.write(); + let tree = open(&bytes).unwrap().image().tree(); + assert_eq!((tree.roots.len(), tree.misplaced.as_slice()), (2, &[0][..])); +} + +/// A path that fails below the top level (here at depth 2) still lands at the top level, so the +/// group it would have been pushed into keeps its indices for the siblings placed after it. +#[test] +fn a_path_failing_below_the_top_level_lands_at_the_top_level() { + let mut img = TestImage::rgb8(8, 8); + let px = |v: u8| rgba(2, 2, move |_, _| [v, v, v, 255]); + let mut group = TestLayer::rgba("Group", 1, 1, Vec::new()); + group.props = vec![(29, vec![]), (31, 0u32.to_be_bytes().to_vec())]; + img.layers.push(group); + let mut stray = TestLayer::rgba("Stray", 2, 2, px(5)); + stray.props = vec![path(&[0, 4, 0])]; + img.layers.push(stray); + let mut a = TestLayer::rgba("A", 2, 2, px(6)); + a.props = vec![path(&[0, 0])]; + img.layers.push(a); + img.layers.push(TestLayer::rgba("Bottom", 8, 8, rgba(8, 8, |_, _| [0, 0, 0, 255]))); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + let (image, tree) = (xcf.image(), xcf.image().tree()); + assert_eq!(names(image, &tree.roots), ["Group", "Stray", "Bottom"]); + assert_eq!(names(image, &tree.roots[0].children), ["A"], "the valid sibling placed after the stray one still lands in the group"); + assert_eq!(tree.misplaced, [1]); +} + +#[test] +fn a_path_deeper_than_the_limit_moves_to_the_top_level() { + let mut img = TestImage::rgb8(8, 8); + let mut deep = TestLayer::rgba("Deep", 1, 1, vec![0; 4]); + deep.props = vec![path(&[0; MAX_DEPTH + 1])]; + let mut edge = TestLayer::rgba("Edge", 1, 1, vec![0; 4]); + edge.props = vec![path(&[0; MAX_DEPTH])]; + img.layers.extend([deep, edge]); + let bytes = img.write(); + let tree = open(&bytes).unwrap().image().tree(); + assert_eq!((tree.roots.len(), tree.too_deep.as_slice(), tree.misplaced.as_slice()), (2, &[0][..], &[1][..])); +} + +#[test] +fn masks_are_read_applied_or_not() { + for apply in [true, false] { + let mut img = TestImage::rgb8(20, 20); + let mut l = TestLayer::rgba("Masked", 6, 6, rgba(6, 6, |_, _| [255, 0, 0, 255])); + l.x = 4; + l.y = 5; + l.mask = Some((0..36).map(|i| (i * 7) as u8).collect()); + l.apply_mask = apply; + img.layers.push(l); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + let layer = &xcf.image().layers[0]; + assert!(layer.has_mask()); + assert_eq!((layer.apply_mask, layer.x, layer.y), (apply, 4, 5)); + let (channel, px) = xcf.layer_mask(0, &mut MAX_PIXEL_BYTES.clone(), GO).unwrap().unwrap(); + assert_eq!((channel, px.width, px.height, px.channels), (Channel { name: "mask".into(), selection: false }, 6, 6, 1)); + assert_eq!(at(&px, 3, 2), [(2 * 6 + 3) as f32 * 7.0 / 255.0]); + } +} + +#[test] +fn sixteen_bit_and_float_samples_are_big_endian() { + // 16-bit gamma integer (250): one 2x1 gray+alpha layer. + let mut img = TestImage::rgb8(2, 1); + img.base_type = 1; + img.precision = 250; + let data: Vec = [0x1234u16, 0xffff, 0x8000, 0x0001].into_iter().flat_map(u16::to_be_bytes).collect(); + let mut l = TestLayer::rgba("G", 2, 1, data); + l.kind = 3; // gray with alpha + img.layers.push(l); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + assert_eq!((xcf.image().base_type, xcf.image().precision), (BaseType::Gray, Precision { bytes: 2, float: false, linear: false })); + let px = pixels(&xcf, 0); + assert_eq!(px.data, [0x1234 as f32 / 65535.0, 1.0, 0x8000 as f32 / 65535.0, 1.0 / 65535.0]); + + // 32-bit float linear (600): RGB without alpha, values above 1 kept. + let mut img = TestImage::rgb8(1, 1); + img.precision = 600; + let mut l = TestLayer::rgba("F", 1, 1, [0.25f32, 1.5, -0.5].into_iter().flat_map(f32::to_be_bytes).collect()); + l.kind = 0; + img.layers.push(l); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + assert_eq!(xcf.image().precision, Precision { bytes: 4, float: true, linear: true }); + assert!(!xcf.image().layers[0].has_alpha()); + let px = pixels(&xcf, 0); + assert_eq!((px.channels, px.data.as_slice()), (3, &[0.25, 1.5, -0.5][..])); + + // 16-bit float (500), 64-bit float (700) and 32-bit integer (350) decode too. + for (precision, bytes, want) in + [(500u32, 0x3a00u16.to_be_bytes().to_vec(), 0.75), (700, 0.75f64.to_be_bytes().to_vec(), 0.75), (350, u32::MAX.to_be_bytes().to_vec(), 1.0)] + { + let mut img = TestImage::rgb8(1, 1); + img.base_type = 1; + img.precision = precision; + let mut l = TestLayer::rgba("F", 1, 1, bytes); + l.kind = 2; + img.layers.push(l); + let bytes = img.write(); + assert_eq!(pixels(&open(&bytes).unwrap(), 0).data, [want], "precision {precision}"); + } +} + +#[test] +fn half_floats_convert_exactly() { + for (bits, want) in [ + (0x0000u16, 0.0f32), + (0x3c00, 1.0), + (0xc000, -2.0), + (0x3555, (1024.0 + 341.0) / 4096.0), + (0x7bff, 65504.0), + (0x0400, 2f32.powi(-14)), + (0x0001, 2f32.powi(-24)), + (0x03ff, 1023.0 * 2f32.powi(-24)), + (0x7c00, f32::INFINITY), + (0xfc00, f32::NEG_INFINITY), + ] { + assert_eq!(half_to_f32(bits), want, "{bits:#06x}"); + } + assert!(half_to_f32(0x8000).is_sign_negative() && half_to_f32(0x8000) == 0.0); + assert!(half_to_f32(0x7e00).is_nan()); +} + +#[test] +fn precision_codes_depend_on_the_version() { + let p = |bytes, float, linear| Precision { bytes, float, linear }; + assert_eq!(Precision::from_header(3, 999), Ok(Precision::GAMMA8)); + assert_eq!(Precision::from_header(4, 3), Ok(p(2, true, true))); + assert_eq!(Precision::from_header(5, 500), Ok(p(4, true, true))); + assert_eq!(Precision::from_header(6, 450), Ok(p(2, true, false))); + assert_eq!(Precision::from_header(7, 500), Ok(p(2, true, true))); + assert_eq!(Precision::from_header(12, 750), Ok(p(8, true, false))); + for (version, code) in [(4, 5), (5, 600), (7, 400), (12, 0)] { + assert!(Precision::from_header(version, code).is_err(), "{version} {code}"); + } +} + +#[test] +fn indexed_images_use_the_colormap() { + let mut img = TestImage::rgb8(2, 1); + img.base_type = 2; + let mut cmap = 3u32.to_be_bytes().to_vec(); + cmap.extend_from_slice(&[255, 0, 0, 0, 255, 0, 0, 0, 255]); + img.image_props.push((1, cmap)); + let mut l = TestLayer::rgba("I", 2, 1, vec![2, 255, 1, 128]); + l.kind = 5; // indexed with alpha + img.layers.push(l); + let mut plain = TestLayer::rgba("P", 2, 1, vec![0, 9]); + plain.kind = 4; // indexed, no alpha; index 9 is past the colormap + img.layers.push(plain); + img.channels.push(("C", vec![255, 0], false)); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + assert_eq!((xcf.image().base_type, xcf.image().colormap.len()), (BaseType::Indexed, 3)); + assert_eq!(pixels(&xcf, 0).data, [0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 128.0 / 255.0]); + let p = pixels(&xcf, 1); + assert_eq!((p.channels, p.data.as_slice()), (3, &[1.0, 0.0, 0.0, 9.0 / 255.0, 9.0 / 255.0, 9.0 / 255.0][..])); + // Channels are plain samples even in an indexed image. + assert_eq!(xcf.channel(0, &mut MAX_PIXEL_BYTES.clone(), GO).unwrap().1.data, [1.0, 0.0]); +} + +#[test] +fn channels_are_the_extras_and_the_selection() { + let mut img = TestImage::rgb8(4, 4); + img.layers.push(TestLayer::rgba("L", 4, 4, rgba(4, 4, |_, _| [0, 0, 0, 255]))); + img.channels.push(("Extra", (0..16).map(|i| i as u8 * 16).collect(), false)); + img.channels.push(("Selection Mask", vec![255; 16], true)); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + assert_eq!(xcf.image().channel_count, 2); + let mut budget = 200; + let (extra, px) = xcf.channel(0, &mut budget, GO).unwrap(); + assert_eq!((extra, at(&px, 3, 1)), (Channel { name: "Extra".into(), selection: false }, &[7.0 * 16.0 / 255.0][..])); + let (selection, px) = xcf.channel(1, &mut budget, GO).unwrap(); + assert_eq!((selection.selection, px.data[0], budget), (true, 1.0, 200 - 2 * 64)); + assert!(xcf.channel(2, &mut budget, GO).is_err()); + assert!(xcf.layer_pixels(1, &mut budget, GO).is_err() && xcf.layer_mask(1, &mut budget, GO).is_err()); +} + +#[test] +fn image_parasites_resolution_guides_and_comment() { + let mut img = TestImage::rgb8(10, 10); + img.image_props.push((19, [300.0f32, 299.0].into_iter().flat_map(f32::to_be_bytes).collect())); + let mut guides = Vec::new(); + for (position, orientation) in [(4i32, 1u8), (7, 2), (-3, 1), (5, 9)] { + guides.extend_from_slice(&position.to_be_bytes()); + guides.push(orientation); + } + img.image_props.push((18, guides)); + let mut parasites = Vec::new(); + parasite_record(&mut parasites, "gimp-comment", b"hello\0"); + parasite_record(&mut parasites, "icc-profile", &[1, 2, 3]); + img.image_props.push((21, parasites)); + // An unknown property is skipped by its length. + img.image_props.push((99, vec![1, 2, 3, 4, 5])); + img.layers.push(TestLayer::rgba("L", 10, 10, rgba(10, 10, |_, _| [0, 0, 0, 255]))); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + let image = xcf.image(); + assert_eq!(image.resolution, Some((300.0, 299.0))); + let (h, v) = (Orientation::Horizontal, Orientation::Vertical); + assert_eq!( + image.guides, + [Guide { position: 4, orientation: h }, Guide { position: 7, orientation: v }], + "a negative guide before version 15 is stray" + ); + assert_eq!((image.comment.as_deref(), image.icc_profile.as_deref()), (Some("hello"), Some(&[1u8, 2, 3][..]))); + assert_eq!(image.path_count, 0); + img.version = 15; + assert_eq!(open(&img.write()).unwrap().image().guides.len(), 3, "from version 15 a negative guide is off canvas, not stray"); +} + +#[test] +fn clipping_text_vector_effects_and_floating_selections_are_flagged() { + let mut img = TestImage::rgb8(4, 4); + img.version = 20; + let mut clipped = TestLayer::rgba("Clipped", 4, 4, rgba(4, 4, |_, _| [1, 1, 1, 255])); + let mut parasite = Vec::new(); + parasite_record(&mut parasite, "gimphoto-clipped", &[1]); + clipped.props = vec![(21, parasite), (26, 1u32.to_be_bytes().to_vec()), (47, vec![0; 8])]; + img.layers.push(clipped); + let mut floating = TestLayer::rgba("Floating Selection", 2, 2, rgba(2, 2, |_, _| [2, 2, 2, 255])); + floating.props = vec![(5, vec![0; 8])]; + img.layers.push(floating); + let mut text = TestLayer::rgba("Bottom", 4, 4, rgba(4, 4, |_, _| [0, 0, 0, 255])); + let mut parasite = Vec::new(); + parasite_record(&mut parasite, "gimp-text-layer", b"(text \"x\")"); + text.props = vec![(21, parasite)]; + img.layers.push(text); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + let image = xcf.image(); + let l = &image.layers; + assert!(l[0].clipped && l[0].text && l[0].vector && !l[0].floating_selection); + assert!(l[1].floating_selection && !l[1].clipped); + assert!(l[2].text && !l[2].vector); + assert_eq!(names(image, &image.tree().roots), ["Clipped", "Bottom"], "the floating selection is not part of the stack"); + // Version 20 layers end with a list of effect pointers. + let effects_end = bytes.windows(8).rposition(|w| w == [0; 8]).unwrap(); + assert!(effects_end > 0); +} + +#[test] +fn layer_effect_pointers_are_counted_and_bounded() { + let layer = |effects: usize| { + let mut w = W::new(20); + for v in [1, 1, 0, 150] { + w.u32(v); + } + w.end(); + let slot = w.slot(); + w.ptr(0); + w.ptr(0); + w.ptr(0); // paths + let at = w.out.len(); + w.patch(slot, at); + for v in [1, 1, 1] { + w.u32(v); + } + w.string("fx"); + w.end(); + w.ptr(0); + w.ptr(0); + for _ in 0..effects { + w.ptr(1); + } + w.ptr(0); + w.out + }; + assert_eq!(open(&layer(1024)).unwrap().image().layers[0].effects, 1024); + assert!(open(&layer(1025)).is_err()); +} + +/// GIMP's link-layer length omits one u32. Trusting it shifts the hierarchy pointer by four +/// bytes, even though the cached pixels and every offset in the file are valid. +#[test] +fn linked_layers_open_cached_pixels_with_short_or_correct_property_lengths() { + for (precision, data) in [ + (150, vec![51, 102, 153, 255]), + (250, [13107u16, 26214, 39321, 65535].into_iter().flat_map(u16::to_be_bytes).collect()), + (600, [0.2f32, 0.4, 0.6, 1.0].into_iter().flat_map(f32::to_be_bytes).collect()), + ] { + for (path, width, height) in [("assets/étiquette.svg", 2000, 1270), ("assets/label.png", 0, 0), ("", 0, 0)] { + let mut payload = W { out: Vec::new(), wide: true }; + payload.u32(1); + payload.string(path); + payload.u32(width); + payload.u32(height); + let payload = payload.out; + let marker = [48u32.to_be_bytes(), (payload.len() as u32).to_be_bytes()].concat(); + let mut img = TestImage::rgb8(1, 1); + img.version = 25; + img.precision = precision; + let mut linked = TestLayer::rgba("Linked", 1, 1, data.clone()); + // Later properties must still be read, including unknown ones skipped by length. + linked.props = vec![(48, payload.clone()), (99, vec![1, 2, 3]), (33, 0.375f32.to_be_bytes().to_vec()), (8, 0u32.to_be_bytes().to_vec())]; + img.layers.push(linked); + img.layers.push(TestLayer::rgba("Bottom", 1, 1, data.clone())); + for short in [false, true] { + let mut bytes = img.write(); + let at = bytes.windows(marker.len()).position(|w| w == marker).unwrap(); + if short { + bytes[at + 4..at + 8].copy_from_slice(&((payload.len() - 4) as u32).to_be_bytes()); + } + let xcf = open(&bytes).unwrap_or_else(|e| panic!("precision {precision}, path {path:?}, short {short}: {e}")); + let layers = &xcf.image().layers; + assert_eq!(layers.len(), 2); + assert_eq!((layers[0].link, layers[0].opacity, layers[0].visible, layers[1].link), (true, 0.375, false, false)); + for layer in 0..2 { + for (got, expected) in pixels(&xcf, layer).data.into_iter().zip([0.2, 0.4, 0.6, 1.0]) { + assert!((got - expected).abs() < 1e-5, "precision {precision}: {got} != {expected}"); + } + } + } + } + } +} + +#[test] +fn truncated_and_oversized_link_layer_fields_are_errors() { + let mut payload = W { out: Vec::new(), wide: true }; + payload.u32(1); + payload.string("assets/label.svg"); + payload.u32(2000); + payload.u32(1270); + let payload = payload.out; + let marker = [48u32.to_be_bytes(), (payload.len() as u32).to_be_bytes()].concat(); + let mut img = TestImage::rgb8(1, 1); + img.version = 25; + let mut linked = TestLayer::rgba("Linked", 1, 1, vec![51, 102, 153, 255]); + linked.props.push((48, payload.clone())); + img.layers.push(linked); + let bytes = img.write(); + let start = bytes.windows(marker.len()).position(|w| w == marker).unwrap() + 8; + // Cut within the flags, string length, path and either dimension. + for end in start..start + payload.len() { + assert!(open(&bytes[..end]).is_err(), "truncated at {end}"); + } + for len in [(MAX_STRING + 1) as u32, u32::MAX] { + let mut oversized = bytes.clone(); + oversized[start + 4..start + 8].copy_from_slice(&len.to_be_bytes()); + assert!(open(&oversized).is_err(), "path length {len}"); + } +} + +#[test] +fn version_3_files_use_32_bit_pointers_and_legacy_modes() { + let mut img = TestImage::rgb8(5, 5); + img.version = 3; + let mut l = TestLayer::rgba("Old", 5, 5, rgba(5, 5, |x, _| [x as u8, 0, 0, 255])); + l.mode = 3; // Multiply (legacy) + img.layers.push(l); + let bytes = img.write(); + assert!(bytes.starts_with(b"gimp xcf v003\0")); + let xcf = open(&bytes).unwrap(); + assert_eq!((xcf.image().version, xcf.image().precision, xcf.image().layers[0].mode), (3, Precision::GAMMA8, 3)); + assert_eq!(at(&pixels(&xcf, 0), 4, 0)[0], 4.0 / 255.0); + // Version 0 ("file") as well. + let mut img0 = TestImage::rgb8(2, 2); + img0.version = 0; + img0.layers.push(TestLayer::rgba("Oldest", 2, 2, rgba(2, 2, |_, _| [7, 7, 7, 255]))); + assert_eq!(open(&img0.write()).unwrap().image().version, 0); + // A version newer than the reader knows still opens. + img0.version = KNOWN_VERSION + 1; + assert_eq!(read_all(&img0.write()), Ok(16)); +} + +#[test] +fn rle_long_runs_and_literals_round_trip() { + // A tile with runs over 127 and long literal stretches, in every byte plane. + let w = 64; + let data = rgba(w, 64, |x, y| if y < 40 { [200, 1, 2, 255] } else { [(x * 7 + y) as u8, (x * 3) as u8, y as u8, 255] }); + assert_eq!(rle_decode(&rle(&data, 4), 4, 64 * 64).unwrap(), data); + // Long literal (op 128) and the error cases. + assert_eq!(rle_decode(&[128, 0, 3, 7, 8, 9], 1, 3).unwrap(), [7, 8, 9]); + assert_eq!(rle_decode(&[127, 0, 4, 9], 1, 4).unwrap(), [9, 9, 9, 9]); + assert_eq!(rle_decode(&[254, 1, 2, 0, 5], 1, 3).unwrap(), [1, 2, 5]); + for bad in [&[][..], &[3], &[127, 0], &[128, 0, 3, 7], &[2, 9], &[253, 1]] { + assert!(rle_decode(bad, 1, 2).is_err(), "{bad:?}"); + } +} + +#[test] +fn limits_and_malformed_structures_are_errors() { + // A canvas past the side limit, and one past the area limit. + let mut big = TestImage::rgb8(1, 1); + big.width = MAX_SIDE + 1; + assert!(open(&big.write()).is_err()); + (big.width, big.height) = (MAX_SIDE, 224); + assert!(open(&big.write()).is_err()); + big.height = 223; + assert!(open(&big.write()).is_ok()); + big.height = 0; + assert!(open(&big.write()).is_err()); + // A layer whose declared size has no pixels behind it (hierarchy pointer to garbage). + let mut img = TestImage::rgb8(4, 4); + img.layers.push(TestLayer::rgba("L", 4, 4, rgba(4, 4, |_, _| [0; 4]))); + let mut bytes = img.write(); + let n = bytes.len(); + bytes[n - 10..].fill(0xff); + assert!(read_all(&bytes).is_err()); + // Wrong signature, unknown version tag, unknown compression, image type and precision. + assert!(matches!(open(b"gimp xcf vXYZ\0"), Err(Error::Invalid(_)))); + assert!(open(b"not an xcf").is_err()); + let good = img.write(); + assert!(read_all(&good).is_ok()); + let patched = |at: usize, v: u8| { + let mut b = good.clone(); + b[at] = v; + open(&b).err() + }; + assert!(patched(14 + 12 + 4 + 8, 3).is_some(), "compression"); + assert!(patched(14 + 11, 3).is_some(), "image type"); + assert!(patched(14 + 15, 1).is_some(), "precision"); + // A layer of another colour model, and an unknown layer type. + for kind in [2, 6] { + img.layers[0].kind = kind; + assert!(open(&img.write()).is_err(), "layer type {kind}"); + } + // Pixels of another size than the layer declares. + img.layers[0].kind = 1; + let mut bytes = img.write(); + let at = bytes.windows(12).rposition(|w| w == [0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 4]).unwrap(); + bytes[at + 3] = 3; + assert!(open(&bytes).is_ok() && read_all(&bytes).is_err()); +} + +#[test] +fn layer_channel_property_and_metadata_counts_are_bounded() { + let header = |w: &mut W| { + for v in [1, 1, 0, 150] { + w.u32(v); + } + w.end(); + }; + // More layer pointers, then more channel pointers, than the limits. + for (layers, channels, ok) in [(MAX_LAYERS + 1, 0, false), (0, MAX_CHANNELS + 1, false), (0, MAX_CHANNELS, true)] { + let mut w = W::new(11); + header(&mut w); + (0..layers).for_each(|_| w.ptr(1)); + w.ptr(0); + (0..channels).for_each(|_| w.ptr(1)); + w.ptr(0); + assert_eq!(open(&w.out).is_ok(), ok, "{layers} layers, {channels} channels"); + } + // 4097 properties. + let mut w = W::new(11); + for v in [1, 1, 0, 150] { + w.u32(v); + } + (0..4097).for_each(|_| w.prop(99, &[])); + w.end(); + w.ptr(0); + w.ptr(0); + assert_eq!(open(&w.out).err(), Some(Error::Invalid("too many properties".into()))); + // A property declaring more than the payload limit. + let mut w = W::new(11); + for v in [1, 1, 0, 150, 99, MAX_PAYLOAD as u32 + 1] { + w.u32(v); + } + assert!(matches!(open(&w.out), Err(Error::Invalid(m)) if m.contains("declares"))); + // Forty pointers to one layer whose name is a megabyte: its copies pass the metadata budget. + let many = |pointers: usize| { + let mut w = W::new(11); + header(&mut w); + let slots: Vec = (0..pointers).map(|_| w.slot()).collect(); + w.ptr(0); + w.ptr(0); + let at = w.out.len(); + slots.into_iter().for_each(|s| w.patch(s, at)); + for v in [1, 1, 1] { + w.u32(v); + } + w.string(&"n".repeat(MAX_STRING - 1)); + w.end(); + w.ptr(0); + w.ptr(0); + w.out + }; + assert!(open(&many(32)).is_ok()); + assert_eq!(open(&many(33)).err(), Some(Error::Invalid("layer metadata exceeds the budget".into()))); +} + +#[test] +fn the_pixel_budget_is_charged_before_decoding_and_decoding_can_be_cancelled() { + let mut img = TestImage::rgb8(200, 200); + img.layers.push(TestLayer::rgba("L", 200, 200, rgba(200, 200, |_, _| [1, 2, 3, 255]))); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + let cost = 200 * 200 * 4 * 4; + let mut budget = cost - 1; + assert!(matches!(xcf.layer_pixels(0, &mut budget, GO), Err(Error::Invalid(m)) if m.contains("pixel limit"))); + let mut budget = cost + 5; + assert!(xcf.layer_pixels(0, &mut budget, GO).is_ok()); + assert_eq!(budget, 5); + assert_eq!(xcf.layer_pixels(0, &mut MAX_PIXEL_BYTES.clone(), &|| false), Err(Error::Cancelled)); +} + +#[test] +fn gzipped_files_are_recognised_by_name_and_inflated() { + use std::io::Write; + let mut img = TestImage::rgb8(3, 3); + img.layers.push(TestLayer::rgba("L", 3, 3, rgba(3, 3, |_, _| [4, 5, 6, 255]))); + let plain = img.write(); + let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + e.write_all(&plain).unwrap(); + let gz = e.finish().unwrap(); + assert!(is_xcf(&plain) && !is_xcf(&gz)); + assert!(is_gzipped_xcf("a/b/photo.XCF.GZ", &gz) && is_gzipped_xcf("x.xcfgz", &gz) && is_gzipped_xcf("c:\\dir.xcf.gz\\y.xcf.gz", &gz)); + assert!(!is_gzipped_xcf("photo.xcf", &gz) && !is_gzipped_xcf("photo.xcf.gz", &plain) && !is_gzipped_xcf("dir.xcf.gz/photo.gz", &gz)); + assert_eq!(gunzip(&gz).unwrap(), plain); + assert!(gunzip(&gz[..gz.len() / 2]).is_err()); +} + +/// `PROP_FLOAT_OPACITY` wins over `PROP_OPACITY` whichever comes first in the file. +#[test] +fn float_opacity_wins_over_opacity_in_either_order() { + let mut img = TestImage::rgb8(4, 4); + // The writer emits OPACITY (0.4 → 102) then FLOAT_OPACITY 0.4; an OPACITY 255 after them must not win. + let mut byte_last = TestLayer::rgba("Float then byte", 4, 4, rgba(4, 4, |_, _| [1, 2, 3, 255])); + byte_last.opacity = 0.4; + byte_last.props = vec![(6, 255u32.to_be_bytes().to_vec())]; + // A later FLOAT_OPACITY replaces the earlier one; one that is not finite does not. + let mut float_last = TestLayer::rgba("Byte then float", 4, 4, rgba(4, 4, |_, _| [1, 2, 3, 255])); + float_last.opacity = 0.4; + float_last.props = vec![(33, 0.25f32.to_be_bytes().to_vec()), (33, f32::NAN.to_be_bytes().to_vec())]; + img.layers.push(byte_last); + img.layers.push(float_last); + let bytes = img.write(); + let xcf = open(&bytes).unwrap(); + assert_eq!((xcf.image().layers[0].opacity, xcf.image().layers[1].opacity), (0.4, 0.25)); +} + +/// One PROP_PARASITES record: name, u32 flags, u32 len, then the payload. +fn parasite_record(out: &mut Vec, name: &str, payload: &[u8]) { + out.extend_from_slice(&((name.len() as u32) + 1).to_be_bytes()); + out.extend_from_slice(name.as_bytes()); + out.push(0); + out.extend_from_slice(&0u32.to_be_bytes()); + out.extend_from_slice(&(payload.len() as u32).to_be_bytes()); + out.extend_from_slice(payload); +} + +#[test] +fn duplicate_parasites_keep_order_and_last_value() { + let mut data = Vec::new(); + parasite_record(&mut data, "gimp-comment", b"first"); + parasite_record(&mut data, "gimp-image-grid", b"grid"); + parasite_record(&mut data, "gimp-comment", b"second"); + data.extend_from_slice(&[0, 0, 0, 9, b'c', b'u', b't']); + let out = parasites(&data); + assert_eq!(out, [("gimp-comment".to_string(), &b"second"[..]), ("gimp-image-grid".to_string(), &b"grid"[..])]); +} + +#[test] +fn a_user_unit_property_is_measured_not_trusted() { + // PROP_USER_UNIT's length word is wrong in every release: three strings (XCF 21+) or five. + // Which it is, is decided by whether a property header follows the third: a fourth string + // shorter than 64 bytes would look like one, so the five-string case here has a long one. + let long = "s".repeat(70); + for strings in [3, 5] { + let mut img = TestImage::rgb8(2, 2); + let mut unit = W { out: Vec::new(), wide: true }; + unit.out.extend_from_slice(&25.4f32.to_be_bytes()); + unit.u32(2); + (0..strings).for_each(|i| unit.string(["id", "sym", "abbr", long.as_str(), "plural"][i])); + img.image_props.push((24, unit.out)); + img.image_props.push((19, [96.0f32, 96.0].into_iter().flat_map(f32::to_be_bytes).collect())); + img.layers.push(TestLayer::rgba("L", 2, 2, rgba(2, 2, |_, _| [4, 5, 6, 255]))); + let mut bytes = img.write(); + let marker = 24u32.to_be_bytes(); + let at = bytes.windows(4).position(|w| w == marker).unwrap(); + bytes[at + 4..at + 8].copy_from_slice(&3u32.to_be_bytes()); + let xcf = open(&bytes).unwrap_or_else(|e| panic!("{strings} strings: {e}")); + assert_eq!(xcf.image().resolution, Some((96.0, 96.0)), "{strings} strings"); + assert_eq!(read_all(&bytes), Ok(16)); + } +} + +#[test] +fn an_rle_run_of_zero_length_is_an_error() { + // Long runs (op 127 / 128) carry a 16-bit length; zero consumes input without producing output. + assert!(rle_decode(&[127, 0, 0, 5, 3, 0, 9], 1, 4).is_err()); + assert!(rle_decode(&[128, 0, 0, 3, 0, 9], 1, 4).is_err()); + assert_eq!(rle_decode(&[127, 0, 4, 9], 1, 4).unwrap(), [9, 9, 9, 9]); +} + +#[test] +fn channel_names_are_charged_to_the_metadata_budget() { + // Channel pointers that all name one channel with a megabyte name: each read copies the name. + let mut w = W::new(11); + for v in [1, 1, 0, 150] { + w.u32(v); + } + w.end(); + w.ptr(0); + let slots: Vec = (0..40).map(|_| w.slot()).collect(); + w.ptr(0); + let at = w.out.len(); + slots.into_iter().for_each(|s| w.patch(s, at)); + w.u32(1); + w.u32(1); + w.string(&"n".repeat(MAX_STRING - 1)); + w.end(); + let hs = w.slot(); + let h = hierarchy(&mut w, 1, 1, 1, &[7], Compression::None); + w.patch(hs, h); + let xcf = open(&w.out).unwrap(); + let mut budget = MAX_PIXEL_BYTES; + let results: Vec<_> = (0..40).map(|i| xcf.channel(i, &mut budget, GO).map(|(c, _)| c.name.len())).collect(); + assert!(results[..32].iter().all(|r| *r == Ok(MAX_STRING - 1)), "32 copies fit the 32 MiB budget"); + assert!(results[32..].iter().all(|r| *r == Err(Error::Invalid("channel metadata exceeds the budget".into())))); +} diff --git a/crates/xcf/src/tiles.rs b/crates/xcf/src/tiles.rs new file mode 100644 index 000000000..5a567558a --- /dev/null +++ b/crates/xcf/src/tiles.rs @@ -0,0 +1,70 @@ +//! One tile's bytes: uncompressed, zlib-coded or RLE-coded. + +use std::io::Read; + +use crate::{Compression, Result, invalid}; + +/// What one tile's bytes decode to, for a drawable of `bpp` bytes per pixel: `pixels × bpp` +/// interleaved bytes. +pub(crate) fn decode(input: &[u8], compression: Compression, bpp: usize, pixels: usize) -> Result> { + let expected = pixels.checked_mul(bpp).ok_or_else(|| invalid("tile size overflow"))?; + match compression { + Compression::None => input.get(..expected).map(<[u8]>::to_vec).ok_or_else(|| invalid("an uncompressed tile is cut short")), + Compression::Zlib => { + let mut out = Vec::with_capacity(expected); + flate2::read::ZlibDecoder::new(input).take(expected as u64).read_to_end(&mut out).map_err(|e| invalid(format!("zlib tile: {e}")))?; + if out.len() != expected { + return Err(invalid("a zlib tile is cut short")); + } + Ok(out) + } + Compression::Rle => rle_decode(input, bpp, pixels), + } +} + +/// RLE tile data: one run-length stream per byte position of the pixel, each of `pixels` bytes. +pub(crate) fn rle_decode(input: &[u8], bpp: usize, pixels: usize) -> Result> { + let short = || invalid("an RLE tile is cut short"); + let mut out = vec![0u8; pixels * bpp]; + let mut pos = 0usize; + let mut plane = Vec::with_capacity(pixels); + for b in 0..bpp { + plane.clear(); + while plane.len() < pixels { + let op = *input.get(pos).ok_or_else(short)?; + pos += 1; + let mut long = || -> Result { + let (p, q) = (input.get(pos).copied().ok_or_else(short)?, input.get(pos + 1).copied().ok_or_else(short)?); + pos += 2; + Ok(usize::from(p) * 256 + usize::from(q)) + }; + let (run, verbatim) = match op { + 0..=126 => (usize::from(op) + 1, false), + 127 => (long()?, false), + 128 => (long()?, true), + _ => (256 - usize::from(op), true), + }; + if plane.len() + run > pixels { + return Err(invalid("an RLE run crosses the end of its tile")); + } + // A long run of length 0 consumes input without producing output: a tile of them + // (reachable from many tile pointers) is work the pixel budget never charges. + if run == 0 { + return Err(invalid("an RLE run has no length")); + } + if verbatim { + let data = input.get(pos..pos + run).ok_or_else(short)?; + pos += run; + plane.extend_from_slice(data); + } else { + let v = *input.get(pos).ok_or_else(short)?; + pos += 1; + plane.resize(plane.len() + run, v); + } + } + for (slot, v) in out.iter_mut().skip(b).step_by(bpp.max(1)).zip(&plane) { + *slot = *v; + } + } + Ok(out) +} diff --git a/crates/xls/Cargo.toml b/crates/xls/Cargo.toml index f742798c5..41d3362fb 100644 --- a/crates/xls/Cargo.toml +++ b/crates/xls/Cargo.toml @@ -12,4 +12,5 @@ workspace = true [dependencies] craft-cfb = { workspace = true } +craft-sheet = { workspace = true } thiserror = { workspace = true } diff --git a/crates/xls/README.md b/crates/xls/README.md index c0b6c7489..7fbb93280 100644 --- a/crates/xls/README.md +++ b/crates/xls/README.md @@ -3,7 +3,8 @@ A clean-room reader for Excel 97-2003 workbooks (`.xls`, BIFF8). It turns the bytes of a file into a `Workbook` that keeps the file's own terms: cells, formulas as text, the format table, column and row records. Mapping that onto an application's document is the caller's work. -No `unsafe`; the only dependencies are `craft-cfb` (the compound file container) and `thiserror`. +No `unsafe`; the only dependencies are `craft-cfb` (the compound file container), `craft-sheet` (cell +positions, values and tables shared with the other spreadsheet formats) and `thiserror`. No third-party implementation was consulted. | Document | Used for | diff --git a/crates/xls/src/expr.rs b/crates/xls/src/expr.rs index 704e2a57c..f4e0b114d 100644 --- a/crates/xls/src/expr.rs +++ b/crates/xls/src/expr.rs @@ -3,12 +3,9 @@ use std::fmt::Write; use std::sync::Arc; -use crate::CellError; +use craft_sheet::{push_col, quote_sheet, sheet_needs_quotes}; -/// Rows and columns of the grid a sheet name is tested against when deciding whether it reads -/// as a cell reference (the SpreadsheetML grid, which is the larger one). -const GRID_ROWS: u32 = 1_048_576; -const GRID_COLS: u32 = 16_384; +use crate::CellError; /// One end of a reference, with `$` anchors. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -116,31 +113,6 @@ pub(crate) enum Expr { Paren(Box), } -/// 0 → `A`, 25 → `Z`, 26 → `AA`. -fn push_col(s: &mut String, col: u32) { - let mut letters = [0u8; 8]; - let mut i = letters.len(); - let mut n = u64::from(col) + 1; - while n > 0 && i > 0 { - i -= 1; - if let Some(l) = letters.get_mut(i) { - *l = b'A' + ((n - 1) % 26) as u8; - } - n = (n - 1) / 26; - } - for &l in letters.get(i..).unwrap_or_default() { - s.push(char::from(l)); - } -} - -/// The A1 text of a cell (`B3`), for messages and tests. -pub(crate) fn a1(row: u32, col: u32) -> String { - let mut s = String::new(); - push_col(&mut s, col); - let _ = write!(s, "{}", u64::from(row) + 1); - s -} - fn push_anchor(s: &mut String, a: &Anchor) { if a.col_abs { s.push('$'); @@ -152,53 +124,6 @@ fn push_anchor(s: &mut String, a: &Anchor) { let _ = write!(s, "{}", u64::from(a.row) + 1); } -/// Whether `name` is an A1 cell reference inside the grid (`A1`, `xfd1048576`). -fn is_a1(name: &str) -> bool { - let letters = name.bytes().take_while(u8::is_ascii_alphabetic).count(); - let Some((cols, digits)) = name.split_at_checked(letters) else { return false }; - if cols.is_empty() || cols.len() > 3 || digits.is_empty() || digits.len() > 7 || !digits.bytes().all(|b| b.is_ascii_digit()) { - return false; - } - let col = cols.bytes().fold(0u32, |n, b| n * 26 + u32::from(b.to_ascii_uppercase() - b'A') + 1); - let row: u32 = digits.parse().unwrap_or(0); - (1..=GRID_COLS).contains(&col) && (1..=GRID_ROWS).contains(&row) -} - -/// Whether `name` reads as an R1C1 reference: `R`, `C`, `RC`, `R1`, `C1`, `R1C`, `RC1`, `R1C1` -/// in any case. -fn is_r1c1_token(name: &str) -> bool { - let mut chars = name.chars().peekable(); - let mut letters = 0; - for letter in ['r', 'c'] { - if chars.peek().is_some_and(|c| c.to_ascii_lowercase() == letter) { - chars.next(); - letters += 1; - while chars.peek().is_some_and(char::is_ascii_digit) { - chars.next(); - } - } - } - letters > 0 && chars.next().is_none() -} - -/// Whether Excel quotes a sheet name in a reference (`'My Sheet'!A1`): it starts with a digit or -/// `.`, holds anything but letters (any script), digits, `_` and `.`, reads as an A1 cell or as -/// an R1C1 reference, or is a boolean. -pub fn sheet_needs_quotes(name: &str) -> bool { - let Some(first) = name.chars().next() else { - return true; - }; - if first.is_ascii_digit() || first == '.' || name.chars().any(|c| !(c.is_alphanumeric() || c == '_' || c == '.')) { - return true; - } - is_a1(name) || is_r1c1_token(name) || name.eq_ignore_ascii_case("TRUE") || name.eq_ignore_ascii_case("FALSE") -} - -/// A sheet name as it is written in a reference: quoted, with `'` doubled, when Excel quotes it. -pub fn quote_sheet(name: &str) -> String { - if sheet_needs_quotes(name) { format!("'{}'", name.replace('\'', "''")) } else { name.to_string() } -} - fn push_reference(s: &mut String, r: &Reference) { match &r.sheet { SheetSel::Current => {} @@ -402,19 +327,4 @@ mod tests { assert_eq!(number_to_text(1e-10), "1E-10"); assert!(number(f64::MAX).parse::().is_ok_and(f64::is_finite)); } - - #[test] - fn sheet_names_are_quoted_when_excel_quotes_them() { - for plain in ["Sheet1", "Data_2", "Übersicht", "a.b"] { - assert!(!sheet_needs_quotes(plain), "{plain}"); - } - for quoted in ["", "My Data", "1st", ".x", "A1", "xfd1048576", "R1C1", "rc", "true", "It's"] { - assert!(sheet_needs_quotes(quoted), "{quoted}"); - } - // Outside the grid it is no cell reference. - assert!(!sheet_needs_quotes("XFE1")); - assert!(!sheet_needs_quotes("A1048577")); - assert_eq!(quote_sheet("It's"), "'It''s'"); - assert_eq!(a1(2, 27), "AB3"); - } } diff --git a/crates/xls/src/lib.rs b/crates/xls/src/lib.rs index 20d73ab4c..0dc33f61b 100644 --- a/crates/xls/src/lib.rs +++ b/crates/xls/src/lib.rs @@ -40,13 +40,12 @@ mod styles; #[doc(hidden)] pub mod testing; -pub use expr::{quote_sheet, sheet_needs_quotes}; +pub use craft_sheet::{DEFAULT_PALETTE, quote_sheet, sheet_needs_quotes}; pub use model::{ Alignment, BorderLine, BorderStyle, Borders, Calc, CalcMode, Cell, CellError, CellFormat, CellRef, Color, Column, DefinedName, Fill, Font, Formula, HAlign, Pattern, Range, Row, Script, Sheet, Underline, VAlign, Value, View, Visibility, Workbook, }; pub use read::{is_xls, read, read_with}; -pub use styles::DEFAULT_PALETTE; /// Why a workbook could not be read. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] diff --git a/crates/xls/src/model.rs b/crates/xls/src/model.rs index 3aedf8697..ce88a043d 100644 --- a/crates/xls/src/model.rs +++ b/crates/xls/src/model.rs @@ -2,98 +2,8 @@ //! the format (widths and heights keep the file's units, formulas are text). use std::collections::BTreeMap; -use std::sync::Arc; -/// A cell position, zero-based. Ordered by row, then column. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct CellRef { - pub row: u32, - pub col: u32, -} - -impl CellRef { - pub const fn new(row: u32, col: u32) -> Self { - CellRef { row, col } - } - - /// The A1 text (`B3`). - pub fn a1(self) -> String { - crate::expr::a1(self.row, self.col) - } -} - -/// A rectangle of cells, both corners included; `first` is the top left one. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct Range { - pub first: CellRef, - pub last: CellRef, -} - -impl Range { - /// The rectangle spanned by two corners, in any order. - pub fn new(a: CellRef, b: CellRef) -> Self { - Range { first: CellRef::new(a.row.min(b.row), a.col.min(b.col)), last: CellRef::new(a.row.max(b.row), a.col.max(b.col)) } - } - - pub fn contains(&self, c: CellRef) -> bool { - (self.first.row..=self.last.row).contains(&c.row) && (self.first.col..=self.last.col).contains(&c.col) - } - - pub fn is_single(&self) -> bool { - self.first == self.last - } -} - -/// The error values a BIFF8 file stores ([MS-XLS] 2.5.10, BErr). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum CellError { - Null, - Div0, - Value, - Ref, - Name, - Num, - NA, - GettingData, -} - -impl CellError { - pub fn as_str(&self) -> &'static str { - match self { - CellError::Null => "#NULL!", - CellError::Div0 => "#DIV/0!", - CellError::Value => "#VALUE!", - CellError::Ref => "#REF!", - CellError::Name => "#NAME?", - CellError::Num => "#NUM!", - CellError::NA => "#N/A", - CellError::GettingData => "#GETTING_DATA", - } - } -} - -/// A cell's stored value (for a formula cell, its saved result). -#[derive(Clone, Debug, Default, PartialEq)] -pub enum Value { - #[default] - Empty, - Number(f64), - Text(Arc), - Bool(bool), - Error(CellError), -} - -impl Value { - /// A number, or `#NUM!` when it is NaN or infinite (Excel never stores those). Negative zero - /// becomes zero. - pub fn number(v: f64) -> Value { - if v.is_finite() { Value::Number(if v == 0.0 { 0.0 } else { v }) } else { Value::Error(CellError::Num) } - } - - pub fn is_empty(&self) -> bool { - matches!(self, Value::Empty) - } -} +pub use craft_sheet::{BorderStyle, CellError, CellRef, HAlign, Pattern, Range, Script, Underline, VAlign, Value, Visibility}; /// A cell's formula. #[derive(Clone, Debug, PartialEq, Eq)] @@ -114,15 +24,6 @@ pub struct Cell { pub formula: Option, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum Visibility { - #[default] - Visible, - Hidden, - /// Hidden, and not offered by Excel's Unhide dialog. - VeryHidden, -} - /// A column's ColInfo record ([MS-XLS] 2.4.53). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Column { @@ -224,24 +125,6 @@ pub enum Color { Rgb(u32), } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum Underline { - #[default] - None, - Single, - Double, - SingleAccounting, - DoubleAccounting, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum Script { - #[default] - Baseline, - Superscript, - Subscript, -} - /// A Font record ([MS-XLS] 2.4.122). #[derive(Clone, Debug, Default, PartialEq)] pub struct Font { @@ -261,29 +144,6 @@ pub struct Font { pub charset: Option, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum HAlign { - #[default] - General, - Left, - Center, - Right, - Fill, - Justify, - CenterAcross, - Distributed, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum VAlign { - Top, - Center, - #[default] - Bottom, - Justify, - Distributed, -} - #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct Alignment { pub h: HAlign, @@ -295,25 +155,6 @@ pub struct Alignment { pub shrink: bool, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum BorderStyle { - #[default] - None, - Thin, - Medium, - Dashed, - Dotted, - Thick, - Double, - Hair, - MediumDashed, - DashDot, - MediumDashDot, - DashDotDot, - MediumDashDotDot, - SlantDashDot, -} - /// One border side. A side without a style has the automatic colour. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct BorderLine { @@ -333,31 +174,6 @@ pub struct Borders { pub diag_up: BorderLine, } -/// Fill patterns, named as SpreadsheetML names them. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum Pattern { - #[default] - None, - Solid, - Gray50, - Gray75, - Gray25, - DarkHorizontal, - DarkVertical, - DarkDown, - DarkUp, - DarkGrid, - DarkTrellis, - LightHorizontal, - LightVertical, - LightDown, - LightUp, - LightGrid, - LightTrellis, - Gray125, - Gray0625, -} - /// A cell's fill. Without a pattern both colours are automatic. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct Fill { diff --git a/crates/xls/src/styles.rs b/crates/xls/src/styles.rs index 59d687848..ea0fcae8e 100644 --- a/crates/xls/src/styles.rs +++ b/crates/xls/src/styles.rs @@ -9,61 +9,7 @@ use crate::model::{ Alignment, BorderLine, BorderStyle, Borders, CellFormat, Color, Fill, Font, HAlign, Pattern, Script, Underline, VAlign, Workbook, }; use crate::records::Cursor; - -/// Built-in number format codes (en-US) by id. Ids not listed (23–36 are East Asian -/// locale formats) read as General. -const BUILTIN_FORMATS: [(u32, &str); 36] = [ - (0, "General"), - (1, "0"), - (2, "0.00"), - (3, "#,##0"), - (4, "#,##0.00"), - (5, "\"$\"#,##0_);\\(\"$\"#,##0\\)"), - (6, "\"$\"#,##0_);[Red]\\(\"$\"#,##0\\)"), - (7, "\"$\"#,##0.00_);\\(\"$\"#,##0.00\\)"), - (8, "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"), - (9, "0%"), - (10, "0.00%"), - (11, "0.00E+00"), - (12, "# ?/?"), - (13, "# ??/??"), - (14, "m/d/yyyy"), - (15, "d-mmm-yy"), - (16, "d-mmm"), - (17, "mmm-yy"), - (18, "h:mm AM/PM"), - (19, "h:mm:ss AM/PM"), - (20, "h:mm"), - (21, "h:mm:ss"), - (22, "m/d/yyyy h:mm"), - (37, "#,##0 ;(#,##0)"), - (38, "#,##0 ;[Red](#,##0)"), - (39, "#,##0.00;(#,##0.00)"), - (40, "#,##0.00;[Red](#,##0.00)"), - (41, "_(* #,##0_);_(* \\(#,##0\\);_(* \"-\"_);_(@_)"), - (42, "_(\"$\"* #,##0_);_(\"$\"* \\(#,##0\\);_(\"$\"* \"-\"_);_(@_)"), - (43, "_(* #,##0.00_);_(* \\(#,##0.00\\);_(* \"-\"??_);_(@_)"), - (44, "_(\"$\"* #,##0.00_);_(\"$\"* \\(#,##0.00\\);_(\"$\"* \"-\"??_);_(@_)"), - (45, "mm:ss"), - (46, "[h]:mm:ss"), - (47, "mmss.0"), - (48, "##0.0E+0"), - (49, "@"), -]; - -pub(crate) fn builtin_format(id: u32) -> Option<&'static str> { - BUILTIN_FORMATS.iter().find(|(i, _)| *i == id).map(|(_, c)| *c) -} - -/// The colour table a workbook without a Palette record uses, as `0xRRGGBB`: the eight fixed -/// colours, then the 56 a Palette record replaces ([MS-XLS] 2.4.188). -pub const DEFAULT_PALETTE: [u32; 64] = [ - 0x000000, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0x000000, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, - 0xFF00FF, 0x00FFFF, 0x800000, 0x008000, 0x000080, 0x808000, 0x800080, 0x008080, 0xC0C0C0, 0x808080, 0x9999FF, 0x993366, 0xFFFFCC, 0xCCFFFF, - 0x660066, 0xFF8080, 0x0066CC, 0xCCCCFF, 0x000080, 0xFF00FF, 0xFFFF00, 0x00FFFF, 0x800080, 0x800000, 0x008080, 0x0000FF, 0x00CCFF, 0xCCFFFF, - 0xCCFFCC, 0xFFFF99, 0x99CCFF, 0xFF99CC, 0xCC99FF, 0xFFCC99, 0x3366FF, 0x33CCCC, 0x99CC00, 0xFFCC00, 0xFF9900, 0xFF6600, 0x666699, 0x969696, - 0x003366, 0x339966, 0x003300, 0x333300, 0x993300, 0x993366, 0x333399, 0x333333, -]; +use craft_sheet::{DEFAULT_PALETTE, builtin_format}; /// Font records kept at most ([MS-XLS] FontIndex allows indexes up to 1022). const MAX_FONTS: usize = 1024; @@ -453,20 +399,3 @@ pub(crate) fn build(r: &StyleRecords, formats: &HashMap, wb: &mut W wb.cell_styles = named; wb.formats.iter().map(|f| *f == plain).collect() } - -#[cfg(test)] -mod tests { - use super::builtin_format; - - #[test] - fn builtin_format_ids() { - assert_eq!((0..=60).filter(|&id| builtin_format(id).is_some()).count(), 36); - assert_eq!(builtin_format(0), Some("General")); - assert_eq!(builtin_format(14), Some("m/d/yyyy")); - assert_eq!(builtin_format(22), Some("m/d/yyyy h:mm")); - assert_eq!(builtin_format(49), Some("@")); - // 23-36 are locale formats, above 49 is custom. - assert_eq!((23..=36).find_map(builtin_format), None); - assert_eq!(builtin_format(50), None); - } -} diff --git a/crates/xlsx/Cargo.toml b/crates/xlsx/Cargo.toml new file mode 100644 index 000000000..68144070a --- /dev/null +++ b/crates/xlsx/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-xlsx" +description = "Excel workbooks (.xlsx, .xlsm, SpreadsheetML in an OPC package) and binary workbooks (.xlsb): the workbook part, shared strings, the styles tables and a worksheet's rows and cells as a stream, with every other part reachable for the caller." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-opc = { workspace = true } +craft-sheet = { workspace = true } +craft-xml = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/xlsx/README.md b/crates/xlsx/README.md new file mode 100644 index 000000000..09b09c698 --- /dev/null +++ b/crates/xlsx/README.md @@ -0,0 +1,41 @@ +# craft-xlsx + +Excel workbooks: `.xlsx`, `.xlsm`, `.xltx`, `.xltm` (SpreadsheetML in an OPC package, +transitional and strict) and `.xlsb` (the same package with binary parts). Clean-room, from +ECMA-376 Part 1 (SpreadsheetML), [MS-XLSB] and observed files. No `unsafe`. + +This is the part layer. `Package::open` opens the container through `craft-opc` and reads: + +| Call | Gives | +|---|---| +| `workbook()` | `Workbook`: sheets in tab order (name, id, visibility, kind, part), the 1904 date flag, defined names, the active tab, and the whole part as a tree | +| `shared_strings()` | `StringItem`s: text, formatted runs, phonetic readings | +| `styles()` | `Styles`: number formats, fonts, fills, borders, cell and cell-style formats, named styles, differential formats, the indexed palette, as indexed tables | +| `sheet(entry, each)` | each `Row` of `Cell`s to a callback, then a `SheetPart`: the rest of the worksheet as a tree, its relationships, columns and merged cells | +| `opc()`, `read_xml()`, `optional_xml()`, `rels()` | any other part | + +A cell keeps the file's terms: a shared-string index, a format index, the formula text as the +file spells it, value and cell metadata indexes. `CellValue::resolve` gives the value it shows. +Shared formulas are not expanded and formulas are not parsed: that needs a formula grammar. + +A binary workbook gives the same `Workbook`, strings, rows and merged cells, with saved values +only: its formulas are token streams that are not decoded, and its styles are not read (each +cell keeps its format index). + +## Hostile input + +- `Limits.package`: ZIP entries, bytes per part and in all (`craft-opc`). +- `Limits.xml`: one XML part. Rows and shared strings are streamed, so this bounds one row, one + string and what is left of a part, not a sheet's length. +- `Limits.binary_records`, `binary_cells`, `binary_text`: a binary workbook, over all its parts + (40 million records, 4 million cells and as many shared strings, 256 MiB of text, as + `craft-xls` allows). Fixed caps: 1024 sheets, 100,000 merged ranges per sheet, 64 nested + extension blocks. +- Cells and rows outside the 1,048,576 × 16,384 grid are dropped and counted. + +SpreadsheetML is read leniently: a damaged optional part is a warning, a damaged worksheet keeps +the rows before the damage. A binary part that does not parse fails the read, since skipping a +record would lose data without a trace. + +Shared with `craft-xls` and `craft-ods` through `craft-sheet`: `CellRef`, `Range`, `Value`, +`CellError`, `Visibility`, sheet-name quoting, built-in number formats and the palette. diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs new file mode 100644 index 000000000..1859b2c4b --- /dev/null +++ b/crates/xlsx/src/lib.rs @@ -0,0 +1,148 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! Excel workbooks: `.xlsx`/`.xlsm` (SpreadsheetML, ECMA-376 Part 1, transitional and strict) and +//! `.xlsb` (the same package with binary parts, [MS-XLSB]). Clean-room, from the specifications +//! and observed files. +//! +//! This is the part layer: a [`Package`] opens the OPC container (`craft-opc`) and reads +//! +//! - the workbook part: sheets, the date system, defined names ([`Workbook`]); +//! - shared strings with their rich-text runs and phonetic readings ([`StringItem`]); +//! - the styles tables as the file has them ([`Styles`]): number formats, fonts, fills, borders, +//! cell formats, named styles and differential formats, by index; +//! - one worksheet at a time as a stream of [`Row`]s of [`Cell`]s, so a sheet of any length is +//! read without holding it; what is left of the part (properties, columns, merged cells, +//! validation, and so on) comes back as a tree ([`SheetPart`]). +//! +//! Nothing is interpreted beyond the format: a cell holds a shared-string index and a format +//! index, a width is in the file's units, a formula is the file's text. Every other part +//! (drawings, charts, pivot caches, macros) is reachable through [`Package::opc`], so a caller +//! can read it or carry it through unchanged. +//! +//! A binary workbook gives the same [`Workbook`], [`StringItem`]s, [`Row`]s and merged cells: +//! saved values only, since formulas there are token streams that are not decoded and styles are +//! not read. +//! +//! Reading SpreadsheetML is lenient: a damaged optional part is skipped and named in +//! [`Package::warnings`]; only an unreadable package or workbook part is an error. Reading a +//! binary workbook is strict: a record that does not parse fails the read, because skipping it +//! would lose data silently. Input is hostile: [`Limits`] bounds the package, the XML and the +//! binary records, cells outside the grid are dropped, and nothing indexes by a number from the +//! file. +//! +//! ``` +//! # fn main() -> Result<(), craft_xlsx::Error> { +//! # let bytes = craft_xlsx::testing::workbook(&[("Prices", r#"02.5"#)], &["Tea"]); +//! let mut package = craft_xlsx::Package::open(&bytes, &craft_xlsx::Limits::default())?; +//! let workbook = package.workbook()?; +//! let strings = package.shared_strings()?; +//! let mut values = Vec::new(); +//! package.sheet(&workbook.sheets[0], |row| { +//! values.extend(row.cells.iter().map(|c| c.value.resolve(&strings, workbook.date_1904))); +//! Ok(()) +//! })?; +//! assert_eq!(values, [craft_xlsx::Value::text("Tea"), craft_xlsx::Value::Number(2.5)]); +//! # Ok(()) +//! # } +//! ``` + +mod package; +mod sheet; +mod strings; +mod styles; +#[doc(hidden)] +pub mod testing; +mod workbook; +mod xlsb; + +pub use craft_sheet::{ + BorderStyle, CellError, CellRef, DEFAULT_PALETTE, HAlign, MAX_COLS, MAX_ROWS, Pattern, Range, Script, Underline, VAlign, Value, Visibility, + builtin_format, builtin_format_id, quote_sheet, sheet_needs_quotes, +}; +pub use package::{Package, is_xlsb}; +pub use sheet::{Cell, CellFormula, CellValue, Column, FormulaKind, Row, SheetPart, iso_date_serial}; +pub use strings::{PhoneticProps, PhoneticRun, StringItem, TextRun, decode_xstring, encode_xstring, rich_text}; +pub use styles::{ + Alignment, Border, BorderEdge, CellStyle, Color, ColorSource, Dxf, Fill, Font, FontScheme, GradientFill, PatternFill, Protection, Styles, Xf, +}; +pub use workbook::{DefinedName, SheetEntry, SheetKind, Workbook}; + +/// Why a workbook could not be read. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The bytes are not a ZIP package, or an entry is damaged. + #[error("the file is not a valid zip package: {0}")] + Zip(String), + /// A part that must be read holds XML that cannot be. + #[error("the file contains invalid XML: {0}")] + Xml(String), + /// The package is not a workbook, or a binary part is damaged. + #[error("the file is not a valid spreadsheet: {0}")] + Invalid(String), + /// More than [`Limits`] or a fixed cap allows. + #[error("the file is too large: {0}")] + TooLarge(String), +} + +impl From for Error { + fn from(e: craft_opc::Error) -> Self { + match e { + e if e.is_limit() => Error::TooLarge(e.to_string()), + craft_opc::Error::Zip(m) => Error::Zip(m), + craft_opc::Error::Xml { .. } => Error::Xml(e.to_string()), + e => Error::Invalid(e.to_string()), + } + } +} + +impl From for Error { + fn from(e: craft_xml::Error) -> Self { + if e.is_limit() { Error::TooLarge(e.to_string()) } else { Error::Xml(e.to_string()) } + } +} + +/// What a read refuses to exceed. The defaults suit a spreadsheet application; a caller that +/// only wants a table of values can lower them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The ZIP package: entries, bytes per part and bytes in all. + pub package: craft_opc::Limits, + /// One XML part. Rows and shared strings are streamed, so `max_nodes` bounds one row or one + /// string and what is left of a part, not a sheet's length. + pub xml: craft_xml::Limits, + /// Records read from a binary workbook, every part together. Records are skipped or decoded + /// without being kept, so this bounds parse time, not memory. Excel writes four records per + /// row besides the cells, and one per formatted empty cell, so a sheet needs many more + /// records than cells. + pub binary_records: usize, + /// Cells with a value read from a binary workbook, over all its sheets; also the most + /// shared-string items. + pub binary_cells: usize, + /// Bytes of decoded text (shared and inline strings) in a binary workbook, over all its parts. + pub binary_text: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { + package: craft_opc::Limits::new(200_000, 512 << 20, 1 << 30), + xml: craft_xml::Limits { max_input: 512 << 20, ..craft_xml::Limits::DEFAULT }, + // The limits of `craft-xls`. + binary_records: 40_000_000, + binary_cells: 4_000_000, + binary_text: 256 << 20, + } + } +} + +/// What a read skipped or repaired, each distinct message once and at most 1000 of them. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Warnings(pub(crate) Vec); + +impl Warnings { + pub(crate) fn warn(&mut self, m: impl Into) { + let m = m.into(); + if self.0.len() < 1000 && !self.0.contains(&m) { + self.0.push(m); + } + } +} diff --git a/crates/xlsx/src/package.rs b/crates/xlsx/src/package.rs new file mode 100644 index 000000000..dc772e46e --- /dev/null +++ b/crates/xlsx/src/package.rs @@ -0,0 +1,275 @@ +//! The OPC package of a workbook and the parts this crate reads from it. + +use craft_opc::{ContentTypes, LazyPackage, Rels}; +use craft_xml::{El, Options, UnknownEntity}; + +use crate::sheet::{Row, RowReader, SheetPart}; +use crate::strings::StringItem; +use crate::styles::Styles; +use crate::workbook::{SheetEntry, Workbook}; +use crate::{Error, Limits, Warnings, xlsb}; + +/// Most bytes of `[Content_Types].xml` read from a binary workbook. +const MAX_CONTENT_TYPES: u64 = 1 << 20; + +/// An open workbook package. Parts are inflated when they are asked for, against the +/// package's [`Limits`]. +pub struct Package<'a> { + opc: LazyPackage<'a>, + limits: Limits, + warnings: Warnings, + workbook_part: String, + /// Content types, for a binary workbook (which checks every part it reads against them). + binary: Option, + workbook_rels: Option, + budget: xlsb::Budget, + /// Shared strings in a binary workbook, once counted: a cell's index is checked against it. + binary_strings: Option, +} + +/// Is this a binary workbook (`.xlsb`): a package whose one workbook relationship points at a +/// part of the XLSB workbook content type? +pub fn is_xlsb(bytes: &[u8]) -> bool { + Package::open(bytes, &Limits::default()).is_ok_and(|p| p.is_binary()) +} + +impl<'a> Package<'a> { + /// Opens the package and finds the workbook part. Nothing else is read yet. + pub fn open(bytes: &'a [u8], limits: &Limits) -> Result, Error> { + let mut opc = LazyPackage::open(bytes, &limits.package)?; + let root = opc.rels("")?; + let documents: Vec<_> = root.all("officeDocument").collect(); + let mut binary = None; + let workbook_part = match documents.first() { + Some(rel) if !rel.external && rel.target.to_ascii_lowercase().ends_with(".bin") => { + let types = opc.read_limited("[Content_Types].xml", MAX_CONTENT_TYPES)?.map(|b| ContentTypes::parse(&b)).unwrap_or_default(); + if documents.len() != 1 { + return Err(xlsb::invalid("expected one workbook relationship")); + } + xlsb::check_type(&types, &rel.target, xlsb::MAIN)?; + binary = Some(types); + rel.target.clone() + } + Some(rel) if !rel.external => rel.target.clone(), + _ => "xl/workbook.xml".to_string(), + }; + Ok(Package { + opc, + limits: *limits, + warnings: Warnings::default(), + workbook_part, + binary, + workbook_rels: None, + budget: xlsb::Budget::default(), + binary_strings: None, + }) + } + + /// A binary workbook (`.xlsb`). + pub fn is_binary(&self) -> bool { + self.binary.is_some() + } + + /// The workbook part's name. + pub fn workbook_part(&self) -> &str { + &self.workbook_part + } + + /// What reading skipped or repaired so far, each message once. + pub fn warnings(&self) -> &[String] { + &self.warnings.0 + } + + /// Adds a warning (a caller reading further parts keeps one list). + pub fn warn(&mut self, m: impl Into) { + self.warnings.warn(m); + } + + /// The package underneath, for the parts this crate does not read. + pub fn opc(&mut self) -> &mut LazyPackage<'a> { + &mut self.opc + } + + /// The XML options parts are read with: local names, an undefined entity kept as written, + /// [`Limits::xml`]. + pub fn xml_options(&self) -> Options<'static> { + Options { unknown_entity: UnknownEntity::Literal, ..Options::local() }.with_limits(self.limits.xml) + } + + /// Part `part` as XML; `Ok(None)` when there is no such part. + pub fn read_xml(&mut self, part: &str) -> Result, Error> { + let options = self.xml_options(); + Ok(self.opc.read_xml(part, &options)?) + } + + /// A part the workbook can do without: missing or unreadable is a warning and `None`; + /// only a limit is an error. + pub fn optional_xml(&mut self, part: &str) -> Result, Error> { + match self.read_xml(part) { + Ok(Some(e)) => Ok(Some(e)), + Ok(None) => { + self.warn(format!("missing part {part}")); + Ok(None) + } + Err(Error::TooLarge(m)) => Err(Error::TooLarge(m)), + Err(e) => { + self.warn(format!("skipped {part}: {e}")); + Ok(None) + } + } + } + + /// The relationships of `part`. + pub fn rels(&mut self, part: &str) -> Result { + Ok(self.opc.rels(part)?) + } + + /// The workbook part's relationships. + pub fn workbook_rels(&mut self) -> Result { + if let Some(r) = &self.workbook_rels { + return Ok(r.clone()); + } + let rels = self.opc.rels(&self.workbook_part)?; + self.workbook_rels = Some(rels.clone()); + Ok(rels) + } + + /// The workbook part. + pub fn workbook(&mut self) -> Result { + if self.binary.is_some() { + let bytes = self.required(&self.workbook_part.clone())?; + let rels = self.workbook_rels()?; + return xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings); + } + let options = self.xml_options(); + let root = match self.opc.read_xml(&self.workbook_part, &options)? { + Some(root) => root, + None if self.workbook_part != "xl/workbook.xml" && self.opc.has("xl/workbook.xml") => { + self.workbook_part = "xl/workbook.xml".into(); + self.workbook_rels = None; + self.opc.read_xml("xl/workbook.xml", &options)?.ok_or_else(|| Error::Invalid("no workbook part".into()))? + } + None if self.opc.has("content.xml") => return Err(Error::Invalid("this is an OpenDocument file, not XLSX".into())), + None => return Err(Error::Invalid("no workbook part".into())), + }; + if root.name != "workbook" { + return Err(Error::Invalid(format!("unexpected root element <{}> in workbook part", root.name))); + } + let rels = self.workbook_rels()?; + Ok(Workbook::from_xml(root, &rels)) + } + + /// The shared strings, empty when the workbook has none. + pub fn shared_strings(&mut self) -> Result, Error> { + let rels = self.workbook_rels()?; + if self.binary.is_some() { + let found: Vec<_> = rels.all("sharedStrings").collect(); + let Some(rel) = found.first() else { + self.binary_strings = Some(0); + return Ok(Vec::new()); + }; + if found.len() > 1 { + return Err(xlsb::invalid("multiple shared-string relationships")); + } + if rel.external { + return Err(xlsb::invalid("external shared-string relationship")); + } + if let Some(types) = &self.binary { + xlsb::check_type(types, &rel.target, xlsb::STRINGS)?; + } + let bytes = self.required(&rel.target)?; + let strings = xlsb::shared_strings(&bytes, &self.limits, &self.budget, &mut self.warnings)?; + self.binary_strings = Some(strings.len()); + return Ok(strings); + } + let Some(rel) = rels.first("sharedStrings").filter(|r| !r.external) else { return Ok(Vec::new()) }; + let Some(bytes) = self.opc.read(&rel.target)? else { + self.warn(format!("missing part {}", rel.target)); + return Ok(Vec::new()); + }; + let mut items = Vec::new(); + let (_, err) = self.xml_options().parse_streaming_partial(&bytes, &["si"], |si| { + items.push(StringItem::read(&si)); + Ok::<(), craft_xml::Error>(()) + }); + if let Some(e) = err { + self.warn(format!("shared strings are damaged ({e}); kept {} strings", items.len())); + } + let dropped: usize = items.iter().map(|s| s.dropped_phonetic_runs).sum(); + if dropped > 0 { + self.warn(format!("shared strings: {dropped} phonetic runs were dropped (bad sb/eb or no reading)")); + } + Ok(items) + } + + /// The styles part, `None` when the workbook has none (or is binary: its styles are not read). + pub fn styles(&mut self) -> Result, Error> { + if self.binary.is_some() { + return Ok(None); + } + let rels = self.workbook_rels()?; + let Some(rel) = rels.first("styles").filter(|r| !r.external) else { + self.warn("no styles part"); + return Ok(None); + }; + Ok(self.optional_xml(&rel.target.clone())?.map(Styles::read)) + } + + /// Reads a worksheet, handing each row to `each` in file order; an error from `each` stops the + /// read and is returned. A damaged worksheet gives the rows before the damage and says so + /// in [`SheetPart::damaged`] and in the warnings. + pub fn sheet(&mut self, entry: &SheetEntry, mut each: impl FnMut(Row) -> Result<(), Error>) -> Result { + let part = entry.part.clone().ok_or_else(|| Error::Invalid(format!("sheet \"{}\" has no part", entry.name)))?; + if self.binary.is_some() { + if let Some(types) = &self.binary { + xlsb::check_type(types, &part, xlsb::WORKSHEET)?; + } + let strings = match self.binary_strings { + Some(n) => n, + None => self.shared_strings()?.len(), + }; + let bytes = self.required(&part)?; + let mut sheet = xlsb::worksheet(&bytes, strings, &self.limits, &self.budget, &mut self.warnings, &mut each)?; + sheet.part = part; + return Ok(sheet); + } + let bytes = self.required(&part)?; + let rels = self.opc.rels(&part)?; + let mut rows = RowReader::default(); + let (root, err) = self.xml_options().parse_streaming_partial(&bytes, &["row"], |e| match rows.row(&e) { + Some(row) => each(row).map_err(Stop::Caller), + None => Ok(()), + }); + let damaged = match err { + Some(Stop::Caller(e)) => return Err(e), + Some(Stop::Xml(e)) => { + self.warn(format!("sheet \"{}\" is damaged ({e}); kept {} rows", entry.name, rows.rows)); + Some(e.to_string()) + } + None => None, + }; + if rows.dropped > 0 { + self.warn(format!("sheet \"{}\": {} cells or rows outside the 1,048,576 × 16,384 grid were dropped", entry.name, rows.dropped)); + } + let mut sheet = + SheetPart { part, root: root.unwrap_or_default(), rels, rows: rows.rows, dropped: rows.dropped, damaged, ..SheetPart::default() }; + sheet.lift(); + Ok(sheet) + } + + fn required(&mut self, part: &str) -> Result, Error> { + self.opc.read(part)?.ok_or_else(|| Error::Invalid(format!("missing part {part}"))) + } +} + +/// Why a streamed worksheet stopped: the XML, or the caller. +enum Stop { + Xml(craft_xml::Error), + Caller(Error), +} + +impl From for Stop { + fn from(e: craft_xml::Error) -> Self { + Stop::Xml(e) + } +} diff --git a/crates/xlsx/src/sheet.rs b/crates/xlsx/src/sheet.rs new file mode 100644 index 000000000..5375436e8 --- /dev/null +++ b/crates/xlsx/src/sheet.rs @@ -0,0 +1,387 @@ +//! A worksheet part (`CT_Worksheet`, ECMA-376 Part 1, 18.3): rows and cells as a stream, the +//! rest of the part as a tree. + +use std::sync::Arc; + +use craft_opc::Rels; +use craft_sheet::{CellError, CellRef, MAX_COLS, MAX_ROWS, Range, Value}; +use craft_xml::El; + +use crate::strings::{StringItem, decode_xstring}; + +/// What a cell's `` holds, by its type (`t`, 18.18.11). +#[derive(Clone, Debug, Default, PartialEq)] +pub enum CellValue { + #[default] + Empty, + Number(f64), + /// `t="s"`: an index into the shared strings. + Shared(u32), + /// `t="str"` (a formula's text result), `_xHHHH_` escapes decoded. + Text(Arc), + /// `t="inlineStr"`: the `` item, or the `` text when there is no ``. + Inline(StringItem), + Bool(bool), + /// `t="e"`. An error text no [`CellError`] has reads as `#VALUE!`. + Error(CellError), + /// `t="d"`: an ISO 8601 date, time or both, as written. See [`iso_date_serial`]. + Date(String), + /// A `` that does not read as its type says (a number that is not one, a shared-string + /// index that is not a number). Kept for the caller to report. + Invalid(String), +} + +impl CellValue { + /// The value a cell shows: shared strings looked up, dates as serial numbers in the + /// workbook's date system. A missing shared string, an unreadable date or an invalid value + /// is empty. + pub fn resolve(&self, strings: &[StringItem], date_1904: bool) -> Value { + match self { + CellValue::Empty | CellValue::Invalid(_) => Value::Empty, + CellValue::Number(n) => Value::number(*n), + CellValue::Shared(i) => strings.get(*i as usize).map_or(Value::Empty, |s| Value::Text(s.text.clone())), + CellValue::Text(t) => Value::Text(t.clone()), + CellValue::Inline(s) => Value::Text(s.text.clone()), + CellValue::Bool(b) => Value::Bool(*b), + CellValue::Error(e) => Value::Error(*e), + CellValue::Date(d) => iso_date_serial(d, date_1904).map_or(Value::Empty, Value::number), + } + } +} + +/// ``'s `t` (18.18.6). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum FormulaKind { + #[default] + Normal, + Shared, + Array, + /// A what-if data table: `r1`, `r2` and its flags are in [`CellFormula::attrs`]. + DataTable, +} + +/// A cell's ``. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CellFormula { + pub kind: FormulaKind, + /// The formula as the file spells it (`_xlfn.` prefixes and all), trimmed. Empty for a + /// cell that shares the formula of its group's first cell. + pub text: String, + /// `si`: the shared formula group. + pub shared_index: Option, + /// `ref`: the range of an array formula or of a shared formula group. + pub range: Option, + /// Every attribute as written. + pub attrs: Vec<(String, String)>, +} + +/// One ``. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Cell { + pub at: CellRef, + /// `s`: an index into [`crate::Styles::cell_xfs`], 0 when absent. + pub style: u32, + pub value: CellValue, + pub formula: Option, + /// `vm`: value metadata (a rich value such as a picture in the cell), 1-based. + pub value_metadata: Option, + /// `cm`: cell metadata (a dynamic array formula), 1-based. + pub cell_metadata: Option, + /// `ph`: show the phonetic reading. + pub phonetic: bool, +} + +/// One `` and its cells. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Row { + /// Zero-based. + pub index: u32, + /// `ht`, points. + pub height: Option, + pub custom_height: bool, + pub hidden: bool, + pub outline_level: u8, + pub collapsed: bool, + /// `s` when `customFormat` is set: the format of the row's empty cells. + pub style: Option, + pub cells: Vec, +} + +/// One ``: columns `first..=last` (zero-based). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Column { + pub first: u32, + pub last: u32, + /// Characters of the default font's maximum digit width, padding included. + pub width: Option, + pub custom_width: bool, + pub best_fit: bool, + pub hidden: bool, + pub outline_level: u8, + pub collapsed: bool, + pub style: Option, +} + +/// A worksheet after its rows were handed out: the rest of the part and what was lifted out of it. +#[derive(Clone, Debug, Default)] +pub struct SheetPart { + pub part: String, + /// The worksheet element without its rows: properties, views, columns, merged cells, + /// conditional formats, validation, hyperlinks, page setup, extensions. Empty for a binary + /// worksheet. + pub root: El, + pub rels: Rels, + pub columns: Vec, + pub merges: Vec, + /// Rows read. + pub rows: u64, + /// Rows and cells dropped because their position was outside the grid or unreadable. + pub dropped: u64, + /// Why reading stopped early, when the part is damaged; the rows before the damage were + /// handed out. + pub damaged: Option, +} + +impl SheetPart { + pub(crate) fn lift(&mut self) { + if let Some(cols) = self.root.child("cols") { + for c in cols.children("col") { + let (Some(min), Some(max)) = (c.attr_u32("min"), c.attr_u32("max")) else { continue }; + if min == 0 || min > MAX_COLS || max < min { + continue; + } + self.columns.push(Column { + first: min - 1, + last: max.min(MAX_COLS) - 1, + width: c.attr_f64("width"), + custom_width: c.flag("customWidth", false), + best_fit: c.flag("bestFit", false), + hidden: c.flag("hidden", false), + outline_level: c.attr_u32("outlineLevel").unwrap_or(0).min(7) as u8, + collapsed: c.flag("collapsed", false), + style: c.attr_u32("style"), + }); + } + } + if let Some(m) = self.root.child("mergeCells") { + self.merges.extend(m.children("mergeCell").filter_map(|m| m.attr("ref").and_then(Range::parse)).filter(|r| !r.is_single())); + } + } +} + +/// Reads rows one at a time, remembering where the last one ended. +#[derive(Default)] +pub(crate) struct RowReader { + next_row: u32, + pub(crate) rows: u64, + pub(crate) dropped: u64, +} + +impl RowReader { + /// `None` for a row outside the grid (counted in `dropped`). + pub(crate) fn row(&mut self, e: &El) -> Option { + self.rows += 1; + let index = match e.attr_u32("r") { + Some(r) if (1..=MAX_ROWS).contains(&r) => r - 1, + Some(_) => { + self.dropped += 1; + return None; + } + None if self.next_row < MAX_ROWS => self.next_row, + None => { + self.dropped += 1; + return None; + } + }; + self.next_row = index + 1; + let mut row = Row { + index, + height: e.attr_f64("ht"), + custom_height: e.flag("customHeight", false), + hidden: e.flag("hidden", false), + outline_level: e.attr_u32("outlineLevel").unwrap_or(0).min(7) as u8, + collapsed: e.flag("collapsed", false), + style: if e.flag("customFormat", false) { e.attr_u32("s") } else { None }, + cells: Vec::new(), + }; + let mut next_col = 0u32; + for c in e.children("c") { + let at = match c.attr("r") { + Some(a) => match CellRef::parse(a.trim()) { + Some(p) => p, + None => { + self.dropped += 1; + continue; + } + }, + None if next_col < MAX_COLS => CellRef::new(index, next_col), + None => { + self.dropped += 1; + continue; + } + }; + next_col = at.col + 1; + row.cells.push(cell(c, at)); + } + Some(row) + } +} + +fn cell(c: &El, at: CellRef) -> Cell { + let v = c.child("v").map(|v| v.text()); + let v = v.as_deref(); + let value = match c.attr("t").unwrap_or("n") { + "s" => match v.map(str::trim) { + Some(t) => t.parse().map_or_else(|_| CellValue::Invalid(t.to_string()), CellValue::Shared), + None => CellValue::Empty, + }, + "str" => v.map_or(CellValue::Empty, |v| CellValue::Text(decode_xstring(v).into())), + "inlineStr" => match c.child("is") { + Some(is) => CellValue::Inline(StringItem::read(is)), + None => v.map_or(CellValue::Empty, |v| CellValue::Text(decode_xstring(v).into())), + }, + "b" => v.map_or(CellValue::Empty, |v| CellValue::Bool(matches!(v.trim(), "1" | "true" | "TRUE"))), + "e" => v.map_or(CellValue::Empty, |v| CellValue::Error(CellError::parse(v.trim()).unwrap_or(CellError::Value))), + "d" => match v.map(str::trim).filter(|v| !v.is_empty()) { + Some(d) => CellValue::Date(d.to_string()), + None => CellValue::Empty, + }, + _ => match v.map(str::trim).filter(|v| !v.is_empty()) { + Some(t) => match t.parse::() { + Ok(n) if n.is_finite() => CellValue::Number(if n == 0.0 { 0.0 } else { n }), + _ => CellValue::Invalid(t.to_string()), + }, + None => CellValue::Empty, + }, + }; + let formula = c.child("f").map(|f| CellFormula { + kind: match f.attr("t") { + Some("shared") => FormulaKind::Shared, + Some("array") => FormulaKind::Array, + Some("dataTable") => FormulaKind::DataTable, + _ => FormulaKind::Normal, + }, + text: f.text().trim().to_string(), + shared_index: f.attr_u32("si"), + range: f.attr("ref").and_then(Range::parse), + attrs: f.attrs.clone(), + }); + Cell { + at, + style: c.attr_u32("s").unwrap_or(0), + value, + formula, + value_metadata: c.attr_u32("vm"), + cell_metadata: c.attr_u32("cm"), + phonetic: c.flag("ph", false), + } +} + +/// Days from 1970-01-01 to a proleptic Gregorian date (the civil-from-days inverse). +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +/// The serial number of a `t="d"` value: `2024-02-29`, `2024-02-29T13:45:30`, `13:45` (a time +/// alone), a trailing `Z` or `+hh:mm` ignored. Years 1900 (1904 in the 1904 system) to 9999; +/// a day past the month's end counts on into the next month, as Excel's `DATE` does. In the +/// 1900 system, dates before 1 March 1900 are one lower than the day count, for the 29 February +/// 1900 that Excel counts. +pub fn iso_date_serial(s: &str, date_1904: bool) -> Option { + let s = s.trim().trim_end_matches('Z'); + let (date, time) = match s.split_once('T') { + Some((d, t)) => (d, Some(t)), + None if s.contains(':') => ("", Some(s)), + None => (s, None), + }; + let mut serial = 0.0; + if !date.is_empty() { + let mut it = date.split('-'); + let y: i64 = it.next()?.parse().ok()?; + let m: i64 = it.next()?.parse().ok()?; + let d: i64 = it.next()?.parse().ok()?; + if it.next().is_some() || !(1..=12).contains(&m) || !(1..=31).contains(&d) || y > 9999 || y < if date_1904 { 1904 } else { 1900 } { + return None; + } + let first = days_from_civil(y, m, 1); + let first = + if date_1904 { first - days_from_civil(1904, 1, 1) } else { first - days_from_civil(1899, 12, 30) - i64::from(y == 1900 && m <= 2) }; + let n = first + d - 1; + let max = days_from_civil(9999, 12, 31) - if date_1904 { days_from_civil(1904, 1, 1) } else { days_from_civil(1899, 12, 30) }; + if !(0..=max).contains(&n) { + return None; + } + serial = n as f64; + } + if let Some(t) = time { + let t = t.split('+').next().unwrap_or(t); + let mut it = t.split(':'); + let h: f64 = it.next()?.parse().ok()?; + let mi: f64 = it.next().unwrap_or("0").parse().ok()?; + let se: f64 = it.next().unwrap_or("0").parse().ok()?; + if !(0.0..24.0).contains(&h) || !(0.0..60.0).contains(&mi) || !(0.0..61.0).contains(&se) { + return None; + } + serial += (h * 3600.0 + mi * 60.0 + se) / 86400.0; + } + Some(serial) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn iso_dates() { + assert_eq!(iso_date_serial("1900-01-01", false), Some(1.0)); + assert_eq!(iso_date_serial("1900-02-28", false), Some(59.0)); + assert_eq!(iso_date_serial("1900-03-01", false), Some(61.0)); + assert_eq!(iso_date_serial("2024-02-29T12:00:00Z", false), Some(45351.5)); + assert_eq!(iso_date_serial("1904-01-02", true), Some(1.0)); + assert_eq!(iso_date_serial("06:00", false), Some(0.25)); + assert_eq!(iso_date_serial("2023-02-31", false), iso_date_serial("2023-03-03", false)); + assert_eq!(iso_date_serial("9999-12-31", false), Some(2_958_465.0)); + for bad in ["1899-12-31", "10000-01-01", "2024-13-01", "2024-01-00", "x", "2024-01-01T25:00", "2024-01-01-01"] { + assert_eq!(iso_date_serial(bad, false), None, "{bad}"); + } + assert_eq!(iso_date_serial("1903-12-31", true), None); + } + + #[test] + fn rows_and_cells() { + let xml = r#"7A1*24 + 1#SPILL!#WHAT1in_x000A_lineabca_x0009_2024-01-01"#; + let mut r = RowReader::default(); + let row = r.row(&craft_xml::Options::local().parse(xml.as_bytes()).unwrap_or_default()).unwrap_or_default(); + assert_eq!((row.index, row.height, row.custom_height, row.style, row.outline_level), (2, Some(20.0), true, Some(4), 7)); + assert_eq!(r.dropped, 1); + let at: Vec = row.cells.iter().map(|c| c.at.a1()).collect(); + assert_eq!(at, ["B3", "C3", "E3", "F3", "G3", "H3", "I3", "J3", "K3", "L3"]); + let values: Vec<&CellValue> = row.cells.iter().map(|c| &c.value).collect(); + assert_eq!(values[0], &CellValue::Shared(7)); + assert_eq!(values[2], &CellValue::Error(CellError::Spill)); + assert_eq!(values[3], &CellValue::Error(CellError::Value)); + assert_eq!(values[4], &CellValue::Bool(true)); + assert!(matches!(values[5], CellValue::Inline(s) if &*s.text == "in\nline")); + assert_eq!(values[6], &CellValue::Invalid("abc".into())); + assert_eq!(values[7], &CellValue::Text("a\t".into())); + assert_eq!(values[8].resolve(&[], false), Value::Number(45292.0)); + let f = row.cells[1].formula.clone().unwrap_or_default(); + assert_eq!((f.kind, f.text.as_str(), f.shared_index, f.range.map(|r| r.a1())), (FormulaKind::Shared, "A1*2", Some(0), Some("C3:C9".into()))); + let last = &row.cells[9]; + assert_eq!((last.value_metadata, last.cell_metadata, last.phonetic, last.style), (Some(1), Some(2), true, 0)); + assert_eq!(row.cells[0].value.resolve(&[], false), Value::Empty); + // Without `r`, the next row follows the last one. + let next = r.row(&craft_xml::El::new("row")).map(|r| r.index); + assert_eq!(next, Some(3)); + assert!(r.row(&craft_xml::El::new("row").with_attr("r", "1048577")).is_none()); + assert!(r.row(&craft_xml::El::new("row").with_attr("r", "0")).is_none()); + assert_eq!((r.rows, r.dropped), (4, 3)); + } +} diff --git a/crates/xlsx/src/strings.rs b/crates/xlsx/src/strings.rs new file mode 100644 index 000000000..641975032 --- /dev/null +++ b/crates/xlsx/src/strings.rs @@ -0,0 +1,196 @@ +//! String items (`CT_Rst`, ECMA-376 Part 1, 18.4): shared strings, inline strings and comment +//! text, with the `_xHHHH_` escapes of `ST_Xstring` (22.9.2.19). + +use std::sync::Arc; + +use craft_xml::El; + +use crate::styles::Font; + +/// A formatted run of a string item (``). +#[derive(Clone, Debug, PartialEq)] +pub struct TextRun { + pub text: String, + /// ``, `None` when the run has none. + pub font: Option, +} + +/// A phonetic reading over part of a string's text (``, 18.4.6). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PhoneticRun { + /// Offsets into the base text in UTF-16 code units, `start < end`, both within the text. + pub start: u32, + pub end: u32, + pub text: String, +} + +/// `` (18.4.7). `kind` and `alignment` are kept only when they are values the +/// schema defines (`ST_PhoneticType`, `ST_PhoneticAlignment`). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PhoneticProps { + pub font_id: u32, + pub kind: Option, + pub alignment: Option, +} + +/// One string item: a shared string (``), an inline string (``) or comment text. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StringItem { + /// The whole text, runs joined, phonetic readings left out. + pub text: Arc, + /// The formatted runs, empty for a plain string. + pub runs: Vec, + pub phonetic_runs: Vec, + pub phonetic: Option, + /// `` elements that were dropped: no offsets, `sb >= eb`, past the end of the text, or + /// no reading. + pub dropped_phonetic_runs: usize, +} + +impl StringItem { + pub(crate) fn read(e: &El) -> StringItem { + let text = rich_text(e); + let runs = e + .children("r") + .map(|r| TextRun { text: decode_xstring(&r.children("t").map(|t| t.text()).collect::()), font: r.child("rPr").map(Font::read) }) + .collect(); + // The length in UTF-16 code units: the widest reading of "the total length of the base + // text", so a run is only dropped when it cannot refer to the text at all. + let len = u32::try_from(text.encode_utf16().count()).unwrap_or(u32::MAX); + let mut phonetic_runs = Vec::new(); + let mut seen = 0usize; + for r in e.children("rPh") { + seen += 1; + let (Some(sb), Some(eb)) = (r.attr_u32("sb"), r.attr_u32("eb")) else { continue }; + let (start, end) = (sb.min(len), eb.min(len)); + let reading = r.child("t").map(|t| decode_xstring(&t.text())).unwrap_or_default(); + if start < end && !reading.is_empty() { + phonetic_runs.push(PhoneticRun { start, end, text: reading }); + } + } + const KINDS: &[&str] = &["halfwidthKatakana", "fullwidthKatakana", "Hiragana", "noConversion"]; + const ALIGNMENTS: &[&str] = &["noControl", "left", "center", "distributed"]; + let phonetic = e.child("phoneticPr").map(|p| PhoneticProps { + font_id: p.attr_u32("fontId").unwrap_or(0), + kind: p.attr("type").map(str::trim).filter(|v| KINDS.contains(v)).map(str::to_string), + alignment: p.attr("alignment").map(str::trim).filter(|v| ALIGNMENTS.contains(v)).map(str::to_string), + }); + StringItem { dropped_phonetic_runs: seen - phonetic_runs.len(), text: Arc::from(text), runs, phonetic_runs, phonetic } + } +} + +/// The text of a string item: `` and the `` of each ``, in order, with `_xHHHH_` +/// escapes decoded. Phonetic runs are not part of the text. +pub fn rich_text(e: &El) -> String { + let mut s = String::new(); + for c in e.elements() { + match c.name.as_str() { + "t" => s.push_str(&c.text()), + "r" => c.children("t").for_each(|t| s.push_str(&t.text())), + _ => {} + } + } + decode_xstring(&s) +} + +fn is_escape(chars: &[char], i: usize) -> bool { + chars.get(i) == Some(&'_') + && chars.get(i + 1) == Some(&'x') + && chars.get(i + 6) == Some(&'_') + && (i + 2..i + 6).all(|k| chars.get(k).is_some_and(char::is_ascii_hexdigit)) +} + +fn escape_unit(chars: &[char], i: usize) -> Option { + let hex: String = chars.get(i + 2..i + 6)?.iter().collect(); + u32::from_str_radix(&hex, 16).ok() +} + +/// Text for a `` or ``: characters XML cannot carry and control characters other than tab +/// and line feed become `_xHHHH_`, and a literal `_xHHHH_` is protected with `_x005F_`. The +/// result still needs XML escaping. +pub fn encode_xstring(s: &str) -> String { + let chars: Vec = s.chars().collect(); + let mut o = String::with_capacity(s.len()); + for (i, &c) in chars.iter().enumerate() { + if is_escape(&chars, i) { + o.push_str("_x005F_"); + } else if !craft_xml::is_xml_char(c) || (c.is_control() && !matches!(c, '\t' | '\n')) { + o.push_str(&format!("_x{:04X}_", c as u32 & 0xFFFF)); + } else { + o.push(c); + } + } + o +} + +/// The inverse of [`encode_xstring`]. Two escapes that form a UTF-16 surrogate pair are one +/// character; an escape that is no character on its own stays as written. +pub fn decode_xstring(s: &str) -> String { + if !s.contains("_x") { + return s.to_string(); + } + let chars: Vec = s.chars().collect(); + let mut o = String::with_capacity(s.len()); + let mut i = 0; + while let Some(&c) = chars.get(i) { + if is_escape(&chars, i) { + let unit = escape_unit(&chars, i); + if let Some(ch) = unit.and_then(char::from_u32) { + o.push(ch); + i += 7; + continue; + } + let pair = unit.filter(|h| (0xD800..=0xDBFF).contains(h) && is_escape(&chars, i + 7)).and_then(|high| { + let low = escape_unit(&chars, i + 7).filter(|l| (0xDC00..=0xDFFF).contains(l))?; + char::from_u32(0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00)) + }); + if let Some(ch) = pair { + o.push(ch); + i += 14; + continue; + } + } + o.push(c); + i += 1; + } + o +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn xstring() { + assert_eq!(decode_xstring("a_x000D_b"), "a\rb"); + assert_eq!(encode_xstring("a\rb"), "a_x000D_b"); + assert_eq!(encode_xstring("_x000D_"), "_x005F_x000D_"); + assert_eq!(decode_xstring("_x005F_x000D_"), "_x000D_"); + assert_eq!(decode_xstring("_x12"), "_x12"); + assert_eq!(decode_xstring("_xD83E__xDD80_"), "\u{1F980}"); + // A lone surrogate is no character: kept as written. + assert_eq!(decode_xstring("_xD83E_!"), "_xD83E_!"); + for s in ["plain", "tab\tline\n", "\u{1}\u{1F}", "_x0041_ _xZZZZ_ é"] { + assert_eq!(decode_xstring(&encode_xstring(s)), s); + } + } + + fn item(xml: &str) -> StringItem { + StringItem::read(&craft_xml::Options::local().parse(xml.as_bytes()).unwrap_or_default()) + } + + #[test] + fn runs_and_phonetics() { + let si = item( + r#"東
京 トウキョウxx"#, + ); + assert_eq!(&*si.text, "東京 "); + assert_eq!(si.runs.len(), 2); + assert_eq!(si.runs[1].font.as_ref().map(|f| (f.bold, f.name.as_deref(), f.size)), Some((Some(true), Some("Arial"), Some(9.0)))); + assert_eq!(si.phonetic_runs, [PhoneticRun { start: 0, end: 2, text: "トウキョウ".into() }]); + assert_eq!(si.dropped_phonetic_runs, 3); + assert_eq!(si.phonetic, Some(PhoneticProps { font_id: 3, kind: Some("Hiragana".into()), alignment: None })); + let plain = item("a_x000A_b"); + assert_eq!((&*plain.text, plain.runs.len()), ("a\nb", 0)); + } +} diff --git a/crates/xlsx/src/styles.rs b/crates/xlsx/src/styles.rs new file mode 100644 index 000000000..ceb9547f0 --- /dev/null +++ b/crates/xlsx/src/styles.rs @@ -0,0 +1,555 @@ +//! The styles part (`xl/styles.xml`, ECMA-376 Part 1, 18.8) as the file has it: tables that +//! cells refer to by index. Attributes a file may leave out are `Option`s, because a +//! differential format (``) states only what it changes. + +use craft_sheet::{BorderStyle, DEFAULT_PALETTE, HAlign, Pattern, Script, Underline, VAlign, builtin_format}; +use craft_xml::El; + +/// Characters of a font name kept (Excel allows 31; damaged files have far more). +const MAX_FONT_NAME_CHARS: usize = 255; + +/// Where a colour comes from (`CT_Color`, 18.8.9). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ColorSource { + /// `auto="1"`, or no attribute that names a colour. + #[default] + Auto, + /// `rgb`: `0xAARRGGBB`. Six hex digits read as opaque. + Rgb(u32), + /// `theme`: an index into the theme's colour scheme. + Theme(u32), + /// `indexed`: an index into [`Styles::palette`]. + Indexed(u32), +} + +/// A colour with its tint (`-1.0` darkest to `1.0` lightest, 0 for none). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Color { + pub source: ColorSource, + pub tint: f64, +} + +impl Color { + pub fn read(e: &El) -> Color { + let source = if e.flag("auto", false) { + ColorSource::Auto + } else if let Some(rgb) = e.attr("rgb") { + parse_argb(rgb).map_or(ColorSource::Auto, ColorSource::Rgb) + } else if let Some(t) = e.attr_u32("theme") { + ColorSource::Theme(t) + } else if let Some(i) = e.attr_u32("indexed") { + ColorSource::Indexed(i) + } else { + ColorSource::Auto + }; + Color { source, tint: e.attr_f64("tint").map_or(0.0, |t| t.clamp(-1.0, 1.0)) } + } + + /// `0xRRGGBB` for an RGB colour, or an indexed one in `palette`; `None` for automatic and + /// theme colours. The tint is not applied. + pub fn rgb(&self, palette: &[u32]) -> Option { + match self.source { + ColorSource::Rgb(v) => Some(v & 0xFF_FFFF), + ColorSource::Indexed(i) => palette.get(i as usize).copied(), + ColorSource::Auto | ColorSource::Theme(_) => None, + } + } +} + +fn parse_argb(s: &str) -> Option { + let h = s.trim().trim_start_matches('#'); + let v = u32::from_str_radix(h, 16).ok().filter(|_| h.bytes().all(|b| b.is_ascii_hexdigit()))?; + match h.len() { + 8 => Some(v), + 6 => Some(0xFF00_0000 | v), + _ => None, + } +} + +/// `scheme` of a font: which theme font it follows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FontScheme { + None, + Major, + Minor, +} + +/// A font (``, or a run's ``, 18.8.22 and 18.4.7). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Font { + pub name: Option, + /// Points. + pub size: Option, + pub bold: Option, + pub italic: Option, + pub strike: Option, + pub outline: Option, + pub shadow: Option, + pub condense: Option, + pub extend: Option, + pub underline: Option, + pub vert_align: Option