diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 0000000000..1037b23108 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,44 @@ +# cargo-nextest (https://nexte.st) runs every test in its own process, in parallel across test +# binaries. The Windows leg of the Workspace gate uses it (.github/workflows/workspace.yml); every +# other leg, and local runs, keep `cargo test`. Nextest does not run doctests, so the Windows leg +# also runs `cargo test --doc`. +# +# cargo nextest run --workspace --profile ci +# cargo test --workspace --doc +# +# Refuse an older nextest: CI installs exactly this version (GHSA-vc25-qg58-w57c is fixed in it). +nextest-version = "0.9.150" + +# Some tests share a resource that an in-process mutex keeps to one test at a time. With one +# process per test those mutexes no longer serialize anything, so these groups do it instead, one +# test at a time, as under `cargo test`. +[test-groups] +# craft-ui: `gpu_test_lock()` / `gpu_lock()`. Each renderer creates its own wgpu instance and +# device, and creating or destroying one while another test uses its device can crash. +gpu = { max-threads = 1 } +# craft-video h264_decode: `FIXTURE_GENERATION` keeps a second producer from replacing a fixture +# file another test is reading. +video-fixtures = { max-threads = 1 } +# craft-print: `PRINT_TICKET_PROVIDER` serializes the Windows PrintTicket provider, and the tests +# share the one test print queue the gate installs. +print = { max-threads = 1 } + +[[profile.default.overrides]] +filter = 'package(craft-ui) & (binary(visual_regression) | test(/^combo::tests::|selected_tab_erases_a_baseline_centered_on_its_bottom_edge/))' +test-group = 'gpu' + +[[profile.default.overrides]] +filter = 'package(craft-video) & binary(h264_decode)' +test-group = 'video-fixtures' + +[[profile.default.overrides]] +filter = 'package(craft-print)' +test-group = 'print' + +# The gate (`--profile ci`). Run every test and list all failures at the end, as `cargo test` +# reports a whole binary. Slow tests are named every 60 seconds; none is stopped for being slow, +# so a hang is still ended by the gate's own timeout, as before. +[profile.ci] +fail-fast = false +slow-timeout = { period = "60s" } +failure-output = "immediate-final" diff --git a/.gitattributes b/.gitattributes index a854bbdb9e..0c35cf7c56 100644 --- a/.gitattributes +++ b/.gitattributes @@ -14,3 +14,6 @@ crates/font-store/index/sources.json -text # The build fixture verifies these license files are copied byte-for-byte. crates/fonts-build/tests/fixture/craft-fonts/fonts/**/OFL.txt -text + +# DXF drawing goldens assert exact writer bytes, including LF on every platform. +crates/dxf/tests/data/drawing_*.dxf -text diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index acbdeff607..02cdf71c82 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -158,7 +158,7 @@ dependencies: repo_id: 192625525 'dtolnay/rust-toolchain@stable': ref: 'stable' - commit: 'sha1-b725eda525362e7cf34af9a7243cac1e3f01a7ec' + commit: 'sha1-39008827e6b4319a349e9a42dfc90579dd25f1ca' owner_id: 1940490 repo_id: 260749683 'step-security/dtolnay-rust-toolchain@v1.0.0': diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 654fe4c020..e40c1b4bc8 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -23,5 +23,5 @@ jobs: # 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 + craft-image-codecs/avif,craft-image-codecs/avif-decode,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,craft-image-codecs/sgi,craft-image-codecs/sunraster,craft-jsonrpc/async-lines secrets: inherit diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index a7a3bb587a..4d717fed82 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -10,6 +10,14 @@ on: permissions: contents: read +concurrency: + # Pull requests share one group per branch, so a newer push cancels the older run. Every other + # run (push to main, a release tag, a manual run) gets a group of its own: it is neither + # cancelled nor replaced while queued, so a main run always finishes and saves the dependency + # cache, and a release run is never cancelled. + group: workspace-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: native: name: Workspace @@ -17,7 +25,8 @@ jobs: with: os: '["ubuntu-latest","windows-latest","macos-latest"]' timeout-minutes: 120 - tools: "" + # The Windows leg runs its tests with nextest (.config/nextest.toml). + tools: cargo-nextest@0.9.150 packages: mesa-vulkan-drivers libvulkan1 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan @@ -39,6 +48,7 @@ jobs: printf 'CRAFT_PSD_CORPUS=%s\n' "$GITHUB_WORKSPACE/$corpus_fetcher/corpus" >> "$GITHUB_ENV" printf 'CRAFT_PDF_TEST_FONT_DIR=%s\n' "$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" command: | + python3 scripts/test-workspace-concurrency.py cargo fmt --check cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings @@ -49,8 +59,12 @@ jobs: cargo fmt --check cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - cargo test --workspace --locked - cargo test --workspace --all-features --locked + # The same tests as `cargo test`, run in parallel across test binaries instead of one + # binary at a time; nextest skips doctests, so `cargo test --doc` runs them. + cargo nextest run --workspace --locked --profile ci + cargo test --workspace --doc --locked + cargo nextest run --workspace --all-features --locked --profile ci + cargo test --workspace --doc --all-features --locked msrv: name: Rust 1.95 diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 32bae195dc..680fa58519 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -6,6 +6,8 @@ author, source and license. Library code and original assets are under the repos | File | Author | Source | License | |---|---|---|---| +| `licenses/jpeg-encoder-0.6.1/`, `crates/image-codecs/NOTICE` | jpeg-encoder contributors and the IJG, libjpeg-turbo and SIMD authors named in the retained notices | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1), used unmodified; source checksums in `SOURCE.json` | (MIT OR Apache-2.0) AND IJG | +| `crates/smime/testdata/` | MailCraft contributors; RFC 9216 example certificates | [MailCraft at 240d1d42](https://github.com/UCS-Care-Group/mailcraft/tree/240d1d42fe394cf3274402b180663ba9b43ca180/crates/smime/testdata), restored unmodified; provenance in the directory README | MIT OR Apache-2.0 (source repository) | | `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files | | `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 | | `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 | @@ -94,3 +96,17 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso | `crates/raw/docs/raf-corpus.sha256` (hashes only; the files are not bundled) | The photographers who contributed each file to raw.pixls.us | [raw.pixls.us](https://raw.pixls.us/) | CC0-1.0 | | `crates/drawingml/src/preset_text.txt` | DeckCraft contributors (Nikita Rakitin); generated by `crates/drawingml/tests/fixtures/make_preset_guides.py` from the guide formulas of ECMA-376 Part 1 `presetShapeDefinitions.xml` | [storytold/deckcraft#650](https://github.com/storytold/deckcraft/pull/650) | MIT OR Apache-2.0 (the formulas are the format's definition in ECMA-376) | | `crates/drawingml/tests/fixtures/preset_table.txt` | DeckCraft contributors (Nikita Rakitin); generated by `crates/drawingml/tests/fixtures/make_preset_table.py` from ECMA-376 Part 1 `presetShapeDefinitions.xml` | [storytold/deckcraft#650](https://github.com/storytold/deckcraft/pull/650) | MIT OR Apache-2.0 (the formulas are the format's definition in ECMA-376) | + +## Binary Apple property lists + +`crates/plist` is extracted from `storytold/craft-anything` (`crates/formats/src/plist.rs` and checked byte reads), at source main `88d1d9cac852aec1c7fd97886db451e005e49d2a`. MIT OR Apache-2.0; source license texts are retained in the crate. Primary import Git authors preserve Brandon Thomas, BFlat, RRFZ and Afloat. Regression imports preserve BFlat. XML, JSON projection, calendar formatting and app policy were not imported into the public API. + +`crates/tga/src/metadata_tests.rs` and metadata-boundary helpers in `crates/tga/src/lib.rs` are adapted from nuclearspike's FilmCraft #1932 at `e7842f76f887005c460c64a8ab51d59d086e6f27` (MIT OR Apache-2.0). Synthetic fixtures are original contributor test data; primary Git author retained. +The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper are ported from Craft Anything `8f3b775157d331dd31cfa4da911e26d8856b8c77` (same MIT OR Apache-2.0 source licenses). Brandon Thomas is the primary import author; retained hardening credits include Afloat, BFlat, Rahul, RRFZ and NetterSilver. The finite-real fix preserves gmrmad1 as author from Craft Anything #1905 (`d85e104f`); quoted-attribute/line-ending regressions preserve RRFZ. Bounds/adaptation and bounded entity scanning are subsequent Dylan M. Taylor changes. App-specific JSON projections and keyed-archive interpretation remain outside this crate. + +## Source-timed MIDI compatibility + +`crates/midi/src/source_timed.rs` is extracted from LoopCraft `crates/midi/src/lib.rs` at `884e67c24b9b68badf6a4a4f7d62492f3673d354` (MIT OR Apache-2.0). The recorded source history for the extracted file is Dylan M. Taylor (`0d150c1f`, `440bc7ed`, `9e50523d`); Git authorship is preserved. It includes the original hostile-file, SMPTE, timing and round-trip tests. UTF-8 truncation and event-budget suffix repairs are subsequent changes. The module is an application-independent source-timed model; it does not depend on LoopCraft. +## Non-seeking WAV primitives + +`crates/audio/src/wav_stream.rs` is extracted from AniCraft `crates/audio/src/wav.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0). Tanish Manku is retained as the primary import author, from original commit `30c121d269a49d9abe54a3834ed4aa0201542535`. Odd-data padding accounting, shared API documentation and regression tests are subsequent Dylan M. Taylor changes. diff --git a/Cargo.lock b/Cargo.lock index c11a134ae5..ef82f1afaf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -116,12 +116,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" dependencies = [ "cfg-if", + "getrandom 0.3.4", "once_cell", "serde", "version_check", "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "aligned" version = "0.4.3" @@ -291,6 +301,51 @@ dependencies = [ "libloading", ] +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "async-broadcast" version = "0.7.2" @@ -531,6 +586,15 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -549,11 +613,20 @@ dependencies = [ "bit-vec 0.10.1", ] +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bit-vec" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] [[package]] name = "bit-vec" @@ -724,6 +797,12 @@ dependencies = [ "cipher 0.4.4", ] +[[package]] +name = "borrow-or-share" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" + [[package]] name = "borsh" version = "1.8.1" @@ -835,6 +914,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + [[package]] name = "bytemuck" version = "1.25.2" @@ -873,6 +958,16 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "bzip2-rs" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "beeb59e7e4c811ab37cc73680c798c7a5da77fc9989c62b09138e31ee740f735" +dependencies = [ + "crc32fast", + "tinyvec", +] + [[package]] name = "calloop" version = "0.13.0" @@ -1083,7 +1178,7 @@ dependencies = [ "crmf", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -1095,7 +1190,19 @@ dependencies = [ "const-oid 0.9.6", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", +] + +[[package]] +name = "cms" +version = "0.3.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d089eddc8a5c984d82fcf1427367a6fa0d019d5af04b6e3197e86c8989533b8d" +dependencies = [ + "const-oid 0.10.3", + "der 0.8.3", + "spki 0.8.1", + "x509-cert 0.3.0", ] [[package]] @@ -1342,6 +1449,7 @@ version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "craft-xml", "log", "proptest", "rayon", @@ -1351,10 +1459,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ber" +version = "0.1.0" + [[package]] name = "craft-captions" version = "0.1.0" dependencies = [ + "craft-media-testkit", "craft-timeline", "craft-xml", "proptest", @@ -1385,6 +1498,32 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-color" +version = "0.1.0" +dependencies = [ + "proptest", + "serde", +] + +[[package]] +name = "craft-control" +version = "0.1.0" +dependencies = [ + "getrandom 0.3.4", + "proptest", + "serde", + "serde_json", +] + +[[package]] +name = "craft-control-protocol" +version = "0.1.0" +dependencies = [ + "serde_json", + "subtle", +] + [[package]] name = "craft-crs" version = "0.1.0" @@ -1420,6 +1559,24 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-dds" +version = "0.1.0" +dependencies = [ + "rayon", +] + +[[package]] +name = "craft-deckcraft-format" +version = "0.1.0" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-designcraft-format" version = "0.1.0" @@ -1561,6 +1718,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-elf" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-eps" version = "0.1.0" @@ -1600,6 +1766,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-fcproj-format" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-fig" version = "0.1.0" @@ -1691,8 +1866,12 @@ name = "craft-font-catalog" version = "0.1.0" dependencies = [ "fontique", + "harfrust 0.13.3", + "kurbo 0.13.1", "skrifa 0.47.0", "thiserror 2.0.21", + "unicode-bidi", + "unicode-segmentation", "windows-registry", "write-fonts 0.54.1", ] @@ -1751,6 +1930,26 @@ dependencies = [ "craft-fonts-build", ] +[[package]] +name = "craft-format" +version = "0.1.0" +dependencies = [ + "craft-zip", + "proptest", + "serde_json", + "sha2 0.10.9", +] + +[[package]] +name = "craft-frame" +version = "0.1.0" +dependencies = [ + "craft-color", + "craft-time", + "rayon", + "serde", +] + [[package]] name = "craft-gainmap" version = "0.1.0" @@ -1773,6 +1972,22 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gridcraft-format" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-gzip" +version = "0.1.0" +dependencies = [ + "flate2", +] + [[package]] name = "craft-hdr" version = "0.1.0" @@ -1785,6 +2000,7 @@ name = "craft-heif" version = "0.1.0" dependencies = [ "heic-rs", + "proptest", "rayon", ] @@ -1801,6 +2017,10 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-http-url" +version = "0.1.0" + [[package]] name = "craft-i18n" version = "0.1.0" @@ -1847,9 +2067,14 @@ name = "craft-image-codecs" version = "0.1.0" dependencies = [ "avif-serialize", + "craft-dds", "craft-heif", "craft-jpeg", + "craft-media-testkit", "craft-metadata", + "craft-tiff", + "craft-video", + "crc32fast", "exr", "flate2", "half", @@ -1864,6 +2089,7 @@ dependencies = [ "ravif", "rayon", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", "tiff", "zune-core", @@ -1878,6 +2104,21 @@ dependencies = [ "indd", ] +[[package]] +name = "craft-ipc" +version = "0.1.0" +dependencies = [ + "chrono", + "getrandom 0.2.17", + "interprocess", + "jsonschema", + "libc", + "serde", + "serde_json", + "sha2 0.10.9", + "widestring", +] + [[package]] name = "craft-jmap" version = "0.1.0" @@ -1897,6 +2138,14 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "craft-jsonrpc" +version = "0.1.0" +dependencies = [ + "serde_json", + "tokio", +] + [[package]] name = "craft-jxl" version = "0.1.0" @@ -1958,6 +2207,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-macho" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-markdown" version = "0.1.0" @@ -1985,6 +2243,32 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mcmat" +version = "0.1.0" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-mcp" +version = "0.1.0" +dependencies = [ + "craft-jsonrpc", + "serde_json", +] + +[[package]] +name = "craft-mcp-server" +version = "0.1.0" +dependencies = [ + "proptest", + "serde_json", +] + [[package]] name = "craft-media" version = "0.1.0" @@ -1997,6 +2281,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-media-source" +version = "0.1.0" +dependencies = [ + "craft-audio", + "craft-color", + "craft-frame", + "craft-media", + "craft-time", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-media-testkit" version = "0.1.0" @@ -2019,6 +2317,7 @@ version = "0.1.0" dependencies = [ "craft-opc", "craft-xml", + "craft-zip", "miniz_oxide 0.9.1", "serde_json", ] @@ -2172,6 +2471,7 @@ dependencies = [ name = "craft-pcraft-format" version = "0.1.0" dependencies = [ + "flate2", "serde", "serde_json", "thiserror 2.0.21", @@ -2229,6 +2529,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pe" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-penpot" version = "0.1.0" @@ -2301,6 +2610,13 @@ dependencies = [ "zbus", ] +[[package]] +name = "craft-plist" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-plotter" version = "0.1.0" @@ -2369,11 +2685,22 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "craft-proto" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "log", + "proptest", + "zeroize", +] + [[package]] name = "craft-ps" version = "0.1.0" dependencies = [ "craft-eps", + "flate2", "kurbo 0.13.1", "miniz_oxide 0.8.9", "pdf-writer", @@ -2419,7 +2746,6 @@ dependencies = [ "base64 0.23.1", "craft-image-codecs", "image", - "rayon", "thiserror 2.0.21", ] @@ -2444,6 +2770,13 @@ dependencies = [ "zune-jpegxl", ] +[[package]] +name = "craft-render-parity" +version = "0.1.0" +dependencies = [ + "craft-cms", +] + [[package]] name = "craft-rtf" version = "0.1.0" @@ -2495,6 +2828,10 @@ dependencies = [ name = "craft-sheet" version = "0.1.0" +[[package]] +name = "craft-shx" +version = "0.1.0" + [[package]] name = "craft-silhouette-studio" version = "0.1.0" @@ -2515,6 +2852,45 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-smime" +version = "0.1.0" +dependencies = [ + "aes 0.9.4", + "base64 0.23.1", + "cbc", + "cms 0.3.0-rc.2", + "const-oid 0.10.3", + "craft-ber", + "der 0.8.3", + "des 0.9.0", + "hmac 0.13.0", + "p256 0.14.0", + "p384 0.14.0", + "pbkdf2", + "pkcs1 0.8.0", + "pkcs12", + "proptest", + "rcgen", + "ring", + "rsa 0.10.0-rc.18", + "serde", + "sha1 0.11.0", + "sha2 0.11.1", + "spki 0.8.1", + "thiserror 2.0.21", + "x509-cert 0.3.0", + "zeroize", +] + +[[package]] +name = "craft-sniff" +version = "0.1.0" + +[[package]] +name = "craft-ssip" +version = "0.1.0" + [[package]] name = "craft-stencilcraft-document" version = "0.1.0" @@ -2555,8 +2931,10 @@ version = "0.1.0" dependencies = [ "craft-image-codecs", "craft-xml", + "data-url", "flate2", "kurbo 0.13.1", + "quick-xml 0.41.0", "resvg 0.48.1", "roxmltree 0.21.2", "thiserror 2.0.21", @@ -2573,12 +2951,30 @@ dependencies = [ "kurbo 0.13.1", ] +[[package]] +name = "craft-tar" +version = "0.1.0" +dependencies = [ + "serde", +] + +[[package]] +name = "craft-tcraft" +version = "0.1.0" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-text" version = "0.1.0" dependencies = [ "hypher", "icu_segmenter", + "kurbo 0.13.1", "miniz_oxide 0.8.9", "unicode-bidi", "unicode-bidi-mirroring", @@ -2591,6 +2987,8 @@ dependencies = [ name = "craft-texture" version = "0.1.0" dependencies = [ + "bytemuck", + "dds", "rayon", "thiserror 2.0.21", ] @@ -2688,6 +3086,14 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-usd" +version = "0.1.0" +dependencies = [ + "lz4_flex", + "thiserror 2.0.21", +] + [[package]] name = "craft-vcard" version = "0.1.0" @@ -2702,6 +3108,7 @@ name = "craft-vectorcraft-format" version = "0.1.0" dependencies = [ "flate2", + "proptest", "serde", "serde_json", "thiserror 2.0.21", @@ -2719,8 +3126,10 @@ dependencies = [ name = "craft-video" version = "0.1.0" dependencies = [ + "craft-jpeg", "craft-media", "craft-media-testkit", + "rav1e", "rayon", "thiserror 2.0.21", ] @@ -2803,6 +3212,7 @@ dependencies = [ name = "craft-xfl" version = "0.1.0" dependencies = [ + "craft-xml", "miniz_oxide 0.8.9", "thiserror 2.0.21", ] @@ -2850,12 +3260,33 @@ dependencies = [ name = "craft-zip" version = "0.1.0" dependencies = [ + "bzip2-rs", "craft-zip", "flate2", + "lzma-rs", + "miniz_oxide 0.8.9", + "ruzstd", + "serde", + "serde_json", "thiserror 2.0.21", "zip", ] +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + [[package]] name = "crc24" version = "0.1.6" @@ -2877,10 +3308,10 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36fe21b96d5b87f5de4b5b7202ec41c00110ac817ce6728fe75fb2fe5962ed92" dependencies = [ - "cms", + "cms 0.2.3", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -3104,6 +3535,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" @@ -3119,6 +3556,19 @@ dependencies = [ "generic-array", ] +[[package]] +name = "dds" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e917a58e17b27d2f15626c490754ccced7f46592dc5b5f39a3013b89cba5f068" +dependencies = [ + "astc-decode", + "bitflags 2.13.2", + "glam", + "resize", + "zerocopy", +] + [[package]] name = "der" version = "0.7.10" @@ -3126,7 +3576,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "der_derive", + "der_derive 0.7.3", "flagset", "pem-rfc7468 0.7.0", "zeroize", @@ -3139,10 +3589,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ "const-oid 0.10.3", + "der_derive 0.8.0", + "flagset", "pem-rfc7468 1.0.0", "zeroize", ] +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "der_derive" version = "0.7.3" @@ -3154,6 +3620,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "der_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "deranged" version = "0.5.9" @@ -3328,6 +3805,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "doctest-file" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2db04e74f0a9a93103b50e90b96024c9b2bdca8bce6a632ec71b88736d3d359" + [[package]] name = "document-features" version = "0.2.12" @@ -3676,6 +4159,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" +dependencies = [ + "serde", +] + [[package]] name = "emath" version = "0.37.0" @@ -3888,6 +4380,17 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" +[[package]] +name = "fancy-regex" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912" +dependencies = [ + "bit-set 0.8.0", + "regex-automata", + "regex-syntax", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -4001,6 +4504,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "fluent-uri" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + [[package]] name = "fmt-derive" version = "0.1.2" @@ -4153,6 +4667,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fraction" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e076045bb43dac435333ed5f04caf35c7463631d0dae2deb2638d94dd0a5b872" +dependencies = [ + "lazy_static", + "num", +] + [[package]] name = "fs-set-times" version = "0.20.3" @@ -4340,6 +4864,12 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glam" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" + [[package]] name = "glifo" version = "0.1.1" @@ -4578,6 +5108,8 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ + "allocator-api2", + "equivalent", "foldhash 0.2.0", ] @@ -5226,6 +5758,19 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "interprocess" +version = "2.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb02ffbf25e8ef0f4a95bff054eef75f6d1bf16919474cf2caa63b21997478a" +dependencies = [ + "doctest-file", + "libc", + "recvmsg", + "widestring", + "windows-sys 0.61.2", +] + [[package]] name = "io-extras" version = "0.19.0" @@ -5403,6 +5948,58 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonschema" +version = "0.49.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ec8a241beed129f06114aa68007e905ca350e7baeb6e17a7631bb7978d91b2" +dependencies = [ + "ahash", + "bytecount", + "data-encoding", + "email_address", + "fancy-regex", + "fraction", + "getrandom 0.3.4", + "idna", + "itoa", + "jsonschema-regex", + "jsonschema-value", + "num-cmp", + "num-traits", + "percent-encoding", + "referencing", + "regex", + "serde", + "serde_json", + "strum", + "unicode-general-category", + "uuid-simd", +] + +[[package]] +name = "jsonschema-regex" +version = "0.49.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91994f45017ed5e66aa8e59b8415f4cb033a6380d7200387b7cf117595fbdf85" +dependencies = [ + "regex-syntax", +] + +[[package]] +name = "jsonschema-value" +version = "0.49.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ec7637f83e510868ae6ed625f7ebfbbde4554ee8ce49854caa5126a8b9b9ecb" +dependencies = [ + "ahash", + "bytecount", + "fraction", + "num-cmp", + "num-traits", + "serde_json", +] + [[package]] name = "jxl-bitstream" version = "1.1.0" @@ -5851,6 +6448,22 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "lz4_flex" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" + +[[package]] +name = "lzma-rs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e" +dependencies = [ + "byteorder", + "crc", +] + [[package]] name = "maybe-owned" version = "0.3.4" @@ -5864,6 +6477,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" dependencies = [ "cfg-if", + "rayon", ] [[package]] @@ -5910,6 +6524,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "micromap" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74" + [[package]] name = "mime" version = "0.3.17" @@ -6154,6 +6774,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -6181,6 +6815,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "num-cmp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa" + [[package]] name = "num-complex" version = "0.4.6" @@ -6609,6 +7249,15 @@ dependencies = [ "phf 0.11.3", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -6687,6 +7336,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + [[package]] name = "p256" version = "0.13.2" @@ -7098,6 +7753,21 @@ dependencies = [ "spki 0.8.1", ] +[[package]] +name = "pkcs12" +version = "0.2.0-rc.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fd993500a1de8a428a2e6cc9a2ec942c99a801a88d58a24fb986c5ad3b767ca" +dependencies = [ + "cms 0.3.0-rc.2", + "const-oid 0.10.3", + "der 0.8.3", + "digest 0.11.3", + "spki 0.8.1", + "x509-cert 0.3.0", + "zeroize", +] + [[package]] name = "pkcs8" version = "0.10.2" @@ -7677,6 +8347,7 @@ dependencies = [ "loop9", "quick-error 2.0.1", "rav1e", + "rayon", "rgb", ] @@ -7727,6 +8398,19 @@ dependencies = [ "cipher 0.5.2", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "read-fonts" version = "0.39.2" @@ -7783,6 +8467,12 @@ dependencies = [ "yoke", ] +[[package]] +name = "recvmsg" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175" + [[package]] name = "redox_syscall" version = "0.4.1" @@ -7820,6 +8510,66 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "referencing" +version = "0.49.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6efa2154ea6f5ce0fdecdd2a8d18f2fa1a39a8fbba91564f555a592e4dce8278" +dependencies = [ + "ahash", + "fluent-uri", + "getrandom 0.3.4", + "hashbrown 0.17.1", + "itoa", + "micromap", + "parking_lot", + "percent-encoding", + "serde_json", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + [[package]] name = "regex-lite" version = "0.1.9" @@ -7887,6 +8637,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "resize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71725ecd5e0197b54fe859055b108688472ab6a358f8fbe5cee4a556b1b5bfea" +dependencies = [ + "rgb", +] + [[package]] name = "resvg" version = "0.45.1" @@ -8094,6 +8853,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "rustix" version = "0.38.44" @@ -8197,9 +8965,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -8624,7 +9392,7 @@ dependencies = [ "spki 0.7.3", "thiserror 2.0.21", "tracing", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -8673,7 +9441,7 @@ dependencies = [ "sigstore-crypto", "sigstore-types", "thiserror 2.0.21", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -8686,7 +9454,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cmpv2", - "cms", + "cms 0.2.3", "const-oid 0.9.6", "der 0.7.10", "hex", @@ -8698,7 +9466,7 @@ dependencies = [ "sigstore-types", "thiserror 2.0.21", "tracing", - "x509-cert", + "x509-cert 0.2.5", "x509-tsp", ] @@ -8725,7 +9493,7 @@ checksum = "d30aff69036e4579b416956e9ba68cec45b793116f78f10842d04c7f8b924bab" dependencies = [ "base64 0.22.1", "chrono", - "cms", + "cms 0.2.3", "const-oid 0.9.6", "hex", "pem", @@ -8744,7 +9512,7 @@ dependencies = [ "thiserror 2.0.21", "tls_codec", "tracing", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -9295,6 +10063,17 @@ dependencies = [ "futures-core", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -9578,9 +10357,21 @@ dependencies = [ "mio", "pin-project-lite", "socket2", + "tokio-macros", "windows-sys 0.61.2", ] +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "tokio-rustls" version = "0.26.6" @@ -10048,6 +10839,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "uuid-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8" +dependencies = [ + "outref", + "vsimd", +] + [[package]] name = "v_frame" version = "0.3.9" @@ -10370,6 +11171,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + [[package]] name = "wait-timeout" version = "0.2.1" @@ -10839,6 +11646,12 @@ dependencies = [ "web-sys", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi-util" version = "0.1.11" @@ -11115,7 +11928,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=72951d7455ebcab569fbd9386c513d3d9f53fb02#72951d7455ebcab569fbd9386c513d3d9f53fb02" +source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57" dependencies = [ "flate2", "fmt-derive", @@ -11286,6 +12099,35 @@ dependencies = [ "tls_codec", ] +[[package]] +name = "x509-cert" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b" +dependencies = [ + "const-oid 0.10.3", + "der 0.8.3", + "spki 0.8.1", +] + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + [[package]] name = "x509-tsp" version = "0.1.0" @@ -11293,7 +12135,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5ceece934a21607055b7ac5c25adb56a2ff559804b10705dc674d1d838c15e1" dependencies = [ "cmpv2", - "cms", + "cms 0.2.3", "der 0.7.10", ] @@ -11356,6 +12198,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec 0.9.1", + "time", +] + [[package]] name = "yeslogic-fontconfig-sys" version = "6.0.1" @@ -11387,7 +12239,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -11498,7 +12350,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -11560,9 +12412,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.1.0" +version = "9.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb" dependencies = [ "crc32fast", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 576efca6f1..c8ae36287e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,15 +11,25 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-shx = { path = "crates/shx" } +craft-http-url = { path = "crates/http-url" } +craft-usd = { path = "crates/usd" } +craft-smime = { path = "crates/smime" } +craft-ssip = { path = "crates/ssip" } +craft-ber = { path = "crates/ber" } +craft-proto = { path = "crates/proto" } +craft-render-parity = { path = "crates/render-parity" } acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` +craft-plist = { path = "crates/plist" } craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } craft-ai-core = { path = "crates/ai-core" } craft-anicraft-format = { path = "crates/anicraft-format" } craft-pdf = { path = "crates/pdf", version = "=0.1.0" } +craft-pe = { path = "crates/pe" } craft-ps = { path = "crates/ps", version = "=0.1.0" } craft-pdn = { path = "crates/pdn" } craft-plate-test = { path = "crates/plate-test" } @@ -34,12 +44,16 @@ hayro-syntax = { version = "=0.7.2", default-features = false, features = ["std" bytemuck = "1" kurbo = "0.13" thiserror = "2" +craft-gzip = { path = "crates/gzip" } +craft-gridcraft-format = { path = "crates/gridcraft-format" } craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } craft-codepage = { path = "crates/codepage" } craft-cms = { path = "crates/cms" } +craft-color = { path = "crates/color" } +craft-frame = { path = "crates/frame" } craft-crs = { path = "crates/crs" } craft-crw = { path = "crates/crw" } craft-csv = { path = "crates/csv" } @@ -48,10 +62,13 @@ craft-dialogs = { path = "crates/dialogs" } craft-doc-binary = { path = "crates/doc-binary" } craft-docx = { path = "crates/docx" } craft-document-bundle = { path = "crates/document-bundle" } +craft-mcmat = { path = "crates/mcmat" } +craft-deckcraft-format = { path = "crates/deckcraft-format" } craft-designcraft-format = { path = "crates/designcraft-format" } craft-dxf = { path = "crates/dxf" } craft-drawingml = { path = "crates/drawingml" } craft-eps = { path = "crates/eps" } +craft-elf = { path = "crates/elf" } craft-file-formats = { path = "crates/file-formats" } craft-file-import = { path = "crates/file-import" } vectorcraft-doc = { git = "https://github.com/storytold/vectorcraft.git", rev = "6b3a6b8788ebcb420d69449199cbdf323888d27e" } @@ -62,6 +79,7 @@ craft-doc = { path = "crates/doc" } craft-docpath = { path = "crates/docpath" } craft-dpx = { path = "crates/dpx" } craft-dwg = { path = "crates/dwg" } +craft-fcproj-format = { path = "crates/fcproj-format" } craft-ecproj-format = { path = "crates/ecproj-format" } craft-figma-rest = { path = "crates/figma-rest" } craft-exr = { path = "crates/exr" } @@ -80,11 +98,15 @@ craft-heif = { path = "crates/heif" } craft-fig = { path = "crates/fig" } craft-fonts-build = { path = "crates/fonts-build" } craft-i18n = { path = "crates/i18n" } +craft-ipc = { path = "crates/ipc" } craft-idml = { path = "crates/idml" } craft-indd = { path = "crates/indd" } craft-jmap = { path = "crates/jmap" } craft-ical = { path = "crates/ical" } craft-jpeg = { path = "crates/jpeg" } +craft-control-protocol = { path = "crates/control-protocol" } +craft-jsonrpc = { path = "crates/jsonrpc" } +craft-mcp = { path = "crates/mcp" } craft-jxl = { path = "crates/jxl" } craft-kiwi = { path = "crates/kiwi" } craft-keymap = { path = "crates/keymap" } @@ -93,9 +115,11 @@ craft-kra = { path = "crates/kra" } craft-audio = { path = "crates/audio" } craft-latex = { path = "crates/latex" } craft-markdown = { path = "crates/markdown" } +craft-macho = { path = "crates/macho" } craft-math = { path = "crates/math" } # No default features: craft-audio turns on the craft-media modules each of its features needs. craft-media = { path = "crates/media", default-features = false } +craft-media-source = { path = "crates/media-source" } craft-materialx = { path = "crates/materialx" } craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } @@ -122,6 +146,7 @@ craft-print = { path = "crates/print" } craft-proof = { path = "crates/proof" } craft-raster-codecs = { path = "crates/raster-codecs" } craft-image-codecs = { path = "crates/image-codecs" } +craft-dds = { path = "crates/dds" } craft-psd = { path = "crates/psd" } craft-pst = { path = "crates/pst" } craft-quit = { path = "crates/quit" } @@ -139,6 +164,7 @@ craft-stencilcraft-document = { path = "crates/stencilcraft-document" } craft-svg-paths = { path = "crates/svg-paths" } craft-stream-codecs = { path = "crates/stream-codecs" } craft-text = { path = "crates/text" } +craft-tcraft = { path = "crates/tcraft" } craft-texture = { path = "crates/texture" } craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } @@ -158,6 +184,8 @@ craft-xcf = { path = "crates/xcf" } craft-xml = { path = "crates/xml" } craft-zip = { path = "crates/zip" } craft-y4m = { path = "crates/y4m" } +craft-sniff = { path = "crates/sniff" } +craft-tar = { path = "crates/tar" } craft-epub = { path = "crates/epub" } craft-ews = { path = "crates/ews" } craft-video = { path = "crates/video" } @@ -180,13 +208,11 @@ chrono = { version = "0.4.45", default-features = false, features = ["std"] } [workspace.lints.rust] unsafe_code = "forbid" -unused_workspace_dependencies = "allow" unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] } [workspace.lints.clippy] cognitive_complexity = "deny" too_many_arguments = "deny" -unused_workspace_dependencies = "allow" wildcard_imports = "deny" dbg_macro = "warn" todo = "warn" diff --git a/NOTICE b/NOTICE index 4fa5e4754e..c3cdbabc8a 100644 --- a/NOTICE +++ b/NOTICE @@ -296,3 +296,126 @@ implementation, https://github.com/macosforge/alac at c38887c5c5e64a4b31108733bd (LICENSE-APACHE). The files are modified: translated to Rust, with bounds checks on hostile input, wrapping integer arithmetic, the unrolled predictor and per-width matrix routines folded into one, and the average bit rate filled in. Those files are Apache-2.0 only. + +JPEG encoding dependency: jpeg-encoder 0.6.1 + +Source: https://crates.io/crates/jpeg-encoder/0.6.1 +Declared license: (MIT OR Apache-2.0) AND IJG. +This software is based in part on the work of the Independent JPEG Group. + +The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0 +alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root. +The dependency is used unmodified; no encoder implementation is vendored here. + +LICENSE-MIT + +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +Original src/fdct.rs opening notice + +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ + +Original src/avx2/fdct.rs opening notice + +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/README.md b/README.md index c6e95bd4f9..a3373f3a3d 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit of compositions, layers, properties, keyframes, effects, masks, shapes, text and footage. Clean room, from EffectCraft. Mapping onto an app's document stays in the app. - [`craft-ai-core`](crates/ai-core/README.md): the data model and contract for AI in the Craft Apps (connections, models, tools, requests, jobs, consent, history, route spec). Pure, no I/O, wasm-safe. Contract in [docs/ai-shared-layer.md](docs/ai-shared-layer.md). +- [`craft-pe`](crates/pe/src/lib.rs): PE/COFF headers (`.exe`, `.dll`, `.sys`, `.efi`) from untrusted bytes, from Craft Anything: the COFF header, PE32/PE32+ optional header with its data directories bounded by the header's real size, the section table, RVA-to-file mapping and the decoded Rich header. - [`craft-pdf`](crates/pdf/README.md): independently optional PDF parsing, interpretation, rasterization and guarded authoring. Apps retain layout, fonts, editing and export policy; writer-only consumers do not enable the shared reader. - [`craft-pdn`](crates/pdn/README.md): Paint.NET documents (`.pdn`, PDN3), read: the layer list, blend modes and chunked gzip pixel blocks, with a data-only MS-NRBF (.NET binary serialization) reader. From PhotoCraft. @@ -88,6 +89,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit black and white levels and as-shot white balance. The complete derivation record (plan, sources log, scripts, verification) is in `crates/crw/clean-room/`. Colour stays in each app. - [`craft-csv`](crates/csv/README.md): delimited text (CSV, TSV) and SYLK: encoding detection (UTF-8, UTF-16, Windows-1252 or Windows-1256), delimiter sniffing, a record parser with a cap on fields per record, field quoting for writers, and a SYLK (`.slk`) reader with R1C1 formulas rewritten to A1. +- [`craft-dds`](crates/dds/README.md): DirectDraw Surface (DDS) textures, read and written: the + top mip level of uncompressed, BC1 to BC3 (DXT1/3/5) and BC4/BC5 (grayscale data and normal + maps) textures, legacy and DX10 headers, and our own block encoder with optional mip chains. No dependencies (rayon behind `parallel`), so an + app that only exports textures needn't take the whole `craft-image-codecs` codec set and its + licences; `craft-image-codecs` reads and writes DDS through it. - [`craft-dialogs`](crates/dialogs/README.md): native file and message dialogs that never block the event loop: queued requests shown at the end of the frame and answered on a later frame, free-standing Open and Folder panels and Save sheets on macOS, case-insensitive filters. What @@ -108,6 +114,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit EMU units and `a:xfrm`, colours with theme slots and colour transforms, preset shape outlines (`a:prstGeom`), custom geometry with guide formulas (`a:custGeom`) and preset text warps (`a:prstTxWarp`). From DeckCraft. Takes `craft-xml` trees; packages stay with each format. +- [`craft-elf`](crates/elf/src/lib.rs): ELF program headers and dynamic section entries from untrusted bytes, from Craft Anything: 32- or 64-bit in either byte order, bounded counts and overflow-checked offsets, virtual-address-to-file mapping through `PT_LOAD`, and segment, permission and dynamic tag names. - [`craft-eps`](crates/eps/README.md): Encapsulated PostScript files as a container: the binary preview header (read and write), the DSC header comments and bounding boxes (also `(atend)`), the EPSI preview bitmap, ASCII85 data, and telling EPS, PostScript and Illustrator files @@ -120,6 +127,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit pages and version detection, and written back; and `model`, the drawing above the tags (header variables, tables, blocks, layouts, entities) and its writer (R12 to 2018), merged from CADCraft's and VectorCraft's readers. Bounded on hostile input. Mapping the model onto a document stays in each app. +- [`craft-deckcraft-format`](crates/deckcraft-format/README.md): the DeckCraft `.deckcraft` package: + identity and sniffing, the `presentation.json` envelope with the presentation as a type + parameter, NaN-safe JSON and the reader for older files with `null` numbers, member names and + compression, and bounded, budgeted member reads. The presentation model and its mapping stay in DeckCraft. - [`craft-dwg`](crates/dwg/README.md): bounded byte-level DWG↔DXF conversion with diagnostics, capped output and an optional child-process worker; the `acadrust` dependency remains isolated behind bytes and is unavailable on wasm32 and FreeBSD/aarch64. @@ -172,6 +183,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit every frame's position, delay, disposal and transparent colour, the loop count and the first frame's colour table, without decompressing pixels. Tells an animation from a still and whether a file can hold the picture it declares before a decoder runs. +- [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook + (`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept + unread and written back into a list. The workbook model and what follows a read stay in GridCraft. - [`craft-hdr`](crates/hdr/src/lib.rs): Radiance HDR (RGBE) picture reader, from FilmCraft: flat, old and new run-length scan lines and all eight axis orders, to linear float RGB. Scan lines are validated before the picture is allocated. @@ -191,6 +205,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit Hasselblad 3FR/FFF, Minolta MRW, Epson ERF, Mamiya MEF, Kodak DCS, Pentax PEF, Samsung SRW, Canon CR2, Nikon NEF/NRW, Panasonic RW2, Fujifilm RAF, Olympus ORF (uncompressed), Sony ARW, Canon CR3 and Canon CRW (through `craft-crw`) so far; demosaicing and everything after stay with the develop pipeline. +- [`craft-render-parity`](crates/render-parity/README.md): test support for the shared develop + pipeline (#587): how far two renders of the same photo are apart (per-channel error, CIEDE2000, + the worst pixel) and whether that is within a stated tolerance. - [`craft-tga`](crates/tga/src/lib.rs): Truevision Targa, from FilmCraft (reader) and PhotoCraft (writer): true-colour, grayscale and colour-mapped pictures, raw or run-length encoded, any origin, to RGBA8, and a run-length writer whose packets end with their scan line. Bounded on @@ -227,6 +244,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit primitives (`.abr`, `.asl`, `.aco`, `.act`, `.ase`, `.grd`, `.pat`, `.atn`, `.csh`, `.shc`) and the Photoshop blocks of a layered TIFF. Bounded and panic-free on hostile input. Compositing and the mapping onto a document stay in each app. +- [`craft-ipc`](crates/ipc/README.md): Craft apps talking on one machine: per-user local sockets (Unix socket, Windows named pipe), token auth, instance discovery, launch on demand, focus hand-off, frame transfer and linked-file watching. Native only: it does not build for `wasm32`. Protocol in [PROTOCOL.md](crates/ipc/PROTOCOL.md). - [`craft-jmap`](crates/jmap/README.md): the JMAP protocol core (RFC 8620), from MailCraft, without sockets: session, requests of method calls with back-references, responses, ids, address templates, credentials and the judgement of HTTP answers, over any HTTP implementation. Bounded @@ -236,7 +254,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit encoder, from PhotoCraft; includes a frame probe for routing. Metadata interpretation stays in each app. - [`craft-raster-codecs`](crates/raster-codecs/README.md): small raster formats, one module each, - from PhotoCraft: DDS (BC1 to BC3, read and write), DICOM, FITS (read and write), IFF/ILBM (read + from PhotoCraft: DDS (BC1 to BC3 read and write, BC4 and BC5 read), DICOM, FITS (read and write), IFF/ILBM (read and write), PCX, PNM/PAM/PFM (read and write) and XPM, into one flat image type. Bounded and panic-free on hostile input. Colour, orientation and the document mapping stay in each app. - [`craft-kiwi`](crates/kiwi/README.md): clean-room decoder and encoder for the kiwi binary schema @@ -250,6 +268,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit AC-3/E-AC-3, MP1/MP2, MP3 encoding), streaming and seeking, and packet decoding for any demuxer. See its README for formats and features. - [`craft-latex`](crates/latex/README.md): LaTeX documents read (the everyday subset) and written (a standalone article), to and from the craft-flow model. +- [`craft-macho`](crates/macho/src/lib.rs): Mach-O header pieces from untrusted bytes, from Craft Anything: universal (fat and fat64) slice tables checked against the file, CPU and load command names, the fixed size each load command needs before its fields are read, and the thread-state program counter. - [`craft-markdown`](crates/markdown/README.md): Markdown read and written (a CommonMark subset with GitHub tables and strikethrough), to and from the craft-flow model. - [`craft-math`](crates/math/README.md): equations as one tree (the Office Math object model) with its syntaxes, read and written: OMML, presentation MathML, LaTeX math and the UnicodeMath linear format. - [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV @@ -379,13 +398,15 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit text-format crates read into and write from. WordCraft's model without its editing code. - [`craft-xlsx`](crates/xlsx/README.md): Excel workbooks (`.xlsx`, `.xlsm`, SpreadsheetML, transitional and strict) and binary workbooks (`.xlsb`) on `craft-opc`: the workbook part, shared strings, the styles tables and worksheet rows streamed one at a time, with limits on the package, the XML and the binary records. - [`craft-ora`](crates/ora/README.md): OpenRaster documents (`.ora`): the ZIP archive and the `stack.xml` layer tree as written, read with bounded sizes and written. From PhotoCraft. +- [`craft-sniff`](crates/sniff/src/lib.rs): what a file is from its first bytes: one dependency-free, wasm-safe signature table naming the format, its media type, extension and family for images, audio, video, 3D models, archives, compressed streams, executables and databases. Identifies only; parsing stays with each format's reader. +- [`craft-tar`](crates/tar/src/lib.rs): TAR (v7, ustar, GNU long names and base-256 sizes, local and global pax overrides) and cpio (newc, crc, odc) member walkers for hostile input, from Craft Anything: list each member, its kind, mode, link target and where its data lies, without extracting. Bounded by the input and a member cap; an optional `serde` feature serializes listings. - [`craft-y4m`](crates/y4m/src/lib.rs): YUV4MPEG2 (`.y4m`) reader, from FilmCraft: the stream header, colour space layouts at 8 to 16 bits, a frame index built from the `FRAME` lines without loading the file, and plane access. Bounded on hostile input. - [`craft-kra`](crates/kra/README.md): Krita documents (`.kra`, `.krz`), read: the ZIP archive, the `maindoc.xml` node tree as written, and the tiled pixel files with their LZF compression, a tile at a time. From PhotoCraft. - [`craft-xcf`](crates/xcf/README.md): GIMP XCF images (`.xcf`, `.xcf.gz`), read: header, properties, parasites, layers with their item paths, channels, and tiled pixels (uncompressed, RLE, zlib) at every precision, under a caller's byte budget. From PhotoCraft. - [`craft-xml`](crates/xml/README.md): bounded XML for hostile input: an owned element tree with limits on size, depth, nodes and attributes, streaming of repeated elements, namespace handling (as written, by local name, or canonical prefixes by URI), escaping and a writer. No DTDs and no entity expansion. -- [`craft-zip`](crates/zip/README.md): ZIP archives from untrusted files: an entry-count check before the archive is indexed (ZIP64 included), entry reads within per-entry and total budgets that count real bytes, duplicate-name detection, a strict structure preflight, and a deterministic stored/deflate writer. The shared ZIP layer for the package formats. +- [`craft-zip`](crates/zip/README.md): ZIP archives from untrusted files: an entry-count check before the archive is indexed (ZIP64 included), entry reads within per-entry and total budgets that count real bytes, duplicate-name detection, a strict structure preflight, and a deterministic stored/deflate writer. The shared ZIP layer for the package formats. With the `lenient` feature, also a reader of the raw bytes without the `zip` crate, from Craft Anything, for inspectors that must describe damaged archives rather than refuse them: the central-directory listing with ZIP64, prepended-stub and multi-volume checks, CP437 and Info-ZIP Unicode Path names, and entry reads (stored, DEFLATE, and bzip2, LZMA, XZ and Zstandard behind `lenient-*` features) checked against the declared size and CRC-32. - [Shared UI component audit](docs/ui-components-audit.md): source inventory, extraction priorities and compatibility boundaries across the Craft suite. - [Theme infrastructure](docs/theme-infrastructure.md): eight-app comparison and the small shared diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index 05894f94e0..efa618fb39 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -57,13 +57,56 @@ pub struct WriteOptions<'a> { /// 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) + write::write(doc, version, &opts.identity, &ReferenceOptions::default(), report) +} + +/// Optional interpretation choices for applications retaining older interchange behavior. +#[derive(Clone, Copy, Debug)] +pub struct ReadOptions { + /// Interpret a source clip's start using its target slot's edit rate. + pub source_slot_rate: bool, + /// Use the referenced mob name when the clip has no explicit name. + pub infer_clip_name: bool, + /// Decode percent escapes in relative network locators. + pub decode_relative_locator: bool, + /// Report selector and nested-scope flattening. + pub report_flattening: bool, + /// Accept truncated PCM WAVE essence summaries. + pub permissive_pcm: bool, +} +impl Default for ReadOptions { + fn default() -> Self { + Self { source_slot_rate: true, infer_clip_name: true, decode_relative_locator: true, report_flattening: true, permissive_pcm: false } + } +} +/// Read using explicitly selected interpretation choices. +pub fn read_with_options(bytes: &[u8], options: &ReadOptions, report: &mut Report) -> Result { + read::read(bytes, options, report) +} + +/// Optional compatibility choices for writing source references and locators. +#[derive(Clone, Copy, Debug)] +pub struct ReferenceOptions { + /// Write source offsets in target-slot units. + pub source_slot_rate: bool, + /// Percent-encode relative locators. + pub encode_relative_locator: bool, +} +impl Default for ReferenceOptions { + fn default() -> Self { + Self { source_slot_rate: true, encode_relative_locator: true } + } +} +/// Write with explicitly selected reference and locator conventions. +pub fn write_with_references(doc: &Document, opts: &WriteOptions<'_>, references: &ReferenceOptions, 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, references, 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) + read::read(bytes, &ReadOptions::default(), report) } /// Whether `bytes` look like an AAF file (a compound file whose root has the AAF root class or a diff --git a/crates/aaf/src/aaf/hostile_tests.rs b/crates/aaf/src/aaf/hostile_tests.rs index 853b0000c6..527e50da8b 100644 --- a/crates/aaf/src/aaf/hostile_tests.rs +++ b/crates/aaf/src/aaf/hostile_tests.rs @@ -108,3 +108,19 @@ fn objects_nested_too_deeply_are_an_error() { let e = store::read(&chain(250)).unwrap_err(); assert!(e.contains("nested too deeply"), "{e}"); } + +/// Many distinct property IDs still reject a duplicate without quadratic scanning. +#[test] +fn duplicate_after_many_distinct_properties_is_rejected() { + let mut props = vec![0x4C, 0x20]; + props.extend_from_slice(&8193u16.to_le_bytes()); + for id in (0..8192u16).chain(std::iter::once(7)) { + props.extend_from_slice(&id.to_le_bytes()); + props.extend_from_slice(&0x82u16.to_le_bytes()); + props.extend_from_slice(&0u16.to_le_bytes()); + } + let mut writer = Writer::new(Version::V3); + writer.stream(Writer::ROOT, "properties", props).unwrap(); + let e = store::read(&writer.finish()).unwrap_err(); + assert!(e.contains("duplicate property id"), "{e}"); +} diff --git a/crates/aaf/src/aaf/read.rs b/crates/aaf/src/aaf/read.rs index 31c841c5d1..9739f87baa 100644 --- a/crates/aaf/src/aaf/read.rs +++ b/crates/aaf/src/aaf/read.rs @@ -67,6 +67,7 @@ fn indirect_f64(d: &[u8]) -> Option { struct R<'a> { report: &'a mut Report, + options: super::ReadOptions, mobs: HashMap, essence: HashMap, doc: Document, @@ -90,7 +91,7 @@ struct NestClip<'a> { /// Compositions nested deeper than this are read as gaps. const MAX_NESTING: usize = 16; -pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { +pub(crate) fn read(bytes: &[u8], options: &super::ReadOptions, 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() })?; @@ -106,7 +107,8 @@ pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { essence.insert(id, d); } } - let mut r = R { report, mobs, essence, doc: Document::default(), sources: HashMap::new(), nests: HashMap::new(), open: Vec::new() }; + let mut r = + R { report, options: *options, 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 @@ -331,7 +333,9 @@ impl R<'_> { items } x if x == cls::SELECTOR => { - self.report.info("a selector was flattened to its selected input"); + if self.options.report_flattening { + self.report.info("a selector was flattened to its selected input"); + } match c.strong(pid::SELECTED) { Some(s) => { let mut items = self.segment(s, rate, kind, depth); @@ -342,7 +346,9 @@ impl R<'_> { } } x if x == cls::NESTED_SCOPE => { - self.report.info("a nested scope was flattened to its final input"); + if self.options.report_flattening { + self.report.info("a nested scope was flattened to its final input"); + } match c.objs(pid::NESTED_SLOTS).last() { Some(s) => { let mut items = self.segment(s, rate, kind, depth); @@ -388,7 +394,12 @@ impl R<'_> { let len = units_to_ticks(len_of(c), rate.0, rate.1); let tagged_name = tagged_values(c, pid::COMPONENT_USER_COMMENTS).into_iter().find(|(k, _)| k == "Clip Name").map(|(_, v)| v); let (Some(id), Some(slot)) = (c.mob_id(pid::SOURCE_ID), c.u32(pid::SOURCE_MOB_SLOT_ID)) else { return CItem::Filler(len) }; - let name = tagged_name.or_else(|| self.mobs.get(&id).and_then(|mob| mob.string(pid::MOB_NAME))).unwrap_or_default(); + let name = if self.options.infer_clip_name { + tagged_name.or_else(|| self.mobs.get(&id).and_then(|mob| mob.string(pid::MOB_NAME))) + } else { + tagged_name + } + .unwrap_or_default(); if id == [0; 32] { return CItem::Filler(len); } @@ -401,6 +412,7 @@ impl R<'_> { .and_then(|mob| mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot))) .and_then(|s| rate_of(s, pid::EDIT_RATE)) .unwrap_or(rate); + let source_rate = if self.options.source_slot_rate { source_rate } else { rate }; let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), source_rate.0, source_rate.1); match self.resolve(id, slot, start, kind, master_key, 0) { Some((source, t)) => CItem::Clip(CClip { len, source, start: t, gain: None, name }), @@ -506,6 +518,7 @@ impl R<'_> { .and_then(|m| m.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(next_slot))) .and_then(|s| rate_of(s, pid::EDIT_RATE)) .unwrap_or(rate); + let source_rate = if self.options.source_slot_rate { source_rate } else { rate }; let inner = units_to_ticks(clip.i64(pid::START_TIME).unwrap_or(0), source_rate.0, source_rate.1); if next == [0; 32] { return None; @@ -545,7 +558,11 @@ impl R<'_> { DataKind::Sound => CKind::Sound, _ => kind, }; - let path = d.objs(pid::LOCATOR).iter().find_map(|l| l.string(pid::URL_STRING)).map(|u| locator_path(&u)); + let path = d + .objs(pid::LOCATOR) + .iter() + .find_map(|l| l.string(pid::URL_STRING)) + .map(|u| if self.options.decode_relative_locator { locator_path(&u) } else { 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) @@ -604,7 +621,8 @@ impl R<'_> { 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) { + let pcm = if self.options.permissive_pcm { craft_audio::essence_pcm::parse_wav(data) } else { crate::pcm::parse_wav(data) }; + if let Some((pcm, ch, sr, bits)) = pcm { s.embedded = Some(pcm); s.file_channels = ch as u32; s.channels = if s.channel.is_some() { 1 } else { ch as u32 }; diff --git a/crates/aaf/src/aaf/store.rs b/crates/aaf/src/aaf/store.rs index 69b14fcf2a..859c0ea776 100644 --- a/crates/aaf/src/aaf/store.rs +++ b/crates/aaf/src/aaf/store.rs @@ -461,11 +461,13 @@ impl R<'_> { if at > props.len() { return Err(bad("truncated property index")); } + // A properties stream can name tens of thousands of ids: do not rescan all earlier ids. + let mut seen = std::collections::HashSet::with_capacity(n); 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) { + if !seen.insert(pid) { return Err(bad("duplicate property id")); } let v = props.get(at..at + len as usize).ok_or_else(|| bad("truncated property value"))?; diff --git a/crates/aaf/src/aaf/tests.rs b/crates/aaf/src/aaf/tests.rs index 3e77944714..34eb2bbb35 100644 --- a/crates/aaf/src/aaf/tests.rs +++ b/crates/aaf/src/aaf/tests.rs @@ -557,3 +557,32 @@ fn relative_media_locator_round_trips_escaped_characters() { let got = read_clean(&bytes); assert!(got.sources.iter().any(|s| s.path.as_deref() == Some("Audio Files/100%20 #1.wav"))); } + +#[test] +fn compatibility_options_keep_relative_paths_and_parent_rate() { + let mut doc = crate::testdoc::sound_only(None); + doc.compositions[0].sample_rate = 44_100; + doc.sources[0].path = Some("Audio Files/100%20 #1.wav".into()); + let mut report = Report::default(); + let references = ReferenceOptions { source_slot_rate: false, encode_relative_locator: false }; + let bytes = write_with_references(&doc, &WriteOptions { identity: IDENTITY, small_sectors: false }, &references, &mut report).unwrap(); + let root = store::read(&bytes).unwrap(); + let mut all = Vec::new(); + walk(&root, &mut all); + assert!( + all.iter().filter(|o| o.class == cls::NETWORK_LOCATOR).any(|o| o.string(pid::URL_STRING).as_deref() == Some("Audio Files/100%20 #1.wav")) + ); + let starts: Vec = all.iter().filter(|o| o.class == cls::SOURCE_CLIP).filter_map(|o| o.i64(pid::START_TIME)).collect(); + assert!(starts.contains(&17_640), "parent rate start: {starts:?}"); + let opts = ReadOptions { + source_slot_rate: false, + infer_clip_name: false, + decode_relative_locator: false, + report_flattening: false, + permissive_pcm: true, + }; + let back = read_with_options(&bytes, &opts, &mut report).unwrap(); + assert!(back.sources.iter().any(|s| s.path.as_deref() == Some("Audio Files/100%20 #1.wav"))); + let clip = back.compositions[0].tracks[0].items.iter().find_map(|i| if let CItem::Clip(c) = i { Some(c) } else { None }).unwrap(); + assert_eq!(clip.start, FrameRate::FPS_25.tick_of(10)); +} diff --git a/crates/aaf/src/aaf/write.rs b/crates/aaf/src/aaf/write.rs index 8c9aae88e1..1fcc6a3320 100644 --- a/crates/aaf/src/aaf/write.rs +++ b/crates/aaf/src/aaf/write.rs @@ -75,6 +75,7 @@ fn definition(class: Auid, id: Auid, name: &str) -> Obj { struct W<'a> { report: &'a mut Report, inexact: bool, + references: super::ReferenceOptions, } struct IdGen { @@ -350,9 +351,15 @@ fn add_tape_mob(first: &Source, tape_id: [u8; 32], timecode: Option<(i64, FrameR } /// Serialise a composition document. -pub(crate) fn write(doc: &Document, version: craft_cfb::Version, identity: &Identity<'_>, report: &mut Report) -> Result> { +pub(crate) fn write( + doc: &Document, + version: craft_cfb::Version, + identity: &Identity<'_>, + references: &super::ReferenceOptions, + report: &mut Report, +) -> Result> { let comp = doc.compositions.first().ok_or(Error::Empty)?; - let mut w = W { report, inexact: false }; + let mut w = W { report, inexact: false, references: *references }; 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(); @@ -360,7 +367,8 @@ pub(crate) fn write(doc: &Document, version: craft_cfb::Version, identity: &Iden // ---- 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: doc.sources.iter().enumerate().map(|(i, s)| (i, source_rate(s))).collect() }; + let rates = if references.source_slot_rate { doc.sources.iter().enumerate().map(|(i, s)| (i, source_rate(s))).collect() } else { HashMap::new() }; + let mut refs = Refs { mobs: master_ref, rates }; 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 }; @@ -795,8 +803,10 @@ fn descriptor(w: &mut W, s: &Source) -> Obj { 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 { + } else if w.references.encode_relative_locator { craft_timeline::path::encode_uri_path(p) + } else { + p.clone() }; d.set(pid::LOCATOR, Value::StrongVec(vec![Obj::new(cls::NETWORK_LOCATOR).data_prop(pid::URL_STRING, utf16z(&url))])); } diff --git a/crates/aaf/src/lib.rs b/crates/aaf/src/lib.rs index ee7448bc05..4968c5b39b 100644 --- a/crates/aaf/src/lib.rs +++ b/crates/aaf/src/lib.rs @@ -29,7 +29,11 @@ mod roundtrip_tests; #[cfg(test)] mod testdoc; +/// Diagnostic types used by readers and writers. +pub use craft_timeline::report; pub use craft_timeline::report::Report; +/// Exact time types used by the composition model. +pub use craft_timeline::time; /// Error from a reader or writer. Unsupported *features* never error; they go in the [`Report`]. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] diff --git a/crates/aaf/src/omf.rs b/crates/aaf/src/omf.rs index 57e0f756c1..bbd2e85713 100644 --- a/crates/aaf/src/omf.rs +++ b/crates/aaf/src/omf.rs @@ -21,7 +21,7 @@ //! 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; +pub mod bento; mod read; mod write; diff --git a/crates/aaf/src/omf/bento.rs b/crates/aaf/src/omf/bento.rs index 00a7e2a26c..171196fe16 100644 --- a/crates/aaf/src/omf/bento.rs +++ b/crates/aaf/src/omf/bento.rs @@ -35,8 +35,8 @@ 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; +pub const MAGIC: [u8; 8] = [0xA4, b'C', b'M', 0xA5, b'H', b'd', b'r', 0xD7]; +pub const LABEL_SIZE: usize = 24; // standard object ids const TOC_OBJECT: u32 = 1; @@ -82,7 +82,7 @@ const MAX_VALUE_BYTES: usize = 16 << 20; const MAX_NAME_BYTES: usize = 4 << 20; /// Builds a Bento container. -pub(crate) struct Writer { +pub struct Writer { data: Vec, names: HashMap<(u32, String), u32>, next: u32, @@ -90,6 +90,12 @@ pub(crate) struct Writer { entries: Vec<(u32, u32, u32, Vec)>, } +impl Default for Writer { + fn default() -> Self { + Self::new() + } +} + impl Writer { pub fn new() -> Writer { Writer { data: Vec::new(), names: HashMap::new(), next: MIN_USER_ID, entries: Vec::new() } @@ -217,9 +223,9 @@ pub(crate) struct Prop { } /// A parsed Bento container. -pub(crate) struct Container<'a> { +pub struct Container<'a> { data: &'a [u8], - pub objects: BTreeMap>, + pub(crate) objects: BTreeMap>, names: HashMap, by_name: HashMap, } @@ -229,11 +235,16 @@ fn be32(b: &[u8], at: usize) -> Option { } /// Whether `b` ends with a Bento label. -pub(crate) fn sniff(b: &[u8]) -> bool { +pub fn sniff(b: &[u8]) -> bool { b.len() >= LABEL_SIZE && b[b.len() - LABEL_SIZE..b.len() - LABEL_SIZE + 8] == MAGIC } impl<'a> Container<'a> { + /// Object identifiers in ascending order. + pub fn object_ids(&self) -> impl Iterator + '_ { + self.objects.keys().copied() + } + pub fn open(data: &'a [u8]) -> Result, String> { if !sniff(data) { return Err("no Bento label at the end of the file".into()); @@ -324,7 +335,7 @@ impl<'a> Container<'a> { } /// The bytes of a value. - pub fn value(&self, p: &Prop) -> Result, String> { + pub(crate) 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(), diff --git a/crates/aaf/src/omf/read.rs b/crates/aaf/src/omf/read.rs index d45b6ff639..9e892a0ce8 100644 --- a/crates/aaf/src/omf/read.rs +++ b/crates/aaf/src/omf/read.rs @@ -12,6 +12,10 @@ type Uid = [u8; 12]; const MAX_REFERENCE_VISITS: usize = 65_536; +/// A source-clip search stopped at its work limit. +#[derive(Clone, Copy)] +struct SearchLimit; + struct R<'a, 'b> { c: &'b Container<'a>, report: &'b mut Report, @@ -21,15 +25,49 @@ struct R<'a, 'b> { media: HashMap>, doc: Document, sources: HashMap<(Uid, u32, String), usize>, + /// Component visits left for [`R::segment`] over the whole document. + budget: usize, + /// Outcome of the source-clip search under each segment: deterministic, so it is made once. + clip_search: HashMap, SearchLimit>>, + /// Visits and queued references left for source-clip searches over the whole document: + /// distinct roots over one shared graph would otherwise each search it in full. + search_budget: usize, } +/// Components one document may expand into timeline items; a small file can reference the same +/// sequence from many places and would otherwise multiply without bound. +const MAX_COMPONENT_VISITS: usize = 1_000_000; + +/// Reported when the shared component budget runs out. +const BUDGET_WARNING: &str = "OMF composition is too large to import completely (the remaining components are dropped)"; +/// Most visited components, and most queued references, one source-clip search may spend. +const MAX_CLIP_SEARCH_VISITS: usize = 100_000; +const MAX_CLIP_SEARCH_PENDING: usize = 1_000_000; +/// Work all source-clip searches in one document may spend together. +const MAX_DOCUMENT_SEARCH_WORK: usize = 2_000_000; + pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { + read_with_budget(bytes, report, MAX_COMPONENT_VISITS) +} + +fn read_with_budget(bytes: &[u8], report: &mut Report, budget: usize) -> 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 mut r = R { + c: &c, + report, + be, + mobs: HashMap::new(), + media: HashMap::new(), + doc: Document::default(), + sources: HashMap::new(), + budget, + clip_search: HashMap::new(), + search_budget: MAX_DOCUMENT_SEARCH_WORK, + }; 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() @@ -66,8 +104,14 @@ pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { cmobs.iter().copied().filter(|m| r.uid(*m, "OMFI:MOBJ:MobID").is_none_or(|id| !referenced.contains(&id))).collect() }; for m in top { + // every composition spends from the budget too: a list of up to 65,535 repeated entries must not yield that many + if r.budget == 0 && !r.doc.compositions.is_empty() { + r.report.warn(BUDGET_WARNING); + break; + } let comp = r.composition(m); r.doc.compositions.push(comp); + r.budget = r.budget.saturating_sub(1); } if r.doc.compositions.is_empty() { return Err(Error::Empty); @@ -166,6 +210,13 @@ impl R<'_, '_> { let slots = self.refs(m, "OMFI:MOBJ:Slots"); let mut na = 0; for s in slots { + if self.budget == 0 { + self.report.warn(BUDGET_WARNING); + break; + } + // Every slot spends a unit, skipped ones too: a list of up to 65,535 repeated slots + // must not cost that much work in each of 65,535 repeated compositions. + self.budget -= 1; 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); @@ -213,13 +264,32 @@ impl R<'_, '_> { fn segment(&mut self, seg: u32, rate: (i64, i64), depth: usize) -> Vec { let len = units_to_ticks(self.len(seg), rate.0, rate.1); + // Depth alone does not bound a graph that references the same component many times at + // every level, so each visit also spends from a per-document budget. + // A visit stopped by depth spends from it too. + if self.budget == 0 { + self.report.warn(BUDGET_WARNING); + return vec![CItem::Filler(len)]; + } + self.budget -= 1; if depth > 32 { return vec![CItem::Filler(len)]; } match &self.class(seg) { b"SEQU" => { let mut out = Vec::new(); + let mut expanded = 0i64; for c in self.refs(seg, "OMFI:SEQU:Components") { + if self.budget == 0 { + // the rest of the sequence keeps its duration as one gap, not a gap per reference + self.report.warn(BUDGET_WARNING); + let rest = self.len(seg).saturating_sub(expanded); + if rest > 0 { + out.push(CItem::Filler(units_to_ticks(rest, rate.0, rate.1))); + } + break; + } + expanded = expanded.saturating_add(self.len(c)); out.extend(self.segment(c, rate, depth + 1)); } out @@ -306,12 +376,66 @@ impl R<'_, '_> { .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, + /// First source clip under `seg`, depth-first; a sequence referencing itself (directly or + /// through a cycle) ends the search rather than the stack. `Err` when the search spent its + /// budget of visited components or queued references before finishing (the answer is unknown). + fn first_clip(&mut self, seg: u32) -> std::result::Result, SearchLimit> { + if let Some(found) = self.clip_search.get(&seg) { + return *found; } + let mut spent = 0; + let found = if self.search_budget == 0 { + Err(SearchLimit) + } else { + let visits = MAX_CLIP_SEARCH_VISITS.min(self.search_budget); + let pending = MAX_CLIP_SEARCH_PENDING.min(self.search_budget); + self.first_clip_within(seg, visits, pending, &mut spent) + }; + self.search_budget = self.search_budget.saturating_sub(spent); + self.clip_search.insert(seg, found); + found + } + + /// `spent` receives the visits plus queued references the search used. + fn first_clip_within(&self, seg: u32, max_visits: usize, max_pending: usize, spent: &mut usize) -> std::result::Result, SearchLimit> { + let mut visited = HashSet::new(); + let mut todo = vec![seg]; + let mut queued = 1usize; + let found = Self::search_from(self, &mut visited, &mut todo, &mut queued, max_visits, max_pending); + *spent = visited.len().saturating_add(queued); + found + } + + fn search_from( + &self, + visited: &mut HashSet, + todo: &mut Vec, + queued: &mut usize, + max_visits: usize, + max_pending: usize, + ) -> std::result::Result, SearchLimit> { + while let Some(seg) = todo.pop() { + if !visited.insert(seg) { + continue; + } + if visited.len() > max_visits { + return Err(SearchLimit); + } + match &self.class(seg) { + b"SCLP" => return Ok(Some(seg)), + b"SEQU" => { + let comps = self.refs(seg, "OMFI:SEQU:Components"); + // sequences may share one component list, so queued references grow with expansions, not visits + *queued = queued.saturating_add(comps.len()); + if *queued > max_pending { + return Err(SearchLimit); + } + todo.extend(comps.into_iter().rev()); + } + _ => {} + } + } + Ok(None) } fn resolve(&mut self, id: Uid, track: u32, start: Tick, master: Option, depth: usize) -> Option<(usize, Tick)> { @@ -328,7 +452,13 @@ impl R<'_, '_> { 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 clip = match self.first_clip(seg) { + Ok(c) => c?, + Err(SearchLimit) => { + self.report.warn("a master mob is too large to search for its source clip (imported as a gap)"); + return None; + } + }; 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")?; @@ -353,7 +483,9 @@ impl R<'_, '_> { 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 fmt = craft_audio::essence_pcm::parse_wav(&summary) + .or_else(|| craft_audio::essence_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) { @@ -373,7 +505,8 @@ impl R<'_, '_> { 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 first = self.first_clip(seg).ok().flatten(); + let tc = first.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| { @@ -415,7 +548,7 @@ impl R<'_, '_> { 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)) { + if let Some((pcm, ch, sr, b)) = craft_audio::essence_pcm::parse_wav(d).or_else(|| craft_audio::essence_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 }; @@ -437,3 +570,200 @@ impl R<'_, '_> { } } } + +#[cfg(test)] +mod tests { + use super::super::bento::Writer; + use super::*; + + fn obj(w: &mut Writer, class: &[u8; 4]) -> u32 { + let id = w.new_object(); + w.set(id, "OMFI:OOBJ:ObjClass", "omfi:ClassID", class); + id + } + fn list(w: &mut Writer, 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()); + } + w.set(o, p, "omfi:ObjRefArray", &v); + } + + fn search(max_visits: usize, max_pending: usize, build: impl FnOnce(&mut Writer) -> u32) -> std::result::Result, SearchLimit> { + let mut w = Writer::new(); + let root = build(&mut w); + let bytes = w.finish(); + let c = Container::open(&bytes).unwrap(); + let mut report = Report::default(); + let r = R { + c: &c, + report: &mut report, + be: true, + mobs: HashMap::new(), + media: HashMap::new(), + doc: Document::default(), + sources: HashMap::new(), + budget: 0, + clip_search: HashMap::new(), + search_budget: MAX_DOCUMENT_SEARCH_WORK, + }; + r.first_clip_within(root, max_visits, max_pending, &mut 0) + } + + #[test] + fn clip_search_reports_its_limits() { + // found within the limits + assert!(matches!( + search(10, 10, |w| { + let (s, c) = (obj(w, b"SEQU"), obj(w, b"SCLP")); + list(w, s, "OMFI:SEQU:Components", &[c]); + s + }), + Ok(Some(_)) + )); + // too many distinct components before any clip + assert!( + search(5, 1000, |w| { + let (s, f) = (obj(w, b"SEQU"), (0..20).map(|_| obj(w, b"FILL")).collect::>()); + list(w, s, "OMFI:SEQU:Components", &f); + s + }) + .is_err() + ); + // few visits, but sequences that each queue a long list of references + assert!( + search(1000, 500, |w| { + let f = obj(w, b"FILL"); + let inner: Vec = (0..20).map(|_| obj(w, b"SEQU")).collect(); + for &i in &inner { + list(w, i, "OMFI:SEQU:Components", &[f; 100]); + } + let s = obj(w, b"SEQU"); + list(w, s, "OMFI:SEQU:Components", &inner); + s + }) + .is_err() + ); + // a search that ends without a clip is not a limit + assert!(matches!(search(10, 10, |w| obj(w, b"FILL")), Ok(None))); + } + + #[test] + fn skipped_slots_spend_the_budget() { + let mut w = Writer::new(); + let head = obj(&mut w, b"HEAD"); + let cm = obj(&mut w, b"CMOB"); + let slot = obj(&mut w, b"MSLT"); + list(&mut w, cm, "OMFI:MOBJ:Slots", &[slot; 200]); + list(&mut w, head, "OMFI:HEAD:Mobs", &[cm]); + list(&mut w, head, "OMFI:HEAD:PrimaryMobs", &[cm]); + let bytes = w.finish(); + let mut report = Report::default(); + read_with_budget(&bytes, &mut report, 50).unwrap(); + assert!(report.mentions(BUDGET_WARNING), "slots with no segment cost nothing before"); + } + + #[test] + fn a_source_clip_search_is_made_once_per_segment() { + let mut w = Writer::new(); + let (s, c) = (obj(&mut w, b"SEQU"), obj(&mut w, b"SCLP")); + list(&mut w, s, "OMFI:SEQU:Components", &[c]); + let bytes = w.finish(); + let c = Container::open(&bytes).unwrap(); + let mut report = Report::default(); + let mut r = R { + c: &c, + report: &mut report, + be: true, + mobs: HashMap::new(), + media: HashMap::new(), + doc: Document::default(), + sources: HashMap::new(), + budget: 0, + clip_search: HashMap::new(), + search_budget: MAX_DOCUMENT_SEARCH_WORK, + }; + let first = r.first_clip(s).ok(); + assert!(matches!(first, Some(Some(_)))); + assert_eq!(r.clip_search.len(), 1); + assert_eq!(r.first_clip(s).ok(), first); + assert_eq!(r.clip_search.len(), 1); + } + + #[test] + fn repeated_slots_and_compositions_spend_the_budget() { + let mut w = Writer::new(); + let head = obj(&mut w, b"HEAD"); + let cm = obj(&mut w, b"CMOB"); + let dd = obj(&mut w, b"DDEF"); + w.set(dd, "OMFI:DDEF:DataKindID", "omfi:UniqueName", b"omfi:data:Sound\0"); + let fill = obj(&mut w, b"FILL"); + w.set(fill, "OMFI:CPNT:DataKind", "omfi:ObjRef", &dd.to_be_bytes()); + let slot = obj(&mut w, b"MSLT"); + w.set(slot, "OMFI:MSLT:Segment", "omfi:ObjRef", &fill.to_be_bytes()); + list(&mut w, cm, "OMFI:MOBJ:Slots", &[slot; 200]); + list(&mut w, head, "OMFI:HEAD:Mobs", &[cm]); + list(&mut w, head, "OMFI:HEAD:PrimaryMobs", &[cm; 200]); + let bytes = w.finish(); + let mut report = Report::default(); + let doc = read_with_budget(&bytes, &mut report, 50).unwrap(); + let tracks: usize = doc.compositions.iter().map(|c| c.tracks.len()).sum(); + assert!(tracks <= 50, "{tracks} tracks from a budget of 50"); + assert!(doc.compositions.len() <= 2, "{} compositions", doc.compositions.len()); + assert!(report.has_warnings()); + } + + fn with_reader(bytes: &[u8], budget: usize, search_budget: usize, f: impl FnOnce(&mut R) -> T) -> (T, Report) { + let c = Container::open(bytes).unwrap(); + let mut report = Report::default(); + let mut r = R { + c: &c, + report: &mut report, + be: true, + mobs: HashMap::new(), + media: HashMap::new(), + doc: Document::default(), + sources: HashMap::new(), + budget, + clip_search: HashMap::new(), + search_budget, + }; + let out = f(&mut r); + (out, report) + } + + #[test] + fn depth_limited_components_spend_the_budget() { + // a chain 33 sequences deep whose last one repeats a depth-limited sequence many times + let mut w = Writer::new(); + let deep = obj(&mut w, b"SEQU"); + let chain: Vec = (0..33).map(|_| obj(&mut w, b"SEQU")).collect(); + for pair in chain.windows(2) { + list(&mut w, pair[0], "OMFI:SEQU:Components", &[pair[1]]); + } + list(&mut w, chain[32], "OMFI:SEQU:Components", &[deep; 1000]); + let bytes = w.finish(); + let (items, report) = with_reader(&bytes, 100, MAX_DOCUMENT_SEARCH_WORK, |r| r.segment(chain[0], (48_000, 1), 0)); + assert!(items.len() <= 100, "{} items from a budget of 100", items.len()); + assert!(report.mentions(BUDGET_WARNING)); + } + + #[test] + fn source_clip_searches_share_a_document_budget() { + // distinct roots over one shared clip-free graph + let mut w = Writer::new(); + let fills: Vec = (0..50).map(|_| obj(&mut w, b"FILL")).collect(); + let shared = obj(&mut w, b"SEQU"); + list(&mut w, shared, "OMFI:SEQU:Components", &fills); + let roots: Vec = (0..30).map(|_| obj(&mut w, b"SEQU")).collect(); + for &root in &roots { + list(&mut w, root, "OMFI:SEQU:Components", &[shared]); + } + let bytes = w.finish(); + let (results, _) = with_reader(&bytes, 0, 500, |r| roots.iter().map(|&root| r.first_clip(root)).collect::>()); + assert!(matches!(results[0], Ok(None)), "the first search fits"); + assert!(results.iter().any(|r| r.is_err()), "later searches run out of the shared budget"); + let (results, _) = with_reader(&bytes, 0, MAX_DOCUMENT_SEARCH_WORK, |r| roots.iter().map(|&root| r.first_clip(root)).collect::>()); + assert!(results.iter().all(|r| matches!(r, Ok(None)))); + } +} diff --git a/crates/aaf/src/pcm.rs b/crates/aaf/src/pcm.rs index 789c976a83..9992b2d3be 100644 --- a/crates/aaf/src/pcm.rs +++ b/crates/aaf/src/pcm.rs @@ -4,8 +4,3 @@ 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/tests/bento_api.rs b/crates/aaf/tests/bento_api.rs new file mode 100644 index 0000000000..93adc33c11 --- /dev/null +++ b/crates/aaf/tests/bento_api.rs @@ -0,0 +1,27 @@ +use craft_aaf::omf::bento::{Container, Writer, sniff}; + +#[test] +fn external_consumer_reads_named_values_and_references() { + let mut writer = Writer::new(); + let first = writer.new_object(); + let second = writer.new_object(); + writer.set(first, "test:value", "test:type", b"long value"); + writer.set_references(first, &[second]); + let bytes = writer.finish(); + assert!(sniff(&bytes)); + let container = Container::open(&bytes).unwrap(); + assert!(container.object_ids().any(|id| id == first)); + assert_eq!(container.get(first, "test:value").as_deref(), Some(b"long value".as_slice())); + assert_eq!(container.resolve(first, second), second); + assert!(Container::open(&bytes[..bytes.len() - 1]).is_err()); +} + +#[test] +fn default_writer_builds_a_readable_empty_container() -> Result<(), String> { + let bytes = Writer::default().finish(); + let container = Container::open(&bytes)?; + let ids: Vec<_> = container.object_ids().collect(); + assert!(!ids.is_empty()); + assert!(ids.windows(2).all(|pair| pair[0] < pair[1])); + Ok(()) +} diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 1590372ad5..08b881e17b 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -70,6 +70,9 @@ pub trait AtomicFs { fn sync_dir(&self, dir: &Path) -> io::Result<()>; /// Give the open temporary file its final permissions. fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()>; + /// Put the open temporary file in group `gid` (Unix only). + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()>; } /// The production file system implementation. @@ -126,6 +129,11 @@ impl AtomicFs for RealFs { fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { file.set_permissions(perms) } + + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + std::os::unix::fs::fchown(file, None, Some(gid)) + } } /// Flush `file` to stable storage (`sync_all`). @@ -342,10 +350,29 @@ fn split(target: &Path, path: &Path) -> io::Result<(PathBuf, String)> { Ok((dir, name.to_string_lossy().into_owned())) } -/// Create a temporary file in `dir`, fill it with `fill`, give it the permissions of the file it -/// replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when the mode -/// already matches after `fill`. A leftover file with the same name is skipped. When any step -/// fails, the temporary file is removed. +/// Give `perms` the replaced file's group, or drop its group bits when the stage cannot join +/// that group. A stage already in the group needs no fchown, which some filesystems reject even +/// as a no-op, and dropping the bits there would narrow a mode the replaced file granted. +#[cfg(unix)] +fn adopt_group(fs: &dyn AtomicFs, file: &File, stage_gid: u32, replaced_gid: u32, perms: std::fs::Permissions) -> io::Result { + use std::os::unix::fs::PermissionsExt; + if perms.mode() & 0o070 == 0 || stage_gid == replaced_gid { + return Ok(perms); + } + if fs.set_group(file, replaced_gid).is_ok() { + return Ok(perms); + } + let mut narrowed = perms; + narrowed.set_mode(narrowed.mode() & !0o070); + Ok(narrowed) +} + +/// Create a temporary file in `dir`, fill it with `fill`, give it the permissions and group of +/// the file it replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when +/// the mode already matches after `fill`; the group bits are dropped when the file cannot be put +/// in the replaced file's group, so they never open the file to a group that was not granted +/// them. A leftover file with the same name is skipped. When any step fails, the temporary file +/// is removed. fn stage( fs: &dyn AtomicFs, dir: &Path, @@ -383,6 +410,14 @@ fn stage( if (file.metadata()?.permissions().mode() & 0o7777) == (p.mode() & 0o7777) { return Ok(()); } + // The group bits belong to the replaced file's group, which a new + // inode need not be in (setgid directory, another primary group). + if let Some(replaced) = replaced { + let stage_gid = std::os::unix::fs::MetadataExt::gid(&file.metadata()?); + let replaced_gid = std::os::unix::fs::MetadataExt::gid(replaced); + let perms = adopt_group(fs, &file, stage_gid, replaced_gid, p)?; + return fs.set_permissions(&file, perms); + } } fs.set_permissions(&file, p) }) @@ -678,6 +713,9 @@ mod tests { fixed_mode: Option, fail_sync_dir: bool, fail_normal_create: bool, + /// Simulate a filesystem that refuses the stage's group change. + #[cfg(unix)] + fail_set_group: bool, normal_collisions: Cell, /// Another process creates the target just before the hard link. created_meanwhile: Option<&'static [u8]>, @@ -750,6 +788,15 @@ mod tests { } /// Record permission restoration and payload length, then inject a configured error /// or delegate the mode change to the real filesystem. + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + self.events.borrow_mut().push("set_group"); + if self.fail_set_group { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: set_group failed")); + } + RealFs.set_group(file, gid) + } + fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { self.events.borrow_mut().push("set_permissions"); #[cfg(unix)] @@ -1090,6 +1137,36 @@ mod tests { Ok(()) } + #[cfg(unix)] + #[test] + fn group_bits_are_dropped_when_the_stage_cannot_join_the_replaced_group() -> io::Result<()> { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let d = TempDir::new("group-fallback"); + let file = File::create(d.0.join("stage"))?; + let gid = file.metadata()?.gid(); + let elsewhere = gid.wrapping_add(1); + + let fs = Faulty { fail_set_group: true, ..Default::default() }; + let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o640))?.mode(); + assert_eq!(mode & 0o777, 0o600, "group bits are dropped when the group cannot be joined"); + assert!(fs.events.borrow().contains(&"set_group")); + + // No group bits: the group change is never attempted. + let fs = Faulty { fail_set_group: true, ..Default::default() }; + let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o600))?.mode(); + assert_eq!(mode & 0o777, 0o600); + assert!(!fs.events.borrow().contains(&"set_group")); + + // A stage already in the replaced file's group keeps its bits untouched. + let fs = Faulty { fail_set_group: true, ..Default::default() }; + let mode = adopt_group(&fs, &file, gid, gid, std::fs::Permissions::from_mode(0o640))?.mode(); + assert_eq!(mode & 0o777, 0o640); + assert!(!fs.events.borrow().contains(&"set_group")); + + assert_no_temp(&d.0); + Ok(()) + } + #[cfg(unix)] #[test] fn normal_policy_preserves_existing_modes_with_private_staging() -> io::Result<()> { @@ -1102,6 +1179,11 @@ mod tests { let fs = Faulty { fail_normal_create: true, ..Default::default() }; replace_with_options(&fs, NO_RETRY, &p, NewFilePermissions::PlatformDefault, |f| f.write_all(b"replacement"))?; assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, mode); + assert_eq!( + std::os::unix::fs::MetadataExt::gid(&std::fs::metadata(&p)?), + std::os::unix::fs::MetadataExt::gid(&d.0.metadata()?), + "kept in the directory's group" + ); assert!(!fs.events.borrow().contains(&"create_new_normal")); assert_eq!(*fs.created_modes.borrow(), [0o600]); } diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index d132f23da2..fe28cec3f8 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-audio" -description = "Audio file I/O and codecs: WAV/AIFF read and write, FLAC encoder, AAC and ALAC decoders and encoders, AC-3/E-AC-3 decoder and encoder, MP3 decoder and encoder, Opus decoder and encoder, MP1/MP2 decoders." +description = "Audio file I/O and codecs: WAV/AIFF read and write, FLAC encoder, AAC and ALAC decoders and encoders, AC-3/E-AC-3 decoder and encoder, MP3 decoder and encoder, Opus decoder and encoder, Vorbis encoder, MP1/MP2 decoders." version.workspace = true edition.workspace = true license.workspace = true @@ -19,23 +19,32 @@ workspace = true # µ-law and free-format MP3 through symphonia. decode = ["decode-native", "symphonia"] # `decode` without symphonia: only the formats with a native decoder (others are Unsupported). -decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-decode", "mp3-decode", "craft-media/isobmff", "craft-media/matroska", "craft-media/ogg", "dep:log"] +decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-decode", "mp3-decode", "craft-media/isobmff", "craft-media/matroska", "craft-media/ogg", "dep:log", "dep:craft-xml"] # The symphonia fallback for the formats with no native decoder yet. symphonia = ["decode-native", "dep:symphonia"] # Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders. # All but Opus are also file formats of `encode` and `FileEncoder`. -encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode"] +encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode", "vorbis-encode"] # Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files. lossless-encode = ["pcm-encode", "flac-encode"] # Encode WAV/BWF/RF64 and AIFF/AIFF-C files. pcm-encode = [] +# Decode FLAC files and frames natively (`flac::decode`, `flac::Decoder`). +flac-decode = [] # Encode FLAC files. flac-encode = ["craft-media/bitstream"] +# The pure-Rust Vorbis encoder (`vorbis::encoder`) and Ogg Vorbis files through `encode` and +# `encode_ogg_vorbis`. +vorbis-encode = ["craft-media/ogg"] # Codec modules on their own, for packet-level use. aac-decode = ["craft-media/bitstream"] # The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`. aac-encode = ["craft-media/bitstream", "craft-media/isobmff"] opus-decode = [] +# QOA (Quite OK Audio) files: decoder and encoder in the `qoa` module, each on its own. +qoa = ["qoa-decode", "qoa-encode"] +qoa-decode = [] +qoa-encode = [] opus-encode = [] ac3-decode = ["craft-media/bitstream"] mpa-decode = ["craft-media/bitstream"] @@ -58,6 +67,7 @@ serde = ["dep:serde", "craft-media/serde"] [dependencies] craft-media = { workspace = true } +craft-xml = { workspace = true, optional = true } thiserror = { workspace = true } serde = { workspace = true, optional = true } log = { version = "0.4", optional = true } @@ -78,6 +88,14 @@ required-features = ["decode", "lossless-encode", "peaks"] name = "codecs" required-features = ["decode", "encode"] +[[test]] +name = "flac_decode" +required-features = ["flac-decode", "flac-encode"] + +[[test]] +name = "qoa_oracle" +required-features = ["qoa"] + [[example]] name = "info" required-features = ["decode"] diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f5..7469a94018 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -29,14 +29,16 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `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`); `wav_pcm`, `aiff_pcm` (a file's integer PCM bit for bit, as `RawPcm`) | the six 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, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode` | +| `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | | `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | +| `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | | `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` | | `alac-decode` | `alac::Decoder` | none | | `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` | | `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none | +| `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | | `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | @@ -355,8 +357,12 @@ let pre_skip = enc.pre_skip(); // samples the player drops at the start The encoder takes 48 kHz only, and craft-audio has no resampler. -craft-media has no Ogg muxer, so `.opus` files cannot be written yet; Opus goes into -Matroska/WebM or MP4: +Opus goes into Ogg, Matroska/WebM or MP4: + +- **Ogg (`.opus`):** `craft_media::ogg::PageWriter` with `head` and `opus_tags` as the two header + packets, each packet's granule position the samples decoded so far (pre-skip included, as + the input above starts with it), and `finish(Some(pre_skip + length))` to trim the end + (RFC 7845 §4). - **Matroska/WebM:** `head` is the track's `CodecPrivate`, and the pre-skip goes in `TrackSpec::codec_delay_ns` (in nanoseconds at 48 kHz). The Matroska muxer cannot write @@ -368,6 +374,27 @@ Matroska/WebM or MP4: timescale), `segment_duration` the audio's length (movie timescale), `media_rate` `0x0001_0000`. +### Encode Ogg Vorbis + +```rust +use craft_audio::{OggVorbisOptions, encode_ogg_vorbis}; + +// 1–8 channels in Vorbis order (5.1: L C R Ls Rs LFE), any sample rate. +let opts = OggVorbisOptions::new(6.0).with_tag("TITLE", "Take 3").with_tag("ARTIST", "Me"); +let ogg: Vec = encode_ogg_vorbis(&buf, &opts)?; +``` + +The encoder is pure Rust (`vorbis::encoder`, from FilmCraft #4481) and builds for wasm32. Quality +runs from -1 to 10 at a variable bit rate: about 18 kbit/s per channel at -1, 100 at 6 and 140 +at 10 on music. `encode` with `EncodeFormat::Ogg` takes a WAV-order layout and writes it in +Vorbis order; its `RateControl::Bitrate` (64–500 kbit/s) picks the quality whose nominal rate +that is (`quality_for_bitrate`), and `RateControl::Quality` 0.0–1.0 is quality -1 to 10. For +streaming, feed `vorbis::encoder::Encoder` and write its packets with `craft_media::ogg::PageWriter` +(identification, `vorbis_comment`, setup, then the audio with each packet's granule position). + +Not yet: short blocks (transients may pre-echo), channel coupling (stereo costs +about twice mono) and bit-rate management. + ### Waveform overviews ```rust @@ -704,6 +731,7 @@ the full tests with ffmpeg and the vectors required. | MP3 encoder | FilmCraft `filmcraft-mp3enc` [4bec22b](https://github.com/storytold/filmcraft/commit/4bec22bd03bd1d995c9cf72e02a284f96d3d72cd) | | ALAC | Apple's reference implementation [macosforge/alac@c38887c](https://github.com/macosforge/alac/tree/c38887c5c5e64a4b31108733bd79ca9b2496d987/codec), Copyright © 2011 Apple Inc., Apache-2.0; ported to Rust and modified (see the `alac` module docs and [NOTICE](../../NOTICE)) | | Opus encoder | EffectCraft `effectcraft-opusenc` [c618429](https://github.com/storytold/effectcraft/commit/c618429252587525a2a6d4b5bccbe4ec5261e1b9) | +| Vorbis encoder | FilmCraft `filmcraft-vorbis` by @JordyUSA ([storytold/filmcraft#4481](https://github.com/storytold/filmcraft/pull/4481)), with partitions of whole sample frames so libvorbis reads surround | Where apps had overlapping implementations, the one that measured better was kept, with the tests of both: @@ -761,3 +789,8 @@ The codec modules' public items keep their names, so apps can re-export them CAF. MP4 and Matroska files decode to presentation length. A packet that fails is concealed, not dropped. A failed source read is `AudioError::Io`. + +WAV timestamps use `bext` when present, including a zero timestamp. Otherwise a bounded iXML +`BWFXML/BEXT` time reference supplies the timestamp (two unsigned 32-bit words; an omitted high +word is zero). Only the first iXML chunk is considered. Invalid or oversized optional XML is +ignored without rejecting the audio. This works for byte-backed and streaming sources. diff --git a/crates/audio/src/aac/config.rs b/crates/audio/src/aac/config.rs index 88be1e214f..3d12b03438 100644 --- a/crates/audio/src/aac/config.rs +++ b/crates/audio/src/aac/config.rs @@ -343,6 +343,51 @@ impl AudioSpecificConfig { } } +/// Why an AudioSpecificConfig prefix cannot be written as an ADTS header. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AdtsConfigError { + /// Fewer than two bytes were supplied. + Short, + /// The prefix names a profile, indexed rate or channel configuration ADTS cannot carry. + Unsupported { + /// Audio object type from the prefix. + object_type: u8, + /// Sampling frequency index from the prefix. + sf_index: u8, + /// Channel configuration from the prefix. + channel_config: u8, + }, +} + +/// ADTS fixed fields taken from the prefix of an AudioSpecificConfig. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AdtsConfig { + /// Audio object type, 1 through 4. + pub object_type: u8, + /// Indexed sample rate, 0 through 12. + pub sf_index: u8, + /// Channel configuration, 1 through 7. + pub channel_config: u8, +} +impl AdtsConfig { + /// Parse only the first two ASC bytes. Unlike a decoder's full ASC parser, this accepts all + /// four object types representable by ADTS and rejects configurations needing a PCE. + pub fn from_asc_prefix(asc: &[u8]) -> std::result::Result { + let (Some(&a), Some(&b)) = (asc.first(), asc.get(1)) else { return Err(AdtsConfigError::Short) }; + let object_type = a >> 3; + let sf_index = ((a & 7) << 1) | (b >> 7); + let channel_config = (b >> 3) & 15; + if !(1..=4).contains(&object_type) || sf_index > 12 || !(1..=7).contains(&channel_config) { + return Err(AdtsConfigError::Unsupported { object_type, sf_index, channel_config }); + } + Ok(Self { object_type, sf_index, channel_config }) + } + /// Write a no-CRC ADTS header with variable-rate buffer fullness for one payload. + pub fn header(self, payload_len: usize) -> Result<[u8; 7]> { + AdtsHeader::write(self.object_type, self.sf_index, self.channel_config, payload_len, 0x7ff) + } +} + /// A parsed ADTS header. #[non_exhaustive] #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -519,6 +564,15 @@ mod tests { assert_eq!(AudioSpecificConfig::parse(&asc.to_bytes().unwrap()).unwrap(), asc); } + #[test] + fn adts_config_preserves_prefix_and_frame_limits() { + let config = AdtsConfig::from_asc_prefix(&[0x12, 0x10]).unwrap(); + assert_eq!(config.header(100).unwrap(), AdtsHeader::write(2, 4, 2, 100, 0x7ff).unwrap()); + assert!(config.header(8185).is_err()); + assert_eq!(AdtsConfig::from_asc_prefix(&[]), Err(AdtsConfigError::Short)); + assert!(matches!(AdtsConfig::from_asc_prefix(&[0x2a, 0x10]), Err(AdtsConfigError::Unsupported { object_type: 5, .. }))); + } + #[test] fn adts_headers_refuse_fields_they_cannot_hold() { for (object_type, sf_index, channel_config) in [(0, 4, 2), (5, 4, 2), (29, 4, 2), (2, 13, 2), (2, 15, 2), (2, 4, 8), (2, 4, 11), (2, 4, 12)] { diff --git a/crates/audio/src/aac/mod.rs b/crates/audio/src/aac/mod.rs index f423a4e22c..fb79ae7439 100644 --- a/crates/audio/src/aac/mod.rs +++ b/crates/audio/src/aac/mod.rs @@ -60,7 +60,7 @@ mod tns; #[cfg(feature = "aac-decode")] pub(crate) use config::split_adts_upto; -pub use config::{AdtsHeader, AudioSpecificConfig, ElementType, ProgramConfig, config_layout, split_adts}; +pub use config::{AdtsConfig, AdtsConfigError, AdtsHeader, AudioSpecificConfig, ElementType, ProgramConfig, config_layout, split_adts}; #[cfg(feature = "aac-decode")] pub use decoder::Decoder; #[cfg(feature = "aac-encode")] diff --git a/crates/audio/src/essence_pcm.rs b/crates/audio/src/essence_pcm.rs new file mode 100644 index 0000000000..dfb119b8b7 --- /dev/null +++ b/crates/audio/src/essence_pcm.rs @@ -0,0 +1,189 @@ +//! Compatibility WAVE and AIFF wrappers for embedded PCM essence in interchange files. +//! PCM inside the model is interleaved little-endian signed integers (8-bit unsigned for WAVE). + +pub use crate::{pcm_aiff_header as aiff_header, pcm_wav_file as wav_file, pcm_wav_header as wav_header}; + +/// PCM, channels, sample rate and bits of a WAVE file (integer PCM only). +pub fn parse_wav(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { + if b.len() < 12 || &b[..4] != b"RIFF" || &b[8..12] != b"WAVE" { + return None; + } + let mut at = 12; + let mut fmt = None; + while at + 8 <= b.len() { + let id = &b[at..at + 4]; + let len = u32::from_le_bytes(b[at + 4..at + 8].try_into().ok()?) as usize; + let body = &b[at + 8..(at + 8).saturating_add(len).min(b.len())]; + if id == b"fmt " && body.len() >= 16 { + let tag = u16::from_le_bytes([body[0], body[1]]); + let ch = u16::from_le_bytes([body[2], body[3]]); + let sr = u32::from_le_bytes(body[4..8].try_into().ok()?); + let bits = u16::from_le_bytes([body[14], body[15]]); + if tag != 1 && tag != 0xFFFE { + return None; + } + if tag == 0xFFFE { + // The first two bytes of the sub-format GUID carry the real format code. + let sub = body.get(24..26)?; + if u16::from_le_bytes([sub[0], sub[1]]) != 1 { + return None; + } + } + fmt = Some((ch, sr, bits)); + } else if id == b"data" { + let (ch, sr, bits) = fmt?; + return Some((body.to_vec(), ch, sr, bits)); + } + at = at.checked_add(8usize.checked_add(len)?.checked_add(len & 1)?)?; + } + None +} + +/// A complete AIFF file (big-endian PCM) from little-endian PCM. +pub fn aiff_file(pcm: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Vec { + let bps = bits.div_ceil(8) as usize; + let frames = pcm.len() / (bps * channels.max(1) as usize).max(1); + let mut v = aiff_header(frames as u32, channels, sample_rate, bits); + for s in pcm.chunks_exact(bps.max(1)) { + if bps == 1 { + v.push(s[0] ^ 0x80); // WAVE 8-bit is unsigned, AIFF signed + } else { + v.extend(s.iter().rev()); + } + } + if (v.len() - 8) & 1 == 1 { + v.push(0); + } + v +} + +/// PCM (converted to little-endian), channels, sample rate and bits of an AIFF / AIFF-C (`NONE` +/// / `twos` / `sowt`) file. +pub fn parse_aiff(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { + if b.len() < 12 || &b[..4] != b"FORM" || !(&b[8..12] == b"AIFF" || &b[8..12] == b"AIFC") { + return None; + } + let aifc = &b[8..12] == b"AIFC"; + let mut at = 12; + let mut comm = None; + while at + 8 <= b.len() { + let id = &b[at..at + 4]; + let len = u32::from_be_bytes(b[at + 4..at + 8].try_into().ok()?) as usize; + let body = &b[at + 8..(at + 8).saturating_add(len).min(b.len())]; + if id == b"COMM" && body.len() >= 18 { + let ch = u16::from_be_bytes([body[0], body[1]]); + let bits = u16::from_be_bytes([body[6], body[7]]); + let sr = from_extended(body[8..18].try_into().ok()?).round() as u32; + // AIFF has no compression code (trailing COMM bytes mean nothing); AIFF-C must name one + // of the integer PCM codes, or the samples are not integer PCM at all + let little = if aifc { + match body.get(18..22)? { + b"NONE" | b"twos" => false, + b"sowt" => true, + _ => return None, + } + } else { + false + }; + comm = Some((ch, sr, bits, little)); + } else if id == b"SSND" && body.len() >= 8 { + let (ch, sr, bits, little) = comm?; + let off = u32::from_be_bytes(body[..4].try_into().ok()?) as usize; + let data = body.get(8usize.checked_add(off)?..)?; + let bps = bits.div_ceil(8) as usize; + let mut pcm = Vec::with_capacity(data.len()); + for s in data.chunks_exact(bps.max(1)) { + if bps == 1 { + pcm.push(s[0] ^ 0x80); + } else if little { + pcm.extend_from_slice(s); + } else { + pcm.extend(s.iter().rev()); + } + } + return Some((pcm, ch, sr, bits)); + } + at = at.checked_add(8usize.checked_add(len)?.checked_add(len & 1)?)?; + } + None +} + +fn from_extended(b: [u8; 10]) -> f64 { + let e = (u16::from_be_bytes([b[0], b[1]]) & 0x7FFF) as i32; + let m = u64::from_be_bytes(b[2..10].try_into().unwrap_or([0; 8])); + if e == 0 && m == 0 { + return 0.0; + } + m as f64 / (1u64 << 63) as f64 * 2f64.powi(e - 16383) +} + +#[cfg(test)] +mod tests { + /// A mutated EDL whose clip ran for days produced an OMF descriptor for more than 4 GiB of + /// PCM: the RIFF size field overflowed ("attempt to add with overflow"). + #[test] + fn huge_wav_header_saturates() { + let h = super::wav_header(u32::MAX, 2, u32::MAX, 24); + assert_eq!(&h[4..8], &u32::MAX.to_le_bytes()); + } + + use super::*; + + #[test] + fn accepts_truncated_essence_summaries() { + let mut wav = wav_file(&[1, 2, 3, 4], 1, 48_000, 16); + wav.truncate(46); + assert_eq!(parse_wav(&wav), Some((vec![1, 2], 1, 48_000, 16))); + let mut aiff = aiff_file(&[1, 2, 3, 4], 1, 48_000, 16); + aiff.truncate(56); + assert_eq!(parse_aiff(&aiff), Some((vec![1, 2], 1, 48_000, 16))); + } + + #[test] + fn wav_and_aiff_round_trip() { + let pcm: Vec = (0..48u8).collect(); // 8 stereo 24-bit frames + let w = wav_file(&pcm, 2, 48_000, 24); + assert_eq!(parse_wav(&w), Some((pcm.clone(), 2, 48_000, 24))); + let a = aiff_file(&pcm, 2, 44_100, 24); + assert_eq!(parse_aiff(&a), Some((pcm.clone(), 2, 44_100, 24))); + let p16: Vec = (0..32u8).collect(); + assert_eq!(parse_aiff(&aiff_file(&p16, 1, 96_000, 16)), Some((p16, 1, 96_000, 16))); + assert!(parse_wav(b"RIFF").is_none()); + assert!(parse_aiff(&a[..30]).is_none()); + for cut in 0..w.len() { + let _ = parse_wav(&w[..cut]); + let _ = parse_aiff(&a[..cut.min(a.len())]); + } + } + + #[test] + fn aifc_needs_an_integer_pcm_compression_code() { + let file = |kind: &[u8; 4], code: &[u8]| { + let mut comm = vec![0, 1, 0, 0, 0, 1, 0, 16]; + comm.extend_from_slice(&[0x40, 0x0E, 0xBB, 0x80, 0, 0, 0, 0, 0, 0]); + comm.extend_from_slice(code); + let mut body = kind.to_vec(); + body.extend_from_slice(b"COMM"); + body.extend_from_slice(&(comm.len() as u32).to_be_bytes()); + body.extend_from_slice(&comm); + if comm.len() & 1 == 1 { + body.push(0); + } + body.extend_from_slice(b"SSND"); + body.extend_from_slice(&10u32.to_be_bytes()); + body.extend_from_slice(&[0; 8]); + body.extend_from_slice(&[0x12, 0x34]); + let mut v = b"FORM".to_vec(); + v.extend_from_slice(&(body.len() as u32).to_be_bytes()); + v.extend_from_slice(&body); + v + }; + assert_eq!(parse_aiff(&file(b"AIFC", b"NONE")).map(|p| p.0), Some(vec![0x34, 0x12])); + assert_eq!(parse_aiff(&file(b"AIFC", b"twos")).map(|p| p.0), Some(vec![0x34, 0x12])); + assert_eq!(parse_aiff(&file(b"AIFC", b"sowt")).map(|p| p.0), Some(vec![0x12, 0x34])); + assert!(parse_aiff(&file(b"AIFC", b"fl32")).is_none(), "float samples are not integer PCM"); + assert!(parse_aiff(&file(b"AIFC", b"")).is_none(), "AIFF-C without a compression code"); + // plain AIFF ignores trailing COMM bytes + assert_eq!(parse_aiff(&file(b"AIFF", b"sowt")).map(|p| p.0), Some(vec![0x34, 0x12])); + } +} diff --git a/crates/audio/src/flac_decode.rs b/crates/audio/src/flac_decode.rs new file mode 100644 index 0000000000..bb56e65c52 --- /dev/null +++ b/crates/audio/src/flac_decode.rs @@ -0,0 +1,603 @@ +//! A native FLAC decoder (RFC 9639): [`decode`] for whole `.flac` files and [`Decoder`] for single +//! frames (the packets of FLAC in MP4, Matroska or Ogg). +//! +//! Every frame is checked against its CRC-8 and CRC-16. Subframe types constant, verbatim, fixed +//! and LPC; Rice partitions with 4- and 5-bit parameters and escaped partitions; wasted bits; +//! left/side, side/right and mid/side stereo; fixed and variable block sizes; 4 to 32 bits per +//! sample. The STREAMINFO MD5 is not verified. +//! +//! Samples come back as `i32`, one `Vec` per channel, in the FLAC channel order. + +/// What went wrong decoding FLAC. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum DecodeError { + /// The data ends early. + #[error("truncated FLAC data")] + Truncated, + /// The data is not valid FLAC. + #[error("invalid FLAC data: {0}")] + Invalid(&'static str), + /// A frame or header failed its CRC. + #[error("FLAC CRC mismatch in {0}")] + Crc(&'static str), + /// Valid FLAC that is not decoded. + #[error("unsupported FLAC feature: {0}")] + Unsupported(&'static str), + /// The stream is longer than the sample limit. + #[error("FLAC stream exceeds the sample limit")] + TooLarge, +} + +/// `Result` of this module. +pub type Result = std::result::Result; + +/// The STREAMINFO metadata block (RFC 9639 section 8.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StreamInfo { + /// Smallest block size in samples. + pub min_block_size: u16, + /// Largest block size in samples. + pub max_block_size: u16, + /// Smallest frame in bytes, 0 if unknown. + pub min_frame_size: u32, + /// Largest frame in bytes, 0 if unknown. + pub max_frame_size: u32, + /// Sample rate in Hz. + pub sample_rate: u32, + /// Channel count, 1 to 8. + pub channels: u8, + /// Bits per sample, 4 to 32. + pub bits_per_sample: u8, + /// Samples per channel in the stream, 0 if unknown. + pub total_samples: u64, + /// MD5 of the unencoded audio, all zero if not set. + pub md5: [u8; 16], +} + +impl StreamInfo { + /// Parse the 34 bytes of a STREAMINFO block body. + pub fn parse(b: &[u8]) -> Result { + let b = b.get(..34).ok_or(DecodeError::Truncated)?; + let packed = u64::from_be_bytes([b[10], b[11], b[12], b[13], b[14], b[15], b[16], b[17]]); + let info = StreamInfo { + min_block_size: u16::from_be_bytes([b[0], b[1]]), + max_block_size: u16::from_be_bytes([b[2], b[3]]), + min_frame_size: u32::from_be_bytes([0, b[4], b[5], b[6]]), + max_frame_size: u32::from_be_bytes([0, b[7], b[8], b[9]]), + sample_rate: (packed >> 44) as u32, + channels: ((packed >> 41) & 7) as u8 + 1, + bits_per_sample: ((packed >> 36) & 31) as u8 + 1, + total_samples: packed & 0xF_FFFF_FFFF, + md5: b[18..34].try_into().map_err(|_| DecodeError::Truncated)?, + }; + if info.bits_per_sample < 4 { + return Err(DecodeError::Invalid("bits per sample below 4")); + } + if info.min_block_size != 0 + && (info.min_block_size < 16 && info.min_block_size != info.max_block_size || info.max_block_size < info.min_block_size) + { + return Err(DecodeError::Invalid("inconsistent block sizes")); + } + Ok(info) + } +} + +/// One decoded frame. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Frame { + /// Sample rate in Hz. + pub sample_rate: u32, + /// Bits per sample. + pub bits_per_sample: u8, + /// `true` when `number` is the first sample's index (variable block size), `false` when it is + /// the frame's index (fixed block size). + pub variable_block_size: bool, + /// The coded number of the frame header. + pub number: u64, + /// Samples per channel in the frame. + pub block_size: usize, + /// One `Vec` per channel, after undoing any stereo decorrelation. + pub channels: Vec>, + /// Bytes the frame took, including the header and CRC footer. + pub size: usize, +} + +// ---- checksums ---- + +fn crc8(data: &[u8]) -> u8 { + let mut crc = 0u8; + for &b in data { + crc ^= b; + for _ in 0..8 { + crc = if crc & 0x80 != 0 { crc << 1 ^ 0x07 } else { crc << 1 }; + } + } + crc +} + +fn crc16(data: &[u8]) -> u16 { + let mut crc = 0u16; + for &b in data { + crc ^= u16::from(b) << 8; + for _ in 0..8 { + crc = if crc & 0x8000 != 0 { crc << 1 ^ 0x8005 } else { crc << 1 }; + } + } + crc +} + +// ---- bits ---- + +struct Bits<'a> { + data: &'a [u8], + /// Position in bits. + pos: usize, +} + +impl<'a> Bits<'a> { + fn new(data: &'a [u8]) -> Self { + Bits { data, pos: 0 } + } + + fn left(&self) -> usize { + self.data.len() * 8 - self.pos + } + + fn bit(&mut self) -> Result { + let byte = *self.data.get(self.pos / 8).ok_or(DecodeError::Truncated)?; + let v = (byte >> (7 - self.pos % 8)) & 1; + self.pos += 1; + Ok(u32::from(v)) + } + + /// `n` bits (0 to 32) as an unsigned number. + fn bits(&mut self, n: u32) -> Result { + if n as usize > self.left() { + return Err(DecodeError::Truncated); + } + let mut v = 0u64; + let mut n = n as usize; + while n > 0 { + let byte = u64::from(self.data[self.pos / 8]); + let avail = 8 - self.pos % 8; + let take = avail.min(n); + v = v << take | (byte >> (avail - take)) & ((1 << take) - 1); + self.pos += take; + n -= take; + } + Ok(v) + } + + /// `n` bits (0 to 33) as a two's complement number. + fn signed(&mut self, n: u32) -> Result { + if n == 0 { + return Ok(0); + } + let v = self.bits(n)? as i64; + Ok(if v >> (n - 1) & 1 == 1 { v - (1 << n) } else { v }) + } + + /// Zero bits up to the next one bit (which is consumed). + fn unary(&mut self) -> Result { + let mut n = 0u64; + loop { + // Skip whole zero bytes when aligned. + if self.pos.is_multiple_of(8) { + while self.data.get(self.pos / 8) == Some(&0) { + self.pos += 8; + n += 8; + } + } + if self.bit()? == 1 { + return Ok(n); + } + n += 1; + } + } + + fn align(&mut self) { + self.pos = self.pos.div_ceil(8) * 8; + } +} + +// ---- frame ---- + +const BLOCK_SIZES: [usize; 16] = [0, 192, 576, 1152, 2304, 4608, 0, 0, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768]; + +/// A frame decoder. `info` supplies what a frame header leaves to the STREAMINFO. +#[derive(Debug, Clone, Copy, Default)] +pub struct Decoder { + info: Option, +} + +impl Decoder { + /// A decoder with the stream's STREAMINFO (needed for frames whose header defers the sample + /// rate or bit depth to it). + pub fn new(info: StreamInfo) -> Decoder { + Decoder { info: Some(info) } + } + + /// A decoder without STREAMINFO: frames that defer to it are an error. + pub fn without_streaminfo() -> Decoder { + Decoder { info: None } + } + + /// Decode the frame at the start of `data`. + pub fn decode_frame(&self, data: &[u8]) -> Result { + // StreamInfo has public fields: container callers can construct it without + // parse(), so validate before it can control shifts and sample reads. + if self.info.is_some_and(|i| !(4..=32).contains(&i.bits_per_sample) || !(1..=8).contains(&i.channels) || i.sample_rate == 0) { + return Err(DecodeError::Invalid("invalid decoder STREAMINFO")); + } + let mut r = Bits::new(data); + if r.bits(15)? != 0x7FFC { + return Err(DecodeError::Invalid("missing frame sync code")); + } + let variable = r.bit()? == 1; + let (bs_code, sr_code) = (r.bits(4)? as usize, r.bits(4)? as usize); + let (ch_code, bps_code) = (r.bits(4)? as usize, r.bits(3)? as usize); + if r.bit()? != 0 { + return Err(DecodeError::Invalid("reserved bit set")); + } + let number = coded_number(&mut r)?; + let block_size = match bs_code { + 0 => return Err(DecodeError::Invalid("reserved block size")), + 6 => r.bits(8)? as usize + 1, + 7 => r.bits(16)? as usize + 1, + c => BLOCK_SIZES[c], + }; + let sample_rate = match sr_code { + 0 => self.info.map(|i| i.sample_rate).ok_or(DecodeError::Invalid("sample rate only in STREAMINFO"))?, + 1 => 88_200, + 2 => 176_400, + 3 => 192_000, + 4 => 8_000, + 5 => 16_000, + 6 => 22_050, + 7 => 24_000, + 8 => 32_000, + 9 => 44_100, + 10 => 48_000, + 11 => 96_000, + 12 => r.bits(8)? as u32 * 1000, + 13 => r.bits(16)? as u32, + 14 => r.bits(16)? as u32 * 10, + _ => return Err(DecodeError::Invalid("forbidden sample rate code")), + }; + let header_len = r.pos.div_ceil(8); + let stored_crc = r.bits(8)? as u8; + if crc8(&data[..header_len]) != stored_crc { + return Err(DecodeError::Crc("a frame header")); + } + let bits = match bps_code { + 0 => self.info.map(|i| u32::from(i.bits_per_sample)).ok_or(DecodeError::Invalid("bit depth only in STREAMINFO"))?, + 1 => 8, + 2 => 12, + 4 => 16, + 5 => 20, + 6 => 24, + 7 => 32, + _ => return Err(DecodeError::Invalid("reserved bit depth")), + }; + let (channels, mode) = match ch_code { + 0..=7 => (ch_code + 1, Stereo::Independent), + 8 => (2, Stereo::LeftSide), + 9 => (2, Stereo::SideRight), + 10 => (2, Stereo::MidSide), + _ => return Err(DecodeError::Invalid("reserved channel assignment")), + }; + let mut out: Vec> = Vec::with_capacity(channels); + for c in 0..channels { + let extra = match (mode, c) { + (Stereo::LeftSide, 1) | (Stereo::SideRight, 0) | (Stereo::MidSide, 1) => 1, + _ => 0, + }; + out.push(subframe(&mut r, block_size, bits + extra)?); + } + r.align(); + let size = r.pos / 8; + let crc = r.bits(16)? as u16; + if crc16(&data[..size]) != crc { + return Err(DecodeError::Crc("a frame")); + } + let size = size + 2; + if mode != Stereo::Independent { + let (first, rest) = out.split_at_mut(1); + let (a, b) = (&mut first[0], &mut rest[0]); + for (x, y) in a.iter_mut().zip(b.iter_mut()) { + match mode { + Stereo::LeftSide => *y = x.wrapping_sub(*y), + Stereo::SideRight => *x = x.wrapping_add(*y), + _ => { + let m = x.wrapping_shl(1) | (*y & 1); + let side = *y; + *x = m.wrapping_add(side) >> 1; + *y = m.wrapping_sub(side) >> 1; + } + } + } + } + let mut chans = Vec::with_capacity(channels); + for c in out { + let v: Result> = c.into_iter().map(|s| checked_sample(s, bits)).collect(); + chans.push(v?); + } + Ok(Frame { sample_rate, bits_per_sample: bits as u8, variable_block_size: variable, number, block_size, channels: chans, size }) + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Stereo { + Independent, + LeftSide, + SideRight, + MidSide, +} + +/// The UTF-8-like coded number of a frame header (up to 36 bits, 7 bytes). +fn coded_number(r: &mut Bits) -> Result { + let first = r.bits(8)? as u8; + let extra = match first { + 0x00..=0x7F => return Ok(u64::from(first)), + 0xC0..=0xDF => 1, + 0xE0..=0xEF => 2, + 0xF0..=0xF7 => 3, + 0xF8..=0xFB => 4, + 0xFC..=0xFD => 5, + 0xFE => 6, + _ => return Err(DecodeError::Invalid("bad coded number")), + }; + let mut v = if extra == 6 { 0 } else { u64::from(first & (0x3F >> extra)) }; + for _ in 0..extra { + let b = r.bits(8)?; + if b & 0xC0 != 0x80 { + return Err(DecodeError::Invalid("bad coded number")); + } + v = v << 6 | (b & 0x3F); + } + Ok(v) +} + +/// One subframe: `bits` is the frame bit depth (plus 1 for a side channel). +fn subframe(r: &mut Bits, n: usize, bits: u32) -> Result> { + if r.bit()? != 0 { + return Err(DecodeError::Invalid("subframe header padding bit set")); + } + let kind = r.bits(6)? as u32; + let wasted = if r.bit()? == 1 { r.unary()? as u32 + 1 } else { 0 }; + if wasted >= bits { + return Err(DecodeError::Invalid("wasted bits leave no sample bits")); + } + let bps = bits - wasted; + let mut s = vec![0i64; n]; + match kind { + 0 => { + let v = r.signed(bps)?; + s.fill(v); + } + 1 => { + for v in s.iter_mut() { + *v = r.signed(bps)?; + } + } + 8..=12 => { + let order = (kind - 8) as usize; + warmup(r, &mut s, order, bps)?; + residual(r, &mut s, order)?; + for i in order..n { + let at = |k: usize| s[i - k]; + // Wrapping: hostile residuals can overflow; such samples fail the range check later. + let p = match order { + 0 => 0, + 1 => at(1), + 2 => at(1).wrapping_mul(2).wrapping_sub(at(2)), + 3 => at(1).wrapping_mul(3).wrapping_sub(at(2).wrapping_mul(3)).wrapping_add(at(3)), + _ => at(1).wrapping_mul(4).wrapping_sub(at(2).wrapping_mul(6)).wrapping_add(at(3).wrapping_mul(4)).wrapping_sub(at(4)), + }; + s[i] = s[i].wrapping_add(p); + } + } + 32..=63 => { + let order = (kind - 31) as usize; + warmup(r, &mut s, order, bps)?; + let precision = r.bits(4)? as u32 + 1; + if precision == 16 { + return Err(DecodeError::Invalid("forbidden coefficient precision")); + } + let shift = r.signed(5)?; + if shift < 0 { + return Err(DecodeError::Invalid("negative prediction shift")); + } + let mut coefs = [0i64; 32]; + for c in coefs.iter_mut().take(order) { + *c = r.signed(precision)?; + } + residual(r, &mut s, order)?; + for i in order..n { + let mut sum = 0i64; + for (k, &c) in coefs.iter().take(order).enumerate() { + sum = sum.wrapping_add(c.wrapping_mul(s[i - 1 - k])); + } + s[i] = s[i].wrapping_add(sum >> shift); + } + } + _ => return Err(DecodeError::Invalid("reserved subframe type")), + } + if wasted > 0 { + for v in s.iter_mut() { + *v = v.wrapping_shl(wasted); + } + } + Ok(s) +} + +fn warmup(r: &mut Bits, s: &mut [i64], order: usize, bps: u32) -> Result<()> { + if order > s.len() { + return Err(DecodeError::Invalid("predictor order above the block size")); + } + for v in s.iter_mut().take(order) { + *v = r.signed(bps)?; + } + Ok(()) +} + +/// The coded residual (RFC 9639 section 9.2.7), into `s[order..]`. +fn residual(r: &mut Bits, s: &mut [i64], order: usize) -> Result<()> { + let method = r.bits(2)?; + let (param_bits, escape) = match method { + 0 => (4, 15), + 1 => (5, 31), + _ => return Err(DecodeError::Invalid("reserved residual coding method")), + }; + let part_order = r.bits(4)? as u32; + let n = s.len(); + let parts = 1usize << part_order; + if !n.is_multiple_of(parts) { + return Err(DecodeError::Invalid("partition order does not divide the block size")); + } + let per = n >> part_order; + if per < order { + return Err(DecodeError::Invalid("partition shorter than the predictor order")); + } + let mut i = order; + for p in 0..parts { + let count = if p == 0 { per - order } else { per }; + let k = r.bits(param_bits)? as u32; + if k == escape { + let width = r.bits(5)? as u32; + for v in s[i..i + count].iter_mut() { + *v = r.signed(width)?; + } + } else { + for v in s[i..i + count].iter_mut() { + let q = r.unary()?; + if q > (1 << 32) { + return Err(DecodeError::Invalid("Rice quotient too large")); + } + let low = r.bits(k)?; + let folded = q << k | low; + *v = if folded & 1 == 0 { (folded >> 1) as i64 } else { -((folded >> 1) as i64) - 1 }; + } + } + i += count; + } + Ok(()) +} + +// ---- files ---- + +/// A decoded file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Decoded { + /// The STREAMINFO block. + pub info: StreamInfo, + /// One `Vec` of samples per channel. + pub channels: Vec>, +} + +/// Most sample values (samples x channels) [`decode`] will produce. +pub const DEFAULT_MAX_VALUES: u64 = 1 << 28; + +/// Decode a whole `.flac` file (an ID3v2 tag in front is skipped). +pub fn decode(bytes: &[u8]) -> Result { + decode_with_limit(bytes, DEFAULT_MAX_VALUES) +} + +/// [`decode`] with a limit on the sample values (samples x channels) produced. +pub fn decode_with_limit(bytes: &[u8], max_values: u64) -> Result { + let mut pos = 0usize; + if bytes.starts_with(b"ID3") { + let size = bytes.get(6..10).ok_or(DecodeError::Truncated)?; + if size.iter().any(|&b| b & 0x80 != 0) { + return Err(DecodeError::Invalid("bad ID3v2 size")); + } + pos = 10 + size.iter().fold(0usize, |a, &b| a << 7 | usize::from(b)); + } + if bytes.get(pos..pos + 4) != Some(b"fLaC") { + return Err(DecodeError::Invalid("missing fLaC marker")); + } + pos += 4; + let mut info: Option = None; + loop { + let head = bytes.get(pos..pos + 4).ok_or(DecodeError::Truncated)?; + let last = head[0] & 0x80 != 0; + let kind = head[0] & 0x7F; + let len = usize::from(head[1]) << 16 | usize::from(head[2]) << 8 | usize::from(head[3]); + let body = bytes.get(pos + 4..pos + 4 + len).ok_or(DecodeError::Truncated)?; + match (kind, &info) { + (0, None) => info = Some(StreamInfo::parse(body)?), + (0, Some(_)) => return Err(DecodeError::Invalid("a second STREAMINFO block")), + (_, None) => return Err(DecodeError::Invalid("STREAMINFO is not the first block")), + (127, _) => return Err(DecodeError::Invalid("forbidden metadata block type")), + _ => {} + } + pos += 4 + len; + if last { + break; + } + } + let info = info.ok_or(DecodeError::Invalid("no STREAMINFO"))?; + let dec = Decoder::new(info); + let mut channels: Vec> = vec![Vec::new(); usize::from(info.channels)]; + let mut total = 0u64; + while pos + 2 <= bytes.len() && bytes[pos] == 0xFF && bytes[pos + 1] & 0xFE == 0xF8 { + let frame = dec.decode_frame(&bytes[pos..])?; + if frame.channels.len() != channels.len() { + return Err(DecodeError::Invalid("the channel count changes inside the stream")); + } + // One file has one sample rate and depth. Otherwise callers would play + // samples under incompatible STREAMINFO metadata. + if frame.sample_rate != info.sample_rate || frame.bits_per_sample != info.bits_per_sample { + return Err(DecodeError::Invalid("frame format differs from STREAMINFO")); + } + total += frame.block_size as u64; + if total.saturating_mul(channels.len() as u64) > max_values { + return Err(DecodeError::TooLarge); + } + for (dst, src) in channels.iter_mut().zip(frame.channels) { + dst.extend_from_slice(&src); + } + pos += frame.size; + } + // Unknown total_samples must not turn a corrupt/truncated next frame into + // a successfully decoded shorter recording. + if pos != bytes.len() { + return Err(DecodeError::Invalid("trailing data or missing frame sync")); + } + if info.total_samples != 0 && total != info.total_samples { + return Err(DecodeError::Truncated); + } + Ok(Decoded { info, channels }) +} + +// Validate the advertised precision, not just the storage type. Malformed +// predictors may produce an i32 that is still invalid for 4–24-bit audio. +fn checked_sample(sample: i64, bits: u32) -> Result { + if !(4..=32).contains(&bits) { + return Err(DecodeError::Invalid("invalid sample bit depth")); + } + let bound = 1i64 << (bits - 1); + if !(-bound..bound).contains(&sample) { + return Err(DecodeError::Invalid("sample outside the bit depth")); + } + i32::try_from(sample).map_err(|_| DecodeError::Invalid("sample outside the bit depth")) +} + +#[cfg(test)] +mod sample_bounds_tests { + use super::checked_sample; + + #[test] + fn samples_must_fit_declared_precision() { + for bits in 4..=32 { + let bound = 1i64 << (bits - 1); + assert_eq!(checked_sample(-bound, bits).map(i64::from), Ok(-bound)); + assert_eq!(checked_sample(bound - 1, bits).map(i64::from), Ok(bound - 1)); + assert!(checked_sample(-bound - 1, bits).is_err()); + assert!(checked_sample(bound, bits).is_err()); + } + assert!(checked_sample(0, 0).is_err()); + assert!(checked_sample(0, 255).is_err()); + } +} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 1c6c73dcfe..e4a1c16952 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -13,6 +13,8 @@ //! demuxers and [`TrackDecoder`]; everything else (FLAC, Vorbis, CAF, ADPCM, A-law, µ-law) through //! `symphonia`, which is to be replaced by native decoders. Feature `decode-native` is the //! same without symphonia. +//! - [`encode_ogg_vorbis`] and [`vorbis::encoder`] (feature `vorbis-encode`): Ogg Vorbis files +//! and Vorbis packets from a pure-Rust encoder, 1 to 8 channels, quality -1 to 10, with tags. //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar //! `f32` in WAV channel order. //! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also @@ -27,7 +29,8 @@ //! - Codec modules for packet-level use, each with its own features: [`aac`] (`aac-decode`, //! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`, and //! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`] -//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-encode`: the packet encoder). +//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder; +//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files). //! //! The shared types below build with no features. @@ -49,12 +52,18 @@ pub mod opus; mod pcm; #[cfg(feature = "peaks")] pub mod peaks; +#[cfg(any(feature = "qoa-decode", feature = "qoa-encode"))] +pub mod qoa; #[cfg(feature = "decode-native")] mod read; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] mod track; +#[cfg(feature = "vorbis-encode")] +pub mod vorbis; #[cfg(any(feature = "decode-native", feature = "pcm-encode"))] mod wav; +/// Bounded WAV/RF64 cue, adtl and XMP marker metadata, without audio decoding. +pub mod wav_markers; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -62,10 +71,23 @@ mod wav; feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", - feature = "eac3-encode" + feature = "eac3-encode", + feature = "vorbis-encode" ))] mod write; +/// PCM WAVE and AIFF wrappers for interchange essence. +#[cfg(feature = "pcm-encode")] +pub mod essence_pcm; +/// Streaming WAVE and AIFF headers and sample packing. +pub mod pcm_export; +/// Interleaved PCM packet decoding. +pub mod pcm_interleaved; +/// Range-backed PCM WAVE access and a 16-bit PCM writer. +pub mod wav_range; +#[cfg(feature = "vorbis-encode")] +pub use write::{OGG_BITRATES, OggVorbisOptions, encode_ogg, encode_ogg_vorbis, quality_for_bitrate}; + /// The FLAC packet encoder (RFC 9639), for a caller that muxes FLAC itself (into MP4, Matroska or /// its own `.flac` writer): planar integer samples in, frames out, and the STREAMINFO to patch in /// at the end. [`FileEncoder`] and [`encode`] write whole `.flac` files from `f32` instead. @@ -85,10 +107,15 @@ mod write; /// assert!(file.len() < 48_000 * 2 * 2 / 2); // well under half of 16-bit PCM /// # Ok::<(), craft_audio::flac::Error>(()) /// ``` -#[cfg(feature = "flac-encode")] +#[cfg(any(feature = "flac-encode", feature = "flac-decode"))] pub mod flac { + #[cfg(feature = "flac-decode")] + pub use crate::flac_decode::{DEFAULT_MAX_VALUES, DecodeError, Decoded, Decoder, Frame, StreamInfo, decode, decode_with_limit}; + #[cfg(feature = "flac-encode")] pub use crate::write::flac::encoder::{Encoder, EncoderConfig, Error, STREAMINFO_OFFSET}; } +#[cfg(feature = "flac-decode")] +mod flac_decode; pub use buffer::AudioBuffer; /// The craft-media this crate is built with, for its containers: using it rather than a separate @@ -107,8 +134,6 @@ pub use read::{ 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", @@ -118,7 +143,20 @@ pub use write::wav_float_header; feature = "ac3-encode", feature = "eac3-encode" ))] -pub use write::{ENCODE_EXTENSIONS, FileEncoder, encode, encode_format_for}; +pub use write::FileEncoder; +#[cfg(feature = "pcm-encode")] +pub use write::wav_float_header; +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "vorbis-encode" +))] +pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; @@ -256,6 +294,10 @@ pub enum EncodeFormat { Ac3, /// An E-AC-3 stream: up to 7.1 at 32, 44.1 or 48 kHz. Eac3, + /// Ogg Vorbis, 1–8 channels at any sample rate, whole-buffer encoding only. Variable bit + /// rate: a [`RateControl::Bitrate`] picks the quality whose nominal rate it is + /// ([`quality_for_bitrate`]), [`RateControl::Quality`] sets it directly. + Ogg, } impl EncodeFormat { @@ -270,6 +312,7 @@ impl EncodeFormat { EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3, + EncodeFormat::Ogg, ]; /// The extension a new file of this format gets, lower case and without the dot: `"wav"`, @@ -284,6 +327,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => "mp3", EncodeFormat::Ac3 => "ac3", EncodeFormat::Eac3 => "eac3", + EncodeFormat::Ogg => "ogg", } } @@ -297,6 +341,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => "audio/mpeg", EncodeFormat::Ac3 => "audio/ac3", EncodeFormat::Eac3 => "audio/eac3", + EncodeFormat::Ogg => "audio/ogg", } } @@ -309,6 +354,7 @@ impl EncodeFormat { EncodeFormat::Aac | EncodeFormat::Alac => Container::Mp4, EncodeFormat::Mp3 => Container::MpegAudio, EncodeFormat::Ac3 | EncodeFormat::Eac3 => Container::Ac3, + EncodeFormat::Ogg => Container::Ogg, } } @@ -322,6 +368,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => CodecId::Mp3, EncodeFormat::Ac3 => CodecId::Ac3, EncodeFormat::Eac3 => CodecId::Eac3, + EncodeFormat::Ogg => CodecId::Vorbis, } } @@ -335,10 +382,11 @@ impl EncodeFormat { EncodeFormat::Mp3 => "mp3-encode", EncodeFormat::Ac3 => "ac3-encode", EncodeFormat::Eac3 => "eac3-encode", + EncodeFormat::Ogg => "vorbis-encode", } } - /// Whether [`encode`] and [`FileEncoder`] write this format in this build (its + /// Whether [`encode`] writes this format in this build (its /// [`feature`](Self::feature) is on): what to filter [`EncodeFormat::ALL`] by for a menu. pub fn is_built(self) -> bool { match self { @@ -349,6 +397,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => cfg!(feature = "mp3-encode"), EncodeFormat::Ac3 => cfg!(feature = "ac3-encode"), EncodeFormat::Eac3 => cfg!(feature = "eac3-encode"), + EncodeFormat::Ogg => cfg!(feature = "vorbis-encode"), } } @@ -359,7 +408,7 @@ impl EncodeFormat { EncodeFormat::Aac => Some(&[7350, 8000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000, 64_000, 88_200, 96_000]), EncodeFormat::Mp3 => Some(&[16_000, 22_050, 24_000, 32_000, 44_100, 48_000]), EncodeFormat::Ac3 | EncodeFormat::Eac3 => Some(&[32_000, 44_100, 48_000]), - EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac | EncodeFormat::Alac => None, + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac | EncodeFormat::Alac | EncodeFormat::Ogg => None, } } @@ -369,7 +418,7 @@ impl EncodeFormat { pub fn max_channels(self) -> u16 { match self { EncodeFormat::Wav | EncodeFormat::Aiff => 32_767, - EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 => 8, + EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 | EncodeFormat::Ogg => 8, EncodeFormat::Ac3 => 6, EncodeFormat::Mp3 => 2, } @@ -386,6 +435,9 @@ impl EncodeFormat { // Apple's layout tags for 1–8 channels, surrounds as back speakers. EncodeFormat::Alac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x37], &[0x3F], &[0x13F], &[0xFF]], EncodeFormat::Mp3 => &[&[0x4], &[0x3]], + // The Vorbis I §4.3.9 layouts for 1–8 channels (6.1 with a back centre and sides, 7.1 + // with sides and backs), written in Vorbis order. + EncodeFormat::Ogg => &[&[0x4], &[0x3], &[0x7], &[0x33], &[0x37], &[0x3F], &[0x70F], &[0x63F]], // The coding modes 1/0 to 3/2 with and without an LFE, by channel count. EncodeFormat::Ac3 => &[&[0x4], &[0x3, 0xC], &[0x7, 0x103, 0xB], &[0x107, 0x603, 0xF, 0x10B], &[0x607, 0x10F, 0x60B], &[0x60F]], // The same, and 7.1 with backs and sides. @@ -427,16 +479,16 @@ impl EncodeFormat { } } - /// Whether the format takes [`RateControl::Quality`]: AAC. The other lossy formats are - /// written at a constant bit rate only. + /// Whether the format takes [`RateControl::Quality`]: AAC and Ogg Vorbis. The other lossy + /// formats are written at a constant bit rate only. pub fn supports_quality(self) -> bool { - self == EncodeFormat::Aac + matches!(self, EncodeFormat::Aac | EncodeFormat::Ogg) } /// Whether the format loses audio: AAC, MP3, AC-3 and E-AC-3. These take /// [`EncodeOptions::rate_control`] and ignore the bit depth and dither. pub fn is_lossy(self) -> bool { - matches!(self, EncodeFormat::Aac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3) + matches!(self, EncodeFormat::Aac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 | EncodeFormat::Ogg) } } @@ -449,10 +501,12 @@ pub enum RateControl { /// set of rates (MP3, AC-3) uses the highest one not above it; a rate outside what the /// stream can carry is moved to the nearest one inside. AAC is written at 6 kbit/s or a /// quarter of the sample rate per channel at least: from about half of that down its encoder - /// codes silence. + /// codes silence. Vorbis takes 64–500 kbit/s and writes the quality whose nominal rate that is + /// ([`quality_for_bitrate`]); its rate varies with the audio. Bitrate(u32), /// A constant quality from 0.0 (smallest) to 1.0 (best), at whatever bit rate each frame - /// needs. AAC only; values outside the range are clamped, and NaN is an error. + /// needs. AAC and Vorbis (0.0 is Vorbis quality -1, 1.0 quality 10); values outside the range + /// are clamped, and NaN is an error. Quality(f32), } @@ -718,3 +772,10 @@ mod tests { assert!(matches!(e, AudioError::Encode(_)), "{e}"); } } + +/// DVD and Blu-ray LPCM packet decoding. +pub mod lpcm; + +/// Non-seeking canonical WAV streaming primitives. +#[cfg(feature = "pcm-encode")] +pub mod wav_stream; diff --git a/crates/audio/src/lpcm.rs b/crates/audio/src/lpcm.rs new file mode 100644 index 0000000000..5ec13b35df --- /dev/null +++ b/crates/audio/src/lpcm.rs @@ -0,0 +1,118 @@ +//! DVD-Video and Blu-ray LPCM packet grammar and sample decoding. + +/// Blu-ray / AVCHD LPCM packet header (4 bytes before the samples). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BlurayLpcm { + /// Sample rate in hertz. + pub sample_rate: u32, + /// Number of decoded channels. + pub channels: usize, + /// Significant bits per sample. + pub bits: u32, +} + +/// Channels of each channel_assignment code (mono, stereo, 3/0, 2/1, 3/1, 2/2, 3/2, 3/2+LFE, +/// 3/4, 3/4+LFE). +const BD_LPCM_CHANNELS: [usize; 12] = [0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8]; + +/// Parse and validate the four-byte Blu-ray LPCM header. +pub fn bluray_lpcm_header(p: &[u8]) -> Option { + if p.len() < 4 { + return None; + } + let channels = *BD_LPCM_CHANNELS.get((p[2] >> 4) as usize).filter(|&&c| c > 0)?; + let sample_rate = match p[2] & 15 { + 1 => 48_000, + 4 => 96_000, + 5 => 192_000, + _ => return None, + }; + let bits = match p[3] >> 6 { + 1 => 16, + 2 => 20, + 3 => 24, + _ => return None, + }; + Some(BlurayLpcm { sample_rate, channels, bits }) +} + +/// Decode one Blu-ray LPCM packet (big-endian; channels padded to an even count; 20-bit +/// samples are stored in 24 bits). +pub fn decode_bluray_lpcm(p: &[u8]) -> Option>> { + let h = bluray_lpcm_header(p)?; + let coded = (h.channels + 1) & !1; + let bps = if h.bits == 16 { 2 } else { 3 }; + let data = &p[4..]; + let n = data.len() / (coded * bps); + let mut out = vec![Vec::with_capacity(n); h.channels]; + for k in 0..n { + for (c, o) in out.iter_mut().enumerate() { + let at = (k * coded + c) * bps; + let v = if bps == 2 { + i16::from_be_bytes([data[at], data[at + 1]]) as f32 / 32768.0 + } else { + (i32::from_be_bytes([data[at], data[at + 1], data[at + 2], 0]) >> 8) as f32 / 8_388_608.0 + }; + o.push(v); + } + } + Some(out) +} + +/// Bytes per two sample frames of DVD LPCM. The caller must bound `channels` to the DVD channel range. +pub fn dvd_lpcm_group_bytes(channels: usize, bits: u32) -> usize { + match bits { + 16 => 4 * channels, + 20 => 5 * channels, + _ => 6 * channels, + } +} + +/// Decode DVD-Video LPCM (big-endian). 16-bit samples are interleaved; 20- and 24-bit samples +/// come in groups of two frames: the upper 16 bits of all the group's samples, then their low +/// 4 / 8 bits. The caller must bound `channels` to the DVD channel range. +pub fn decode_dvd_lpcm(data: &[u8], channels: usize, bits: u32) -> Vec> { + let ch = channels.max(1); + let group = dvd_lpcm_group_bytes(ch, bits); + let groups = data.len() / group; + let mut out = vec![Vec::with_capacity(groups * 2); ch]; + for g in 0..groups { + let b = &data[g * group..(g + 1) * group]; + for f in 0..2 { + for (c, o) in out.iter_mut().enumerate() { + let k = f * ch + c; + let hi = i16::from_be_bytes([b[2 * k], b[2 * k + 1]]) as i32; + let v = match bits { + 16 => hi as f32 / 32768.0, + 20 => { + let nib = b[4 * ch + k / 2]; + let lo = if k.is_multiple_of(2) { nib >> 4 } else { nib & 15 } as i32; + ((hi << 4) | lo) as f32 / 524_288.0 + } + _ => ((hi << 8) | b[4 * ch + k] as i32) as f32 / 8_388_608.0, + }; + o.push(v); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn bluray_header_and_even_channel_padding() { + let packet = [0, 0, 0x31, 0x40, 0x40, 0, 0xc0, 0]; + assert_eq!(bluray_lpcm_header(&packet), Some(BlurayLpcm { sample_rate: 48_000, channels: 2, bits: 16 })); + assert_eq!(decode_bluray_lpcm(&packet), Some(vec![vec![0.5], vec![-0.5]])); + assert_eq!(decode_bluray_lpcm(&packet[..3]), None); + } + #[test] + fn dvd_lpcm_16_20_and_24_bit_groups() { + assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0], 1, 16), vec![vec![0.5, -0.5]]); + assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0, 0], 1, 20), vec![vec![0.5, -0.5]]); + assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0, 0, 0], 1, 24), vec![vec![0.5, -0.5]]); + assert_eq!(decode_dvd_lpcm(&[1, 2, 3], 1, 16), vec![Vec::::new()]); + } +} diff --git a/crates/audio/src/opus/decode/celt/mdct.rs b/crates/audio/src/opus/decode/celt/mdct.rs index b3bfcf0f7a..7503d9ebe1 100644 --- a/crates/audio/src/opus/decode/celt/mdct.rs +++ b/crates/audio/src/opus/decode/celt/mdct.rs @@ -4,141 +4,7 @@ //! producing the N/2 "folded" time samples; the window overlap region is then unfolded against the //! folded tail of the previous block, which the caller keeps in place in the output buffer. -#[derive(Clone, Copy, Default, Debug)] -pub struct Cpx { - pub re: f32, - pub im: f32, -} - -impl Cpx { - #[inline] - fn mul(self, o: Cpx) -> Cpx { - Cpx { re: self.re * o.re - self.im * o.im, im: self.re * o.im + self.im * o.re } - } - #[inline] - fn add(self, o: Cpx) -> Cpx { - Cpx { re: self.re + o.re, im: self.im + o.im } - } - #[inline] - fn sub(self, o: Cpx) -> Cpx { - Cpx { re: self.re - o.re, im: self.im - o.im } - } -} - -/// Mixed-radix (2, 3, 4, 5) forward complex FFT, unscaled. Radix 2, 3 and 4 use dedicated -/// butterflies; radix 5 uses a generic one. -pub struct Fft { - n: usize, - factors: Vec, - twiddle: Vec, -} - -impl Fft { - pub fn new(n: usize) -> Fft { - let mut factors = Vec::new(); - let mut m = n; - for p in [4usize, 2, 3, 5] { - while m.is_multiple_of(p) { - factors.push(p); - m /= p; - } - } - assert_eq!(m, 1, "unsupported FFT size {n}"); - let twiddle = (0..n) - .map(|k| { - let ph = -2.0 * std::f64::consts::PI * k as f64 / n as f64; - Cpx { re: ph.cos() as f32, im: ph.sin() as f32 } - }) - .collect(); - Fft { n, factors, twiddle } - } - - pub fn process(&self, data: &mut [Cpx], scratch: &mut Vec) { - scratch.clear(); - scratch.extend_from_slice(&data[..self.n]); - self.rec(&mut data[..self.n], scratch, 1, self.n, 0, 1); - } - - fn rec(&self, out: &mut [Cpx], inp: &[Cpx], in_stride: usize, n: usize, fi: usize, tw_stride: usize) { - let p = self.factors[fi]; - let m = n / p; - if m == 1 { - for (i, o) in out.iter_mut().enumerate().take(p) { - *o = inp[i * in_stride]; - } - } else { - for q in 0..p { - self.rec(&mut out[q * m..(q + 1) * m], &inp[q * in_stride..], in_stride * p, m, fi + 1, tw_stride * p); - } - } - let tw = &self.twiddle; - match p { - 2 => { - for k in 0..m { - let a0 = out[k]; - let a1 = out[m + k].mul(tw[k * tw_stride]); - out[k] = a0.add(a1); - out[m + k] = a0.sub(a1); - } - } - 4 => { - for k in 0..m { - let t0 = out[k]; - let t1 = out[m + k].mul(tw[k * tw_stride]); - let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); - let t3 = out[3 * m + k].mul(tw[3 * k * tw_stride]); - let s0 = t0.add(t2); - let d0 = t0.sub(t2); - let s1 = t1.add(t3); - let d1 = t1.sub(t3); - out[k] = s0.add(s1); - out[2 * m + k] = s0.sub(s1); - // -j * d1 = (d1.im, -d1.re) - out[m + k] = Cpx { re: d0.re + d1.im, im: d0.im - d1.re }; - out[3 * m + k] = Cpx { re: d0.re - d1.im, im: d0.im + d1.re }; - } - } - 3 => { - // sin(-2*pi/3) = -sqrt(3)/2 - let h = tw[self.n / 3].im; - for k in 0..m { - let t0 = out[k]; - let t1 = out[m + k].mul(tw[k * tw_stride]); - let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); - let s = t1.add(t2); - let d = t1.sub(t2); - let a = Cpx { re: t0.re - 0.5 * s.re, im: t0.im - 0.5 * s.im }; - out[k] = t0.add(s); - // j * h * d = (-h * d.im, h * d.re) - out[m + k] = Cpx { re: a.re - h * d.im, im: a.im + h * d.re }; - out[2 * m + k] = Cpx { re: a.re + h * d.im, im: a.im - h * d.re }; - } - } - _ => { - // Radix 5 (at most once per transform): generic butterfly with the five roots of - // unity looked up once. - let mut w5 = [Cpx::default(); 5]; - for (q, w) in w5.iter_mut().enumerate() { - *w = tw[q * (self.n / p)]; - } - let mut t = [Cpx::default(); 5]; - for k in 0..m { - t[0] = out[k]; - for q in 1..p { - t[q] = out[q * m + k].mul(tw[q * k * tw_stride]); - } - for q2 in 0..p { - let mut acc = t[0]; - for q in 1..p { - acc = acc.add(t[q].mul(w5[(q * q2) % p])); - } - out[q2 * m + k] = acc; - } - } - } - } - } -} +use crate::opus::fft::{Cpx, Fft}; pub struct Imdct { /// Full MDCT length (2x the number of coefficients). diff --git a/crates/audio/src/opus/decode/celt/rate.rs b/crates/audio/src/opus/decode/celt/rate.rs index 782d68d5c9..29e8566c14 100644 --- a/crates/audio/src/opus/decode/celt/rate.rs +++ b/crates/audio/src/opus/decode/celt/rate.rs @@ -1,272 +1,45 @@ //! Pulse cache and bit allocation (RFC 6716 §4.3.3, §4.3.4.1). -use super::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS, OVERLAP}; +use super::tables::{EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS, OVERLAP}; use crate::opus::decode::range::{BITRES, RangeDecoder}; -const MAX_PSEUDO: i32 = 40; -const LOG_MAX_PSEUDO: i32 = 6; +pub use crate::opus::rate_common::get_pulses; +#[cfg(test)] +use crate::opus::rate_common::log2_frac; +#[cfg(test)] +pub use crate::opus::rate_common::pvq_v; pub const MAX_FINE_BITS: i32 = 8; const FINE_OFFSET: i32 = 21; pub const QTHETA_OFFSET: i32 = 4; pub const QTHETA_OFFSET_TWOPHASE: i32 = 16; const ALLOC_STEPS: i32 = 6; -/// Number of pulses represented by pseudo-pulse index `i`. -pub fn get_pulses(i: i32) -> i32 { - if i < 8 { i } else { (8 + (i & 7)) << ((i >> 3) - 1) } -} - -/// Conservative (rounded up) log2 of `val` with `frac` fractional bits. -pub fn log2_frac(mut val: u32, mut frac: u32) -> i32 { - let mut l = crate::opus::decode::range::ilog(val); - if val & val.wrapping_sub(1) != 0 { - if l > 16 { - val = ((val - 1) >> (l - 16)) + 1; - } else { - val <<= 16 - l; - } - let mut l = (l - 1) << frac; - loop { - let b = (val >> 16) as i32; - l += b << frac; - val = (val + b as u32) >> b; - val = (val * val + 0x7FFF) >> 15; - if frac == 0 { - break; - } - frac -= 1; - } - l + (val > 0x8000) as i32 - } else { - l -= 1; - l << frac - } -} - -/// PVQ codebook size V(N, K) as u128 (saturating far above 2^32). -pub fn pvq_v(n: usize, k: usize) -> u128 { - // V(N,K) = V(N-1,K) + V(N,K-1) + V(N-1,K-1); computed row by row. - if k == 0 { - return 1; - } - if n == 0 { - return 0; - } - let mut row = vec![0u128; k + 1]; // V(0, k) - row[0] = 1; - for _ in 0..n { - let mut prev_diag = row[0]; // V(n-1, 0) - // V(n, 0) = 1 - for kk in 1..=k { - let up = row[kk]; // V(n-1, kk) - let v = up.saturating_add(row[kk - 1]).saturating_add(prev_diag); - prev_diag = up; - row[kk] = v.min(u128::MAX >> 8); - } - row[0] = 1; - } - row[k] -} - -fn fits_in32(n: usize, k: i32) -> bool { - pvq_v(n, k as usize) <= u32::MAX as u128 -} - -/// Precomputed per-mode data shared by all CELT decoders. +/// Decoder mode: shared allocation tables and decoder-specific inverse transforms. pub struct Mode { - /// log2 of band width in 1/8 bits. - pub log_n: [i32; NB_EBANDS], - /// Index into `cache_bits` for `(LM+1)*NB_EBANDS + band` (-1 when unused). - pub cache_index: Vec, - /// `cache[0]` = max pseudo-pulses; `cache[k]` = bits(k) - 1 in 1/8 bits. - pub cache_bits: Vec, - /// Per-band maximum allocation: `[(2*LM + C-1)*NB_EBANDS + band]`. - pub caps: Vec, + core: crate::opus::rate_common::Mode, pub window: [f32; OVERLAP], pub mdct: [super::mdct::Imdct; MAX_LM + 1], } - impl Mode { - pub fn new() -> Mode { - let mut log_n = [0i32; NB_EBANDS]; - for (i, l) in log_n.iter_mut().enumerate() { - *l = log2_frac((EBANDS[i + 1] - EBANDS[i]) as u32, BITRES); - } - let (cache_index, cache_bits) = compute_pulse_cache(MAX_LM as i32); - let mut m = Mode { - log_n, - cache_index, - cache_bits, - caps: Vec::new(), + pub fn new() -> Self { + let mut mode = Self { + core: crate::opus::rate_common::Mode::new(), window: [0.0; OVERLAP], mdct: [super::mdct::Imdct::new(1920), super::mdct::Imdct::new(960), super::mdct::Imdct::new(480), super::mdct::Imdct::new(240)], }; - m.caps = compute_caps(&m); for i in 0..OVERLAP { let x = std::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / OVERLAP as f64; let s = x.sin(); - m.window[i] = (std::f64::consts::FRAC_PI_2 * s * s).sin() as f32; + mode.window[i] = (std::f64::consts::FRAC_PI_2 * s * s).sin() as f32; } - m - } - - #[inline] - pub fn cache(&self, lm: i32, band: usize) -> &[u8] { - let idx = self.cache_index[((lm + 1) as usize) * NB_EBANDS + band]; - &self.cache_bits[idx.max(0) as usize..] - } - - pub fn bits2pulses(&self, band: usize, lm: i32, bits: i32) -> i32 { - let cache = self.cache(lm, band); - let mut lo = 0i32; - let mut hi = cache[0] as i32; - let bits = bits - 1; - for _ in 0..LOG_MAX_PSEUDO { - let mid = (lo + hi + 1) >> 1; - if cache[mid as usize] as i32 >= bits { - hi = mid; - } else { - lo = mid; - } - } - let lo_bits = if lo == 0 { -1 } else { cache[lo as usize] as i32 }; - if bits - lo_bits <= cache[hi as usize] as i32 - bits { lo } else { hi } - } - - pub fn pulses2bits(&self, band: usize, lm: i32, pulses: i32) -> i32 { - if pulses == 0 { 0 } else { self.cache(lm, band)[pulses as usize] as i32 + 1 } - } - - /// Per-band allocation caps for this frame (`init_caps`). - pub fn init_caps(&self, lm: usize, c: usize) -> [i32; NB_EBANDS] { - let mut cap = [0i32; NB_EBANDS]; - for (i, cp) in cap.iter_mut().enumerate() { - let n = (EBANDS[i + 1] - EBANDS[i]) << lm; - *cp = ((self.caps[NB_EBANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * n) >> 2; - } - cap + mode } } - -fn compute_pulse_cache(lm_max: i32) -> (Vec, Vec) { - let nb = NB_EBANDS; - let rows = (lm_max + 2) as usize; - let mut index = vec![-1i16; nb * rows]; - let mut entries: Vec<(usize, i32, usize)> = Vec::new(); // (N, K, offset) - let mut curr = 0usize; - for i in 0..rows { - for j in 0..nb { - let n = (((EBANDS[j + 1] - EBANDS[j]) << i) >> 1) as usize; - index[i * nb + j] = -1; - // Reuse the entry of an earlier band with the same size. - 'search: for k in 0..=i { - for nn in 0..nb { - if k == i && nn >= j { - break; - } - if n == (((EBANDS[nn + 1] - EBANDS[nn]) << k) >> 1) as usize { - index[i * nb + j] = index[k * nb + nn]; - break 'search; - } - } - } - if index[i * nb + j] == -1 && n != 0 { - let mut k = 0; - while k < MAX_PSEUDO && fits_in32(n, get_pulses(k + 1)) { - k += 1; - } - index[i * nb + j] = curr as i16; - entries.push((n, k, curr)); - curr += (k + 1) as usize; - } - } +impl std::ops::Deref for Mode { + type Target = crate::opus::rate_common::Mode; + fn deref(&self) -> &Self::Target { + &self.core } - let mut bits = vec![0u8; curr]; - for &(n, k, off) in &entries { - let maxk = get_pulses(k) as usize; - let tmp = required_bits(n, maxk, BITRES); - for j in 1..=k { - bits[off + j as usize] = (tmp[get_pulses(j) as usize] - 1) as u8; - } - bits[off] = k as u8; - } - (index, bits) -} - -/// Bits (1/2^frac units, rounded up) needed for each K in `0..=maxk` for dimension `n`. -fn required_bits(n: usize, maxk: usize, frac: u32) -> Vec { - let mut out = vec![0i32; maxk + 1]; - if n == 1 { - for o in out.iter_mut().skip(1) { - *o = 1 << frac; - } - } else { - for (k, o) in out.iter_mut().enumerate().skip(1) { - let v = pvq_v(n, k); - *o = log2_frac(v as u32, frac); - } - } - out -} - -fn compute_caps(m: &Mode) -> Vec { - let nb = NB_EBANDS; - let mut caps = vec![0u8; (MAX_LM + 1) * 2 * nb]; - for i in 0..=MAX_LM as i32 { - for c in 1..=2i32 { - for j in 0..nb { - let mut n0 = EBANDS[j + 1] - EBANDS[j]; - let max_bits = if n0 << i == 1 { - (c * (1 + MAX_FINE_BITS)) << BITRES - } else { - let mut lm0 = 0; - if n0 > 2 { - n0 >>= 1; - lm0 -= 1; - } else if n0 <= 1 { - lm0 = i.min(1); - n0 <<= lm0; - } - let pcache = m.cache(lm0, j); - let mut mb = pcache[pcache[0] as usize] as i32 + 1; - let mut n = n0; - for k in 0..(i - lm0) { - mb <<= 1; - let offset = ((m.log_n[j] + ((lm0 + k) << BITRES)) >> 1) - QTHETA_OFFSET; - let num = 459 * ((2 * n - 1) * offset + mb); - let den = ((2 * n - 1) << 9) - 459; - let qb = ((num + (den >> 1)) / den).min(57); - mb += qb; - n <<= 1; - } - if c == 2 { - mb <<= 1; - let offset = ((m.log_n[j] + (i << BITRES)) >> 1) - if n == 2 { QTHETA_OFFSET_TWOPHASE } else { QTHETA_OFFSET }; - let ndof = 2 * n - 1 - (n == 2) as i32; - let p = if n == 2 { 512 } else { 487 }; - let num = p * (mb + ndof * offset); - let den = (ndof << 9) - p; - let qb = ((num + (den >> 1)) / den).min(if n == 2 { 64 } else { 61 }); - mb += qb; - } - let ndof = c * n + if c == 2 && n > 2 { 1 } else { 0 }; - let mut offset = ((m.log_n[j] + (i << BITRES)) >> 1) - FINE_OFFSET; - if n == 2 { - offset += (1 << BITRES) >> 2; - } - let num = mb + ndof * offset; - let den = (ndof - 1) << BITRES; - let qb = ((num + (den >> 1)) / den).min(MAX_FINE_BITS); - mb += (c * qb) << BITRES; - mb - }; - let w = c * ((EBANDS[j + 1] - EBANDS[j]) << i); - let v = (4 * max_bits / w) - 64; - caps[((i * 2 + c - 1) as usize) * nb + j] = v.clamp(0, 255) as u8; - } - } - } - caps } /// Result of the allocation process. @@ -296,89 +69,8 @@ pub struct AllocationInput<'a, 'd> { pub fn compute_allocation(input: AllocationInput<'_, '_>) -> Allocation { let AllocationInput { mode: m, start, end, offsets, cap, trim: alloc_trim, total, channels: c, lm, decoder: dec } = input; - let ci = c as i32; - let lmi = lm as i32; - let mut total = total.max(0); - let mut skip_start = start; - let skip_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; - total -= skip_rsv; - let mut intensity_rsv = 0; - let mut dual_stereo_rsv = 0; - if c == 2 { - intensity_rsv = LOG2_FRAC_TABLE[end - start]; - if intensity_rsv > total { - intensity_rsv = 0; - } else { - total -= intensity_rsv; - dual_stereo_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; - total -= dual_stereo_rsv; - } - } - let mut bits1 = [0i32; NB_EBANDS]; - let mut bits2 = [0i32; NB_EBANDS]; - let mut thresh = [0i32; NB_EBANDS]; - let mut trim_offset = [0i32; NB_EBANDS]; - for j in start..end { - let w = EBANDS[j + 1] - EBANDS[j]; - thresh[j] = (ci << BITRES).max(((3 * w) << lmi << BITRES) >> 4); - trim_offset[j] = (ci * w * (alloc_trim - 5 - lmi) * (end as i32 - j as i32 - 1) * (1 << (lmi + BITRES as i32))) >> 6; - if w << lmi == 1 { - trim_offset[j] -= ci << BITRES; - } - } - let nb_alloc = ALLOC.len() as i32; - let mut lo = 1; - let mut hi = nb_alloc - 1; - loop { - let mut done = false; - let mut psum = 0; - let mid = (lo + hi) >> 1; - for j in (start..end).rev() { - let n = EBANDS[j + 1] - EBANDS[j]; - let mut bitsj = (ci * n * (ALLOC[mid as usize][j] as i32)) << lmi >> 2; - if bitsj > 0 { - bitsj = (bitsj + trim_offset[j]).max(0); - } - bitsj += offsets[j]; - if bitsj >= thresh[j] || done { - done = true; - psum += bitsj.min(cap[j]); - } else if bitsj >= ci << BITRES { - psum += ci << BITRES; - } - } - if psum > total { - hi = mid - 1; - } else { - lo = mid + 1; - } - if lo > hi { - break; - } - } - hi = lo; - lo -= 1; - for j in start..end { - let n = EBANDS[j + 1] - EBANDS[j]; - let mut bits1j = (ci * n * (ALLOC[lo as usize][j] as i32)) << lmi >> 2; - let mut bits2j = if hi >= nb_alloc { cap[j] } else { (ci * n * (ALLOC[hi as usize][j] as i32)) << lmi >> 2 }; - if bits1j > 0 { - bits1j = (bits1j + trim_offset[j]).max(0); - } - if bits2j > 0 { - bits2j = (bits2j + trim_offset[j]).max(0); - } - if lo > 0 { - bits1j += offsets[j]; - } - bits2j += offsets[j]; - if offsets[j] > 0 { - skip_start = j; - } - bits2j = (bits2j - bits1j).max(0); - bits1[j] = bits1j; - bits2[j] = bits2j; - } + let crate::opus::rate_common::Bracket { skip_start, bits1, bits2, thresh, total, skip_rsv, intensity_rsv, dual_stereo_rsv } = + crate::opus::rate_common::bracket(start, end, offsets, cap, alloc_trim, total, c, lm); interp_bits2pulses(InterpPulsesInput { mode: m, start, diff --git a/crates/audio/src/opus/decode/celt/tables.rs b/crates/audio/src/opus/decode/celt/tables.rs index f2381f7147..b65d05c09b 100644 --- a/crates/audio/src/opus/decode/celt/tables.rs +++ b/crates/audio/src/opus/decode/celt/tables.rs @@ -14,6 +14,7 @@ pub const MAX_LM: usize = 3; pub const PREEMPH: f32 = 0.850_006_1; /// Static allocation table (Table 57), indexed `[quality][band]`, in 1/32 bit per MDCT bin. +#[cfg(not(feature = "opus-encode"))] pub const ALLOC: [[u8; NB_EBANDS]; 11] = transpose([ [0, 90, 110, 118, 126, 134, 144, 152, 162, 172, 200], [0, 80, 100, 110, 119, 127, 137, 145, 155, 165, 200], @@ -38,6 +39,7 @@ pub const ALLOC: [[u8; NB_EBANDS]; 11] = transpose([ [0, 0, 0, 0, 0, 1, 1, 1, 1, 20, 104], ]); +#[cfg(not(feature = "opus-encode"))] const fn transpose(t: [[u8; 11]; NB_EBANDS]) -> [[u8; NB_EBANDS]; 11] { let mut out = [[0u8; NB_EBANDS]; 11]; let mut b = 0; diff --git a/crates/audio/src/opus/decode/silk/resampler.rs b/crates/audio/src/opus/decode/silk/resampler.rs index 0671778ccb..7d3f803eff 100644 --- a/crates/audio/src/opus/decode/silk/resampler.rs +++ b/crates/audio/src/opus/decode/silk/resampler.rs @@ -4,25 +4,7 @@ //! RFC 6716 Table 54 (and the integer delays used when no rate conversion is needed), so that the //! SILK output lines up with the CELT layer in Hybrid mode. -/// Dot product with eight independent partial sums, so the additions pipeline and the loop -/// vectorises instead of waiting on one 4-cycle add chain. Rounds differently from a -/// sequential sum (the resampler is not normative). -#[inline] -fn dot8(a: &[f32], b: &[f32]) -> f32 { - let mut s = [0f32; 8]; - let (ca, ra) = a.as_chunks::<8>(); - let (cb, rb) = b.as_chunks::<8>(); - for (x, y) in ca.iter().zip(cb) { - for l in 0..8 { - s[l] += x[l] * y[l]; - } - } - let mut acc = ((s[0] + s[4]) + (s[1] + s[5])) + ((s[2] + s[6]) + (s[3] + s[7])); - for (x, y) in ra.iter().zip(rb) { - acc += x * y; - } - acc -} +use crate::opus::dot::dot8; #[derive(Clone)] pub struct Resampler { diff --git a/crates/audio/src/opus/dot.rs b/crates/audio/src/opus/dot.rs new file mode 100644 index 0000000000..536209e0a1 --- /dev/null +++ b/crates/audio/src/opus/dot.rs @@ -0,0 +1,20 @@ +//! Shared fixed-order FIR dot product. + +/// Dot product with eight independent partial sums, which the compiler can vectorise (a single +/// running sum is bound by the latency of the float addition). The sums are combined pairwise. +#[inline] +pub(super) fn dot8(a: &[f32], b: &[f32]) -> f32 { + let mut s = [0f32; 8]; + let (ca, ra) = a.as_chunks::<8>(); + let (cb, rb) = b.as_chunks::<8>(); + for (x, y) in ca.iter().zip(cb) { + for l in 0..8 { + s[l] += x[l] * y[l]; + } + } + let mut acc = ((s[0] + s[4]) + (s[1] + s[5])) + ((s[2] + s[6]) + (s[3] + s[7])); + for (x, y) in ra.iter().zip(rb) { + acc += x * y; + } + acc +} diff --git a/crates/audio/src/opus/encoder/bands.rs b/crates/audio/src/opus/encoder/bands.rs index 604aab5958..697332eb2e 100644 --- a/crates/audio/src/opus/encoder/bands.rs +++ b/crates/audio/src/opus/encoder/bands.rs @@ -8,7 +8,8 @@ use crate::opus::encoder::range::{BITRES, RangeEncoder, ilog}; use crate::opus::encoder::rate::{Mode, QTHETA_OFFSET, get_pulses}; -use crate::opus::encoder::tables::{EBANDS, NB_EBANDS}; +use crate::opus::encoder::tables::EBANDS; +use crate::opus::encoder::{CeltFrame, rate::Allocation}; pub const SPREAD_NORMAL: usize = 2; @@ -55,7 +56,7 @@ fn exp_rotation1_inv(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) { if len <= stride { return; } - if len >= 2 * stride + 1 { + if len > 2 * stride { for i in 0..=len - 2 * stride - 1 { let x1 = x[i]; let x2 = x[i + stride]; @@ -96,12 +97,24 @@ pub fn exp_rotation_inv(x: &mut [f32], len: usize, k: usize, spread: usize) { } } +/// Relative slack for the pulse-candidate filter in [`pvq_search`]: far above the f32 rounding of +/// the filter score (a few 1e-7), far below the spread of real scores. +const PVQ_SCORE_SLACK: f32 = 1e-5; + /// Greedy PVQ search: the integer vector `y` with `sum |y| = k` closest in direction to `x`. pub fn pvq_search(x: &[f32], k: usize, y: &mut [i32]) { let n = x.len(); y[..n].fill(0); - let abs: Vec = x.iter().map(|v| v.abs()).collect(); - let sum: f32 = abs.iter().sum(); + // `abs`, `dy` (2 y + 1, infinite in the padding) and the per-pass scores `score`, each padded to + // whole 8-lane chunks. + let np = n.next_multiple_of(8); + let mut buf = vec![0f32; 3 * np]; + let (abs, rest) = buf.split_at_mut(np); + let (dy, score) = rest.split_at_mut(np); + for (a, v) in abs.iter_mut().zip(x) { + *a = v.abs(); + } + let sum: f32 = abs[..n].iter().sum(); if !sum.is_finite() || sum <= 1e-15 { y[0] = k as i32; return; @@ -113,30 +126,69 @@ pub fn pvq_search(x: &[f32], k: usize, y: &mut [i32]) { // Pre-project onto the pyramid (rounding down) and place the rest greedily. let r = (k as f32 - 1.0) / sum; for j in 0..n { - let p = (abs[j] * r).floor() as i32; + // Non-negative and at most k, so the truncating cast is the floor. + let p = (abs[j] * r) as i32; y[j] = p; placed += p as usize; xy += abs[j] * p as f32; yy += (p * p) as f32; } } + for j in 0..np { + dy[j] = if j < n { 2.0 * y[j] as f32 + 1.0 } else { f32::INFINITY }; + } while placed < k { + // Vectorisable scores (xy + |x_j|)^2 / (yy + 2 y_j + 1) and their maximum. + for ((sc, &a), &d) in score.iter_mut().zip(abs.iter()).zip(dy.iter()) { + let t = xy + a; + *sc = t * t / (yy + d); + } + let mut lane_max = [0f32; 8]; + for c in score.as_chunks::<8>().0 { + for i in 0..8 { + lane_max[i] = if c[i] > lane_max[i] { c[i] } else { lane_max[i] }; + } + } + let top = lane_max.iter().fold(0f32, |m, &v| if v > m { v } else { m }); + // The exact cross-multiplied test below, in index order with the first maximum winning, only + // matters for entries within rounding distance of the top score: every other entry is beaten + // by the top one whenever it is reached and never beats it afterwards. Running the test on + // those alone therefore picks the same pulse as running it on all of them. + let filter = top > 1e-30 && top.is_finite(); + let lo = top * (1.0 - PVQ_SCORE_SLACK); + // Usually exactly one entry qualifies; its index falls out of a lane-wise count. + let mut count = [0u32; 8]; + let mut index = [0u32; 8]; + for (ci, c) in score.as_chunks::<8>().0.iter().enumerate() { + for i in 0..8 { + let hit = u32::from(c[i] >= lo); + count[i] += hit; + index[i] += hit * (ci * 8 + i) as u32; + } + } let mut best = 0usize; - let mut best_num = -1f32; - let mut best_den = 1f32; - for j in 0..n { - let num = xy + abs[j]; - let num = num * num; - let den = yy + 2.0 * y[j] as f32 + 1.0; - if num * best_den > best_num * den { - best_num = num; - best_den = den; - best = j; + if filter && count.iter().sum::() == 1 { + best = index.iter().sum::() as usize; + } else { + let mut best_num = -1f32; + let mut best_den = 1f32; + for j in 0..n { + if !filter || score[j] >= lo { + let num = xy + abs[j]; + let num = num * num; + let den = yy + 2.0 * y[j] as f32 + 1.0; + if num * best_den > best_num * den { + best_num = num; + best_den = den; + best = j; + } + } } } xy += abs[best]; yy += 2.0 * y[best] as f32 + 1.0; y[best] += 1; + dy[best] = 2.0 * y[best] as f32 + 1.0; placed += 1; } for j in 0..n { @@ -146,25 +198,45 @@ pub fn pvq_search(x: &[f32], k: usize, y: &mut [i32]) { } } -/// Encodes the PVQ codeword `y` (`sum |y| = k`) as the index the RFC 6716 §4.3.4.2 decoder maps -/// back to `y`. -pub fn encode_pulses(y: &[i32], k: usize, enc: &mut RangeEncoder, v: &mut Vec) { - let n = y.len(); - let w = k + 1; - v.clear(); - v.resize((n + 1) * w, 0); +/// Largest band width and pulse count the encoder codes (176 coefficients, `get_pulses(40)` = 128). +const PVQ_MAX_N: usize = 176; +const PVQ_MAX_K: usize = 128; + +/// Row-major `V(n, k)` for `n <= max_n`, `k <= max_k` with row stride `max_k + 1`, saturated at +/// `u32::MAX` (a codebook that large is never coded, see `rate::fits_in32`). +fn build_pvq_table(max_n: usize, max_k: usize) -> Vec { + let w = max_k + 1; + let mut v = vec![0u32; (max_n + 1) * w]; v[0] = 1; - for nn in 1..=n { + for nn in 1..=max_n { v[nn * w] = 1; - for kk in 1..=k { - let a = v[(nn - 1) * w + kk]; - let b = v[nn * w + kk - 1]; - let c = v[(nn - 1) * w + kk - 1]; - v[nn * w + kk] = a.saturating_add(b).saturating_add(c); + for kk in 1..=max_k { + let sum = v[(nn - 1) * w + kk] as u64 + v[nn * w + kk - 1] as u64 + v[(nn - 1) * w + kk - 1] as u64; + v[nn * w + kk] = sum.min(u32::MAX as u64) as u32; } } - let total = v[n * w + k]; - let vv = |nn: usize, kx: usize| v[nn * w + kx]; + v +} + +fn pvq_table() -> &'static [u32] { + static TABLE: std::sync::OnceLock> = std::sync::OnceLock::new(); + TABLE.get_or_init(|| build_pvq_table(PVQ_MAX_N, PVQ_MAX_K)) +} + +/// Encodes the PVQ codeword `y` (`sum |y| = k`) as the index the RFC 6716 §4.3.4.2 decoder maps +/// back to `y`. +pub fn encode_pulses(y: &[i32], k: usize, enc: &mut RangeEncoder) { + let n = y.len(); + // Shapes outside the coded range (never produced by the band layout) get a local table. + let local; + let (v, w) = if n <= PVQ_MAX_N && k <= PVQ_MAX_K { + (pvq_table(), PVQ_MAX_K + 1) + } else { + local = build_pvq_table(n, k); + (&local[..], k + 1) + }; + let row = |nn: usize| &v[nn * w..(nn + 1) * w]; + let total = row(n)[k] as u64; let mut index = 0u64; let mut kk = k; for j in 0..n { @@ -173,10 +245,11 @@ pub fn encode_pulses(y: &[i32], k: usize, enc: &mut RangeEncoder, v: &mut Vec { pub i: usize, pub spread: usize, pub remaining_bits: i32, - pvq_v: Vec, iy: Vec, tmp: Vec, } @@ -217,7 +289,7 @@ impl BandEnc<'_, '_> { let q = qn as u32; let half = q >> 1; let ft = (half + 1) * (half + 1); - let (fl, fs) = if it <= half { (it * (it + 1) >> 1, it + 1) } else { (ft - ((q + 1 - it) * (q + 2 - it) >> 1), q + 1 - it) }; + let (fl, fs) = if it <= half { ((it * (it + 1)) >> 1, it + 1) } else { (ft - (((q + 1 - it) * (q + 2 - it)) >> 1), q + 1 - it) }; self.enc.encode(fl, fl + fs, ft); itheta = ((it * 16384) / q) as i32; } @@ -287,36 +359,29 @@ impl BandEnc<'_, '_> { iy.clear(); iy.resize(n, 0); pvq_search(&tmp, k, &mut iy); - encode_pulses(&iy, k, self.enc, &mut self.pvq_v); + encode_pulses(&iy, k, self.enc); self.iy = iy; self.tmp = tmp; } } } -/// Codes all band shapes (`quant_all_bands`, encoder side, long blocks). `x` holds `c` channels -/// of `n` normalised MDCT coefficients each. -#[allow(clippy::too_many_arguments)] -pub fn quant_all_bands( - m: &Mode, - start: usize, - end: usize, - x: &[f32], - n_total: usize, - c: usize, - pulses: &[i32; NB_EBANDS], - spread: usize, - dual_stereo: bool, - intensity: usize, - total_bits: i32, - mut balance: i32, - enc: &mut RangeEncoder, - lm: usize, - coded_bands: usize, -) { +/// Shape-coding controls, independent of the selected band allocation. +pub struct BandCoding { + pub spread: usize, + pub total_bits: i32, +} + +/// Codes all band shapes (`quant_all_bands`, encoder side, long blocks). `x` holds +/// `frame.channels` channels of `n_total` normalised MDCT coefficients each. +pub fn quant_all_bands(m: &Mode, frame: CeltFrame, x: &[f32], n_total: usize, allocation: &Allocation, coding: BandCoding, enc: &mut RangeEncoder) { + let CeltFrame { start, end, channels: c, lm } = frame; + let Allocation { pulses, dual_stereo, intensity, coded_bands, balance, .. } = allocation; + let (dual_stereo, intensity, coded_bands, mut balance) = (*dual_stereo, *intensity, *coded_bands, *balance); + let BandCoding { spread, total_bits } = coding; let mm = 1usize << lm; debug_assert!(c == 1 || dual_stereo || intensity <= start, "stereo frames are coded as dual stereo"); - let mut ctx = BandEnc { m, enc, i: 0, spread, remaining_bits: 0, pvq_v: Vec::new(), iy: Vec::new(), tmp: Vec::new() }; + let mut ctx = BandEnc { m, enc, i: 0, spread, remaining_bits: 0, iy: Vec::new(), tmp: Vec::new() }; for i in start..end { ctx.i = i; let xo = mm * EBANDS[i] as usize; @@ -362,7 +427,7 @@ mod tests { x[i + stride] = c * x2 + s * x1; x[i] = c * x1 + ms * x2; } - if len >= 2 * stride + 1 { + if len > 2 * stride { for i in (0..=len - 2 * stride - 1).rev() { let x1 = x[i]; let x2 = x[i + stride]; @@ -466,12 +531,11 @@ mod tests { #[test] fn pvq_index_roundtrip_exhaustive() { - let mut v = Vec::new(); for n in 1..6usize { for k in 1..6usize { for y in all_codewords(n, k) { let mut e = RangeEncoder::new(); - encode_pulses(&y, k, &mut e, &mut v); + encode_pulses(&y, k, &mut e); let buf = e.done(16); let mut d = RangeDecoder::new(&buf); assert_eq!(decode_pulses(n, k, &mut d), y, "n={n} k={k}"); @@ -480,6 +544,165 @@ mod tests { } } + /// The per-call table encoder this module used before the shared table. + fn encode_pulses_reference(y: &[i32], k: usize, enc: &mut RangeEncoder) { + let n = y.len(); + let w = k + 1; + let mut v = vec![0u64; (n + 1) * w]; + v[0] = 1; + for nn in 1..=n { + v[nn * w] = 1; + for kk in 1..=k { + let a = v[(nn - 1) * w + kk]; + let b = v[nn * w + kk - 1]; + let c = v[(nn - 1) * w + kk - 1]; + v[nn * w + kk] = a.saturating_add(b).saturating_add(c); + } + } + let total = v[n * w + k]; + let vv = |nn: usize, kx: usize| v[nn * w + kx]; + let mut index = 0u64; + let mut kk = k; + for j in 0..n { + if kk == 0 { + break; + } + let rem = n - j; + let t = y[j].unsigned_abs() as usize; + let mut base: u64 = (0..kk - t).map(|m| vv(rem - 1, m)).sum(); + if y[j] < 0 { + base += (vv(rem - 1, kk) + vv(rem, kk)) / 2; + } + index += base; + kk -= t; + } + if total >= 2 { + enc.uint(index as u32, total as u32); + } + } + + #[test] + fn pvq_table_encode_matches_per_call_table() { + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move |m: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed % m + }; + let mut checked = 0; + for n in (1..=PVQ_MAX_N).step_by(5).chain([PVQ_MAX_N]) { + for k in (1..=PVQ_MAX_K).step_by(3).chain([PVQ_MAX_K]) { + if crate::opus::encoder::rate::pvq_v(n, k) > u32::MAX as u128 { + continue; + } + for _ in 0..4 { + let mut y = vec![0i32; n]; + for _ in 0..k { + let at = next(n as u64) as usize; + y[at] += if next(2) == 0 { 1 } else { -1 }; + } + // Opposite pulses cancel; top up so that sum |y| = k again. + let mut have: usize = y.iter().map(|v| v.unsigned_abs() as usize).sum(); + while have < k { + let at = next(n as u64) as usize; + y[at] += if y[at] < 0 { -1 } else { 1 }; + have += 1; + } + let (mut a, mut b) = (RangeEncoder::new(), RangeEncoder::new()); + encode_pulses(&y, k, &mut a); + encode_pulses_reference(&y, k, &mut b); + assert_eq!(a.done(16), b.done(16), "n={n} k={k}"); + checked += 1; + } + } + } + assert!(checked > 100, "{checked}"); + } + + /// The scalar greedy search the vectorised one replaced. + fn pvq_search_ref(x: &[f32], k: usize, y: &mut [i32]) { + let n = x.len(); + y[..n].fill(0); + let abs: Vec = x.iter().map(|v| v.abs()).collect(); + let sum: f32 = abs.iter().sum(); + if !sum.is_finite() || sum <= 1e-15 { + y[0] = k as i32; + return; + } + let mut placed = 0usize; + let mut xy = 0f32; + let mut yy = 0f32; + if k > n / 2 { + let r = (k as f32 - 1.0) / sum; + for j in 0..n { + let p = (abs[j] * r).floor() as i32; + y[j] = p; + placed += p as usize; + xy += abs[j] * p as f32; + yy += (p * p) as f32; + } + } + while placed < k { + let mut best = 0usize; + let mut best_num = -1f32; + let mut best_den = 1f32; + for j in 0..n { + let num = xy + abs[j]; + let num = num * num; + let den = yy + 2.0 * y[j] as f32 + 1.0; + if num * best_den > best_num * den { + best_num = num; + best_den = den; + best = j; + } + } + xy += abs[best]; + yy += 2.0 * y[best] as f32 + 1.0; + y[best] += 1; + placed += 1; + } + for j in 0..n { + if x[j] < 0.0 { + y[j] = -y[j]; + } + } + } + + #[test] + fn pvq_search_matches_scalar_reference() { + let mut state = 0x9e3779b97f4a7c15u64; + let mut rnd = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0 + }; + let mut a = vec![0i32; 200]; + let mut b = vec![0i32; 200]; + let mut cases = 0; + for round in 0..6000 { + let n = 1 + (round * 37 + (rnd().abs() * 176.0) as usize) % 176; + let k = 1 + (rnd().abs() * 127.0) as usize; + let scale = [1.0f32, 1e-9, 1e6, 3e-3][round % 4]; + let x: Vec = (0..n) + .map(|_| match round % 6 { + 0 => rnd(), + 1 => if rnd() > 0.8 { rnd() } else { 0.0 }, + 2 => (rnd() * 4.0).round() / 4.0, + 3 => if rnd() > 0.0 { 1.0 } else { -1.0 }, + 4 => rnd().powi(5), + _ => if rnd() > 0.95 { 3.0 * rnd() } else { 1e-4 * rnd() }, + } * scale) + .collect(); + pvq_search(&x, k, &mut a); + pvq_search_ref(&x, k, &mut b); + assert_eq!(a[..n], b[..n], "n={n} k={k} round={round}"); + cases += 1; + } + assert_eq!(cases, 6000); + } + #[test] fn pvq_search_finds_good_direction() { let x: Vec = (0..32).map(|i| ((i as f32) * 0.7).sin()).collect(); diff --git a/crates/audio/src/opus/encoder/energy.rs b/crates/audio/src/opus/encoder/energy.rs index 8d4f357d0e..fb5cc5a4b6 100644 --- a/crates/audio/src/opus/encoder/energy.rs +++ b/crates/audio/src/opus/encoder/energy.rs @@ -4,8 +4,9 @@ //! The quantised energies are updated with exactly the decoder's arithmetic so the prediction //! state never drifts between encoder and decoder. +use crate::opus::encoder::CeltFrame; use crate::opus::encoder::range::RangeEncoder; -use crate::opus::encoder::rate::MAX_FINE_BITS; +use crate::opus::encoder::rate::{Allocation, MAX_FINE_BITS}; use crate::opus::encoder::tables::{BETA_COEF, BETA_INTRA, E_PROB_MODEL, NB_EBANDS, PRED_COEF, SMALL_ENERGY_ICDF}; const LAPLACE_MINP: u32 = 1; @@ -56,18 +57,15 @@ pub fn laplace_encode(enc: &mut RangeEncoder, value: i32, mut fs: u32, decay: u3 /// `quant_coarse_energy` for one prediction mode. `e` holds the target log2 energies (relative /// to `E_MEANS`), `old_e` the quantised energies, updated in place. `budget` is the frame size in /// bits. -#[allow(clippy::too_many_arguments)] pub fn quant_coarse_energy( - start: usize, - end: usize, + frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], intra: bool, enc: &mut RangeEncoder, - c: usize, - lm: usize, budget: i32, ) { + let CeltFrame { start, end, channels: c, lm } = frame; let prob = &E_PROB_MODEL[lm][intra as usize]; let (coef, beta) = if intra { (0.0, BETA_INTRA) } else { (PRED_COEF[lm], BETA_COEF[lm]) }; let mut prev = [0f32; 2]; @@ -112,14 +110,13 @@ pub fn quant_coarse_energy( /// `quant_fine_energy`: raw bits refining each band's quantised energy. pub fn quant_fine_energy( - start: usize, - end: usize, + frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], fine_quant: &[i32; NB_EBANDS], enc: &mut RangeEncoder, - c: usize, ) { + let CeltFrame { start, end, channels: c, .. } = frame; for i in start..end { let fq = fine_quant[i]; if fq <= 0 { @@ -139,18 +136,16 @@ pub fn quant_fine_energy( /// `quant_energy_finalise`: spends the bits left at the end of the frame on one more bit of /// energy resolution per band, in priority order. -#[allow(clippy::too_many_arguments)] pub fn quant_energy_finalise( - start: usize, - end: usize, + frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], - fine_quant: &[i32; NB_EBANDS], - fine_priority: &[i32; NB_EBANDS], + allocation: &Allocation, mut bits_left: i32, enc: &mut RangeEncoder, - c: usize, ) { + let CeltFrame { start, end, channels: c, .. } = frame; + let Allocation { fine_quant, fine_priority, .. } = allocation; for prio in 0..2 { let mut i = start; while i < end && bits_left >= c as i32 { diff --git a/crates/audio/src/opus/encoder/mdct.rs b/crates/audio/src/opus/encoder/mdct.rs index 6a42cce960..7cac21d932 100644 --- a/crates/audio/src/opus/encoder/mdct.rs +++ b/crates/audio/src/opus/encoder/mdct.rs @@ -9,84 +9,7 @@ use crate::opus::encoder::tables::OVERLAP; -#[derive(Clone, Copy, Default, Debug)] -pub struct Cpx { - pub re: f32, - pub im: f32, -} - -impl Cpx { - #[inline] - fn mul(self, o: Cpx) -> Cpx { - Cpx { re: self.re * o.re - self.im * o.im, im: self.re * o.im + self.im * o.re } - } - #[inline] - fn add(self, o: Cpx) -> Cpx { - Cpx { re: self.re + o.re, im: self.im + o.im } - } -} - -/// Mixed-radix (2, 3, 4, 5) forward complex FFT, unscaled (decimation in time, recursive). -pub struct Fft { - n: usize, - factors: Vec, - twiddle: Vec, -} - -impl Fft { - pub fn new(n: usize) -> Fft { - let mut factors = Vec::new(); - let mut m = n; - for p in [4usize, 2, 3, 5] { - while m.is_multiple_of(p) { - factors.push(p); - m /= p; - } - } - assert_eq!(m, 1, "unsupported FFT size {n}"); - let twiddle = (0..n) - .map(|k| { - let ph = -2.0 * std::f64::consts::PI * k as f64 / n as f64; - Cpx { re: ph.cos() as f32, im: ph.sin() as f32 } - }) - .collect(); - Fft { n, factors, twiddle } - } - - pub fn process(&self, data: &mut [Cpx], scratch: &mut Vec) { - scratch.clear(); - scratch.extend_from_slice(&data[..self.n]); - self.rec(&mut data[..self.n], scratch, 1, self.n, 0, 1); - } - - fn rec(&self, out: &mut [Cpx], inp: &[Cpx], in_stride: usize, n: usize, fi: usize, tw_stride: usize) { - let p = self.factors[fi]; - let m = n / p; - if m == 1 { - for (i, o) in out.iter_mut().enumerate().take(p) { - *o = inp[i * in_stride]; - } - } else { - for q in 0..p { - self.rec(&mut out[q * m..(q + 1) * m], &inp[q * in_stride..], in_stride * p, m, fi + 1, tw_stride * p); - } - } - let big = self.n; - let mut t = [Cpx::default(); 5]; - for k in 0..m { - for (q, tq) in t.iter_mut().enumerate().take(p) { - *tq = out[q * m + k].mul(self.twiddle[(q * k * tw_stride) % big]); - } - for q2 in 0..p { - let mut acc = Cpx::default(); - for (q, tq) in t.iter().enumerate().take(p) { - acc = acc.add(tq.mul(self.twiddle[((q * q2) % p) * (big / p)])); - } - out[q2 * m + k] = acc; - } - } - } -} +use crate::opus::fft::{Cpx, Fft}; /// Forward MDCT producing `n` coefficients from a block of `n + OVERLAP` samples. pub struct Mdct { @@ -199,6 +122,31 @@ mod tests { .collect() } + #[test] + fn fft_matches_dft() { + // Every radix combination, including the 480-point size of the 20 ms frame. + for &n in &[2usize, 3, 4, 5, 6, 8, 12, 15, 16, 20, 24, 30, 48, 60, 120, 240, 480] { + let fft = Fft::new(n); + let x: Vec = (0..n).map(|i| Cpx { re: ((i * 37 % 101) as f32 - 50.0) / 7.0, im: ((i * 53 % 89) as f32 - 44.0) / 9.0 }).collect(); + let mut y = x.clone(); + fft.process(&mut y, &mut Vec::new()); + for k in 0..n { + let (mut re, mut im) = (0f64, 0f64); + for (j, v) in x.iter().enumerate() { + let ph = -2.0 * std::f64::consts::PI * ((j * k) % n) as f64 / n as f64; + re += v.re as f64 * ph.cos() - v.im as f64 * ph.sin(); + im += v.re as f64 * ph.sin() + v.im as f64 * ph.cos(); + } + assert!( + (y[k].re as f64 - re).abs() < 2e-3 && (y[k].im as f64 - im).abs() < 2e-3, + "n={n} k={k}: ({}, {}) vs ({re}, {im})", + y[k].re, + y[k].im + ); + } + } + } + #[test] fn matches_direct_formula() { for &n in &[240usize, 960] { diff --git a/crates/audio/src/opus/encoder/mod.rs b/crates/audio/src/opus/encoder/mod.rs index cbb0d79843..8a3df07f1a 100644 --- a/crates/audio/src/opus/encoder/mod.rs +++ b/crates/audio/src/opus/encoder/mod.rs @@ -10,8 +10,9 @@ //! above in the same range-coded frame; constant packet size. //! - **CELT** (fullband): MDCT transform coding; constant packet size. //! -//! From EffectCraft's `effectcraft-opusenc` (storytold/effectcraft@c618429). Public items keep their -//! names, so EffectCraft can re-export this module. +//! From EffectCraft's `effectcraft-opusenc` (storytold/effectcraft@c618429), with its later speed-ups +//! and CELT stage refactor up to storytold/effectcraft@d6c9ad66. Public items keep their names, so +//! EffectCraft can re-export this module. //! //! ``` //! # #[cfg(feature = "opus-encode")] { @@ -26,6 +27,7 @@ //! # } //! ``` +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] // The bit-allocation code mirrors the normative integer arithmetic; keep C-like shift expressions. #![allow(clippy::precedence, clippy::int_plus_one)] @@ -36,19 +38,28 @@ mod range; mod rate; mod resample; mod silk; -mod tables; +pub(super) mod tables; use std::sync::OnceLock; -use bands::{SPREAD_NORMAL, quant_all_bands}; +use bands::{BandCoding, SPREAD_NORMAL, quant_all_bands}; use energy::{quant_coarse_energy, quant_energy_finalise, quant_fine_energy}; use mdct::Mdct; use range::{BITRES, RangeEncoder}; -use rate::{Mode as CeltMode, compute_allocation}; +use rate::{AllocationInput, Mode as CeltMode, compute_allocation}; use resample::Downsampler; use silk::SilkEncoder; use tables::{E_MEANS, EBANDS, NB_EBANDS, OVERLAP, PREEMPH, SPREAD_ICDF, TF_SELECT_TABLE, TRIM_ICDF}; +/// Band range, channel count and transform size shared by CELT coding stages. +#[derive(Clone, Copy)] +struct CeltFrame { + start: usize, + end: usize, + channels: usize, + lm: usize, +} + /// Samples per channel in one 20 ms frame at 48 kHz. const N: usize = 960; /// LM of a 20 ms frame (8 short blocks). @@ -338,7 +349,7 @@ impl Encoder { Mode::Celt => { let (log_e, silence) = self.celt_analysis(pcm); let len = self.frame_bytes; - packet.extend_from_slice(&self.encode_celt(RangeEncoder::new(), len, 0, NB_EBANDS, &log_e, silence)); + packet.extend_from_slice(&self.encode_celt(RangeEncoder::new(), len, 0..NB_EBANDS, &log_e, silence)); } Mode::Silk => { let x = self.silk_input(pcm); @@ -368,7 +379,7 @@ impl Encoder { } let (log_e, _) = self.celt_analysis(pcm); let end = if self.bandwidth == Bandwidth::SuperWideband { 19 } else { NB_EBANDS }; - packet.extend_from_slice(&self.encode_celt(enc, len, HYBRID_START_BAND, end, &log_e, false)); + packet.extend_from_slice(&self.encode_celt(enc, len, HYBRID_START_BAND..end, &log_e, false)); } } Ok(packet) @@ -430,10 +441,18 @@ impl Encoder { /// Codes one CELT frame (RFC 6716 §4.3, in bitstream order) of `len` bytes into `enc` /// (which already holds the SILK frame in hybrid mode), coding bands `start..end`, and /// finalises the frame. - #[allow(clippy::too_many_arguments)] - fn encode_celt(&mut self, mut enc: RangeEncoder, len: usize, start: usize, end: usize, log_e: &[f32; 2 * NB_EBANDS], silence: bool) -> Vec { + fn encode_celt( + &mut self, + mut enc: RangeEncoder, + len: usize, + bands: std::ops::Range, + log_e: &[f32; 2 * NB_EBANDS], + silence: bool, + ) -> Vec { let m = celt_mode(); let c = self.channels; + let frame = CeltFrame { start: bands.start, end: bands.end, channels: c, lm: LM }; + let CeltFrame { start, end, .. } = frame; if c == 1 { for i in 0..NB_EBANDS { self.old_band_e[i] = self.old_band_e[i].max(self.old_band_e[NB_EBANDS + i]); @@ -462,10 +481,10 @@ impl Encoder { let mut enc_intra = enc.clone(); let mut old_intra = self.old_band_e; enc_intra.bit_logp(true, 3); - quant_coarse_energy(start, end, log_e, &mut old_intra, true, &mut enc_intra, c, LM, total_bits_raw); + quant_coarse_energy(frame, log_e, &mut old_intra, true, &mut enc_intra, total_bits_raw); enc.bit_logp(false, 3); let mut old_inter = self.old_band_e; - quant_coarse_energy(start, end, log_e, &mut old_inter, false, &mut enc, c, LM, total_bits_raw); + quant_coarse_energy(frame, log_e, &mut old_inter, false, &mut enc, total_bits_raw); if enc_intra.tell_frac() < enc.tell_frac() { enc = enc_intra; self.old_band_e = old_intra; @@ -473,14 +492,14 @@ impl Encoder { self.old_band_e = old_inter; } } else { - quant_coarse_energy(start, end, log_e, &mut self.old_band_e, false, &mut enc, c, LM, total_bits_raw); + quant_coarse_energy(frame, log_e, &mut self.old_band_e, false, &mut enc, total_bits_raw); } // TF resolution: no changes. { let mut budget = total_bits_raw; let mut tell = enc.tell(); let mut logp = 4; - let tf_select_rsv = LM > 0 && tell + logp + 1 <= budget; + let tf_select_rsv = LM > 0 && tell + logp < budget; budget -= tf_select_rsv as i32; for _ in start..end { if tell + logp <= budget { @@ -512,27 +531,11 @@ impl Encoder { enc.icdf(alloc_trim as usize, &TRIM_ICDF, 7); } let bits = (total_bits_raw << BITRES) - enc.tell_frac() - 1; - let alloc = compute_allocation(m, start, end, &offsets, &cap, alloc_trim, bits, c, LM, &mut enc); - quant_fine_energy(start, end, log_e, &mut self.old_band_e, &alloc.fine_quant, &mut enc, c); - quant_all_bands( - m, - start, - end, - &self.freq, - N, - c, - &alloc.pulses, - SPREAD_NORMAL, - alloc.dual_stereo, - alloc.intensity, - total_bits_raw << BITRES, - alloc.balance, - &mut enc, - LM, - alloc.coded_bands, - ); + let alloc = compute_allocation(m, frame, AllocationInput { offsets: &offsets, cap: &cap, trim: alloc_trim, bits }, &mut enc); + quant_fine_energy(frame, log_e, &mut self.old_band_e, &alloc.fine_quant, &mut enc); + quant_all_bands(m, frame, &self.freq, N, &alloc, BandCoding { spread: SPREAD_NORMAL, total_bits: total_bits_raw << BITRES }, &mut enc); let bits_left = total_bits_raw - enc.tell(); - quant_energy_finalise(start, end, log_e, &mut self.old_band_e, &alloc.fine_quant, &alloc.fine_priority, bits_left, &mut enc, c); + quant_energy_finalise(frame, log_e, &mut self.old_band_e, &alloc, bits_left, &mut enc); debug_assert!(enc.tell() <= total_bits_raw, "frame overflow: {} > {}", enc.tell(), total_bits_raw); if c == 1 { let (a, b) = self.old_band_e.split_at_mut(NB_EBANDS); diff --git a/crates/audio/src/opus/encoder/rate.rs b/crates/audio/src/opus/encoder/rate.rs index c360f9da7b..3eb9575d4a 100644 --- a/crates/audio/src/opus/encoder/rate.rs +++ b/crates/audio/src/opus/encoder/rate.rs @@ -4,254 +4,18 @@ //! spec-derived `filmcraft-opus` decoder (first-party, MIT OR Apache-2.0) step by step; the only //! difference is that the encoder *writes* the band-skip, intensity and dual-stereo symbols. -use crate::opus::encoder::range::{BITRES, RangeEncoder, ilog}; -use crate::opus::encoder::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS}; +use crate::opus::encoder::CeltFrame; +use crate::opus::encoder::range::{BITRES, RangeEncoder}; +use crate::opus::encoder::tables::{EBANDS, LOG2_FRAC_TABLE, NB_EBANDS}; -const MAX_PSEUDO: i32 = 40; -const LOG_MAX_PSEUDO: i32 = 6; +#[cfg(test)] +pub use crate::opus::rate_common::pvq_v; +pub use crate::opus::rate_common::{Mode, get_pulses}; pub const MAX_FINE_BITS: i32 = 8; const FINE_OFFSET: i32 = 21; pub const QTHETA_OFFSET: i32 = 4; -pub const QTHETA_OFFSET_TWOPHASE: i32 = 16; const ALLOC_STEPS: i32 = 6; -/// Number of pulses represented by pseudo-pulse index `i`. -pub fn get_pulses(i: i32) -> i32 { - if i < 8 { i } else { (8 + (i & 7)) << ((i >> 3) - 1) } -} - -/// Conservative (rounded up) log2 of `val` with `frac` fractional bits. -pub fn log2_frac(mut val: u32, mut frac: u32) -> i32 { - let mut l = ilog(val); - if val & val.wrapping_sub(1) != 0 { - if l > 16 { - val = ((val - 1) >> (l - 16)) + 1; - } else { - val <<= 16 - l; - } - let mut l = (l - 1) << frac; - loop { - let b = (val >> 16) as i32; - l += b << frac; - val = (val + b as u32) >> b; - val = (val * val + 0x7FFF) >> 15; - if frac == 0 { - break; - } - frac -= 1; - } - l + (val > 0x8000) as i32 - } else { - l -= 1; - l << frac - } -} - -/// PVQ codebook size V(N, K) (saturating far above 2^32). -pub fn pvq_v(n: usize, k: usize) -> u128 { - if k == 0 { - return 1; - } - if n == 0 { - return 0; - } - let mut row = vec![0u128; k + 1]; - row[0] = 1; - for _ in 0..n { - let mut prev_diag = row[0]; - for kk in 1..=k { - let up = row[kk]; - let v = up.saturating_add(row[kk - 1]).saturating_add(prev_diag); - prev_diag = up; - row[kk] = v.min(u128::MAX >> 8); - } - row[0] = 1; - } - row[k] -} - -fn fits_in32(n: usize, k: i32) -> bool { - pvq_v(n, k as usize) <= u32::MAX as u128 -} - -/// Precomputed per-mode data. -pub struct Mode { - /// log2 of band width in 1/8 bits. - pub log_n: [i32; NB_EBANDS], - cache_index: Vec, - cache_bits: Vec, - caps: Vec, -} - -impl Mode { - pub fn new() -> Mode { - let mut log_n = [0i32; NB_EBANDS]; - for (i, l) in log_n.iter_mut().enumerate() { - *l = log2_frac((EBANDS[i + 1] - EBANDS[i]) as u32, BITRES); - } - let (cache_index, cache_bits) = compute_pulse_cache(MAX_LM as i32); - let mut m = Mode { log_n, cache_index, cache_bits, caps: Vec::new() }; - m.caps = compute_caps(&m); - m - } - - #[inline] - pub fn cache(&self, lm: i32, band: usize) -> &[u8] { - let idx = self.cache_index[((lm + 1) as usize) * NB_EBANDS + band]; - &self.cache_bits[idx.max(0) as usize..] - } - - pub fn bits2pulses(&self, band: usize, lm: i32, bits: i32) -> i32 { - let cache = self.cache(lm, band); - let mut lo = 0i32; - let mut hi = cache[0] as i32; - let bits = bits - 1; - for _ in 0..LOG_MAX_PSEUDO { - let mid = (lo + hi + 1) >> 1; - if cache[mid as usize] as i32 >= bits { - hi = mid; - } else { - lo = mid; - } - } - let lo_bits = if lo == 0 { -1 } else { cache[lo as usize] as i32 }; - if bits - lo_bits <= cache[hi as usize] as i32 - bits { lo } else { hi } - } - - pub fn pulses2bits(&self, band: usize, lm: i32, pulses: i32) -> i32 { - if pulses == 0 { 0 } else { self.cache(lm, band)[pulses as usize] as i32 + 1 } - } - - /// Per-band allocation caps for this frame (`init_caps`). - pub fn init_caps(&self, lm: usize, c: usize) -> [i32; NB_EBANDS] { - let mut cap = [0i32; NB_EBANDS]; - for (i, cp) in cap.iter_mut().enumerate() { - let n = (EBANDS[i + 1] - EBANDS[i]) << lm; - *cp = (self.caps[NB_EBANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * n >> 2; - } - cap - } -} - -fn compute_pulse_cache(lm_max: i32) -> (Vec, Vec) { - let nb = NB_EBANDS; - let rows = (lm_max + 2) as usize; - let mut index = vec![-1i16; nb * rows]; - let mut entries: Vec<(usize, i32, usize)> = Vec::new(); - let mut curr = 0usize; - for i in 0..rows { - for j in 0..nb { - let n = (((EBANDS[j + 1] - EBANDS[j]) << i) >> 1) as usize; - index[i * nb + j] = -1; - 'search: for k in 0..=i { - for nn in 0..nb { - if k == i && nn >= j { - break; - } - if n == (((EBANDS[nn + 1] - EBANDS[nn]) << k) >> 1) as usize { - index[i * nb + j] = index[k * nb + nn]; - break 'search; - } - } - } - if index[i * nb + j] == -1 && n != 0 { - let mut k = 0; - while k < MAX_PSEUDO && fits_in32(n, get_pulses(k + 1)) { - k += 1; - } - index[i * nb + j] = curr as i16; - entries.push((n, k, curr)); - curr += (k + 1) as usize; - } - } - } - let mut bits = vec![0u8; curr]; - for &(n, k, off) in &entries { - let maxk = get_pulses(k) as usize; - let tmp = required_bits(n, maxk, BITRES); - for j in 1..=k { - bits[off + j as usize] = (tmp[get_pulses(j) as usize] - 1) as u8; - } - bits[off] = k as u8; - } - (index, bits) -} - -fn required_bits(n: usize, maxk: usize, frac: u32) -> Vec { - let mut out = vec![0i32; maxk + 1]; - if n == 1 { - for o in out.iter_mut().skip(1) { - *o = 1 << frac; - } - } else { - for (k, o) in out.iter_mut().enumerate().skip(1) { - *o = log2_frac(pvq_v(n, k) as u32, frac); - } - } - out -} - -fn compute_caps(m: &Mode) -> Vec { - let nb = NB_EBANDS; - let mut caps = vec![0u8; (MAX_LM + 1) * 2 * nb]; - for i in 0..=MAX_LM as i32 { - for c in 1..=2i32 { - for j in 0..nb { - let mut n0 = EBANDS[j + 1] - EBANDS[j]; - - let max_bits = if n0 << i == 1 { - c * (1 + MAX_FINE_BITS) << BITRES - } else { - let mut lm0 = 0; - if n0 > 2 { - n0 >>= 1; - lm0 -= 1; - } else if n0 <= 1 { - lm0 = i.min(1); - n0 <<= lm0; - } - let pcache = m.cache(lm0, j); - let mut mb = pcache[pcache[0] as usize] as i32 + 1; - let mut n = n0; - for k in 0..(i - lm0) { - mb <<= 1; - let offset = ((m.log_n[j] + ((lm0 + k) << BITRES)) >> 1) - QTHETA_OFFSET; - let num = 459 * ((2 * n - 1) * offset + mb); - let den = ((2 * n - 1) << 9) - 459; - let qb = ((num + (den >> 1)) / den).min(57); - mb += qb; - n <<= 1; - } - if c == 2 { - mb <<= 1; - let offset = ((m.log_n[j] + (i << BITRES)) >> 1) - if n == 2 { QTHETA_OFFSET_TWOPHASE } else { QTHETA_OFFSET }; - let ndof = 2 * n - 1 - (n == 2) as i32; - let p = if n == 2 { 512 } else { 487 }; - let num = p * (mb + ndof * offset); - let den = (ndof << 9) - p; - let qb = ((num + (den >> 1)) / den).min(if n == 2 { 64 } else { 61 }); - mb += qb; - } - let ndof = c * n + if c == 2 && n > 2 { 1 } else { 0 }; - let mut offset = ((m.log_n[j] + (i << BITRES)) >> 1) - FINE_OFFSET; - if n == 2 { - offset += (1 << BITRES) >> 2; - } - let num = mb + ndof * offset; - let den = (ndof - 1) << BITRES; - let qb = ((num + (den >> 1)) / den).min(MAX_FINE_BITS); - mb += c * qb << BITRES; - mb - }; - let w = c * ((EBANDS[j + 1] - EBANDS[j]) << i); - let v = (4 * max_bits / w) - 64; - caps[((i * 2 + c - 1) as usize) * nb + j] = v.clamp(0, 255) as u8; - } - } - } - caps -} - /// Result of the allocation process. pub struct Allocation { pub coded_bands: usize, @@ -263,125 +27,43 @@ pub struct Allocation { pub fine_priority: [i32; NB_EBANDS], } -/// `clt_compute_allocation`, encoder side. Stereo frames are always coded as dual (L/R) stereo -/// with no intensity bands, and no band is skipped voluntarily. -#[allow(clippy::too_many_arguments)] -pub fn compute_allocation( - m: &Mode, - start: usize, - end: usize, - offsets: &[i32; NB_EBANDS], - cap: &[i32; NB_EBANDS], - alloc_trim: i32, - total: i32, - c: usize, - lm: usize, - enc: &mut RangeEncoder, -) -> Allocation { - let ci = c as i32; - let lmi = lm as i32; - let mut total = total.max(0); - let mut skip_start = start; - let skip_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; - total -= skip_rsv; - let mut intensity_rsv = 0; - let mut dual_stereo_rsv = 0; - if c == 2 { - intensity_rsv = LOG2_FRAC_TABLE[end - start]; - if intensity_rsv > total { - intensity_rsv = 0; - } else { - total -= intensity_rsv; - dual_stereo_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; - total -= dual_stereo_rsv; - } - } - let mut bits1 = [0i32; NB_EBANDS]; - let mut bits2 = [0i32; NB_EBANDS]; - let mut thresh = [0i32; NB_EBANDS]; - let mut trim_offset = [0i32; NB_EBANDS]; - for j in start..end { - let w = EBANDS[j + 1] - EBANDS[j]; - thresh[j] = (ci << BITRES).max((3 * w << lmi << BITRES) >> 4); - trim_offset[j] = ci * w * (alloc_trim - 5 - lmi) * (end as i32 - j as i32 - 1) * (1 << (lmi + BITRES as i32)) >> 6; - if w << lmi == 1 { - trim_offset[j] -= ci << BITRES; - } - } - let nb_alloc = ALLOC.len() as i32; - let mut lo = 1; - let mut hi = nb_alloc - 1; - loop { - let mut done = false; - let mut psum = 0; - let mid = (lo + hi) >> 1; - for j in (start..end).rev() { - let n = EBANDS[j + 1] - EBANDS[j]; - let mut bitsj = ci * n * (ALLOC[mid as usize][j] as i32) << lmi >> 2; - if bitsj > 0 { - bitsj = (bitsj + trim_offset[j]).max(0); - } - bitsj += offsets[j]; - if bitsj >= thresh[j] || done { - done = true; - psum += bitsj.min(cap[j]); - } else if bitsj >= ci << BITRES { - psum += ci << BITRES; - } - } - if psum > total { - hi = mid - 1; - } else { - lo = mid + 1; - } - if lo > hi { - break; - } - } - hi = lo; - lo -= 1; - for j in start..end { - let n = EBANDS[j + 1] - EBANDS[j]; - let mut bits1j = ci * n * (ALLOC[lo as usize][j] as i32) << lmi >> 2; - let mut bits2j = if hi >= nb_alloc { cap[j] } else { ci * n * (ALLOC[hi as usize][j] as i32) << lmi >> 2 }; - if bits1j > 0 { - bits1j = (bits1j + trim_offset[j]).max(0); - } - if bits2j > 0 { - bits2j = (bits2j + trim_offset[j]).max(0); - } - if lo > 0 { - bits1j += offsets[j]; - } - bits2j += offsets[j]; - if offsets[j] > 0 { - skip_start = j; - } - bits2j = (bits2j - bits1j).max(0); - bits1[j] = bits1j; - bits2[j] = bits2j; - } - interp_bits2pulses(m, start, end, skip_start, &bits1, &bits2, &thresh, cap, total, skip_rsv, intensity_rsv, dual_stereo_rsv, c, lm, enc) +/// Per-band limits, boosts and available budget for the allocation search. +pub struct AllocationInput<'a> { + pub offsets: &'a [i32; NB_EBANDS], + pub cap: &'a [i32; NB_EBANDS], + pub trim: i32, + pub bits: i32, } -#[allow(clippy::too_many_arguments)] -fn interp_bits2pulses( - m: &Mode, - start: usize, - end: usize, +/// `clt_compute_allocation`, encoder side. Stereo frames are always coded as dual (L/R) stereo +/// with no intensity bands, and no band is skipped voluntarily. +pub fn compute_allocation(m: &Mode, frame: CeltFrame, input: AllocationInput<'_>, enc: &mut RangeEncoder) -> Allocation { + let CeltFrame { start, end, channels: c, lm } = frame; + let AllocationInput { offsets, cap, trim: alloc_trim, bits: total } = input; + let crate::opus::rate_common::Bracket { skip_start, bits1, bits2, thresh, total, skip_rsv, intensity_rsv, dual_stereo_rsv } = + crate::opus::rate_common::bracket(start, end, offsets, cap, alloc_trim, total, c, lm); + let interpolation = + AllocationInterpolation { skip_start, bits1: &bits1, bits2: &bits2, thresh: &thresh, cap, total, skip_rsv, intensity_rsv, dual_stereo_rsv }; + interp_bits2pulses(m, frame, interpolation, enc) +} + +/// Bracketing allocation vectors and signalling reserves for the interpolation stage. +struct AllocationInterpolation<'a> { skip_start: usize, - bits1: &[i32; NB_EBANDS], - bits2: &[i32; NB_EBANDS], - thresh: &[i32; NB_EBANDS], - cap: &[i32; NB_EBANDS], - mut total: i32, + bits1: &'a [i32; NB_EBANDS], + bits2: &'a [i32; NB_EBANDS], + thresh: &'a [i32; NB_EBANDS], + cap: &'a [i32; NB_EBANDS], + total: i32, skip_rsv: i32, - mut intensity_rsv: i32, - mut dual_stereo_rsv: i32, - c: usize, - lm: usize, - enc: &mut RangeEncoder, -) -> Allocation { + intensity_rsv: i32, + dual_stereo_rsv: i32, +} + +fn interp_bits2pulses(m: &Mode, frame: CeltFrame, interpolation: AllocationInterpolation<'_>, enc: &mut RangeEncoder) -> Allocation { + let CeltFrame { start, end, channels: c, lm } = frame; + let AllocationInterpolation { skip_start, bits1, bits2, thresh, cap, mut total, skip_rsv, mut intensity_rsv, mut dual_stereo_rsv } = + interpolation; let ci = c as i32; let alloc_floor = ci << BITRES; let stereo = (c > 1) as i32; @@ -393,7 +75,7 @@ fn interp_bits2pulses( let mut psum = 0; let mut done = false; for j in (start..end).rev() { - let tmp = bits1[j] + (mid * bits2[j] >> ALLOC_STEPS); + let tmp = bits1[j] + ((mid * bits2[j]) >> ALLOC_STEPS); if tmp >= thresh[j] || done { done = true; psum += tmp.min(cap[j]); @@ -411,7 +93,7 @@ fn interp_bits2pulses( let mut psum = 0; let mut done = false; for j in (start..end).rev() { - let mut tmp = bits1[j] + (lo * bits2[j] >> ALLOC_STEPS); + let mut tmp = bits1[j] + ((lo * bits2[j]) >> ALLOC_STEPS); if tmp < thresh[j] && !done { tmp = if tmp >= alloc_floor { alloc_floor } else { 0 }; } else { @@ -500,9 +182,9 @@ fn interp_bits2pulses( if n == 2 { offset += (den << BITRES) >> 2; } - if bits[j] + offset < den * 2 << BITRES { + if bits[j] + offset < (den * 2) << BITRES { offset += nclogn >> 2; - } else if bits[j] + offset < den * 3 << BITRES { + } else if bits[j] + offset < (den * 3) << BITRES { offset += nclogn >> 3; } let mut eb = (bits[j] + offset + (den << (BITRES - 1))).max(0); @@ -513,7 +195,7 @@ fn interp_bits2pulses( eb = eb.min(MAX_FINE_BITS); ebits[j] = eb; fine_priority[j] = (eb * (den << BITRES) >= bits[j] + offset) as i32; - bits[j] -= ci * eb << BITRES; + bits[j] -= (ci * eb) << BITRES; } else { excess = (bit - (ci << BITRES)).max(0); bits[j] = bit - excess; @@ -523,7 +205,7 @@ fn interp_bits2pulses( if excess > 0 { let extra_fine = (excess >> (stereo + BITRES as i32)).min(MAX_FINE_BITS - ebits[j]); ebits[j] += extra_fine; - let extra_bits = extra_fine * ci << BITRES; + let extra_bits = (extra_fine * ci) << BITRES; fine_priority[j] = (extra_bits >= excess - balance) as i32; excess -= extra_bits; } diff --git a/crates/audio/src/opus/encoder/resample.rs b/crates/audio/src/opus/encoder/resample.rs index 9045cb86d3..a72589919c 100644 --- a/crates/audio/src/opus/encoder/resample.rs +++ b/crates/audio/src/opus/encoder/resample.rs @@ -45,6 +45,8 @@ fn design(fc: f64, beta: f64, delay: usize) -> Vec { h.iter().map(|&v| v as f32).collect() } +use crate::opus::dot::dot8; + /// Decimates one channel of 48 kHz audio by 3, 4 or 6. #[derive(Clone)] pub struct Downsampler { @@ -77,7 +79,7 @@ impl Downsampler { let t = taps - 1 + self.factor * j; let win = &self.buf[t + 1 - taps..=t]; // h is symmetric, so the window can be taken in forward order. - out.push(win.iter().zip(&self.h).map(|(a, b)| a * b).sum()); + out.push(dot8(win, &self.h)); } let n = self.buf.len(); self.buf.copy_within(n - (taps - 1).., 0); @@ -97,6 +99,16 @@ mod tests { (x.iter().map(|&v| (v as f64).powi(2)).sum::() / x.len() as f64).sqrt() } + #[test] + fn dot8_matches_sequential_sum() { + for len in [0usize, 1, 7, 8, 9, 63, 167, 251] { + let a: Vec = (0..len).map(|i| ((i * 37 % 101) as f32 - 50.0) / 50.0).collect(); + let b: Vec = (0..len).map(|i| ((i * 53 % 89) as f32 - 44.0) / 44.0).collect(); + let exact: f64 = a.iter().zip(&b).map(|(&x, &y)| x as f64 * y as f64).sum(); + assert!((dot8(&a, &b) as f64 - exact).abs() < 1e-4, "len {len}"); + } + } + #[test] fn passes_band_and_rejects_aliases() { for &(fs, pass, stop) in &[(16_000u32, 6_000.0, 8_600.0), (12_000, 4_500.0, 6_500.0), (8_000, 3_000.0, 4_500.0)] { diff --git a/crates/audio/src/opus/encoder/silk/analysis.rs b/crates/audio/src/opus/encoder/silk/analysis.rs index 4393310761..d800520461 100644 --- a/crates/audio/src/opus/encoder/silk/analysis.rs +++ b/crates/audio/src/opus/encoder/silk/analysis.rs @@ -69,28 +69,55 @@ pub fn levinson(r: &[f64], order: usize) -> Vec { } /// Evaluates the symmetric polynomial `p` (length `d + 1`, `d` even) as the cosine series -/// `e^{jωd/2} P(e^{jω})`. -fn cos_series(p: &[f64], w: f64) -> f64 { +/// `e^{jωd/2} P(e^{jω})`, with `cos_m(m)` giving `cos(m ω)`. +#[inline] +fn cos_series_with(p: &[f64], cos_m: impl Fn(usize) -> f64) -> f64 { let h = (p.len() - 1) / 2; let mut s = p[h]; for k in 0..h { - s += 2.0 * p[k] * ((h - k) as f64 * w).cos(); + s += 2.0 * p[k] * cos_m(h - k); } s } +fn cos_series(p: &[f64], w: f64) -> f64 { + cos_series_with(p, |m| (m as f64 * w).cos()) +} + +/// Number of grid intervals the root search scans over `[0, π]`. +const GRID: usize = 1024; +/// Largest multiple of ω in the series (half the LPC order, at most 16 / 2). +const MAX_H: usize = 8; +/// Bisection steps per root: the bracket shrinks to 3e-9 rad, far below one Q15 NLSF step (9.6e-5 rad). +const BISECT_STEPS: usize = 20; + +/// `cos(m · π g / GRID)` for every grid point `g` and `m` in `0..=MAX_H`, computed with the same +/// expression as [`cos_series`], so the table values are bit-identical to calling `cos` there. +fn grid_cos() -> &'static [[f64; MAX_H + 1]] { + static TABLE: std::sync::OnceLock> = std::sync::OnceLock::new(); + TABLE.get_or_init(|| { + (0..=GRID) + .map(|g| { + let w = std::f64::consts::PI * g as f64 / GRID as f64; + std::array::from_fn(|m| (m as f64 * w).cos()) + }) + .collect() + }) +} + fn roots(p: &[f64], out: &mut Vec) { - const GRID: usize = 1024; + let grid = grid_cos(); + let at_grid = |g: usize| cos_series_with(p, |m| grid[g][m]); let mut w0 = 0.0; - let mut f0 = cos_series(p, w0); + let mut f0 = at_grid(0); for g in 1..=GRID { let w1 = std::f64::consts::PI * g as f64 / GRID as f64; - let f1 = cos_series(p, w1); + let f1 = at_grid(g); if f0 == 0.0 { out.push(w0); } else if f0 * f1 < 0.0 { let (mut lo, mut hi, mut flo) = (w0, w1, f0); - for _ in 0..40 { + for _ in 0..BISECT_STEPS { let mid = 0.5 * (lo + hi); let fm = cos_series(p, mid); if fm * flo <= 0.0 { @@ -111,6 +138,9 @@ fn roots(p: &[f64], out: &mut Vec) { /// when the root search fails (unstable or degenerate filter). pub fn a2nlsf(a: &[f64]) -> Option> { let d = a.len(); + if d > 2 * MAX_H { + return None; + } let mut c = vec![0f64; d + 2]; c[0] = 1.0; for k in 0..d { @@ -199,9 +229,20 @@ pub fn pitch_search(x: &[f32], start: usize, len: usize, fs_khz: usize) -> Pitch let score = full[(lag - min_lag) as usize]; // Contour: per-subframe lag offsets around the chosen lag. let cb: &[[i32; 4]] = if fs_khz == 8 { &CB_NB_20 } else { &CB_WB_20 }; + // The contour search revisits the same (subframe, lag) pairs for neighbouring base lags and + // codebook entries, so each correlation is computed once. + let span = (18 * fs - min_lag + 1) as usize; + let memo = std::cell::RefCell::new(vec![f64::NAN; 4 * span]); let sub_score = |k: usize, l: i32| -> f64 { let l = l.clamp(min_lag, 18 * fs); - ncorr(x, start + k * sub..start + (k + 1) * sub, l as usize) + let slot = k * span + (l - min_lag) as usize; + let cached = memo.borrow()[slot]; + if !cached.is_nan() { + return cached; + } + let v = ncorr(x, start + k * sub..start + (k + 1) * sub, l as usize); + memo.borrow_mut()[slot] = v; + v }; let mut best = (f64::MIN, lag, 0usize); for l0 in (lag - 2).max(min_lag)..=(lag + 2).min(max_lag) { @@ -319,4 +360,59 @@ mod tests { } } } + + /// The root search as it was before the grid table: `cos` called for every evaluation. + fn roots_reference(p: &[f64], out: &mut Vec) { + let mut w0 = 0.0; + let mut f0 = cos_series(p, w0); + for g in 1..=GRID { + let w1 = std::f64::consts::PI * g as f64 / GRID as f64; + let f1 = cos_series(p, w1); + if f0 == 0.0 { + out.push(w0); + } else if f0 * f1 < 0.0 { + let (mut lo, mut hi, mut flo) = (w0, w1, f0); + for _ in 0..BISECT_STEPS { + let mid = 0.5 * (lo + hi); + let fm = cos_series(p, mid); + if fm * flo <= 0.0 { + hi = mid; + } else { + lo = mid; + flo = fm; + } + } + out.push(0.5 * (lo + hi)); + } + w0 = w1; + f0 = f1; + } + } + + #[test] + fn grid_table_roots_are_bit_identical_to_direct_cos() { + let mut seed = 7u64; + let mut rnd = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 + }; + let mut found = 0; + for len in [11usize, 17] { + for _ in 0..300 { + let mut p = vec![0f64; len]; + for k in 0..len / 2 + 1 { + p[k] = rnd(); + p[len - 1 - k] = p[k]; + } + let (mut a, mut b) = (Vec::new(), Vec::new()); + roots(&p, &mut a); + roots_reference(&p, &mut b); + assert_eq!(a.iter().map(|v| v.to_bits()).collect::>(), b.iter().map(|v| v.to_bits()).collect::>()); + found += a.len(); + } + } + assert!(found > 1000, "{found}"); + } } diff --git a/crates/audio/src/opus/encoder/silk/mod.rs b/crates/audio/src/opus/encoder/silk/mod.rs index d82e537e0a..0fda4f59ad 100644 --- a/crates/audio/src/opus/encoder/silk/mod.rs +++ b/crates/audio/src/opus/encoder/silk/mod.rs @@ -129,6 +129,48 @@ struct Coded { pulses: Vec, } +/// Noise-feedback history (decoded − input), most recent first, as a double-length ring: each +/// sample is stored at `pos` and `pos + MAX_LPC_ORDER`, so `buf[pos..pos + MAX_LPC_ORDER]` is +/// always the contiguous window and a push costs two stores instead of a shift. +struct NfRing { + buf: [f64; 2 * MAX_LPC_ORDER], + /// Index of the most recent sample, always below `MAX_LPC_ORDER`. + pos: usize, +} + +impl NfRing { + fn new(hist: &[f64; MAX_LPC_ORDER]) -> Self { + let mut buf = [0.0; 2 * MAX_LPC_ORDER]; + buf[..MAX_LPC_ORDER].copy_from_slice(hist); + buf[MAX_LPC_ORDER..].copy_from_slice(hist); + NfRing { buf, pos: 0 } + } + + /// The history, most recent first. + fn window(&self) -> &[f64] { + self.buf.get(self.pos..self.pos + MAX_LPC_ORDER).unwrap_or(&[]) + } + + /// Makes `v` the most recent sample and drops the oldest. + fn push(&mut self, v: f64) { + self.pos = self.pos.checked_sub(1).unwrap_or(MAX_LPC_ORDER - 1); + for i in [self.pos, self.pos + MAX_LPC_ORDER] { + if let Some(slot) = self.buf.get_mut(i) { + *slot = v; + } + } + } + + /// The history as a plain array, most recent first. + fn to_array(&self) -> [f64; MAX_LPC_ORDER] { + let mut out = [0.0; MAX_LPC_ORDER]; + for (o, v) in out.iter_mut().zip(self.window()) { + *o = *v; + } + out + } +} + #[derive(Clone)] struct Channel { fs_khz: usize, @@ -237,7 +279,7 @@ impl Channel { let sub = self.sub; let order = self.order; let st = &mut self.dec; - let nf = &mut self.nf; + let mut ring = NfRing::new(&self.nf); let off = if p.signal_type == 0 { offset + INACTIVE_OFFSET } else { offset }; let gamma = nf_gamma(off); let mut nf_c = [0f64; MAX_LPC_ORDER]; @@ -355,7 +397,7 @@ impl Channel { } let lpc_q14 = lpc_pred.saturating_mul(16); // Target excitation (Q14) for this sample. - let fb: f64 = (0..order).map(|j| nf_c[j] * nf[j]).sum(); + let fb: f64 = nf_c.iter().zip(ring.window()).take(order).map(|(c, e)| c * e).sum(); let tgt = (x[n] as f64 + fb).clamp(-32768.0, 32767.0) * inv_g - lpc_q14 as f64 - ltp_q14 as f64; let sgn = if seed_v < 0 { -1.0 } else { 1.0 }; let u = sgn * tgt; @@ -394,11 +436,11 @@ impl Channel { let v = res.saturating_add(lpc_q14); s_lpc[MAX_LPC_ORDER + i] = v; xq[n] = sat16(rshift_round(smulww(v, gain_q10), 8)) as i16; - nf.copy_within(0..MAX_LPC_ORDER - 1, 1); - nf[0] = xq[n] as f64 - x[n] as f64; + ring.push(xq[n] as f64 - x[n] as f64); } s_lpc.copy_within(sub..sub + MAX_LPC_ORDER, 0); } + self.nf = ring.to_array(); st.s_lpc_q14.copy_from_slice(&s_lpc[..MAX_LPC_ORDER]); st.out_buf[..l].copy_from_slice(&xq); (Coded { gain_ix, gains_q16, seed, pulses }, xq) @@ -485,6 +527,14 @@ struct Prep { pred_q13: [i32; 2], } +/// One rate-loop trial: the frame coded at gain offset `offset`. +struct Trial { + offset: f64, + bits: i32, + state: SilkEncoder, + coder: RangeEncoder, +} + /// SILK encoder for one mono or stereo (mid/side) stream. #[derive(Clone)] pub struct SilkEncoder { @@ -635,11 +685,20 @@ impl SilkEncoder { pub fn encode(&mut self, input: &[Vec], target_bits: f64, max_bits: i32, enc: &mut RangeEncoder) { let prep = self.prepare(input); let start_bits = enc.tell(); - let trial = |s: &Self, o: f64| -> i32 { - let mut t = s.clone(); - let mut e = enc.clone(); - t.code(&prep, o, &mut e); - e.tell() - start_bits + // Every trial codes the frame into a clone of the encoder and the range coder. The result + // is kept per offset: the hard-limit check below hits the memo for the chosen offset, and + // the final step adopts that trial instead of coding the frame once more. + let mut trials: Vec = Vec::new(); + let mut trial = |s: &Self, o: f64| -> i32 { + if let Some(t) = trials.iter().find(|t| t.offset == o) { + return t.bits; + } + let mut state = s.clone(); + let mut coder = enc.clone(); + state.code(&prep, o, &mut coder); + let bits = coder.tell() - start_bits; + trials.push(Trial { offset: o, bits, state, coder }); + bits }; // Bisection on the gain offset: the smallest offset (finest quantisation) within budget. let target = target_bits.min(max_bits as f64); @@ -701,8 +760,20 @@ impl SilkEncoder { while trial(self, o) > max_bits && o < 12.0 { o += 1.0; } + match trials.iter().position(|t| t.offset == o) { + Some(i) => { + let t = trials.swap_remove(i); + *self = t.state; + *enc = t.coder; + } + None => self.code(&prep, o, enc), + } + self.end_frame(&prep, o); + } + + /// Advances the input history and the frame counter after frame `prep` was coded at `o`. + fn end_frame(&mut self, prep: &Prep, o: f64) { self.last_offset = o; - self.code(&prep, o, enc); for ch in 0..self.channels { self.ch[ch].push_history(&prep.x[ch]); } @@ -712,3 +783,80 @@ impl SilkEncoder { self.frame += 1; } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Deterministic speech-like test input: two harmonics with a moving pitch, a syllable + /// envelope, noise and short silences, at the internal rate and 16-bit scale. + fn signal(len: usize, fs_khz: usize, seed: u32) -> Vec { + let mut s = seed; + let fs = (fs_khz * 1000) as f64; + (0..len) + .map(|i| { + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let noise = (s >> 8) as f64 / (1u32 << 24) as f64 - 0.5; + let t = i as f64 / fs; + let f0 = 140.0 + 40.0 * (t * 1.3).sin(); + let env = ((t * 4.0).sin().max(0.0)).powf(0.7); + let voiced = (std::f64::consts::TAU * f0 * t).sin() + 0.5 * (std::f64::consts::TAU * 2.0 * f0 * t).sin(); + (8000.0 * env * voiced + 600.0 * noise) as f32 + }) + .collect() + } + + #[test] + fn nf_ring_matches_a_shifted_history() { + let mut hist = [0f64; MAX_LPC_ORDER]; + for (i, h) in hist.iter_mut().enumerate() { + *h = i as f64 * 0.5 - 3.0; + } + let mut ring = NfRing::new(&hist); + assert_eq!(ring.window(), &hist[..]); + for n in 0..100 { + let v = (n as f64 * 0.37).sin() * 100.0; + hist.copy_within(0..MAX_LPC_ORDER - 1, 1); + hist[0] = v; + ring.push(v); + assert_eq!(ring.window(), &hist[..], "after push {n}"); + } + assert_eq!(ring.to_array(), hist); + } + + /// The rate loop adopts the memoised trial for the chosen offset. A second encoder that codes + /// every frame afresh at that offset (what the loop did before the memo) must produce the + /// same bytes, frame after frame, so the adopted encoder and range-coder states are exact. + #[test] + fn adopting_the_memoised_trial_equals_coding_the_frame_again() { + for (fs_khz, channels, target_bits, max_bits) in + [(8, 1, 200.0, 1000), (12, 1, 320.0, 1000), (16, 1, 480.0, 1000), (16, 2, 640.0, 1000), (16, 1, 900.0, 400), (8, 2, 120.0, 160)] + { + let mut memo = SilkEncoder::new(fs_khz, channels); + let mut fresh = memo.clone(); + let l = memo.frame_len(); + let frames = 40; + let left = signal(l * frames, fs_khz, 7); + let right: Vec = signal(l * frames + 37, fs_khz, 11)[37..].iter().map(|v| v * 0.6).collect(); + for f in 0..frames { + let mut input = vec![left[f * l..(f + 1) * l].to_vec()]; + if channels == 2 { + input.push(right[f * l..(f + 1) * l].to_vec()); + } + let mut enc = RangeEncoder::new(); + memo.encode(&input, target_bits, max_bits, &mut enc); + let o = memo.last_offset; + let prep = fresh.prepare(&input); + let mut enc_fresh = RangeEncoder::new(); + fresh.code(&prep, o, &mut enc_fresh); + fresh.end_frame(&prep, o); + assert_eq!(enc.tell(), enc_fresh.tell(), "{fs_khz} kHz {channels} ch frame {f}"); + assert_eq!(enc.done(1275), enc_fresh.done(1275), "{fs_khz} kHz {channels} ch frame {f}"); + for c in 0..channels { + assert_eq!(memo.ch[c].nf, fresh.ch[c].nf, "noise feedback, channel {c}, frame {f}"); + assert_eq!(memo.ch[c].dec.s_lpc_q14, fresh.ch[c].dec.s_lpc_q14, "LPC state, channel {c}, frame {f}"); + } + } + } + } +} diff --git a/crates/audio/src/opus/fft.rs b/crates/audio/src/opus/fft.rs new file mode 100644 index 0000000000..300c78d482 --- /dev/null +++ b/crates/audio/src/opus/fft.rs @@ -0,0 +1,130 @@ +//! Shared CELT forward complex FFT. + +#[derive(Clone, Copy, Default, Debug)] +pub struct Cpx { + pub re: f32, + pub im: f32, +} + +impl Cpx { + #[inline] + pub(crate) fn mul(self, o: Cpx) -> Cpx { + Cpx { re: self.re * o.re - self.im * o.im, im: self.re * o.im + self.im * o.re } + } + #[inline] + pub(crate) fn add(self, o: Cpx) -> Cpx { + Cpx { re: self.re + o.re, im: self.im + o.im } + } + #[inline] + pub(crate) fn sub(self, o: Cpx) -> Cpx { + Cpx { re: self.re - o.re, im: self.im - o.im } + } +} + +/// Mixed-radix (2, 3, 4, 5) forward complex FFT, unscaled (decimation in time, recursive). +pub struct Fft { + pub(crate) n: usize, + pub(crate) factors: Vec, + pub(crate) twiddle: Vec, +} + +impl Fft { + pub fn new(n: usize) -> Fft { + let mut factors = Vec::new(); + let mut m = n; + for p in [4usize, 2, 3, 5] { + while m.is_multiple_of(p) { + factors.push(p); + m /= p; + } + } + assert_eq!(m, 1, "unsupported FFT size {n}"); + let twiddle = (0..n) + .map(|k| { + let ph = -2.0 * std::f64::consts::PI * k as f64 / n as f64; + Cpx { re: ph.cos() as f32, im: ph.sin() as f32 } + }) + .collect(); + Fft { n, factors, twiddle } + } + + pub fn process(&self, data: &mut [Cpx], scratch: &mut Vec) { + scratch.clear(); + scratch.extend_from_slice(&data[..self.n]); + self.rec(&mut data[..self.n], scratch, 1, self.n, 0, 1); + } + + fn rec(&self, out: &mut [Cpx], inp: &[Cpx], in_stride: usize, n: usize, fi: usize, tw_stride: usize) { + let p = self.factors[fi]; + let m = n / p; + if m == 1 { + for (i, o) in out.iter_mut().enumerate().take(p) { + *o = inp[i * in_stride]; + } + } else { + for q in 0..p { + self.rec(&mut out[q * m..(q + 1) * m], &inp[q * in_stride..], in_stride * p, m, fi + 1, tw_stride * p); + } + } + // The twiddle index q * k * tw_stride is always below n, so no modulo is needed. + let tw = &self.twiddle; + match p { + 2 => { + for k in 0..m { + let a0 = out[k]; + let a1 = out[m + k].mul(tw[k * tw_stride]); + out[k] = a0.add(a1); + out[m + k] = a0.sub(a1); + } + } + 4 => { + for k in 0..m { + let t0 = out[k]; + let t1 = out[m + k].mul(tw[k * tw_stride]); + let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); + let t3 = out[3 * m + k].mul(tw[3 * k * tw_stride]); + let (s0, d0) = (t0.add(t2), t0.sub(t2)); + let (s1, d1) = (t1.add(t3), t1.sub(t3)); + out[k] = s0.add(s1); + out[2 * m + k] = s0.sub(s1); + // The odd outputs combine d0 with -j * d1 = (d1.im, -d1.re) and its negative. + out[m + k] = Cpx { re: d0.re + d1.im, im: d0.im - d1.re }; + out[3 * m + k] = Cpx { re: d0.re - d1.im, im: d0.im + d1.re }; + } + } + 3 => { + // Imaginary part of exp(-2 pi i / 3) = -sqrt(3) / 2. + let h = tw[self.n / 3].im; + for k in 0..m { + let t0 = out[k]; + let t1 = out[m + k].mul(tw[k * tw_stride]); + let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); + let (s, d) = (t1.add(t2), t1.sub(t2)); + let a = Cpx { re: t0.re - 0.5 * s.re, im: t0.im - 0.5 * s.im }; + out[k] = t0.add(s); + // j * h * d = (-h * d.im, h * d.re) + out[m + k] = Cpx { re: a.re - h * d.im, im: a.im + h * d.re }; + out[2 * m + k] = Cpx { re: a.re + h * d.im, im: a.im - h * d.re }; + } + } + _ => { + // Generic DFT butterfly (radix 5, once per transform). + let roots: [Cpx; 5] = std::array::from_fn(|q| if q < p { tw[q * (self.n / p)] } else { Cpx::default() }); + let mut t = [Cpx::default(); 5]; + for k in 0..m { + t[0] = out[k]; + for q in 1..p { + t[q] = out[q * m + k].mul(tw[q * k * tw_stride]); + } + for q2 in 0..p { + let mut acc = t[0]; + for q in 1..p { + acc = acc.add(t[q].mul(roots[(q * q2) % p])); + } + out[q2 * m + k] = acc; + } + } + } + } + } +} diff --git a/crates/audio/src/opus/mod.rs b/crates/audio/src/opus/mod.rs index b67e1ef3d7..84e81ec8c0 100644 --- a/crates/audio/src/opus/mod.rs +++ b/crates/audio/src/opus/mod.rs @@ -7,14 +7,18 @@ //! 20 ms, mono or stereo). From EffectCraft's `effectcraft-opusenc` (storytold/effectcraft@c618429). //! //! Public items keep their names, so FilmCraft and EffectCraft can re-export this module. The two -//! halves come from separate crates and do not share code yet (each has its own range coder, MDCT -//! and band tables). [`Bandwidth`] is one type for both (`encoder::Bandwidth` is the same type); +//! halves share the FFT, resampling dot product and CELT allocation preparation; range coders and +//! mode-specific MDCT processing remain separate. [`Bandwidth`] is one type for both (`encoder::Bandwidth` is the same type); //! the two `Mode` enums keep their apps' variant names and convert into each other. // Index loops and long argument lists follow the specification's pseudo-code (FilmCraft and // EffectCraft allow these lints workspace-wide). #![allow(clippy::needless_range_loop, clippy::too_many_arguments)] +mod dot; +mod fft; +mod rate_common; + #[cfg(feature = "opus-decode")] mod decode; #[cfg(feature = "opus-encode")] diff --git a/crates/audio/src/opus/rate_common.rs b/crates/audio/src/opus/rate_common.rs new file mode 100644 index 0000000000..86b27c90a4 --- /dev/null +++ b/crates/audio/src/opus/rate_common.rs @@ -0,0 +1,362 @@ +//! CELT pulse cache and allocation caps shared by encoder and decoder. + +#[cfg(not(feature = "opus-encode"))] +use super::decode::celt::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS}; +#[cfg(feature = "opus-encode")] +use super::encoder::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS}; + +const BITRES: u32 = 3; +const MAX_PSEUDO: i32 = 40; +const LOG_MAX_PSEUDO: i32 = 6; +const MAX_FINE_BITS: i32 = 8; +const FINE_OFFSET: i32 = 21; +const QTHETA_OFFSET: i32 = 4; +const QTHETA_OFFSET_TWOPHASE: i32 = 16; +fn ilog(x: u32) -> i32 { + (32 - x.leading_zeros()) as i32 +} + +/// Number of pulses represented by pseudo-pulse index `i`. +pub fn get_pulses(i: i32) -> i32 { + if i < 8 { i } else { (8 + (i & 7)) << ((i >> 3) - 1) } +} + +/// Conservative (rounded up) log2 of `val` with `frac` fractional bits. +pub fn log2_frac(mut val: u32, mut frac: u32) -> i32 { + let mut l = ilog(val); + if val & val.wrapping_sub(1) != 0 { + if l > 16 { + val = ((val - 1) >> (l - 16)) + 1; + } else { + val <<= 16 - l; + } + let mut l = (l - 1) << frac; + loop { + let b = (val >> 16) as i32; + l += b << frac; + val = (val + b as u32) >> b; + val = (val * val + 0x7FFF) >> 15; + if frac == 0 { + break; + } + frac -= 1; + } + l + (val > 0x8000) as i32 + } else { + l -= 1; + l << frac + } +} + +/// PVQ codebook size V(N, K) (saturating far above 2^32). +pub fn pvq_v(n: usize, k: usize) -> u128 { + if k == 0 { + return 1; + } + if n == 0 { + return 0; + } + let mut row = vec![0u128; k + 1]; + row[0] = 1; + for _ in 0..n { + let mut prev_diag = row[0]; + for kk in 1..=k { + let up = row[kk]; + let v = up.saturating_add(row[kk - 1]).saturating_add(prev_diag); + prev_diag = up; + row[kk] = v.min(u128::MAX >> 8); + } + row[0] = 1; + } + row[k] +} + +fn fits_in32(n: usize, k: i32) -> bool { + pvq_v(n, k as usize) <= u32::MAX as u128 +} + +/// Precomputed per-mode data. +pub struct Mode { + /// log2 of band width in 1/8 bits. + pub log_n: [i32; NB_EBANDS], + pub(crate) cache_index: Vec, + pub(crate) cache_bits: Vec, + pub(crate) caps: Vec, +} + +impl Mode { + pub fn new() -> Mode { + let mut log_n = [0i32; NB_EBANDS]; + for (i, l) in log_n.iter_mut().enumerate() { + *l = log2_frac((EBANDS[i + 1] - EBANDS[i]) as u32, BITRES); + } + let (cache_index, cache_bits) = compute_pulse_cache(MAX_LM as i32); + let mut m = Mode { log_n, cache_index, cache_bits, caps: Vec::new() }; + m.caps = compute_caps(&m); + m + } + + #[inline] + pub fn cache(&self, lm: i32, band: usize) -> &[u8] { + let idx = self.cache_index[((lm + 1) as usize) * NB_EBANDS + band]; + &self.cache_bits[idx.max(0) as usize..] + } + + pub fn bits2pulses(&self, band: usize, lm: i32, bits: i32) -> i32 { + let cache = self.cache(lm, band); + let mut lo = 0i32; + let mut hi = cache[0] as i32; + let bits = bits - 1; + for _ in 0..LOG_MAX_PSEUDO { + let mid = (lo + hi + 1) >> 1; + if cache[mid as usize] as i32 >= bits { + hi = mid; + } else { + lo = mid; + } + } + let lo_bits = if lo == 0 { -1 } else { cache[lo as usize] as i32 }; + if bits - lo_bits <= cache[hi as usize] as i32 - bits { lo } else { hi } + } + + pub fn pulses2bits(&self, band: usize, lm: i32, pulses: i32) -> i32 { + if pulses == 0 { 0 } else { self.cache(lm, band)[pulses as usize] as i32 + 1 } + } + + /// Per-band allocation caps for this frame (`init_caps`). + pub fn init_caps(&self, lm: usize, c: usize) -> [i32; NB_EBANDS] { + let mut cap = [0i32; NB_EBANDS]; + for (i, cp) in cap.iter_mut().enumerate() { + let n = (EBANDS[i + 1] - EBANDS[i]) << lm; + *cp = ((self.caps[NB_EBANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * n) >> 2; + } + cap + } +} + +fn compute_pulse_cache(lm_max: i32) -> (Vec, Vec) { + let nb = NB_EBANDS; + let rows = (lm_max + 2) as usize; + let mut index = vec![-1i16; nb * rows]; + let mut entries: Vec<(usize, i32, usize)> = Vec::new(); + let mut curr = 0usize; + for i in 0..rows { + for j in 0..nb { + let n = (((EBANDS[j + 1] - EBANDS[j]) << i) >> 1) as usize; + index[i * nb + j] = -1; + 'search: for k in 0..=i { + for nn in 0..nb { + if k == i && nn >= j { + break; + } + if n == (((EBANDS[nn + 1] - EBANDS[nn]) << k) >> 1) as usize { + index[i * nb + j] = index[k * nb + nn]; + break 'search; + } + } + } + if index[i * nb + j] == -1 && n != 0 { + let mut k = 0; + while k < MAX_PSEUDO && fits_in32(n, get_pulses(k + 1)) { + k += 1; + } + index[i * nb + j] = curr as i16; + entries.push((n, k, curr)); + curr += (k + 1) as usize; + } + } + } + let mut bits = vec![0u8; curr]; + for &(n, k, off) in &entries { + let maxk = get_pulses(k) as usize; + let tmp = required_bits(n, maxk, BITRES); + for j in 1..=k { + bits[off + j as usize] = (tmp[get_pulses(j) as usize] - 1) as u8; + } + bits[off] = k as u8; + } + (index, bits) +} + +fn required_bits(n: usize, maxk: usize, frac: u32) -> Vec { + let mut out = vec![0i32; maxk + 1]; + if n == 1 { + for o in out.iter_mut().skip(1) { + *o = 1 << frac; + } + } else { + for (k, o) in out.iter_mut().enumerate().skip(1) { + *o = log2_frac(pvq_v(n, k) as u32, frac); + } + } + out +} + +fn compute_caps(m: &Mode) -> Vec { + let nb = NB_EBANDS; + let mut caps = vec![0u8; (MAX_LM + 1) * 2 * nb]; + for i in 0..=MAX_LM as i32 { + for c in 1..=2i32 { + for j in 0..nb { + let mut n0 = EBANDS[j + 1] - EBANDS[j]; + + let max_bits = if n0 << i == 1 { + (c * (1 + MAX_FINE_BITS)) << BITRES + } else { + let mut lm0 = 0; + if n0 > 2 { + n0 >>= 1; + lm0 -= 1; + } else if n0 <= 1 { + lm0 = i.min(1); + n0 <<= lm0; + } + let pcache = m.cache(lm0, j); + let mut mb = pcache[pcache[0] as usize] as i32 + 1; + let mut n = n0; + for k in 0..(i - lm0) { + mb <<= 1; + let offset = ((m.log_n[j] + ((lm0 + k) << BITRES)) >> 1) - QTHETA_OFFSET; + let num = 459 * ((2 * n - 1) * offset + mb); + let den = ((2 * n - 1) << 9) - 459; + let qb = ((num + (den >> 1)) / den).min(57); + mb += qb; + n <<= 1; + } + if c == 2 { + mb <<= 1; + let offset = ((m.log_n[j] + (i << BITRES)) >> 1) - if n == 2 { QTHETA_OFFSET_TWOPHASE } else { QTHETA_OFFSET }; + let ndof = 2 * n - 1 - (n == 2) as i32; + let p = if n == 2 { 512 } else { 487 }; + let num = p * (mb + ndof * offset); + let den = (ndof << 9) - p; + let qb = ((num + (den >> 1)) / den).min(if n == 2 { 64 } else { 61 }); + mb += qb; + } + let ndof = c * n + if c == 2 && n > 2 { 1 } else { 0 }; + let mut offset = ((m.log_n[j] + (i << BITRES)) >> 1) - FINE_OFFSET; + if n == 2 { + offset += (1 << BITRES) >> 2; + } + let num = mb + ndof * offset; + let den = (ndof - 1) << BITRES; + let qb = ((num + (den >> 1)) / den).min(MAX_FINE_BITS); + mb += (c * qb) << BITRES; + mb + }; + let w = c * ((EBANDS[j + 1] - EBANDS[j]) << i); + let v = (4 * max_bits / w) - 64; + caps[((i * 2 + c - 1) as usize) * nb + j] = v.clamp(0, 255) as u8; + } + } + } + caps +} + +/// Shared allocation search before encoder/decoder signalling diverges. +pub struct Bracket { + pub skip_start: usize, + pub bits1: [i32; NB_EBANDS], + pub bits2: [i32; NB_EBANDS], + pub thresh: [i32; NB_EBANDS], + pub total: i32, + pub skip_rsv: i32, + pub intensity_rsv: i32, + pub dual_stereo_rsv: i32, +} + +pub fn bracket( + start: usize, + end: usize, + offsets: &[i32; NB_EBANDS], + cap: &[i32; NB_EBANDS], + alloc_trim: i32, + total: i32, + c: usize, + lm: usize, +) -> Bracket { + let ci = c as i32; + let lmi = lm as i32; + let mut total = total.max(0); + let mut skip_start = start; + let skip_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; + total -= skip_rsv; + let mut intensity_rsv = 0; + let mut dual_stereo_rsv = 0; + if c == 2 { + intensity_rsv = LOG2_FRAC_TABLE[end - start]; + if intensity_rsv > total { + intensity_rsv = 0; + } else { + total -= intensity_rsv; + dual_stereo_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; + total -= dual_stereo_rsv; + } + } + let mut bits1 = [0i32; NB_EBANDS]; + let mut bits2 = [0i32; NB_EBANDS]; + let mut thresh = [0i32; NB_EBANDS]; + let mut trim_offset = [0i32; NB_EBANDS]; + for j in start..end { + let w = EBANDS[j + 1] - EBANDS[j]; + thresh[j] = (ci << BITRES).max(((3 * w) << lmi << BITRES) >> 4); + trim_offset[j] = (ci * w * (alloc_trim - 5 - lmi) * (end as i32 - j as i32 - 1) * (1 << (lmi + BITRES as i32))) >> 6; + if w << lmi == 1 { + trim_offset[j] -= ci << BITRES; + } + } + let nb_alloc = ALLOC.len() as i32; + let mut lo = 1; + let mut hi = nb_alloc - 1; + loop { + let mut done = false; + let mut psum = 0; + let mid = (lo + hi) >> 1; + for j in (start..end).rev() { + let n = EBANDS[j + 1] - EBANDS[j]; + let mut bitsj = (ci * n * (ALLOC[mid as usize][j] as i32)) << lmi >> 2; + if bitsj > 0 { + bitsj = (bitsj + trim_offset[j]).max(0); + } + bitsj += offsets[j]; + if bitsj >= thresh[j] || done { + done = true; + psum += bitsj.min(cap[j]); + } else if bitsj >= ci << BITRES { + psum += ci << BITRES; + } + } + if psum > total { + hi = mid - 1; + } else { + lo = mid + 1; + } + if lo > hi { + break; + } + } + hi = lo; + lo -= 1; + for j in start..end { + let n = EBANDS[j + 1] - EBANDS[j]; + let mut bits1j = (ci * n * (ALLOC[lo as usize][j] as i32)) << lmi >> 2; + let mut bits2j = if hi >= nb_alloc { cap[j] } else { (ci * n * (ALLOC[hi as usize][j] as i32)) << lmi >> 2 }; + if bits1j > 0 { + bits1j = (bits1j + trim_offset[j]).max(0); + } + if bits2j > 0 { + bits2j = (bits2j + trim_offset[j]).max(0); + } + if lo > 0 { + bits1j += offsets[j]; + } + bits2j += offsets[j]; + if offsets[j] > 0 { + skip_start = j; + } + bits2j = (bits2j - bits1j).max(0); + bits1[j] = bits1j; + bits2[j] = bits2j; + } + Bracket { skip_start, bits1, bits2, thresh, total, skip_rsv, intensity_rsv, dual_stereo_rsv } +} diff --git a/crates/audio/src/pcm_export.rs b/crates/audio/src/pcm_export.rs new file mode 100644 index 0000000000..618ba281de --- /dev/null +++ b/crates/audio/src/pcm_export.rs @@ -0,0 +1,287 @@ +//! Audio-only files: WAV (RIFF, little-endian PCM; RF64 past 4 GiB) and AIFF (big-endian PCM), +//! 16, 24 or 32-bit integer or 32-bit float ([`SampleFormat`]), for streaming export. +//! Float WAV is `WAVE_FORMAT_IEEE_FLOAT` with a `fact` chunk; float AIFF is AIFF-C (`fl32`). +//! +//! The header is written first from the known length (`header`), then the samples in chunks +//! (`encode`) and the pad byte (`pad`), so an export streams to disk instead of building the +//! file in memory. + +/// PCM representation in an exported file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SampleFormat { + /// 16-bit signed integer. + Int16, + /// 24-bit signed integer. + Int24, + /// 32-bit signed integer. + Int32, + /// 32-bit IEEE float. + Float32, +} + +impl SampleFormat { + /// Bits per sample. + pub fn bits(self) -> u16 { + match self { + Self::Int16 => 16, + Self::Int24 => 24, + Self::Int32 | Self::Float32 => 32, + } + } + /// Bytes per sample. + pub fn bytes(self) -> usize { + usize::from(self.bits() / 8) + } + /// Whether this is a floating point format. + pub fn is_float(self) -> bool { + self == Self::Float32 + } + /// Clip and quantize one sample with symmetric integer full scale; NaN becomes silence. + pub fn quantise(self, s: f32) -> i32 { + let s = s.clamp(-1.0, 1.0); + match self { + Self::Int16 => (s * 32_767.0).round() as i32, + Self::Int24 => (s * 8_388_607.0).round() as i32, + Self::Int32 => (f64::from(s) * 2_147_483_647.0).round() as i32, + Self::Float32 => 0, + } + } + /// Sanitize a floating sample: NaN becomes silence, infinity becomes the largest finite value. + pub fn float(s: f32) -> f32 { + if s.is_nan() { 0.0 } else { s.clamp(f32::MIN, f32::MAX) } + } +} + +/// The container of an audio-only export. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PcmContainer { + /// RIFF/WAVE or RF64. + Wav, + /// AIFF or AIFF-C. + Aiff, +} + +/// Bytes of sample data for `frames` frames, or None when that does not fit 64 bits. +fn data_len(frames: u64, channels: u16, format: SampleFormat) -> Option { + frames.checked_mul(u64::from(channels))?.checked_mul(format.bytes() as u64) +} + +/// The pad byte after an odd-sized data chunk (RIFF and AIFF chunks are word-aligned). +pub fn pad(frames: u64, channels: u16, format: SampleFormat) -> &'static [u8] { + if data_len(frames, channels, format).is_some_and(|n| n & 1 == 1) { &[0] } else { &[] } +} + +/// `KSDATAFORMAT_SUBTYPE_PCM` / `_IEEE_FLOAT` after their first two bytes (the format tag). +const SUBTYPE_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; + +/// AIFF-C format version 1 (`FVER`). +const AIFC_VERSION_1: u32 = 0xA280_5140; + +/// The AIFF-C compression name of `fl32`, as a Pascal string of even length. +const FL32_NAME: &[u8] = b"\x1532-bit floating point"; + +/// Everything before the samples of a file of `frames` frames. A WAV whose RIFF size would not +/// fit 32 bits (4 GiB: 24-bit 5.1 at 96 kHz after about 41 minutes) is written as RF64 (EBU Tech +/// 3306), with the 64-bit sizes in a `ds64` chunk. AIFF has no 64-bit form, so a longer AIFF is +/// an error naming WAV instead. +pub fn header(container: PcmContainer, channels: u16, sample_rate: u32, format: SampleFormat, frames: u64) -> Result, String> { + let too_long = || "the audio is too long to write".to_string(); + if channels == 0 { + return Err("audio needs at least one channel".into()); + } + if sample_rate == 0 { + return Err("audio needs a sample rate".into()); + } + let bits = format.bits(); + let bps = bits / 8; + let float = format.is_float(); + let data = data_len(frames, channels, format).ok_or_else(too_long)?; + let block_align = channels.checked_mul(bps).ok_or("too many audio channels")?; + match container { + PcmContainer::Wav => { + let byte_rate = + u32::try_from(u64::from(sample_rate) * u64::from(block_align)).map_err(|_| "the audio sample rate is too high".to_string())?; + let ext = channels > 2; + // plain PCM has no cbSize; IEEE float has an empty one + let fmt_len: u32 = if ext { + 40 + } else if float { + 18 + } else { + 16 + }; + // every format but integer PCM has a `fact` chunk (the frame count; RF64: in `ds64`) + let fact_len: u64 = if float { 12 } else { 0 }; + let padded = data.checked_add(data & 1).ok_or_else(too_long)?; + // "WAVE" + fmt chunk + fact chunk + data chunk header + samples + let riff = (4 + 8 + u64::from(fmt_len) + fact_len + 8).checked_add(padded).ok_or_else(too_long)?; + let rf64 = riff > u64::from(u32::MAX); + let mut v = Vec::with_capacity(100); + if rf64 { + const DS64: u64 = 8 + 28; + v.extend_from_slice(b"RF64"); + v.extend_from_slice(&u32::MAX.to_le_bytes()); + v.extend_from_slice(b"WAVEds64"); + v.extend_from_slice(&28u32.to_le_bytes()); + v.extend_from_slice(&riff.checked_add(DS64).ok_or_else(too_long)?.to_le_bytes()); + v.extend_from_slice(&data.to_le_bytes()); + v.extend_from_slice(&frames.to_le_bytes()); + v.extend_from_slice(&0u32.to_le_bytes()); // no table entries + } else { + v.extend_from_slice(b"RIFF"); + v.extend_from_slice(&(riff as u32).to_le_bytes()); + v.extend_from_slice(b"WAVE"); + } + let tag: u16 = if float { 3 } else { 1 }; + v.extend_from_slice(b"fmt "); + v.extend_from_slice(&fmt_len.to_le_bytes()); + v.extend_from_slice(&(if ext { 0xFFFE } else { tag }).to_le_bytes()); + v.extend_from_slice(&channels.to_le_bytes()); + v.extend_from_slice(&sample_rate.to_le_bytes()); + v.extend_from_slice(&byte_rate.to_le_bytes()); + v.extend_from_slice(&block_align.to_le_bytes()); + v.extend_from_slice(&bits.to_le_bytes()); + if ext { + // cbSize, valid bits, channel mask, KSDATAFORMAT_SUBTYPE_PCM / _IEEE_FLOAT + v.extend_from_slice(&22u16.to_le_bytes()); + v.extend_from_slice(&bits.to_le_bytes()); + let mask: u32 = if channels == 6 { 0x3F } else { 0 }; + v.extend_from_slice(&mask.to_le_bytes()); + v.extend_from_slice(&tag.to_le_bytes()); + v.extend_from_slice(&SUBTYPE_TAIL); + } else if float { + v.extend_from_slice(&0u16.to_le_bytes()); + } + if float { + v.extend_from_slice(b"fact"); + v.extend_from_slice(&4u32.to_le_bytes()); + v.extend_from_slice(&(if rf64 { u32::MAX } else { u32::try_from(frames).unwrap_or(u32::MAX) }).to_le_bytes()); + } + v.extend_from_slice(b"data"); + v.extend_from_slice(&(if rf64 { u32::MAX } else { data as u32 }).to_le_bytes()); + Ok(v) + } + PcmContainer::Aiff => { + let aiff_too_long = || "AIFF holds at most 4 GB of audio: export WAV, which has no such limit".to_string(); + let frames32 = u32::try_from(frames).map_err(|_| aiff_too_long())?; + // SSND: offset + block size + samples + let ssnd = u32::try_from(data.checked_add(8).ok_or_else(aiff_too_long)?).map_err(|_| aiff_too_long())?; + // floats need AIFF-C: a version chunk, and the compression type and name in COMM + let comm: u32 = if float { 18 + 4 + FL32_NAME.len() as u32 } else { 18 }; + let fver: u32 = if float { 8 + 4 } else { 0 }; + let form = (4u32 + fver + (8 + comm)) + .checked_add(8) + .and_then(|n| n.checked_add(ssnd)) + .and_then(|n| n.checked_add(ssnd & 1)) + .ok_or_else(aiff_too_long)?; + let mut v = Vec::with_capacity(90); + v.extend_from_slice(b"FORM"); + v.extend_from_slice(&form.to_be_bytes()); + if float { + v.extend_from_slice(b"AIFCFVER"); + v.extend_from_slice(&4u32.to_be_bytes()); + v.extend_from_slice(&AIFC_VERSION_1.to_be_bytes()); + } else { + v.extend_from_slice(b"AIFF"); + } + v.extend_from_slice(b"COMM"); + v.extend_from_slice(&comm.to_be_bytes()); + v.extend_from_slice(&channels.to_be_bytes()); + v.extend_from_slice(&frames32.to_be_bytes()); + v.extend_from_slice(&bits.to_be_bytes()); + v.extend_from_slice(&extended(sample_rate)); + if float { + v.extend_from_slice(b"fl32"); + v.extend_from_slice(FL32_NAME); + } + v.extend_from_slice(b"SSND"); + v.extend_from_slice(&ssnd.to_be_bytes()); + v.extend_from_slice(&0u32.to_be_bytes()); // offset + v.extend_from_slice(&0u32.to_be_bytes()); // block size + Ok(v) + } + } +} + +/// Append interleaved samples in `format` (little-endian for WAV, big-endian for AIFF). +pub fn encode(container: PcmContainer, interleaved: &[f32], format: SampleFormat, out: &mut Vec) { + let bps = format.bytes(); + out.reserve(interleaved.len().saturating_mul(bps)); + for &s in interleaved { + let q = if format.is_float() { SampleFormat::float(s).to_bits() as i32 } else { format.quantise(s) }; + match container { + PcmContainer::Wav => out.extend_from_slice(q.to_le_bytes().get(..bps).unwrap_or_default()), + PcmContainer::Aiff => out.extend_from_slice(q.to_be_bytes().get(4 - bps..).unwrap_or_default()), + } + } +} + +/// A whole file in memory (short audio; exports stream with [`header`] and [`encode`]). +fn write_whole(container: PcmContainer, interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result, String> { + let per_frame = usize::from(channels.max(1)); + if !interleaved.len().is_multiple_of(per_frame) { + return Err("the samples do not make whole frames".into()); + } + let frames = (interleaved.len() / per_frame) as u64; + let mut v = header(container, channels, sample_rate, format, frames)?; + encode(container, interleaved, format, &mut v); + v.extend_from_slice(pad(frames, channels, format)); + Ok(v) +} + +/// A RIFF/WAVE file of interleaved samples. More than two channels are written as +/// `WAVE_FORMAT_EXTENSIBLE` with the speaker mask of the layout (6 channels: L, R, C, LFE, Ls, Rs +/// = `0x3F`). +pub fn write_wav(interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result, String> { + write_whole(PcmContainer::Wav, interleaved, channels, sample_rate, format) +} + +/// IEEE 754 80-bit extended encoding of a sample rate (AIFF `COMM`). +pub fn extended(rate: u32) -> [u8; 10] { + let mut out = [0u8; 10]; + if rate == 0 { + return out; + } + let shift = rate.leading_zeros(); + let mant = (rate as u64) << (32 + shift); + let exp = 16383 + 31 - shift as u16; + out[..2].copy_from_slice(&exp.to_be_bytes()); + out[2..].copy_from_slice(&mant.to_be_bytes()); + out +} + +/// An AIFF file (`FORM`/`AIFF`, `COMM` + `SSND`; AIFF-C for floats) of interleaved samples. +pub fn write_aiff(interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result, String> { + write_whole(PcmContainer::Aiff, interleaved, channels, sample_rate, format) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn streaming_formats_preserve_samples_and_bounds() { + let samples = [1.0, -1.0, f32::NAN]; + let wav = write_wav(&samples, 1, 48_000, SampleFormat::Int24).unwrap(); + assert_eq!(&wav[..4], b"RIFF"); + assert_eq!(&wav[44..53], &[255, 255, 127, 1, 0, 128, 0, 0, 0]); + let h = header(PcmContainer::Wav, 6, 96_000, SampleFormat::Int24, 96_000 * 3600).unwrap(); + assert_eq!(&h[..4], b"RF64"); + assert!(header(PcmContainer::Aiff, 2, 48_000, SampleFormat::Int24, u64::MAX).is_err()); + let aiff = write_aiff(&[0.25, -3.0], 1, 44_100, SampleFormat::Float32).unwrap(); + assert_eq!(&aiff[8..12], b"AIFC"); + assert_eq!(&aiff[aiff.len() - 8..], [0.25f32.to_be_bytes(), (-3.0f32).to_be_bytes()].concat()); + } + + #[test] + fn zero_channels_rates_and_partial_frames_are_refused() { + for container in [PcmContainer::Wav, PcmContainer::Aiff] { + assert!(header(container, 0, 48_000, SampleFormat::Int16, 1).is_err()); + assert!(header(container, 1, 0, SampleFormat::Int16, 1).is_err()); + assert!(header(container, 2, 48_000, SampleFormat::Int16, 0).is_ok(), "zero frames stay valid"); + } + assert!(write_wav(&[0.5], 0, 48_000, SampleFormat::Int16).is_err()); + assert!(write_wav(&[0.1, 0.2, 0.3], 2, 48_000, SampleFormat::Int16).is_err()); + assert!(write_aiff(&[0.1, 0.2, 0.3], 2, 48_000, SampleFormat::Int16).is_err()); + assert!(write_aiff(&[0.1, 0.2], 2, 48_000, SampleFormat::Int16).is_ok()); + } +} diff --git a/crates/audio/src/pcm_interleaved.rs b/crates/audio/src/pcm_interleaved.rs new file mode 100644 index 0000000000..f08c19202f --- /dev/null +++ b/crates/audio/src/pcm_interleaved.rs @@ -0,0 +1,96 @@ +//! Interleaved PCM packet decoding into caller-owned planar channels. + +/// The sample representation in an interleaved PCM packet. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Format { + /// Bits per sample. + pub bits: u16, + /// IEEE floating-point samples. + pub float: bool, + /// Big-endian sample bytes. + pub big_endian: bool, + /// Signed 8-bit integers (wider integer PCM is signed). + pub signed: bool, +} + +/// Append complete interleaved frames to caller-owned planar channels. Empty channel slices and +/// zero-bit formats append nothing. Incomplete frames are ignored; unsupported widths produce +/// silent samples, matching the container adapters that use this API. +pub fn decode_into(data: &[u8], cfg: Format, out: &mut [Vec]) { + let ch = out.len(); + if cfg.bits == 0 || ch == 0 { + return; + } + let bps = usize::from(cfg.bits).div_ceil(8); + let Some(frame_bytes) = bps.checked_mul(ch).filter(|&n| n > 0) else { return }; + let n = data.len() / frame_bytes; + for channel in out.iter_mut() { + channel.reserve(n); + } + // `n` is whole frames within `data`, so every sample slice below is in bounds. + for i in 0..n { + for (c, o) in out.iter_mut().enumerate() { + let off = (i * ch + c) * bps; + let b = &data[off..off + bps]; + let v = match (cfg.bits, cfg.float, cfg.big_endian) { + (32, true, false) => f32::from_le_bytes([b[0], b[1], b[2], b[3]]), + (32, true, true) => f32::from_be_bytes([b[0], b[1], b[2], b[3]]), + (64, true, false) => f64::from_le_bytes(b.try_into().unwrap_or([0; 8])) as f32, + (64, true, true) => f64::from_be_bytes(b.try_into().unwrap_or([0; 8])) as f32, + (8, _, _) => { + if cfg.signed { + b[0] as i8 as f32 / 128.0 + } else { + (b[0] as f32 - 128.0) / 128.0 + } + } + (16, _, false) => i16::from_le_bytes([b[0], b[1]]) as f32 / 32768.0, + (16, _, true) => i16::from_be_bytes([b[0], b[1]]) as f32 / 32768.0, + (24, _, false) => (i32::from_le_bytes([0, b[0], b[1], b[2]]) >> 8) as f32 / 8_388_608.0, + (24, _, true) => (i32::from_be_bytes([b[0], b[1], b[2], 0]) >> 8) as f32 / 8_388_608.0, + (32, false, false) => i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2_147_483_648.0, + (32, false, true) => i32::from_be_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2_147_483_648.0, + _ => 0.0, + }; + o.push(v); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn decodes_endian_and_interleaving_without_touching_partial_frames() { + let mut channels = vec![Vec::new(), Vec::new()]; + let fmt = Format { bits: 16, float: false, big_endian: true, signed: true }; + decode_into(&[0x40, 0, 0xc0, 0, 0xff], fmt, &mut channels); + assert_eq!(channels, [vec![0.5], vec![-0.5]]); + decode_into(&[0; 8], Format { bits: 0, ..fmt }, &mut channels); + assert_eq!(channels, [vec![0.5], vec![-0.5]]); + } + #[test] + fn decodes_sample_representations_and_ignores_invalid_inputs() { + let base = Format { bits: 8, float: false, big_endian: false, signed: false }; + let cases: &[(Format, &[u8], f32)] = &[ + (base, &[192], 0.5), + (Format { signed: true, ..base }, &[192], -0.5), + (Format { bits: 16, ..base }, &[0, 64], 0.5), + (Format { bits: 24, ..base }, &[0, 0, 64], 0.5), + (Format { bits: 24, big_endian: true, ..base }, &[0xc0, 0, 0], -0.5), + (Format { bits: 32, ..base }, &[0, 0, 0, 64], 0.5), + (Format { bits: 32, big_endian: true, ..base }, &[0xc0, 0, 0, 0], -0.5), + (Format { bits: 32, float: true, ..base }, &0.5_f32.to_le_bytes(), 0.5), + (Format { bits: 32, float: true, big_endian: true, ..base }, &(-0.5_f32).to_be_bytes(), -0.5), + (Format { bits: 64, float: true, ..base }, &0.5_f64.to_le_bytes(), 0.5), + (Format { bits: 64, float: true, big_endian: true, ..base }, &(-0.5_f64).to_be_bytes(), -0.5), + (Format { bits: 12, ..base }, &[0xff, 0xff], 0.0), + ]; + for &(format, bytes, expected) in cases { + let mut out = [vec![1.0]]; + decode_into(bytes, format, &mut out); + assert_eq!(out[0], [1.0, expected], "{format:?}"); + } + decode_into(&[1], base, &mut []); + } +} diff --git a/crates/audio/src/qoa.rs b/crates/audio/src/qoa.rs new file mode 100644 index 0000000000..a044301378 --- /dev/null +++ b/crates/audio/src/qoa.rs @@ -0,0 +1,411 @@ +//! QOA ("Quite OK Audio"): a decoder (feature `qoa-decode`) and an encoder (feature `qoa-encode`) +//! for whole `.qoa` files, 16-bit, 1 to 8 channels. +//! +//! Written from the published QOA specification (qoaformat.org). A file is an 8-byte header (the +//! magic `qoaf` and the number of samples per channel) followed by frames of up to 5120 samples +//! per channel. Each frame starts with its channel count, sample rate, sample count and size, then +//! the state of one 4-tap sign-sign LMS predictor per channel, then 64-bit slices of 20 samples: +//! a 4-bit scale factor and twenty 3-bit quantised residuals, the channels interleaved slice by +//! slice. +//! +//! Streaming files (a sample count of 0 in the header) are not supported. +//! Samples are `i16`, one `Vec` per channel. + +#[cfg(feature = "qoa-decode")] +const MAX_FRAME_SAMPLES: usize = 5120; +const SLICE_SAMPLES: usize = 20; +const LMS_LEN: usize = 4; +const MAGIC: &[u8; 4] = b"qoaf"; +/// The most channels a file may have. +pub const MAX_CHANNELS: usize = 8; + +/// `dequant[scale factor][quantised residual]`: `round(round((sf + 1)^2.75) * [0.75, -0.75, 2.5, +/// -2.5, 4.5, -4.5, 7, -7])`. +const DEQUANT: [[i32; 8]; 16] = [ + [1, -1, 3, -3, 5, -5, 7, -7], + [5, -5, 18, -18, 32, -32, 49, -49], + [16, -16, 53, -53, 95, -95, 147, -147], + [34, -34, 113, -113, 203, -203, 315, -315], + [63, -63, 210, -210, 378, -378, 588, -588], + [104, -104, 345, -345, 621, -621, 966, -966], + [158, -158, 528, -528, 950, -950, 1477, -1477], + [228, -228, 760, -760, 1368, -1368, 2128, -2128], + [316, -316, 1053, -1053, 1895, -1895, 2947, -2947], + [422, -422, 1405, -1405, 2529, -2529, 3934, -3934], + [548, -548, 1828, -1828, 3290, -3290, 5117, -5117], + [696, -696, 2320, -2320, 4176, -4176, 6496, -6496], + [868, -868, 2893, -2893, 5207, -5207, 8099, -8099], + [1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933], + [1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005], + [1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336], +]; + +/// What went wrong reading or writing a QOA file. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + /// The input is not a QOA file, or is damaged or truncated. + #[error("malformed QOA: {0}")] + Malformed(&'static str), + /// A valid file this module does not handle (a streaming file). + #[error("unsupported QOA: {0}")] + Unsupported(&'static str), + /// The samples or settings given to the encoder cannot be written as QOA. + #[error("QOA cannot encode: {0}")] + InvalidInput(&'static str), +} + +/// A decoded file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Audio { + /// Sample rate in Hz (1 to 16 777 215). + pub sample_rate: u32, + /// One `Vec` of samples per channel, all the same length. + pub channels: Vec>, +} + +/// The predictor: the last four samples and four weights. +#[derive(Clone, Copy)] +struct Lms { + history: [i32; LMS_LEN], + weights: [i32; LMS_LEN], +} + +impl Lms { + fn new() -> Self { + Lms { history: [0; LMS_LEN], weights: [0, 0, -(1 << 13), 1 << 14] } + } + + fn predict(&self) -> i32 { + let mut p = 0i32; + for i in 0..LMS_LEN { + p = p.wrapping_add(self.weights[i].wrapping_mul(self.history[i])); + } + p >> 13 + } + + fn update(&mut self, sample: i32, residual: i32) { + let delta = residual >> 4; + for i in 0..LMS_LEN { + self.weights[i] += if self.history[i] < 0 { -delta } else { delta }; + } + self.history.copy_within(1.., 0); + self.history[LMS_LEN - 1] = sample; + } +} + +fn clamp16(v: i32) -> i32 { + v.clamp(-32768, 32767) +} + +#[cfg(feature = "qoa-decode")] +mod decode { + use super::{Audio, DEQUANT, Error, LMS_LEN, Lms, MAGIC, MAX_CHANNELS, MAX_FRAME_SAMPLES, SLICE_SAMPLES, clamp16}; + + fn be16(b: &[u8], i: usize) -> u16 { + u16::from_be_bytes([b[i], b[i + 1]]) + } + + /// Decode a whole `.qoa` file. + /// + /// The declared length is checked against the input before anything is allocated: a slice of + /// 8 bytes holds at most 20 samples, so a file cannot declare more samples than that. + pub fn decode(bytes: &[u8]) -> Result { + if bytes.len() < 8 || &bytes[..4] != MAGIC { + return Err(Error::Malformed("missing the qoaf magic")); + } + let total = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize; + if total == 0 { + return Err(Error::Unsupported("streaming files (a sample count of 0)")); + } + if bytes.len() < 16 { + return Err(Error::Malformed("truncated frame header")); + } + let channels = usize::from(bytes[8]); + let sample_rate = u32::from_be_bytes([0, bytes[9], bytes[10], bytes[11]]); + if channels == 0 || channels > MAX_CHANNELS || sample_rate == 0 { + return Err(Error::Malformed("bad channel count or sample rate")); + } + // 8 bytes (20 samples) per channel at the very least, plus the frame headers. + let room = (bytes.len() - 8) / (8 * channels) * SLICE_SAMPLES; + if total > room { + return Err(Error::Malformed("the file is too short for its declared length")); + } + let mut out: Vec> = Vec::new(); + for _ in 0..channels { + let mut v = Vec::new(); + v.try_reserve_exact(total).map_err(|_| Error::Malformed("too many samples"))?; + out.push(v); + } + let mut pos = 8; + let mut done = 0usize; + while done < total { + let head = bytes.get(pos..pos + 8).ok_or(Error::Malformed("truncated frame header"))?; + let rate = u32::from_be_bytes([0, head[1], head[2], head[3]]); + if usize::from(head[0]) != channels || rate != sample_rate { + return Err(Error::Malformed("the channel count or sample rate changes between frames")); + } + let samples = usize::from(be16(head, 4)); + let size = usize::from(be16(head, 6)); + let slices = samples.div_ceil(SLICE_SAMPLES); + if samples == 0 || samples > MAX_FRAME_SAMPLES || samples > total - done { + return Err(Error::Malformed("bad frame sample count")); + } + if size != 8 + 16 * channels + 8 * slices * channels { + return Err(Error::Malformed("frame size does not match its sample count")); + } + let frame = bytes.get(pos..pos + size).ok_or(Error::Malformed("truncated frame"))?; + let mut lms = [Lms::new(); MAX_CHANNELS]; + for (c, state) in lms.iter_mut().take(channels).enumerate() { + let at = 8 + c * 16; + for i in 0..LMS_LEN { + state.history[i] = i32::from(be16(frame, at + 2 * i) as i16); + state.weights[i] = i32::from(be16(frame, at + 8 + 2 * i) as i16); + } + } + let mut at = 8 + 16 * channels; + for s in 0..slices { + let n = (samples - s * SLICE_SAMPLES).min(SLICE_SAMPLES); + for (c, state) in lms.iter_mut().take(channels).enumerate() { + let mut slice = u64::from_be_bytes([ + frame[at], + frame[at + 1], + frame[at + 2], + frame[at + 3], + frame[at + 4], + frame[at + 5], + frame[at + 6], + frame[at + 7], + ]); + at += 8; + let table = &DEQUANT[(slice >> 60) as usize & 15]; + for _ in 0..n { + let dequantised = table[(slice >> 57) as usize & 7]; + slice <<= 3; + let sample = clamp16(state.predict() + dequantised); + out[c].push(sample as i16); + state.update(sample, dequantised); + } + } + } + pos += size; + done += samples; + } + Ok(Audio { sample_rate, channels: out }) + } +} +#[cfg(feature = "qoa-decode")] +pub use decode::decode; + +#[cfg(feature = "qoa-encode")] +mod encode { + use super::{DEQUANT, Error, Lms, MAGIC, MAX_CHANNELS, SLICE_SAMPLES, clamp16}; + + /// The quantised residual (0..8) whose dequantised value is nearest `residual`. + fn quantise(table: &[i32; 8], residual: i32) -> usize { + let mut best = 0; + let mut best_err = i64::MAX; + for (q, &d) in table.iter().enumerate() { + let e = i64::from(residual - d).pow(2); + if e < best_err { + best = q; + best_err = e; + } + } + best + } + + /// Encode one slice of one channel with every scale factor and keep the one with the least + /// squared error. Returns the 64-bit slice; `lms` is advanced to the chosen result. + fn encode_slice(lms: &mut Lms, samples: &[i16]) -> u64 { + let mut best: Option<(i64, u64, Lms)> = None; + for (sf, table) in DEQUANT.iter().enumerate() { + let mut trial = *lms; + let mut slice = sf as u64; + let mut err = 0i64; + for k in 0..SLICE_SAMPLES { + let mut q = 0; + if let Some(&s) = samples.get(k) { + let predicted = trial.predict(); + q = quantise(table, i32::from(s) - predicted); + let sample = clamp16(predicted + table[q]); + err += i64::from(i32::from(s) - sample).pow(2); + trial.update(sample, table[q]); + } + slice = slice << 3 | q as u64; + } + // 4 + 60 bits are in `slice`; the scale factor belongs on top. + let slice = slice & ((1 << 60) - 1) | (sf as u64) << 60; + if best.as_ref().is_none_or(|b| err < b.0) { + best = Some((err, slice, trial)); + } + } + match best { + Some((_, slice, state)) => { + *lms = state; + slice + } + None => 0, + } + } + + /// Encode `channels` (one `Vec` of samples per channel, all the same length) as a `.qoa` file. + pub fn encode(sample_rate: u32, channels: &[Vec]) -> Result, Error> { + let n = channels.len(); + if n == 0 || n > MAX_CHANNELS { + return Err(Error::InvalidInput("QOA stores 1 to 8 channels")); + } + if sample_rate == 0 || sample_rate > 0x00ff_ffff { + return Err(Error::InvalidInput("the sample rate must be 1 to 16777215 Hz")); + } + let total = channels[0].len(); + if channels.iter().any(|c| c.len() != total) { + return Err(Error::InvalidInput("the channels differ in length")); + } + let total32 = u32::try_from(total).map_err(|_| Error::InvalidInput("too many samples"))?; + if total == 0 { + return Err(Error::InvalidInput("QOA cannot store an empty file")); + } + let mut out = Vec::with_capacity(8 + total * n / 2); + out.extend_from_slice(MAGIC); + out.extend_from_slice(&total32.to_be_bytes()); + let mut lms = [Lms::new(); MAX_CHANNELS]; + let mut start = 0; + while start < total { + let len = (total - start).min(5120); + let slices = len.div_ceil(SLICE_SAMPLES); + let size = 8 + 16 * n + 8 * slices * n; + out.push(n as u8); + out.extend_from_slice(&sample_rate.to_be_bytes()[1..]); + out.extend_from_slice(&(len as u16).to_be_bytes()); + out.extend_from_slice(&(size as u16).to_be_bytes()); + // The state a frame starts from is written as 16-bit values, so the predictor + // continues from exactly what a decoder reads. + for state in lms.iter_mut().take(n) { + for v in state.history.iter_mut().chain(state.weights.iter_mut()) { + *v = i32::from(*v as i16); + out.extend_from_slice(&(*v as i16).to_be_bytes()); + } + } + for s in 0..slices { + let from = start + s * SLICE_SAMPLES; + let to = (from + SLICE_SAMPLES).min(start + len); + for (c, state) in lms.iter_mut().take(n).enumerate() { + out.extend_from_slice(&encode_slice(state, &channels[c][from..to]).to_be_bytes()); + } + } + start += len; + } + Ok(out) + } +} +#[cfg(feature = "qoa-encode")] +pub use encode::encode; + +#[cfg(all(test, feature = "qoa-decode", feature = "qoa-encode"))] +mod tests { + use super::*; + + fn tone(frames: usize, ch: usize) -> Vec> { + (0..ch) + .map(|c| (0..frames).map(|i| (((i as f64) * (0.03 + 0.01 * c as f64)).sin() * 12000.0 + ((i * 7919) % 200) as f64) as i16).collect()) + .collect() + } + + fn snr(a: &[i16], b: &[i16]) -> f64 { + let (mut s, mut e) = (0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + s += f64::from(x).powi(2); + e += (f64::from(x) - f64::from(y)).powi(2); + } + 10.0 * (s / e.max(1.0)).log10() + } + + #[test] + fn dequant_table_matches_its_formula() { + for (sf, row) in DEQUANT.iter().enumerate() { + let scale = ((sf as f64 + 1.0).powf(2.75)).round(); + for (q, base) in [0.75, -0.75, 2.5, -2.5, 4.5, -4.5, 7.0, -7.0].into_iter().enumerate() { + assert_eq!(f64::from(row[q]), (scale * base).round(), "sf {sf} q {q}"); + } + } + } + + #[test] + fn round_trips_with_a_good_signal_to_noise_ratio() { + for (frames, ch) in [(1, 1), (19, 2), (20, 1), (21, 2), (5120, 1), (5121, 2), (12_345, 8)] { + let src = tone(frames, ch); + let bytes = encode(44_100, &src).unwrap(); + let back = decode(&bytes).unwrap(); + assert_eq!((back.sample_rate, back.channels.len(), back.channels[0].len()), (44_100, ch, frames)); + if frames > 1000 { + for (c, (a, b)) in src.iter().zip(&back.channels).enumerate() { + assert!(snr(a, b) > 25.0, "{frames}x{ch} channel {c}"); + } + } + } + } + + #[test] + fn silence_and_full_scale_extremes_survive() { + let silent = vec![vec![0i16; 3000]]; + // No residual value is zero, so silence decodes to a tiny residue, never exactly 0. + let quiet = decode(&encode(8000, &silent).unwrap()).unwrap(); + assert!(quiet.channels[0].iter().all(|&s| s.abs() <= 2), "silence stays within 2 LSB"); + let square: Vec = (0..4000).map(|i| if (i / 50) % 2 == 0 { i16::MAX } else { i16::MIN }).collect(); + let back = decode(&encode(48_000, std::slice::from_ref(&square)).unwrap()).unwrap(); + assert_eq!(back.channels[0].len(), square.len()); + } + + #[test] + fn the_file_has_the_documented_layout() { + let bytes = encode(48_000, &tone(100, 2)).unwrap(); + assert_eq!(&bytes[..4], b"qoaf"); + assert_eq!(u32::from_be_bytes(bytes[4..8].try_into().unwrap()), 100); + assert_eq!(bytes[8], 2); + assert_eq!(&bytes[9..12], &48_000u32.to_be_bytes()[1..]); + assert_eq!(u16::from_be_bytes([bytes[12], bytes[13]]), 100); + // 8 header + 2 channels * 16 state + 5 slices * 2 channels * 8 + assert_eq!(usize::from(u16::from_be_bytes([bytes[14], bytes[15]])), 8 + 32 + 80); + assert_eq!(bytes.len(), 8 + 8 + 32 + 80); + // The first frame starts from the specified predictor state. + assert_eq!(&bytes[16 + 8..16 + 16], &[0, 0, 0, 0, 0xe0, 0, 0x40, 0]); + } + + #[test] + fn invalid_input_to_the_encoder_is_refused() { + assert!(encode(44_100, &[]).is_err()); + assert!(encode(0, &[vec![0; 10]]).is_err()); + assert!(encode(1 << 24, &[vec![0; 10]]).is_err()); + assert!(encode(44_100, &[vec![0; 10], vec![0; 9]]).is_err()); + assert!(encode(44_100, &[vec![]]).is_err()); + assert!(encode(44_100, &vec![vec![0; 10]; 9]).is_err()); + } + + #[test] + fn hostile_input_is_an_error_not_a_panic() { + let good = encode(44_100, &tone(6000, 2)).unwrap(); + for len in 0..good.len().min(600) { + let _ = decode(&good[..len]); + } + assert!(decode(&good[..good.len() - 1]).is_err()); + // A header that declares more samples than the bytes can hold. + let mut huge = good.clone(); + huge[4..8].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(decode(&huge).is_err()); + // A streaming file, and a frame whose size field lies. + let mut streaming = good.clone(); + streaming[4..8].fill(0); + assert_eq!(decode(&streaming), Err(Error::Unsupported("streaming files (a sample count of 0)"))); + let mut lying = good.clone(); + lying[14] ^= 1; + assert!(decode(&lying).is_err()); + let mut zero_rate = good.clone(); + zero_rate[9..12].fill(0); + assert!(decode(&zero_rate).is_err()); + let mut changed = good; + let second = 8 + usize::from(u16::from_be_bytes([changed[14], changed[15]])); + changed[second] = 1; + assert!(decode(&changed).is_err()); + } +} diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index bd9c2301ac..c1552d7e29 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -115,6 +115,50 @@ fn parse_bext(c: &[u8]) -> Option { }) } +/// Cap optional metadata independently of audio length, including on range-backed sources. +const IXML_MAX: usize = 1 << 20; + +/// iXML's BEXT mirror is a fallback only: a real `bext` always wins, including timestamp zero. +/// Read the two unsigned 32-bit words, not arbitrary text that merely contains their tag names. +fn ixml_time_reference(bytes: &[u8]) -> Option { + let options = craft_xml::Options { + doctype: craft_xml::Doctype::Reject, + ..craft_xml::Options::default().strict().with_limits(craft_xml::Limits { + max_input: IXML_MAX, + max_depth: 32, + max_nodes: 8192, + max_attrs: 64, + max_attrs_total: 8192, + ..craft_xml::Limits::default() + }) + }; + let root = options.parse(bytes).ok()?; + if root.name != "BWFXML" { + return None; + } + let mut bexts = root.children("BEXT"); + let bext = bexts.next()?; + if bexts.next().is_some() { + return None; + } + let word = |name: &str| -> Option> { + let mut fields = bext.children(name); + let Some(field) = fields.next() else { return Some(None) }; + if fields.next().is_some() || field.children.iter().any(|n| matches!(n, craft_xml::Node::El(_))) { + return None; + } + let text = field.text(); + let text = text.trim(); + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + Some(Some(text.parse().ok()?)) + }; + let low = word("BWF_TIME_REFERENCE_LOW")??; + let high = word("BWF_TIME_REFERENCE_HIGH")?.unwrap_or(0); + Some((u64::from(high) << 32) | u64::from(low)) +} + /// Refuse the WAVE file at `at`, which symphonia reads (A-law, ADPCM, ...), if an INFO entry /// claims more bytes than the file holds: symphonia allocates each entry's length. Chunks are /// walked where symphonia reads them: after the bytes a chunk's parser used, not its length. @@ -239,7 +283,7 @@ fn pcm_layout(fmt: &Fmt) -> Result> { } /// Parse a WAV file's chunks: its format, `bext` metadata and where its samples are. Only chunk -/// headers and the small `fmt `, `bext` and `ds64` bodies are read. +/// headers, small `fmt `, `bext` and `ds64` bodies, and at most one 1 MiB iXML document are read. pub(crate) fn parse(src: &Src<'_>) -> Result { if !is_wav(&src.bytes_upto(0, 12)) { return Err(AudioError::Malformed("not a RIFF/RF64 WAVE file".into())); @@ -249,6 +293,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { let mut ds64_data: Option = None; let mut fmt: Option = None; let mut bwf: Option = None; + let mut ixml_time = None; + let mut ixml_seen = false; let mut data: Option<(u64, u64)> = None; let mut pos: u64 = 12; @@ -288,7 +334,18 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { let small = |n: u64| src.bytes(body, usize::try_from(declared.min(n)).unwrap_or(0)).unwrap_or_default(); match &id { b"fmt " => fmt = Some(parse_fmt(&small(256))?), - b"bext" => bwf = parse_bext(&small(4096)), + b"bext" => { + if let Some(info) = parse_bext(&small(4096)) { + bwf = Some(info); + } + } + b"iXML" if !ixml_seen => { + // Inspect at most one bounded document, not 100,000 individually bounded trees. + ixml_seen = true; + if declared <= IXML_MAX as u64 { + ixml_time = ixml_time_reference(&small(IXML_MAX as u64)); + } + } b"ds64" => ds64_data = le_u64(&small(64), 8), _ => {} } @@ -297,6 +354,9 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { pos = next; } + if bwf.is_none() { + bwf = ixml_time.map(|time_reference| BwfInfo { time_reference, ..BwfInfo::default() }); + } let fmt = fmt.ok_or_else(|| AudioError::Malformed("WAV has no fmt chunk".into()))?; if fmt.channels == 0 { return Err(AudioError::Malformed("WAV declares zero channels".into())); diff --git a/crates/audio/src/vorbis/encoder/book.rs b/crates/audio/src/vorbis/encoder/book.rs new file mode 100644 index 0000000000..b392cf27c9 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/book.rs @@ -0,0 +1,287 @@ +//! Bit packing (Vorbis I §2) and codebooks (§3): Huffman lengths, the codeword assignment the +//! decoder derives from them, VQ lattices (lookup type 1) and the header encoding. + +use super::{Error, Result}; + +/// LSB-first bit packer (Vorbis I §2.1.4): bits fill each byte from its least significant end. +#[derive(Clone, Debug, Default)] +pub struct BitWriter { + buf: Vec, + bits: u64, +} + +impl BitWriter { + pub fn new() -> BitWriter { + BitWriter::default() + } + + /// Writes the low `n` bits of `v` (`n` ≤ 32). + pub fn write(&mut self, v: u32, n: u32) { + let n = n.min(32); + for i in 0..n { + let bit = (v >> i) & 1; + let at = (self.bits / 8) as usize; + if at == self.buf.len() { + self.buf.push(0); + } + if bit != 0 + && let Some(b) = self.buf.get_mut(at) + { + *b |= 1 << (self.bits % 8); + } + self.bits += 1; + } + } + + pub fn flag(&mut self, b: bool) { + self.write(b as u32, 1); + } + + /// Writes a codeword MSB first: the decoder walks the tree from its first bit. + fn codeword(&mut self, word: u32, len: u32) { + for i in (0..len).rev() { + self.write((word >> i) & 1, 1); + } + } + + pub fn bytes(&mut self, data: &[u8]) { + for &b in data { + self.write(u32::from(b), 8); + } + } + + pub fn finish(self) -> Vec { + self.buf + } +} + +/// `ilog` of the specification (§9.2.1): the position of the highest set bit, 0 for 0. +pub fn ilog(v: u32) -> u32 { + 32 - v.leading_zeros() +} + +/// The 32-bit float format of codebook headers (§9.2.2), for values it represents exactly. +pub fn float32_pack(v: f64) -> u32 { + if v == 0.0 || !v.is_finite() { + return 0; + } + let sign = if v < 0.0 { 0x8000_0000u32 } else { 0 }; + let mut m = v.abs(); + let mut exp: i32 = 0; + // a 21-bit mantissa: scale into [2^20, 2^21) + while m >= (1 << 21) as f64 { + m /= 2.0; + exp += 1; + } + while m < (1 << 20) as f64 { + m *= 2.0; + exp -= 1; + } + let mant = (m.round() as u32).min((1 << 21) - 1); + let biased = (exp + 788).clamp(0, 1023) as u32; + sign | (biased << 21) | mant +} + +/// Huffman code lengths (1..=`max_len`) for `weights`, every entry coded. +pub fn huffman_lengths(weights: &[f64], max_len: u32) -> Vec { + let n = weights.len(); + if n <= 1 { + return vec![1; n]; + } + let total: f64 = weights.iter().map(|w| if w.is_finite() { w.max(0.0) } else { 0.0 }).sum::().max(1e-300); + let mut floor = 1e-9; + loop { + let w: Vec = weights.iter().map(|&x| (if x.is_finite() { x.max(0.0) } else { 0.0 }) / total + floor).collect(); + let lens = huffman(&w); + if lens.iter().all(|&l| l <= max_len) || floor > 1.0 { + return lens.into_iter().map(|l| l.clamp(1, max_len)).collect(); + } + floor *= 4.0; + } +} + +fn huffman(w: &[f64]) -> Vec { + // nodes: (weight, children) with leaves first + let n = w.len(); + let mut parent = vec![usize::MAX; 2 * n]; + let mut weight: Vec = w.to_vec(); + let mut alive: Vec = (0..n).collect(); + while alive.len() > 1 { + alive.sort_by(|&a, &b| weight[b].partial_cmp(&weight[a]).unwrap_or(std::cmp::Ordering::Equal).then(b.cmp(&a))); + let (Some(a), Some(b)) = (alive.pop(), alive.pop()) else { break }; + let id = weight.len(); + weight.push(weight[a] + weight[b]); + if parent.len() <= id { + parent.resize(id + 1, usize::MAX); + } + parent[a] = id; + parent[b] = id; + alive.push(id); + } + (0..n) + .map(|i| { + let mut d = 0; + let mut x = i; + while let Some(&p) = parent.get(x) { + if p == usize::MAX { + break; + } + d += 1; + x = p; + } + d + }) + .collect() +} + +/// The codewords the decoder assigns to `lengths` (§3.2.1): in entry order, each entry gets the +/// lowest available codeword of its length (no prefix of an assigned codeword, and no assigned +/// codeword a prefix of it). An error when the lengths do not fit a prefix code. +pub fn assign_codewords(lengths: &[u32]) -> Result> { + // A trie of the assigned codewords: `children[node]` (0 = none), `leaf[node]`. + let mut children: Vec<[usize; 2]> = vec![[0, 0]]; + let mut leaf = vec![false]; + let mut words = Vec::with_capacity(lengths.len()); + for &len in lengths { + if len == 0 || len > 32 { + return Err(Error::Internal("codeword length")); + } + let bits = lowest_free(&children, &leaf, 0, len).ok_or(Error::Internal("over-subscribed codebook"))?; + let mut node = 0usize; + let mut word = 0u32; + for &bit in &bits { + word = (word << 1) | bit as u32; + node = match children[node][bit] { + 0 => { + children.push([0, 0]); + leaf.push(false); + let id = children.len() - 1; + children[node][bit] = id; + id + } + c => c, + }; + } + leaf[node] = true; + words.push(word); + } + Ok(words) +} + +/// The leftmost free path of `depth` bits below `node` (depth-first, 0 before 1). +fn lowest_free(children: &[[usize; 2]], leaf: &[bool], node: usize, depth: u32) -> Option> { + if leaf[node] || depth == 0 { + return None; + } + for bit in 0..2 { + let c = children[node][bit]; + if c == 0 { + let mut p = vec![bit]; + p.resize(depth as usize, 0); + return Some(p); + } + if let Some(mut rest) = lowest_free(children, leaf, c, depth - 1) { + rest.insert(0, bit); + return Some(rest); + } + } + None +} + +/// A codebook: entry lengths and codewords, and for VQ books a lattice (lookup type 1). +#[derive(Clone, Debug)] +pub struct Codebook { + pub dimensions: u32, + pub lengths: Vec, + pub words: Vec, + /// Lattice values per dimension (lookup type 1: `values^dimensions == entries`). + pub lattice: Option, +} + +#[derive(Clone, Copy, Debug)] +pub struct Lattice { + pub minimum: f64, + pub delta: f64, + /// Values per dimension. + pub values: u32, +} + +impl Codebook { + /// A scalar book (no lookup) of `weights.len()` entries. + pub fn scalar(dimensions: u32, weights: &[f64]) -> Result { + let lengths = huffman_lengths(weights, 20); + let words = assign_codewords(&lengths)?; + Ok(Codebook { dimensions, lengths, words, lattice: None }) + } + + /// A lattice VQ book: `values` integers per dimension from `minimum` in steps of `delta`; + /// `weight(v)` is the relative probability of one component `v`. + pub fn lattice(dimensions: u32, values: u32, minimum: i32, delta: i32, weight: impl Fn(i32) -> f64) -> Result { + let entries = values.checked_pow(dimensions).ok_or(Error::Internal("codebook size"))?; + let w: Vec = (0..entries) + .map(|e| { + let mut p = 1.0; + let mut rest = e; + for _ in 0..dimensions { + let t = (rest % values) as i32; + rest /= values; + p *= weight(minimum + t * delta); + } + p + }) + .collect(); + let lengths = huffman_lengths(&w, 20); + let words = assign_codewords(&lengths)?; + Ok(Codebook { dimensions, lengths, words, lattice: Some(Lattice { minimum: f64::from(minimum), delta: f64::from(delta), values }) }) + } + + pub fn entries(&self) -> usize { + self.lengths.len() + } + + /// Writes entry `e`. + pub fn put(&self, w: &mut BitWriter, e: usize) { + if let (Some(&word), Some(&len)) = (self.words.get(e), self.lengths.get(e)) { + w.codeword(word, len); + } + } + + /// The entry of the lattice vector `v` (component 0 is the least significant digit, §3.2.1). + pub fn entry_of(&self, v: &[i32]) -> usize { + let Some(l) = self.lattice else { return 0 }; + let mut e = 0usize; + let mut scale = 1usize; + for &x in v.iter().take(self.dimensions as usize) { + let t = ((f64::from(x) - l.minimum) / l.delta).round().clamp(0.0, f64::from(l.values - 1)) as usize; + e += t * scale; + scale *= l.values as usize; + } + e + } + + /// The header encoding (§3.2.1). + pub fn write_header(&self, w: &mut BitWriter) { + w.write(0x56_4342, 24); + w.write(self.dimensions, 16); + w.write(self.entries() as u32, 24); + w.flag(false); // not ordered + w.flag(false); // not sparse + for &l in &self.lengths { + w.write(l - 1, 5); + } + match self.lattice { + None => w.write(0, 4), + Some(l) => { + w.write(1, 4); + w.write(float32_pack(l.minimum), 32); + w.write(float32_pack(l.delta), 32); + let bits = ilog(l.values - 1).max(1); + w.write(bits - 1, 4); + w.flag(false); // sequence_p + for m in 0..l.values { + w.write(m, bits); + } + } + } + } +} diff --git a/crates/audio/src/vorbis/encoder/floor.rs b/crates/audio/src/vorbis/encoder/floor.rs new file mode 100644 index 0000000000..503385bd37 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/floor.rs @@ -0,0 +1,207 @@ +//! Floor type 1 (Vorbis I §7): a piecewise-linear spectral envelope in the decoder's dB scale. +//! +//! The encoder picks a target value at each of the floor's X positions, codes it against the +//! decoder's prediction from its neighbours (step 2 of §7.2.4, inverted), and renders the curve +//! exactly as the decoder will (`render_line`, integer arithmetic), so the residue is computed +//! against the very floor the decoder multiplies it by. + +use super::book::{BitWriter, Codebook, ilog}; + +/// `floor1_multiplier`: 2, so values run 0..128 and step two entries of the dB table. +pub const MULTIPLIER: u32 = 2; +/// The value range for [`MULTIPLIER`] 2. +pub const RANGE: i32 = 128; +const RANGE_BITS: u32 = 10; +/// Points per partition, and partitions. +pub const CLASS_DIM: usize = 4; +pub const PARTITIONS: usize = 8; + +/// Step (in dB) between entries of `floor1_inverse_dB_table`: it runs from 1.0649863e-07 to 1 +/// over 256 entries. +fn db_step() -> f64 { + (1.0f64 / 1.064_986_3e-7).ln() / 255.0 +} + +/// `floor1_inverse_dB_table[i]`. +pub fn inverse_db(i: i32) -> f32 { + (f64::from(i.clamp(0, 255) - 255) * db_step()).exp() as f32 +} + +/// The table index whose amplitude is nearest (in dB) to `a`. +pub fn db_index(a: f32) -> i32 { + if !a.is_finite() || a <= 0.0 { + return 0; + } + ((f64::from(a)).ln() / db_step() + 255.0).round().clamp(0.0, 255.0) as i32 +} + +/// A floor 1 configuration for blocks of `n/2 = 2^RANGE_BITS` bins. +#[derive(Clone, Debug)] +pub struct Floor1 { + /// X positions: 0, 1024, then the partitions' points. + pub xs: Vec, + /// Index of the book coding the point values. + pub book: usize, + /// For each point (in coding order) its low and high neighbours. + neighbours: Vec<(usize, usize)>, + /// Point indices sorted by X. + sorted: Vec, +} + +impl Floor1 { + /// Points spaced about evenly in log frequency over 1..1024. + pub fn new(book: usize) -> Floor1 { + let count = CLASS_DIM * PARTITIONS; + let mut xs = vec![0, 1 << RANGE_BITS]; + let mut last = 0; + for i in 1..=count { + // geometric from 2 to ~1000 bins, at least one bin apart + let x = (2.0f64 * (500.0f64).powf((i - 1) as f64 / (count - 1) as f64)).round() as i32; + let x = x.max(last + 1).min((1 << RANGE_BITS) - 1); + xs.push(x); + last = x; + } + let neighbours = (0..xs.len()) + .map(|i| { + if i < 2 { + return (0, 0); + } + let (mut lo, mut hi) = (0usize, 1usize); + for j in 0..i { + if xs[j] < xs[i] && xs[j] > xs[lo] { + lo = j; + } + if xs[j] > xs[i] && xs[j] < xs[hi] { + hi = j; + } + } + (lo, hi) + }) + .collect(); + let mut sorted: Vec = (0..xs.len()).collect(); + sorted.sort_by_key(|&i| xs[i]); + Floor1 { xs, book, neighbours, sorted } + } + + /// The setup-header encoding (§7.2.2): one class of `CLASS_DIM` points, no subclasses. + pub fn write_header(&self, w: &mut BitWriter) { + w.write(PARTITIONS as u32, 5); + for _ in 0..PARTITIONS { + w.write(0, 4); + } + w.write(CLASS_DIM as u32 - 1, 3); + w.write(0, 2); // no subclasses + w.write(self.book as u32 + 1, 8); + w.write(MULTIPLIER - 1, 2); + w.write(RANGE_BITS, 4); + for &x in &self.xs[2..] { + w.write(x as u32, RANGE_BITS); + } + } + + /// Codes the target values `want` (one per point, 0..RANGE) into `w`; returns the floor curve + /// the decoder renders (`n2` amplitudes). + pub fn encode(&self, w: &mut BitWriter, book: &Codebook, want: &[i32], n2: usize) -> Vec { + let n = self.xs.len(); + let want = |i: usize| want.get(i).copied().unwrap_or(0).clamp(0, RANGE - 1); + let mut fin = vec![0i32; n]; + let mut used = vec![false; n]; + let mut coded = vec![0u32; n]; + fin[0] = want(0); + fin[1] = want(1); + used[0] = true; + used[1] = true; + for i in 2..n { + let (lo, hi) = self.neighbours[i]; + let pred = render_point(self.xs[lo], fin[lo], self.xs[hi], fin[hi], self.xs[i]); + let f = want(i); + let (highroom, lowroom) = (RANGE - pred, pred); + let room = 2 * highroom.min(lowroom); + let val = if f == pred { + 0 + } else { + let d = f - pred; + let inside = if d > 0 { 2 * d } else { -2 * d - 1 }; + if inside < room { + inside + } else if highroom > lowroom { + f - pred + lowroom + } else { + pred - f + highroom - 1 + } + }; + coded[i] = val.clamp(0, RANGE - 1) as u32; + if val != 0 { + used[lo] = true; + used[hi] = true; + used[i] = true; + fin[i] = f; + } else { + fin[i] = pred; + } + } + let bits = ilog(RANGE as u32 - 1); + w.write(fin[0] as u32, bits); + w.write(fin[1] as u32, bits); + for &c in &coded[2..] { + book.put(w, c as usize); + } + self.render(&fin, &used, n2) + } + + /// The decoder's curve (§7.2.4 step 2, `render_line`) as amplitudes. + fn render(&self, fin: &[i32], used: &[bool], n2: usize) -> Vec { + let mut v = vec![0i32; n2]; + let m = MULTIPLIER as i32; + let (mut lx, mut ly) = (0i32, fin[self.sorted[0]] * m); + let (mut hx, mut hy) = (0i32, ly); + for &i in &self.sorted[1..] { + if used[i] { + hy = fin[i] * m; + hx = self.xs[i]; + render_line(lx, ly, hx, hy, &mut v); + lx = hx; + ly = hy; + } + } + if (hx as usize) < n2 { + render_line(hx, hy, n2 as i32, hy, &mut v); + } + v.iter().map(|&i| inverse_db(i)).collect() + } +} + +fn render_point(x0: i32, y0: i32, x1: i32, y1: i32, x: i32) -> i32 { + let dy = y1 - y0; + let adx = (x1 - x0).max(1); + let err = dy.abs() * (x - x0); + let off = err / adx; + if dy < 0 { y0 - off } else { y0 + off } +} + +fn render_line(x0: i32, y0: i32, x1: i32, y1: i32, v: &mut [i32]) { + let dy = y1 - y0; + let adx = x1 - x0; + if adx <= 0 { + return; + } + let base = dy / adx; + let sy = if dy < 0 { base - 1 } else { base + 1 }; + let ady = dy.abs() - base.abs() * adx; + let (mut y, mut err) = (y0, 0); + if let Some(s) = v.get_mut(x0 as usize) { + *s = y; + } + for x in x0 + 1..x1 { + err += ady; + if err >= adx { + err -= adx; + y += sy; + } else { + y += base; + } + if let Some(s) = v.get_mut(x as usize) { + *s = y; + } + } +} diff --git a/crates/audio/src/vorbis/encoder/mdct.rs b/crates/audio/src/vorbis/encoder/mdct.rs new file mode 100644 index 0000000000..3802a24d63 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/mdct.rs @@ -0,0 +1,134 @@ +//! Forward MDCT of a windowed block of `n` samples to `n/2` coefficients: +//! `X[k] = Σ x[j] cos(2π/n · (j + 1/2 + n/4)(k + 1/2))`, the transform the Vorbis decoder inverts +//! (Vorbis I §1.3.2, §4.3.9). Computed as a DCT-IV of the folded block through an `n/8`-point +//! complex FFT. + +use std::f64::consts::PI; + +#[derive(Clone, Copy, Default, Debug)] +struct Cpx { + re: f64, + im: f64, +} + +impl Cpx { + fn mul(self, o: Cpx) -> Cpx { + Cpx { re: self.re * o.re - self.im * o.im, im: self.re * o.im + self.im * o.re } + } +} + +/// A forward MDCT for one block size (a power of two, at least 16). +#[derive(Clone, Debug)] +pub struct Mdct { + n: usize, + twiddle: Vec, + post: Vec, + fft_tw: Vec, + rev: Vec, +} + +impl Mdct { + pub fn new(n: usize) -> Mdct { + let m = n / 2; // DCT-IV length + let h = m / 2; // FFT length + let twiddle = (0..h).map(|j| cis(-PI * (4.0 * j as f64 + 1.0) / (4.0 * m as f64))).collect(); + let post = (0..h).map(|k| cis(-PI * k as f64 / m as f64)).collect(); + let fft_tw = (0..h / 2).map(|j| cis(-2.0 * PI * j as f64 / h as f64)).collect(); + let bits = h.trailing_zeros(); + let rev = (0..h).map(|i| if bits == 0 { 0 } else { i.reverse_bits() >> (usize::BITS - bits) }).collect(); + Mdct { n, twiddle, post, fft_tw, rev } + } + + /// `x`: `n` windowed samples; `out`: `n/2` coefficients (scaled by `scale`). + pub fn forward(&self, x: &[f32], out: &mut [f32], scale: f64) { + let n = self.n; + let m = n / 2; + let q = n / 4; + let at = |i: usize| f64::from(x.get(i).copied().unwrap_or(0.0)); + // fold (a, b, c, d) to the DCT-IV input (-c_r - d, a - b_r) + let mut v = vec![0f64; m]; + for (i, s) in v.iter_mut().enumerate() { + *s = if i < q { -at(3 * q - 1 - i) - at(3 * q + i) } else { at(i - q) - at(3 * q - 1 - i) }; + } + // DCT-IV through a half-length complex FFT + let h = m / 2; + let mut z: Vec = (0..h).map(|j| Cpx { re: v[2 * j], im: v[m - 1 - 2 * j] }.mul(self.twiddle[j])).collect(); + self.fft(&mut z); + for (k, c) in z.iter().enumerate() { + let d = c.mul(self.post[k]); + if let Some(o) = out.get_mut(2 * k) { + *o = (d.re * scale) as f32; + } + if let Some(o) = out.get_mut(m - 1 - 2 * k) { + *o = (-d.im * scale) as f32; + } + } + } + + /// In-place radix-2 FFT (`e^{-2πi jk/h}`). + fn fft(&self, a: &mut [Cpx]) { + let h = a.len(); + for i in 0..h { + let j = self.rev[i]; + if i < j { + a.swap(i, j); + } + } + let mut len = 2; + while len <= h { + let step = h / len; + for start in (0..h).step_by(len) { + for k in 0..len / 2 { + let w = self.fft_tw[k * step]; + let u = a[start + k]; + let t = a[start + k + len / 2].mul(w); + a[start + k] = Cpx { re: u.re + t.re, im: u.im + t.im }; + a[start + k + len / 2] = Cpx { re: u.re - t.re, im: u.im - t.im }; + } + } + len *= 2; + } + } +} + +fn cis(t: f64) -> Cpx { + Cpx { re: t.cos(), im: t.sin() } +} + +/// The Vorbis window (§4.3.1) for a block of `n` between blocks of the same size. +pub fn window(n: usize) -> Vec { + (0..n) + .map(|i| { + let s = (PI * (i as f64 + 0.5) / n as f64).sin(); + (PI / 2.0 * s * s).sin() as f32 + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_direct_formula() { + for n in [16usize, 64, 256, 2048] { + let x: Vec = (0..n).map(|i| ((i * 7919 % 211) as f32 - 105.0) / 50.0).collect(); + let mut fast = vec![0f32; n / 2]; + Mdct::new(n).forward(&x, &mut fast, 1.0); + for k in [0usize, 1, 2, n / 4, n / 2 - 1] { + let direct: f64 = + (0..n).map(|j| f64::from(x[j]) * (2.0 * PI / n as f64 * (j as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos()).sum(); + assert!((direct - f64::from(fast[k])).abs() < 1e-3 * (1.0 + direct.abs()), "n={n} k={k}: {direct} vs {}", fast[k]); + } + } + } + + #[test] + fn the_window_is_power_complementary() { + let w = window(2048); + for i in 0..1024 { + let s = w[i] * w[i] + w[i + 1024] * w[i + 1024]; + assert!((s - 1.0).abs() < 1e-5, "{i}: {s}"); + } + } +} diff --git a/crates/audio/src/vorbis/encoder/mod.rs b/crates/audio/src/vorbis/encoder/mod.rs new file mode 100644 index 0000000000..95be88244b --- /dev/null +++ b/crates/audio/src/vorbis/encoder/mod.rs @@ -0,0 +1,494 @@ +//! Pure-Rust Vorbis I encoder, written from the Vorbis I specification (Xiph.Org, 2020-07-04). +//! +//! No `unsafe` and no C code; builds for `wasm32-unknown-unknown`. ffmpeg is used only as an +//! external test oracle. +//! +//! The stream: one mode of 2048-sample blocks; per channel a floor 1 envelope of 34 points; one +//! residue type 2 over the interleaved channels, partitions of 32 values (a multiple of the +//! channel count for 3, 5, 6 and 7 channels) in seven classes (silent, +//! three single-pass lattice books, and two- and three-pass cascades for large values); no channel +//! coupling. Quality (-1 to 10) sets how far the floor sits from the spectral envelope (below it +//! for tonal regions, above it for noise-like ones, from the spectral flatness), and with it the +//! residue's precision: variable bit rate, like other Vorbis encoders. +//! +//! From FilmCraft's `filmcraft-vorbis` by @JordyUSA (storytold/filmcraft#4481). +//! +//! The packets go into Ogg with [`craft_media::ogg::PageWriter`] and a comment header from +//! [`craft_media::ogg::vorbis_comment`]; [`crate::encode_ogg_vorbis`] does all of it for a +//! whole buffer. +//! +//! ``` +//! use craft_audio::vorbis::encoder::{Encoder, EncoderConfig}; +//! +//! let mut enc = Encoder::new(EncoderConfig::new(48_000, 2, 5.0))?; +//! let tone: Vec = (0..4_800).map(|i| (i as f32 * 0.05).sin() * 0.5).collect(); +//! let mut packets = enc.encode(&[&tone, &tone])?; +//! packets.extend(enc.finish()?); +//! // the last granule position is the input's length, so a decoder trims the padding +//! assert_eq!(packets.last().map(|p| p.1), Some(4_800)); +//! assert_eq!(&enc.identification()[1..7], b"vorbis"); +//! # Ok::<(), craft_audio::vorbis::encoder::Error>(()) +//! ``` + +// Index loops follow the specification, as in FilmCraft (which allows this lint workspace-wide). +#![allow(clippy::needless_range_loop)] + +mod book; +mod floor; +mod mdct; + +use book::{BitWriter, Codebook}; +use floor::Floor1; +use mdct::Mdct; + +/// Why an encoder could not be created or input could not be encoded. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// A setting or the input is outside what the encoder takes. + #[error("invalid argument: {0}")] + InvalidArgument(&'static str), + /// An encoder invariant failed (a bug, reported instead of panicking). + #[error("internal error: {0}")] + Internal(&'static str), +} + +/// The encoder's result type. +pub type Result = std::result::Result; + +/// Block size (samples); the short block size of the header is never used. +pub const BLOCK: usize = 2048; +const HOP: usize = BLOCK / 2; +/// Residue values per partition for `channels` channels: 32, or for 3, 5, 6 and 7 channels a +/// multiple of the channel count (48, 40, 48, 56). libvorbis decodes each partition of an +/// interleaved (type 2) residue as if it started on channel 0, so a partition must hold whole +/// sample frames; the size also divides `channels × 1024` and is a multiple of every book's +/// dimension (4). +fn partition_size(channels: usize) -> usize { + match channels { + 3 | 6 => 48, + 5 => 40, + 7 => 56, + _ => 32, + } +} +const CLASSES: usize = 8; +/// Largest residue magnitude the cascade codes: 7·225 + 7·15 + 7. +const MAX_RESIDUE: i32 = 1687; + +/// The quality a NaN or infinite setting reads as. +pub const DEFAULT_QUALITY: f32 = 6.0; + +/// Encoder settings. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EncoderConfig { + /// Samples per second, 1 to 768 000. + pub sample_rate: u32, + /// 1 to 8, in Vorbis channel order (§4.3.9). + pub channels: usize, + /// -1 (smallest) to 10 (best); clamped. + pub quality: f32, +} + +impl EncoderConfig { + /// Settings for `channels` channels (in Vorbis order) at `sample_rate` and `quality`. + pub fn new(sample_rate: u32, channels: usize, quality: f32) -> EncoderConfig { + EncoderConfig { sample_rate, channels, quality } + } +} + +/// Book indices in the setup header. +const BOOK_CLASS: usize = 0; +const BOOK_FLOOR: usize = 1; +const BOOK_A1_SPARSE: usize = 2; +const BOOK_A1: usize = 3; +const BOOK_A2: usize = 4; +const BOOK_A4: usize = 5; +const BOOK_F: usize = 6; +const BOOK_M: usize = 7; +const BOOK_C: usize = 8; + +/// Books per class and pass (`None`: nothing coded in that pass). +const CASCADE: [[Option; 3]; CLASSES] = [ + [None, None, None], + [Some(BOOK_A1_SPARSE), None, None], + [Some(BOOK_A1), None, None], + [Some(BOOK_A2), None, None], + [Some(BOOK_A4), None, None], + [Some(BOOK_F), None, None], + [Some(BOOK_M), Some(BOOK_F), None], + [Some(BOOK_C), Some(BOOK_M), Some(BOOK_F)], +]; + +/// A Vorbis encoder for one stream: planar `f32` in, Vorbis packets with their granule +/// positions out. +pub struct Encoder { + cfg: EncoderConfig, + books: Vec, + floor: Floor1, + mdct: Mdct, + window: Vec, + /// Input not yet past a block, per channel; the next block starts at `start`. + pending: Vec>, + /// Read cursor into `pending`: consumed hops are dropped once per call, not per block. + start: usize, + samples_in: u64, + blocks: u64, + finished: bool, + /// Floor offset below the envelope (dB) for tonal and for noise-like regions. + tonal_db: f32, + noise_db: f32, + /// Residue magnitudes below this quantise to 0. + dead_zone: f32, +} + +impl Encoder { + /// An encoder for `cfg`: 1 to 8 channels, a sample rate of 1 to 768 000; the quality is + /// clamped to -1..=10, and NaN or infinite reads as [`DEFAULT_QUALITY`]. + pub fn new(cfg: EncoderConfig) -> Result { + if !(1..=8).contains(&cfg.channels) { + return Err(Error::InvalidArgument("Vorbis encoder: 1 to 8 channels")); + } + if !(1..=768_000).contains(&cfg.sample_rate) { + return Err(Error::InvalidArgument("Vorbis encoder: sample rate")); + } + let quality = if cfg.quality.is_finite() { cfg.quality.clamp(-1.0, 10.0) } else { DEFAULT_QUALITY }; + let cfg = EncoderConfig { quality, ..cfg }; + let books = vec![ + Codebook::scalar(2, &(0..CLASSES * CLASSES).map(|e| class_weight(e / CLASSES) * class_weight(e % CLASSES)).collect::>())?, + Codebook::scalar(1, &(0..floor::RANGE).map(|v| 1.0 / (1.0 + f64::from(v)).powf(1.6)).collect::>())?, + Codebook::lattice(4, 3, -1, 1, |v| if v == 0 { 0.92 } else { 0.04 })?, + Codebook::lattice(4, 3, -1, 1, |v| if v == 0 { 0.5 } else { 0.25 })?, + Codebook::lattice(2, 5, -2, 1, |v| 0.6f64.powi(v.abs()))?, + Codebook::lattice(2, 9, -4, 1, |v| 0.7f64.powi(v.abs()))?, + Codebook::lattice(2, 15, -7, 1, |v| 0.8f64.powi(v.abs()))?, + Codebook::lattice(2, 15, -105, 15, |v| 0.55f64.powi((v / 15).abs()))?, + Codebook::lattice(2, 15, -1575, 225, |v| 0.4f64.powi((v / 225).abs()))?, + ]; + Ok(Encoder { + cfg, + books, + floor: Floor1::new(BOOK_FLOOR), + mdct: Mdct::new(BLOCK), + window: mdct::window(BLOCK), + // the first block is centred on sample 0: the decoder's first output is input sample 0 + pending: vec![vec![0.0; HOP]; cfg.channels], + start: 0, + samples_in: 0, + blocks: 0, + finished: false, + // tones 4 dB (-1) to 30.4 dB (10) under their envelope; noise 14 dB above it (-1) + // to 4.1 dB (10) + tonal_db: 4.0 + 2.4 * (quality + 1.0), + noise_db: -14.0 + 0.9 * (quality + 1.0), + dead_zone: 0.8 - 0.025 * (quality + 1.0), + }) + } + + /// Channels per sample frame. + pub fn channels(&self) -> usize { + self.cfg.channels + } + + /// The quality in use, after clamping. + pub fn quality(&self) -> f32 { + self.cfg.quality + } + + /// Input samples per channel taken so far. + pub fn samples_in(&self) -> u64 { + self.samples_in + } + + /// The identification header packet (§4.2.2): the first packet of the stream. + pub fn identification(&self) -> Vec { + let mut w = BitWriter::new(); + w.write(1, 8); + w.bytes(b"vorbis"); + w.write(0, 32); + w.write(self.cfg.channels as u32, 8); + w.write(self.cfg.sample_rate, 32); + w.write(0, 32); // bit rates: unset (variable) + w.write(0, 32); + w.write(0, 32); + w.write(8, 4); // 256-sample short blocks (unused) + w.write(11, 4); // 2048-sample long blocks + w.flag(true); + w.finish() + } + + /// The setup header packet (§4.2.4): codebooks, floor, residue, mapping and mode. It follows + /// the comment header. + pub fn setup(&self) -> Vec { + let mut w = BitWriter::new(); + w.write(5, 8); + w.bytes(b"vorbis"); + w.write(self.books.len() as u32 - 1, 8); + for b in &self.books { + b.write_header(&mut w); + } + w.write(0, 6); // one time-domain transform placeholder + w.write(0, 16); + w.write(0, 6); // one floor + w.write(1, 16); + self.floor.write_header(&mut w); + w.write(0, 6); // one residue, type 2 + w.write(2, 16); + let end = (self.cfg.channels * HOP) as u32; + w.write(0, 24); + w.write(end, 24); + w.write(partition_size(self.cfg.channels) as u32 - 1, 24); + w.write(CLASSES as u32 - 1, 6); + w.write(BOOK_CLASS as u32, 8); + for c in &CASCADE { + let bits: u32 = c.iter().enumerate().map(|(j, b)| u32::from(b.is_some()) << j).sum(); + w.write(bits & 7, 3); + w.flag(bits > 7); + if bits > 7 { + w.write(bits >> 3, 5); + } + } + for c in &CASCADE { + for b in c.iter().flatten() { + w.write(*b as u32, 8); + } + } + w.write(0, 6); // one mapping, type 0 + w.write(0, 16); + w.flag(false); // one submap + w.flag(false); // no coupling + w.write(0, 2); + w.write(0, 8); // submap 0: time, floor 0, residue 0 + w.write(0, 8); + w.write(0, 8); + w.write(0, 6); // one mode: long blocks, mapping 0 + w.flag(true); + w.write(0, 16); + w.write(0, 16); + w.write(0, 8); + w.flag(true); + w.finish() + } + + /// Encodes planar samples (one slice per channel, all the same length, nominal range ±1); + /// returns the packets completed with their granule positions. NaN or infinite samples, or a + /// channel count or length mismatch, are an error. + pub fn encode(&mut self, planar: &[&[f32]]) -> Result, i64)>> { + if self.finished { + return Err(Error::InvalidArgument("Vorbis encoder: encode after finish")); + } + if planar.len() != self.cfg.channels { + return Err(Error::InvalidArgument("Vorbis encoder: one slice per channel")); + } + let len = planar.first().map_or(0, |p| p.len()); + if planar.iter().any(|p| p.len() != len) { + return Err(Error::InvalidArgument("Vorbis encoder: channels of different lengths")); + } + if planar.iter().any(|p| p.iter().any(|v| !v.is_finite())) { + return Err(Error::InvalidArgument("Vorbis encoder: NaN or infinite sample")); + } + for (b, p) in self.pending.iter_mut().zip(planar) { + b.extend_from_slice(p); + } + self.samples_in += len as u64; + self.drain() + } + + /// Encodes what remains, padded with silence; the last packet's granule position is the + /// input's length, so the decoder trims the padding (§A.2). + pub fn finish(&mut self) -> Result, i64)>> { + if self.finished { + return Ok(Vec::new()); + } + self.finished = true; + // block k ends output at k·HOP: blocks 0..=ceil(len / HOP) + let blocks = self.samples_in.div_ceil(HOP as u64) + 1; + let missing = blocks.saturating_sub(self.blocks) as usize; + self.compact(); + let need = (missing + 1) * HOP; + for b in self.pending.iter_mut() { + if b.len() < need { + b.resize(need, 0.0); + } + } + let mut out = Vec::new(); + for _ in 0..missing { + out.push(self.block()?); + } + Ok(out) + } + + fn drain(&mut self) -> Result, i64)>> { + let mut out = Vec::new(); + while self.pending.first().is_some_and(|b| b.len().saturating_sub(self.start) >= BLOCK) { + out.push(self.block()?); + } + self.compact(); + Ok(out) + } + + /// Drops the hops already encoded from the front of every channel buffer. + fn compact(&mut self) { + for b in self.pending.iter_mut() { + b.drain(..self.start.min(b.len())); + } + self.start = 0; + } + + /// Encodes the block at `start` in `pending` and advances by a hop. + fn block(&mut self) -> Result<(Vec, i64)> { + let ch = self.cfg.channels; + let mut w = BitWriter::new(); + w.write(0, 1); // audio packet; one mode, so no mode number + w.flag(true); // previous and next windows long + w.flag(true); + let mut residue = vec![0i32; ch * HOP]; + let mut any = false; + let mut x = vec![0f32; BLOCK]; + let mut coeffs = vec![0f32; HOP]; + for c in 0..ch { + let src = self.pending.get(c).and_then(|b| b.get(self.start..)).ok_or(Error::Internal("channel buffer"))?; + for (i, v) in x.iter_mut().enumerate() { + *v = src.get(i).copied().unwrap_or(0.0).clamp(-8.0, 8.0) * self.window[i]; + } + self.mdct.forward(&x, &mut coeffs, 2.0 / HOP as f64); + let peak = coeffs.iter().fold(0f32, |m, v| m.max(v.abs())); + // (a NaN peak cannot happen: samples are finite and clamped) + if peak <= 1e-7 { + w.flag(false); // floor unused: the channel is silent + continue; + } + any = true; + w.flag(true); + let want = self.floor_targets(&coeffs); + let curve = self.floor.encode(&mut w, &self.books[BOOK_FLOOR], &want, HOP); + for (k, (&v, &f)) in coeffs.iter().zip(&curve).enumerate() { + let r = if f > 0.0 { v / f } else { 0.0 }; + // a dead zone: values just past half a step are noise peaks, not worth a ±1 + let q = if r.abs() < self.dead_zone { 0.0 } else { r.round() }; + residue[k * ch + c] = if q.is_finite() { (q as i32).clamp(-MAX_RESIDUE, MAX_RESIDUE) } else { 0 }; + } + } + if any { + self.write_residue(&mut w, &residue); + } + let granule = if self.blocks == 0 { + 0 + } else { + let natural = self.blocks.saturating_mul(HOP as u64); + if self.finished { natural.min(self.samples_in) } else { natural } + }; + self.start += HOP; + self.blocks += 1; + Ok((w.finish(), i64::try_from(granule).unwrap_or(i64::MAX))) + } + + /// Floor values at the floor's points: the spectral envelope (power smoothed over a quarter of + /// the frequency, at least 8 bins, on each side) less an offset that grows with the region's tonality, from its + /// spectral flatness: noise needs a few dB of precision, tones much more. + fn floor_targets(&self, coeffs: &[f32]) -> Vec { + let n = coeffs.len(); + let mut cum = vec![0f64; n + 1]; + let mut cum_ln = vec![0f64; n + 1]; + for (i, &v) in coeffs.iter().enumerate() { + let p = f64::from(v) * f64::from(v); + cum[i + 1] = cum[i] + p; + cum_ln[i + 1] = cum_ln[i] + (p + 1e-30).ln(); + } + self.floor + .xs + .iter() + .map(|&x| { + let k = (x as usize).min(n - 1); + let half = (k / 4).max(8); + let (lo, hi) = (k.saturating_sub(half), (k + half + 1).min(n)); + let len = (hi - lo) as f64; + let am = (cum[hi] - cum[lo]) / len; + let gm = ((cum_ln[hi] - cum_ln[lo]) / len).exp(); + // spectral flatness: about -2.5 dB for noise, far below for a tone + let sfm_db = 10.0 * (gm / am.max(1e-30)).max(1e-30).log10(); + let tonality = ((-sfm_db - 2.5) / 20.0).clamp(0.0, 1.0); + let offset = tonality * f64::from(self.tonal_db) + (1.0 - tonality) * f64::from(self.noise_db); + let amp = (am.sqrt() * 10f64.powf(-offset / 20.0)).max(1e-7) as f32; + (floor::db_index(amp) + 1) / floor::MULTIPLIER as i32 + }) + .collect() + } + + /// Residue type 2 (§8.6.2 with the interleaved vector): classes per partition, then the + /// cascade's passes in the decoder's order. + fn write_residue(&self, w: &mut BitWriter, r: &[i32]) { + let partition = partition_size(self.cfg.channels); + let parts = r.len() / partition; + let classes: Vec = r.chunks(partition).map(class_of).collect(); + let per_word = self.books[BOOK_CLASS].dimensions as usize; + for pass in 0..3 { + let mut pc = 0; + while pc < parts { + if pass == 0 { + let mut e = 0usize; + for i in 0..per_word { + e = e * CLASSES + classes.get(pc + i).copied().unwrap_or(0); + } + self.books[BOOK_CLASS].put(w, e); + } + for _ in 0..per_word { + if pc >= parts { + break; + } + let class = classes[pc]; + if let Some(b) = CASCADE[class][pass] { + let book = &self.books[b]; + let dims = book.dimensions as usize; + let part = &r[pc * partition..(pc + 1) * partition]; + for chunk in part.chunks(dims) { + let v: Vec = chunk.iter().map(|&x| pass_value(x, class, pass)).collect(); + book.put(w, book.entry_of(&v)); + } + } + pc += 1; + } + } + } + } +} + +/// Relative frequency of each residue class (for the class book's code lengths). +fn class_weight(c: usize) -> f64 { + [0.3, 0.2, 0.12, 0.12, 0.1, 0.08, 0.06, 0.02].get(c).copied().unwrap_or(0.01) +} + +/// The part of residue value `v` coded in `pass` for `class`: the passes add up to `v`. +fn pass_value(v: i32, class: usize, pass: usize) -> i32 { + let split = |v: i32, step: i32| -> (i32, i32) { + let a = ((f64::from(v) / f64::from(step)).round() as i32).clamp(-7, 7); + (a * step, v - a * step) + }; + match (class, pass) { + (6, 0) => split(v, 15).0, + (6, _) => split(v, 15).1, + (7, 0) => split(v, 225).0, + (7, 1) => split(split(v, 225).1, 15).0, + (7, _) => split(split(v, 225).1, 15).1, + _ => v, + } +} + +/// The residue class of a partition: silent; ±1 with at most four nonzero values, or more; then +/// by the largest magnitude. +fn class_of(p: &[i32]) -> usize { + let m = p.iter().map(|v| v.abs()).max().unwrap_or(0); + match m { + 0 => 0, + 1 if p.iter().filter(|&&v| v != 0).count() <= 4 => 1, + 1 => 2, + 2 => 3, + 3..=4 => 4, + 5..=7 => 5, + 8..=112 => 6, + _ => 7, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/audio/src/vorbis/encoder/tests.rs b/crates/audio/src/vorbis/encoder/tests.rs new file mode 100644 index 0000000000..b1ae874635 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/tests.rs @@ -0,0 +1,285 @@ +//! Unit tests, and ffmpeg (as an external oracle only) decoding the encoder's streams. + +#![allow(clippy::unwrap_used)] + +use std::path::Path; +use std::process::Command; + +use super::book::{BitWriter, assign_codewords, float32_pack}; +use super::{BLOCK, Encoder, EncoderConfig, HOP, partition_size}; + +#[test] +fn codewords_follow_the_specification_example() { + // Vorbis I §3.2.1: lengths 2 4 4 4 4 2 3 3 + let words = assign_codewords(&[2, 4, 4, 4, 4, 2, 3, 3]).unwrap(); + assert_eq!(words, [0b00, 0b0100, 0b0101, 0b0110, 0b0111, 0b10, 0b110, 0b111]); + assert!(assign_codewords(&[1, 1, 1]).is_err(), "over-subscribed"); +} + +#[test] +fn every_book_is_a_complete_prefix_code() { + let e = Encoder::new(EncoderConfig::new(48_000, 2, 5.0)).unwrap(); + for (i, b) in e.books.iter().enumerate() { + let kraft: f64 = b.lengths.iter().map(|&l| 0.5f64.powi(l as i32)).sum(); + assert!((kraft - 1.0).abs() < 1e-9, "book {i}: Kraft sum {kraft}"); + assert!(b.lengths.iter().all(|&l| (1..=20).contains(&l))); + for (a, (&wa, &la)) in b.words.iter().zip(&b.lengths).enumerate() { + for (c, (&wc, &lc)) in b.words.iter().zip(&b.lengths).enumerate() { + if a != c && la <= lc { + assert_ne!(wc >> (lc - la), wa, "book {i}: codeword {a} is a prefix of {c}"); + } + } + } + } +} + +#[test] +fn float32_pack_is_exact_for_lattice_values() { + let unpack = |x: u32| { + let mant = f64::from(x & 0x1F_FFFF); + let exp = ((x >> 21) & 0x3FF) as i32 - 788; + let v = mant * 2f64.powi(exp); + if x & 0x8000_0000 != 0 { -v } else { v } + }; + for v in [1.0, -1.0, -2.0, -4.0, -7.0, -105.0, 15.0, -1575.0, 225.0, 0.5, 3.0] { + assert_eq!(unpack(float32_pack(v)), v); + } + assert_eq!(float32_pack(0.0), 0); +} + +#[test] +fn bits_are_packed_lsb_first() { + let mut w = BitWriter::new(); + w.write(0b1, 1); + w.write(0b10, 2); + w.write(0x1F, 5); + w.write(0xABC, 12); + assert_eq!(w.finish(), [0b1111_1101, 0xBC, 0x0A]); +} + +#[test] +fn hostile_input_is_an_error_not_a_panic() { + assert!(Encoder::new(EncoderConfig::new(48_000, 0, 3.0)).is_err()); + assert!(Encoder::new(EncoderConfig::new(48_000, 9, 3.0)).is_err()); + assert!(Encoder::new(EncoderConfig::new(0, 2, 3.0)).is_err()); + assert_eq!(Encoder::new(EncoderConfig::new(48_000, 1, f32::NAN)).unwrap().cfg.quality, 6.0, "NaN quality uses the default, as the export does"); + let mut e = Encoder::new(EncoderConfig::new(44_100, 2, 3.0)).unwrap(); + assert!(e.encode(&[&[0.0; 4]]).is_err()); + assert!(e.encode(&[&[0.0; 4], &[0.0; 3]]).is_err()); + assert!(e.encode(&[&[f32::NAN; 4], &[0.0; 4]]).is_err()); + let loud = vec![1e30f32; 5000]; + assert!(!e.encode(&[&loud, &loud]).unwrap().is_empty()); + assert!(!e.finish().unwrap().is_empty()); + assert!(e.finish().unwrap().is_empty()); + assert!(e.encode(&[&[0.0; 4], &[0.0; 4]]).is_err()); +} + +#[test] +fn granules_count_the_samples_and_trim_the_end() { + for len in [0usize, 1, 1023, 1024, 1025, 48_000] { + let mut e = Encoder::new(EncoderConfig::new(48_000, 1, 3.0)).unwrap(); + let x = vec![0.1f32; len]; + let mut packets = e.encode(&[&x]).unwrap(); + packets.extend(e.finish().unwrap()); + assert_eq!(packets.len(), len.div_ceil(HOP) + 1, "len {len}"); + // packet k ends output at k·1024 samples; the last one at the input's length + let want: Vec = (0..packets.len()).map(|k| ((k * HOP) as i64).min(len as i64)).collect(); + let got: Vec = packets.iter().map(|p| p.1).collect(); + assert_eq!(got, want, "len {len}"); + } +} + +// --- ffmpeg oracle --- + +/// An Ogg Vorbis file of the three headers and the audio packets, through craft-media's writer. +fn ogg(packets: &[(Vec, i64)]) -> Vec { + let mut w = craft_media::ogg::PageWriter::new(7); + let mut out = Vec::new(); + for (i, (p, g)) in packets.iter().enumerate() { + out.extend(if i < 3 { w.header(p) } else { w.packet(p, *g) }); + } + out.extend(w.finish(None)); + out +} + +fn comment() -> Vec { + craft_media::ogg::vorbis_comment("test", &[]) +} + +/// Encodes `input` (planar) and decodes it with ffmpeg's `decoder`; returns the planar output. +/// ffmpeg's decoders to check: its own `vorbis` always, and `libvorbis` when ffmpeg has it. +fn decoders(ff: &Path) -> Vec<&'static str> { + let list = + Command::new(ff).args(["-hide_banner", "-decoders"]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default(); + if list.lines().any(|l| l.split_whitespace().nth(1) == Some("libvorbis")) { + vec!["vorbis", "libvorbis"] + } else { + eprintln!("SKIPPED (libvorbis decoder): this ffmpeg has no libvorbis; checking its own decoder only"); + vec!["vorbis"] + } +} + +fn round_trip(input: &[Vec], rate: u32, quality: f32, decoder: &str, name: &str) -> Option<(Vec>, usize)> { + let ff = craft_media_testkit::ffmpeg_or_skip("vorbis oracle")?; + let mut e = Encoder::new(EncoderConfig::new(rate, input.len(), quality)).unwrap(); + let mut packets = vec![(e.identification(), 0), (comment(), 0), (e.setup(), 0)]; + let n = input[0].len(); + let mut at = 0; + while at < n { + let end = (at + 4410).min(n); + let s: Vec<&[f32]> = input.iter().map(|c| &c[at..end]).collect(); + packets.extend(e.encode(&s).unwrap()); + at = end; + } + packets.extend(e.finish().unwrap()); + let bytes: usize = packets[3..].iter().map(|p| p.0.len()).sum(); + let dir = craft_media_testkit::fixtures_dir("audio/vorbis-encoder"); + let path = dir.join(format!("{name}.ogg")); + std::fs::write(&path, ogg(&packets)).unwrap(); + let out = Command::new(ff) + .args(["-v", "error", "-xerror", "-c:a", decoder, "-i"]) + .arg(&path) + .args(["-f", "f32le", "-c:a", "pcm_f32le", "-"]) + .output() + .unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{name} {decoder}: {}", String::from_utf8_lossy(&out.stderr)); + let pcm: Vec = out.stdout.as_chunks::<4>().0.iter().map(|&b| f32::from_le_bytes(b)).collect(); + let ch = input.len(); + Some(((0..ch).map(|c| pcm.iter().skip(c).step_by(ch).copied().collect()).collect(), bytes)) +} + +fn snr_db(a: &[f32], b: &[f32]) -> f64 { + let (mut s, mut e) = (0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + s += f64::from(x) * f64::from(x); + e += (f64::from(x) - f64::from(y)).powi(2); + } + 10.0 * (s.max(1e-20) / e.max(1e-20)).log10() +} + +fn music(n: usize, seed: u32) -> Vec { + let mut r = seed; + (0..n) + .map(|i| { + let t = i as f32 / 48_000.0; + r = r.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let noise = (r >> 8) as f32 / 8_388_608.0 - 1.0; + let chord: f32 = [220.0f32, 277.18, 329.63, 440.0] + .iter() + .enumerate() + .map(|(k, f)| (0.2 / (k + 1) as f32) * (2.0 * std::f32::consts::PI * f * t).sin()) + .sum(); + chord + 0.01 * noise + }) + .collect() +} + +/// Harmonic chords changing every half second, with decaying noise bursts (music-like). +fn chords(n: usize, seed: u32) -> Vec { + let mut r = seed; + let notes = [220.0f32, 277.2, 329.6, 440.0, 349.2, 523.3, 392.0, 659.3]; + (0..n) + .map(|i| { + let t = i as f32 / 48_000.0; + let chord = (t * 2.0) as usize; + let mut s = 0.0; + for k in 0..3 { + let f = notes[(chord * 3 + k * 2) % notes.len()]; + for h in 1..6 { + s += (2.0 * std::f32::consts::PI * f * h as f32 * t).sin() * 0.08 / h as f32; + } + } + r = r.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let env = (-(t * 2.0).fract() * 3.0).exp(); + s * (0.5 + 0.5 * env) + 0.02 * ((r >> 8) as f32 / 8_388_608.0 - 1.0) * env + }) + .collect() +} + +/// ffmpeg's own Vorbis decoder and libvorbis read every stream exactly as long as the input, +/// with SNR floors about 6 dB (chords 4 dB) under what the encoder measured when written, and bit +/// rates near libvorbis's for the same quality. +/// A signal, and per quality the SNR floor and the bit-rate range (kbit/s). +type Case = (&'static str, Vec>, [(f32, f64, std::ops::Range); 5]); + +#[test] +fn ffmpeg_decodes_every_quality() { + let Some(ff) = craft_media_testkit::ffmpeg_or_skip("vorbis oracle") else { return }; + let n = 48_000 * 3; + let cases: [Case; 2] = [ + ( + "music", + vec![music(n, 1), music(n, 2).iter().map(|v| v * 0.7).collect()], + [(-1.0, 3.0, 15..90), (0.0, 6.5, 20..110), (3.0, 12.0, 60..180), (6.0, 18.5, 120..280), (10.0, 25.5, 180..400)], + ), + ( + "chords", + vec![chords(n, 1), chords(n, 2).iter().map(|v| v * 0.8).collect()], + [(-1.0, 4.5, 20..90), (0.0, 6.0, 25..110), (3.0, 10.0, 70..200), (6.0, 14.0, 130..300), (10.0, 19.0, 180..420)], + ), + ]; + for (name, input, levels) in &cases { + for (q, floor, kbps) in levels { + for decoder in decoders(&ff) { + let Some((out, bytes)) = round_trip(input, 48_000, *q, decoder, &format!("{name}{q}")) else { return }; + assert!(out.iter().all(|c| c.len() == n), "{name} q{q} {decoder}: length {}", out[0].len()); + let snr = snr_db(&input[0][4096..], &out[0][4096..]); + assert!(snr >= *floor, "{name} q{q} {decoder}: {snr:.2} dB < {floor}"); + let rate = bytes * 8 / 3 / 1000; + assert!(kbps.contains(&rate), "{name} q{q}: {rate} kbit/s outside {kbps:?}"); + } + } + } +} + +/// Mono, 44.1 kHz, 3.0, 5.1 and 6.1 streams decode too, with libvorbis as well (which reads each +/// residue partition from channel 0); a silent channel costs one bit per block. +#[test] +fn channel_counts_and_rates() { + let Some(ff) = craft_media_testkit::ffmpeg_or_skip("vorbis oracle") else { return }; + let n = 44_100; + for (rate, ch) in [(44_100u32, 1usize), (22_050, 2), (48_000, 3), (48_000, 6), (48_000, 7)] { + let mut input: Vec> = (0..ch).map(|c| chords(n, c as u32 + 1).iter().map(|v| v * (1.0 - 0.1 * c as f32)).collect()).collect(); + if ch == 6 { + input[3] = vec![0.0; n]; + } + for decoder in decoders(&ff) { + let Some((mut out, _)) = round_trip(&input, rate, 5.0, decoder, &format!("ch{ch}_{rate}_{decoder}")) else { return }; + if decoder == "vorbis" { + // ffmpeg's decoder gives WAV order (5.1: FL FR FC LFE BL BR); the stream is in Vorbis + // order (L C R Ls Rs LFE), which libvorbis passes through + let wav_to_vorbis: &[usize] = match ch { + 3 => &[0, 2, 1], + 6 => &[0, 2, 1, 4, 5, 3], + 7 => &[0, 2, 1, 5, 6, 4, 3], + _ => &[0, 1], + }; + if ch > 2 { + out = wav_to_vorbis.iter().map(|&i| out[i].clone()).collect(); + } + } + assert_eq!(out.len(), ch); + for (c, (a, b)) in input.iter().zip(&out).enumerate() { + assert_eq!(b.len(), n, "{ch} ch {rate} Hz {decoder}: channel {c} length"); + if a.iter().all(|&v| v == 0.0) { + assert!(b.iter().all(|v| v.abs() < 1e-6), "silent channel {c}"); + } else { + let snr = snr_db(&a[4096..], &b[4096..]); + assert!(snr > 8.0, "{ch} ch {rate} Hz {decoder} channel {c}: {snr:.1} dB"); + } + } + } + } +} + +/// Every partition holds whole sample frames (libvorbis decodes each one from channel 0), splits +/// the interleaved residue evenly and fits every book's dimension. +#[test] +fn partitions_hold_whole_frames() { + for ch in 1..=8 { + let p = partition_size(ch); + assert_eq!(p % ch, 0, "{ch} channels"); + assert_eq!((ch * BLOCK / 2) % p, 0, "{ch} channels"); + assert_eq!(p % 4, 0, "{ch} channels"); + } +} diff --git a/crates/audio/src/vorbis/mod.rs b/crates/audio/src/vorbis/mod.rs new file mode 100644 index 0000000000..29c423f1d0 --- /dev/null +++ b/crates/audio/src/vorbis/mod.rs @@ -0,0 +1,4 @@ +//! Vorbis I (feature `vorbis-encode`): the pure-Rust [`encoder`]. Decoding Vorbis goes through +//! [`crate::decode`]. + +pub mod encoder; diff --git a/crates/audio/src/wav_markers.rs b/crates/audio/src/wav_markers.rs new file mode 100644 index 0000000000..0bf4e75684 --- /dev/null +++ b/crates/audio/src/wav_markers.rs @@ -0,0 +1,721 @@ +//! Markers a WAV file carries, read from its RIFF chunks. +//! +//! Two encodings are read into separate lists for the caller to map and merge: +//! - **Cue points** (the standard): a `cue ` chunk with one point per marker, named by `labl` (or +//! `note`) sub-chunks of a `LIST` `adtl` chunk, and given a length by `ltxt`. +//! - **XMP** (Adobe's tools): an `_PMX` chunk holding an XMP packet whose `xmpDM:markers` list has +//! one entry per marker (`xmpDM:startTime`, `xmpDM:duration`, `xmpDM:name`), counted in frames +//! of `xmpDM:frameRate` (`f44100` for samples at 44.1 kHz), or with an explicit +//! FrameCount rate suffix (`15f24`, `15f30000s1001`). Durations with a distinct rate +//! are converted to the marker start rate without app-specific time quantization. +//! +//! RF64 files (WAVs over 4 GB) carry a `0xFFFFFFFF` size for a chunk too big for 32 bits and give its real size in a +//! `ds64` chunk; those sizes are resolved so the chunks after the audio are still found. +//! +//! The file is untrusted input: every read is bounds-checked, sizes use checked arithmetic, and +//! the number of markers, of `adtl` sub-chunks looked at and the size of the XMP packet are capped. + +use std::collections::{HashMap, HashSet}; + +/// Marker coordinates before app-specific time quantization. Explicit XMP duration +/// rates are normalized to the start coordinate rate; bare counts retain the legacy +/// track/file-rate interpretation. +#[derive(Clone, Debug, PartialEq)] +pub struct Marker { + /// Start in frames at `rate`. + pub start: f64, + /// Duration in frames at `rate`. + pub duration: f64, + /// Frames per second; consumers decide how invalid or absent rates map to their timeline. + pub rate: f64, + /// Label text. + pub name: String, +} +/// Separate source lists: rounding, deduplication, ordering and labels belong to the caller. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Markers { + /// RIFF cue/adtl markers in file order. + pub cue: Vec, + /// XMP markers in packet order. + pub xmp: Vec, + /// A chunk-inventory or cue-label retention limit omitted metadata. Marker coordinates + /// remain available when only their label was omitted. Existing marker/XMP prefix limits + /// are separate and do not set this flag. + pub limited: bool, +} + +/// Most markers read from one file. +pub const MAX_MARKERS: usize = 10_000; +/// Largest XMP packet read (bytes). +const MAX_XMP: usize = 4 << 20; +/// Most `adtl` sub-chunks (`labl`, `note`, `ltxt`) looked at in one file: a few per cue point is plenty. +const MAX_ADTL_RECORDS: usize = 4 * MAX_MARKERS; +/// Most entries read from an RF64 file's `ds64` size table. +const MAX_DS64_TABLE: usize = 1_024; +/// Maximum retained RIFF chunk descriptors (including empty chunks). +pub const MAX_CHUNKS: usize = 100_000; +/// Maximum UTF-8 bytes in one retained cue label. +pub const MAX_LABEL_BYTES: usize = 64 * 1024; +/// Aggregate cue label bytes, enforced separately for the name map and emitted markers. +pub const MAX_LABEL_TOTAL_BYTES: usize = 4 * 1024 * 1024; + +fn u32_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_le_bytes(s.try_into().ok()?)) +} + +fn u64_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(8)?)?; + Some(u64::from_le_bytes(s.try_into().ok()?)) +} + +/// The text of a NUL-terminated label (the rest of the chunk), lossily decoded. +fn label(b: &[u8]) -> Option { + // Look only as far as one label can be retained; never copy an arbitrary chunk body. + let end = b.iter().take(MAX_LABEL_BYTES + 1).position(|&c| c == 0).unwrap_or(b.len()); + if end > MAX_LABEL_BYTES { + return None; + } + let text = String::from_utf8_lossy(b.get(..end)?); + let text = text.trim(); + (text.len() <= MAX_LABEL_BYTES).then(|| text.to_string()) +} + +/// Whether `bytes` start a RIFF/WAVE file. +pub fn is_wav(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some(b"RIFF" | b"RF64")) && bytes.get(8..12) == Some(b"WAVE") +} + +/// The sizes an RF64 file's `ds64` chunk gives for chunks too big for the 32-bit size field. +struct Ds64 { + /// The `data` chunk's size. + data: u64, + /// Other chunks: `(id, size)`. + table: Vec<([u8; 4], u64)>, +} + +impl Ds64 { + /// The real size of chunk `id`, when the file says. + fn size_of(&self, id: &[u8; 4]) -> Option { + if id == b"data" { Some(self.data) } else { self.table.iter().find(|(t, _)| t == id).map(|(_, size)| *size) } + } +} + +/// The `ds64` chunk of an RF64 file (`RF64`, size, `WAVE`, then `ds64`); `None` for any other file or one whose +/// `ds64` doesn't fit. +fn ds64(bytes: &[u8]) -> Option { + if bytes.get(0..4) != Some(b"RF64") || bytes.get(12..16) != Some(b"ds64") { + return None; + } + let size = usize::try_from(u32_at(bytes, 16)?).ok()?; + let body = bytes.get(20..20usize.checked_add(size)?)?; + // riff size (8), data size (8), sample count (8), table length (4), then `(id, size)` entries of 12 bytes + let data = u64_at(body, 8)?; + let entries = usize::try_from(u32_at(body, 24)?).ok()?; + let mut table = Vec::new(); + for i in 0..entries.min(MAX_DS64_TABLE) { + let at = 28usize.checked_add(i.checked_mul(12)?)?; + let id = <[u8; 4]>::try_from(body.get(at..at.checked_add(4)?)?).ok()?; + table.push((id, u64_at(body, at + 4)?)); + } + Some(Ds64 { data, table }) +} + +/// The chunks of a WAVE file as `(id, body)`, stopping at the first one that doesn't fit. +fn chunks<'a>(bytes: &'a [u8], limited: &mut bool) -> Vec<([u8; 4], &'a [u8])> { + let big = ds64(bytes); + let mut out = Vec::new(); + let mut at = 12usize; + while let Some(head) = bytes.get(at..at.saturating_add(8)) { + if out.len() == MAX_CHUNKS { + *limited = true; + break; + } + let (Ok(id), Some(field)) = (<[u8; 4]>::try_from(&head[..4]), u32_at(head, 4)) else { break }; + // In an RF64 file a size field of 0xFFFFFFFF stands for the size `ds64` gives. + let size = match &big { + Some(d) if field == u32::MAX => d.size_of(&id).unwrap_or(u64::from(field)), + _ => u64::from(field), + }; + let start = at.saturating_add(8); + let Some(end) = usize::try_from(size).ok().and_then(|n| start.checked_add(n)) else { break }; + let Some(body) = bytes.get(start..end) else { break }; + out.push((id, body)); + // Chunks are padded to an even size. + at = end.saturating_add(end & 1); + } + out +} + +/// Read bounded cue/adtl and XMP metadata without interpreting application timeline policy. +pub fn read(bytes: &[u8]) -> Markers { + if !is_wav(bytes) { + return Markers::default(); + } + let mut limited = false; + let chunks = chunks(bytes, &mut limited); + let rate = chunks.iter().find(|(id, _)| id == b"fmt ").and_then(|(_, b)| u32_at(b, 4)).map_or(0.0, f64::from); + let cue = cue_markers(&chunks, rate, &mut limited); + let xmp = chunks.iter().find(|(id, _)| id == b"_PMX").map_or_else(Vec::new, |(_, xmp)| xmp_markers(xmp, rate)); + Markers { cue, xmp, limited } +} + +/// Cue points named and sized by the `adtl` list. +fn cue_markers(chunks: &[([u8; 4], &[u8])], rate: f64, limited: &mut bool) -> Vec { + let Some((_, cue)) = chunks.iter().find(|(id, _)| id == b"cue ") else { return Vec::new() }; + let count = (u32_at(cue, 0).unwrap_or(0) as usize).min(MAX_MARKERS); + // The cue points first: `(id, offset in samples)`. + let mut points = Vec::new(); + for i in 0..count { + let Some(point) = cue.get(4usize.saturating_add(i.saturating_mul(24))..) else { break }; + let (Some(id), Some(offset)) = (u32_at(point, 0), u32_at(point, 20)) else { break }; + points.push((id, offset)); + } + // Only the names and lengths of those ids are kept, so a hostile `adtl` list cannot grow them past the cue count, + // and each record is a lookup, not a scan. + let wanted: HashSet = points.iter().map(|(id, _)| *id).collect(); + let mut names: HashMap = HashMap::new(); + let mut lengths: HashMap = HashMap::new(); + let mut name_bytes = 0usize; + let mut records = 0usize; + 'lists: for (_, list) in chunks.iter().filter(|(id, b)| id == b"LIST" && b.get(0..4) == Some(b"adtl")) { + let mut at = 4usize; + while let Some(head) = list.get(at..at.saturating_add(8)) { + let (Ok(id), Some(size)) = (<[u8; 4]>::try_from(&head[..4]), u32_at(head, 4)) else { break }; + let start = at.saturating_add(8); + let Some(end) = start.checked_add(size as usize) else { break }; + let Some(body) = list.get(start..end) else { break }; + records += 1; + if records > MAX_ADTL_RECORDS { + break 'lists; + } + if let Some(cue_id) = u32_at(body, 0).filter(|c| wanted.contains(c)) { + match &id { + // A `labl` is the name; a `note` only when there is none. + b"labl" | b"note" if id == *b"labl" || !names.contains_key(&cue_id) => { + let without_old = name_bytes.saturating_sub(names.get(&cue_id).map_or(0, String::len)); + let text = label(body.get(4..).unwrap_or_default()) + .filter(|text| text.len() <= MAX_LABEL_TOTAL_BYTES.saturating_sub(without_old)) + .unwrap_or_else(|| { + *limited = true; + String::new() + }); + name_bytes = without_old + text.len(); + names.insert(cue_id, text); + } + // The first `ltxt` of a cue point gives its length. + b"ltxt" => { + lengths.entry(cue_id).or_insert_with(|| u32_at(body, 4).unwrap_or(0)); + } + _ => {} + } + } + at = end.saturating_add(end & 1); + } + } + let mut emitted_bytes = 0usize; + points + .into_iter() + .map(|(id, offset)| { + let comment = match names.get(&id) { + Some(text) if text.len() <= MAX_LABEL_TOTAL_BYTES.saturating_sub(emitted_bytes) => { + emitted_bytes += text.len(); + text.clone() + } + Some(_) => { + *limited = true; + String::new() + } + None => String::new(), + }; + let length = lengths.get(&id).copied().unwrap_or(0); + Marker { start: f64::from(offset), duration: f64::from(length), rate, name: comment } + }) + .collect() +} + +/// The text of `name` in an XMP entry, as an attribute (`name="v"`) or an element +/// (`v`). +fn xmp_value(entry: &str, name: &str) -> Option { + // Each entry starts just after ` in_tag = true, + b'>' => in_tag = false, + b'\'' | b'"' if in_tag => { + let quote = bytes[at]; + at += 1; + while at < bytes.len() && bytes[at] != quote { + at += 1; + } + } + _ if in_tag && (at == 0 || xml_space(bytes[at - 1])) && bytes[at..].starts_with(name.as_bytes()) => { + let mut value = at + name.len(); + while value < bytes.len() && xml_space(bytes[value]) { + value += 1; + } + if bytes.get(value) == Some(&b'=') { + value += 1; + while value < bytes.len() && xml_space(bytes[value]) { + value += 1; + } + if let Some("e @ (b'\'' | b'"')) = bytes.get(value) { + let start = value + 1; + let end = bytes.get(start..)?.iter().position(|&b| b == quote)? + start; + return Some(unescape(entry.get(start..end)?)); + } + } + } + _ => {} + } + at += 1; + } + let open = format!("<{name}>"); + let i = entry.find(&open)?; + let rest = entry.get(i + open.len()..)?; + Some(unescape(rest.get(..rest.find('<')?)?)) +} + +fn xml_space(b: u8) -> bool { + matches!(b, b' ' | b'\t' | b'\r' | b'\n') +} + +fn unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find('&') { + out.push_str(rest.get(..i).unwrap_or_default()); + let tail = rest.get(i..).unwrap_or_default(); + let Some(semi) = tail.as_bytes().iter().take(11).position(|b| *b == b';') else { + out.push('&'); + rest = tail.get(1..).unwrap_or_default(); + continue; + }; + let ent = tail.get(1..semi).unwrap_or_default(); + match ent { + "amp" => out.push('&'), + "lt" => out.push('<'), + "gt" => out.push('>'), + "quot" => out.push('"'), + "apos" => out.push('\''), + _ => { + let code = ent + .strip_prefix("#x") + .and_then(|h| u32::from_str_radix(h, 16).ok()) + .or_else(|| ent.strip_prefix('#').and_then(|d| d.parse().ok())); + match code.and_then(char::from_u32) { + Some(c) => out.push(c), + None => out.push_str(tail.get(..=semi).unwrap_or_default()), + } + } + } + rest = tail.get(semi + 1..).unwrap_or_default(); + } + out.push_str(rest); + out.trim().to_string() +} + +/// A frame rate as XMP writes it: `f44100`, or `f30000s1001` (rate over scale). +fn xmp_rate(text: &str) -> Option { + let t = text.trim().strip_prefix('f')?; + let (num, den) = t.split_once('s').unwrap_or((t, "1")); + let (n, d): (f64, f64) = (num.parse().ok()?, den.parse().ok()?); + (n.is_finite() && d.is_finite() && n > 0.0 && d > 0.0 && (n / d).is_finite() && n / d > 0.0).then_some(n / d) +} + +/// Adobe XMP FrameCount: a count optionally followed by `fRATE[sSCALE]`. +/// Bare counts retain the caller's legacy track/file-rate interpretation. +fn xmp_count(text: &str, default_rate: f64) -> Option<(f64, f64)> { + let text = text.trim(); + let (count, rate) = match text.find('f') { + Some(at) => (text.get(..at)?, xmp_rate(text.get(at..)?)?), + None => (text, default_rate), + }; + let count: f64 = count.parse().ok()?; + (count.is_finite() && rate.is_finite() && rate > 0.0).then_some((count, rate)) +} + +/// The markers of an XMP packet's `xmpDM:markers` entries. +fn xmp_markers(packet: &[u8], file_rate: f64) -> Vec { + let text = String::from_utf8_lossy(packet.get(..packet.len().min(MAX_XMP)).unwrap_or_default()); + let mut out = Vec::new(); + // The frame rate belongs to the track an entry follows. + let mut rate = file_rate; + for entry in text.split("= MAX_MARKERS { + break; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TimedMarker { + time: f64, + duration: f64, + comment: String, + } + fn read(bytes: &[u8]) -> Vec { + let metadata = super::read(bytes); + let time = |frames: f64, rate: f64| if rate > 0.0 && frames.is_finite() { (frames / rate).max(0.0) } else { 0.0 }; + let map = |m: Marker| TimedMarker { time: time(m.start, m.rate), duration: time(m.duration, m.rate), comment: m.name }; + let mut out: Vec<_> = metadata.cue.into_iter().map(map).collect(); + let mut seen: HashSet<_> = out.iter().map(|m| (m.comment.clone(), m.time.to_bits())).collect(); + for m in metadata.xmp.into_iter().map(map) { + if seen.insert((m.comment.clone(), m.time.to_bits())) { + out.push(m); + } + } + out.truncate(MAX_MARKERS); + out.sort_by(|a, b| a.time.total_cmp(&b.time)); + out + } + + fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut v = id.to_vec(); + v.extend((body.len() as u32).to_le_bytes()); + v.extend(body); + if body.len() % 2 == 1 { + v.push(0); + } + v + } + + fn fmt(rate: u32) -> Vec { + let mut b = Vec::new(); + b.extend(1u16.to_le_bytes()); // PCM + b.extend(1u16.to_le_bytes()); // mono + b.extend(rate.to_le_bytes()); + b.extend((rate * 2).to_le_bytes()); + b.extend(2u16.to_le_bytes()); + b.extend(16u16.to_le_bytes()); + chunk(b"fmt ", &b) + } + + fn wav(chunks: &[Vec]) -> Vec { + let body: Vec = chunks.iter().flatten().copied().collect(); + let mut v = b"RIFF".to_vec(); + v.extend((body.len() as u32 + 4).to_le_bytes()); + v.extend(b"WAVE"); + v.extend(body); + v + } + + fn cue(points: &[(u32, u32)]) -> Vec { + let mut b = (points.len() as u32).to_le_bytes().to_vec(); + for (id, offset) in points { + b.extend(id.to_le_bytes()); + b.extend(0u32.to_le_bytes()); + b.extend(b"data"); + b.extend(0u32.to_le_bytes()); + b.extend(0u32.to_le_bytes()); + b.extend(offset.to_le_bytes()); + } + chunk(b"cue ", &b) + } + + fn labl(id: &[u8; 4], cue_id: u32, text: &str) -> Vec { + let mut b = cue_id.to_le_bytes().to_vec(); + b.extend(text.as_bytes()); + b.push(0); + chunk(id, &b) + } + + fn adtl(subs: &[Vec]) -> Vec { + let mut b = b"adtl".to_vec(); + b.extend(subs.iter().flatten()); + chunk(b"LIST", &b) + } + + #[test] + fn cue_points_are_named_by_the_adtl_list_and_timed_in_samples() { + let file = wav(&[ + fmt(44100), + chunk(b"data", &[0; 8]), + cue(&[(2, 88200), (1, 22050)]), + adtl(&[labl(b"labl", 1, "SEQ01_Prologue"), labl(b"labl", 2, "SEQ02_Vallee_P1_Agriculture")]), + ]); + let m = read(&file); + assert_eq!(m.len(), 2); + assert_eq!((m[0].comment.as_str(), m[0].time), ("SEQ01_Prologue", 0.5)); + assert_eq!((m[1].comment.as_str(), m[1].time), ("SEQ02_Vallee_P1_Agriculture", 2.0)); + } + + #[test] + fn a_note_names_a_cue_only_when_it_has_no_label_and_ltxt_gives_a_length() { + let mut ltxt = 1u32.to_le_bytes().to_vec(); + ltxt.extend(44100u32.to_le_bytes()); + ltxt.extend([0; 16]); + let file = wav(&[ + fmt(44100), + cue(&[(1, 0), (2, 44100)]), + adtl(&[labl(b"note", 1, "from note"), chunk(b"ltxt", <xt), labl(b"labl", 2, "named"), labl(b"note", 2, "ignored")]), + ]); + let m = read(&file); + assert_eq!((m[0].comment.as_str(), m[0].duration), ("from note", 1.0)); + assert_eq!(m[1].comment, "named"); + } + + const XMP_ELEMENTS: &str = r#"MarkersCuef44100441000One & Two13230022050Three"#; + + #[test] + fn xmp_markers_are_read_as_elements_in_frames_of_the_track_rate() { + let file = wav(&[fmt(48000), chunk(b"_PMX", XMP_ELEMENTS.as_bytes())]); + let m = read(&file); + assert_eq!(m.len(), 2); + // 44100 frames at f44100 is one second, whatever the file's own rate. + assert_eq!((m[0].comment.as_str(), m[0].time), ("One & Two", 1.0)); + assert_eq!((m[1].comment.as_str(), m[1].time, m[1].duration), ("Three", 3.0, 0.5)); + } + + #[test] + fn xmp_markers_are_read_as_attributes_and_use_the_file_rate_without_a_track_rate() { + let xmp = r#""#; + let m = read(&wav(&[fmt(48000), chunk(b"_PMX", xmp.as_bytes())])); + assert_eq!((m[0].comment.as_str(), m[0].time), ("Attr é", 0.5)); + } + + #[test] + fn a_marker_in_both_encodings_is_listed_once() { + let xmp = r#""#; + let file = wav(&[fmt(44100), cue(&[(1, 44100)]), adtl(&[labl(b"labl", 1, "Same")]), chunk(b"_PMX", xmp.as_bytes())]); + let names: Vec = read(&file).into_iter().map(|m| m.comment).collect(); + assert_eq!(names, ["Same", "Only XMP"]); + } + + #[test] + fn damaged_or_hostile_files_read_as_far_as_they_go_without_panicking() { + assert!(read(b"").is_empty()); + assert!(read(b"RIFF").is_empty()); + assert!(read(b"not a wav file at all").is_empty()); + let good = wav(&[fmt(44100), cue(&[(1, 44100)]), adtl(&[labl(b"labl", 1, "Kept")])]); + // Every truncation is safe. + for n in 0..good.len() { + let _ = read(&good[..n]); + } + // A cue count far beyond the chunk, and chunk sizes past the end of the file. + let mut huge = 0xFFFF_FFFFu32.to_le_bytes().to_vec(); + huge.extend([0; 24]); + let m = read(&wav(&[fmt(44100), chunk(b"cue ", &huge)])); + assert!(m.len() <= 1); + let mut lying = good.clone(); + lying.extend(b"LIST\xff\xff\xff\xffadtl"); + assert_eq!(read(&lying).len(), 1); + // No sample rate: times are zero, not a division by zero. + let m = read(&wav(&[cue(&[(1, 44100)])])); + assert_eq!(m[0].time, 0.0); + } + + /// A chunk whose size field says `field` (an RF64 file's `0xFFFFFFFF`) while its body is `body`. + fn chunk_with_size_field(id: &[u8; 4], field: u32, body: &[u8]) -> Vec { + let mut v = id.to_vec(); + v.extend(field.to_le_bytes()); + v.extend(body); + if body.len() % 2 == 1 { + v.push(0); + } + v + } + + /// An RF64 `ds64` chunk: the `data` chunk's size and a table of other chunks' sizes. + fn ds64_chunk(data_size: u64, table: &[([u8; 4], u64)]) -> Vec { + let mut b = 0u64.to_le_bytes().to_vec(); // riff size (not used) + b.extend(data_size.to_le_bytes()); + b.extend(0u64.to_le_bytes()); // sample count + b.extend((table.len() as u32).to_le_bytes()); + for (id, size) in table { + b.extend(id); + b.extend(size.to_le_bytes()); + } + chunk(b"ds64", &b) + } + + fn rf64(chunks: &[Vec]) -> Vec { + let body: Vec = chunks.iter().flatten().copied().collect(); + let mut v = b"RF64".to_vec(); + v.extend(u32::MAX.to_le_bytes()); + v.extend(b"WAVE"); + v.extend(body); + v + } + + #[test] + fn rf64_markers_after_a_data_chunk_of_sentinel_size_are_read() { + let audio = [0u8; 8]; + let file = rf64(&[ + ds64_chunk(audio.len() as u64, &[]), + fmt(44100), + chunk_with_size_field(b"data", u32::MAX, &audio), + cue(&[(1, 44100)]), + adtl(&[labl(b"labl", 1, "After the audio")]), + ]); + let m = read(&file); + assert_eq!(m.len(), 1); + assert_eq!((m[0].comment.as_str(), m[0].time), ("After the audio", 1.0)); + } + + #[test] + fn rf64_sizes_of_other_chunks_come_from_the_ds64_table() { + let junk = [7u8; 6]; + let tail = || [cue(&[(1, 8000)]), adtl(&[labl(b"labl", 1, "Found")])].concat(); + let with_entry = rf64(&[ds64_chunk(0, &[(*b"junk", junk.len() as u64)]), fmt(8000), chunk_with_size_field(b"junk", u32::MAX, &junk), tail()]); + assert_eq!(read(&with_entry)[0].comment, "Found"); + // Without the table entry the sentinel is all there is, and what follows is not reached. + let without = rf64(&[ds64_chunk(0, &[]), fmt(8000), chunk_with_size_field(b"junk", u32::MAX, &junk), tail()]); + assert!(read(&without).is_empty()); + } + + #[test] + fn hostile_rf64_size_tables_read_as_far_as_they_go_without_panicking() { + // sizes that overflow when added to an offset + for data in [u64::MAX, u64::MAX - 7, 1 << 63] { + let file = + rf64(&[ds64_chunk(data, &[(*b"junk", u64::MAX)]), fmt(8000), chunk_with_size_field(b"data", u32::MAX, &[0; 4]), cue(&[(1, 0)])]); + assert!(read(&file).is_empty()); + } + // a table that claims far more entries than its chunk holds + let mut liar = ds64_chunk(0, &[]); + liar[8 + 24..8 + 28].copy_from_slice(&u32::MAX.to_le_bytes()); + let _ = read(&rf64(&[liar, fmt(8000), cue(&[(1, 0)])])); + // every truncation of a good RF64 file is safe + let good = rf64(&[ + ds64_chunk(4, &[]), + fmt(44100), + chunk_with_size_field(b"data", u32::MAX, &[0; 4]), + cue(&[(1, 44100)]), + adtl(&[labl(b"labl", 1, "Kept")]), + ]); + assert_eq!(read(&good).len(), 1); + for n in 0..good.len() { + let _ = read(&good[..n]); + } + } + + #[test] + fn a_huge_adtl_list_is_read_in_linear_time_and_only_for_the_cue_points_that_exist() { + // Records for ids that have no cue point are skipped, not stored, and the number looked at is capped. + let junk = |n: u32| (1000..1000 + n).map(|id| labl(b"labl", id, "n")).collect::>(); + let started = std::time::Instant::now(); + // the real label comes first: read + let mut subs = vec![labl(b"labl", 1, "Real")]; + subs.extend(junk(100_000)); + let m = read(&wav(&[fmt(44100), cue(&[(1, 44100)]), adtl(&subs)])); + assert_eq!(m[0].comment, "Real"); + // it comes after more records than are looked at: not read, and the marker is still there + let mut subs = junk(MAX_ADTL_RECORDS as u32 + 10); + subs.push(labl(b"labl", 1, "Too late")); + let m = read(&wav(&[fmt(44100), cue(&[(1, 44100)]), adtl(&subs)])); + assert_eq!((m.len(), m[0].comment.as_str()), (1, "")); + assert!(started.elapsed() < std::time::Duration::from_secs(5), "took {:?}", started.elapsed()); + } + + #[test] + fn metadata_keeps_original_coordinates_and_separate_sources() { + let xmp = br#""#; + let file = wav(&[fmt(44100), cue(&[(1, 1)]), adtl(&[labl(b"labl", 1, "Same")]), chunk(b"_PMX", xmp)]); + let data = super::read(&file); + assert_eq!(data.cue[0].start, 1.0); + assert_eq!(data.cue[0].rate, 44100.0); + assert_eq!(data.xmp[0].start, 1.0); + assert_eq!(data.xmp[0].duration, 2.0); + assert_eq!(data.cue.len(), 1); + assert_eq!(data.xmp.len(), 1); + } + + #[test] + fn repeated_unterminated_entities_preserve_text_with_bounded_lookahead() { + let text = "&".repeat(100_000); + assert_eq!(unescape(&text), text); + assert_eq!(unescape("A A & &unknown;"), "A A & &unknown;"); + } + #[test] + fn repeated_cue_ids_cannot_multiply_label_storage() { + let text = "x".repeat(MAX_LABEL_BYTES); + let points: Vec<_> = (0..MAX_MARKERS).map(|i| (1, i as u32)).collect(); + let file = wav(&[fmt(44100), cue(&points), adtl(&[labl(b"labl", 1, &text)])]); + let metadata = super::read(&file); + assert_eq!(metadata.cue.len(), MAX_MARKERS); + assert_eq!(metadata.cue.iter().map(|m| m.name.len()).sum::(), MAX_LABEL_TOTAL_BYTES); + assert!(metadata.limited); + assert_eq!(metadata.cue[0].name, text); + assert!(metadata.cue[MAX_MARKERS - 1].name.is_empty()); + assert_eq!(metadata.cue[MAX_MARKERS - 1].start, (MAX_MARKERS - 1) as f64); + } + + #[test] + fn cue_name_map_and_single_label_are_bounded() { + let count = MAX_LABEL_TOTAL_BYTES / MAX_LABEL_BYTES + 2; + let text = "x".repeat(MAX_LABEL_BYTES); + let points: Vec<_> = (0..count as u32).map(|i| (i, i)).collect(); + let labels: Vec<_> = (0..count as u32).map(|i| labl(b"labl", i, &text)).collect(); + let metadata = super::read(&wav(&[fmt(44100), cue(&points), adtl(&labels)])); + assert!(metadata.limited); + assert_eq!(metadata.cue.iter().map(|m| m.name.len()).sum::(), MAX_LABEL_TOTAL_BYTES); + let oversized = "x".repeat(MAX_LABEL_BYTES + 1); + let metadata = super::read(&wav(&[fmt(44100), cue(&[(1, 3)]), adtl(&[labl(b"labl", 1, &oversized)])])); + assert!(metadata.limited); + assert_eq!(metadata.cue[0].start, 3.0); + assert!(metadata.cue[0].name.is_empty()); + } + + #[test] + fn empty_chunk_inventory_is_bounded() { + let empty = chunk(b"junk", &[]); + let many = empty.repeat(MAX_CHUNKS + 1); + let metadata = super::read(&wav(&[many, fmt(44100), cue(&[(1, 1)])])); + assert!(metadata.limited); + assert!(metadata.cue.is_empty()); + } + + #[test] + fn entity_lookahead_keeps_previous_semicolon_boundary() { + assert_eq!(unescape("A"), "A"); + assert_eq!(unescape("A"), "A"); + } + #[test] + fn xmp_quotes_spacing_and_attribute_boundaries() { + let packet = br#""#; + let markers = xmp_markers(packet, 48000.0); + assert_eq!(markers.len(), 1); + assert_eq!((markers[0].start, markers[0].duration, markers[0].rate), (24000.0, 12000.0, 48000.0)); + assert_eq!(markers[0].name, "single & quoted"); + let spoof = r#" label=" xmpDM:startTime='7'" otherxmpDM:startTime='8' xmpDM:startTime = '9'/>"#; + assert_eq!(xmp_value(spoof, "xmpDM:startTime").as_deref(), Some("9")); + assert!(xmp_value(" xmpDM:startTime='unterminated", "xmpDM:startTime").is_none()); + } + + #[test] + fn xmp_frame_counts_preserve_explicit_and_mixed_rates() { + let packet = br#""#; + let markers = xmp_markers(packet, 44100.0); + assert_eq!(markers.len(), 3); + assert_eq!((markers[0].start, markers[0].rate), (15.0, 24.0)); + assert!((markers[0].duration / markers[0].rate - 0.5005).abs() < 1e-12); + assert_eq!((markers[1].start, markers[1].duration, markers[1].rate), (48000.0, 24000.0, 48000.0)); + assert_eq!((markers[2].start, markers[2].duration, markers[2].rate), (15.0, 12.0, 24.0)); + for invalid in ["15f0", "15f24s0", "15fNaN", "15finf", "NaN", "1e999", "15f24junk"] { + assert!(xmp_count(invalid, 48000.0).is_none(), "{invalid}"); + } + } +} diff --git a/crates/audio/src/wav_range.rs b/crates/audio/src/wav_range.rs new file mode 100644 index 0000000000..33762caf2f --- /dev/null +++ b/crates/audio/src/wav_range.rs @@ -0,0 +1,223 @@ +//! Range-backed PCM WAVE reader and canonical 16-bit writer. +//! +//! Reads chunk headers and only the requested sample range; it never loads a whole file. + +use crate::{AudioError, Result}; +use craft_media::ByteSource; + +/// Whether a prefix identifies a RIFF or RF64 WAVE file. +pub fn sniff(b: &[u8]) -> bool { + b.len() >= 12 && (&b[0..4] == b"RIFF" || &b[0..4] == b"RF64") && &b[8..12] == b"WAVE" +} + +const MAX_CHUNKS: usize = 1 << 16; +const IXML_MAX: u64 = 1 << 20; +/// Maximum sample data returned by a single range read. +pub const MAX_RANGE_BYTES: u64 = 4 << 20; + +fn le16(b: &[u8], o: usize) -> u16 { + b.get(o..o.saturating_add(2)).and_then(|s| s.try_into().ok()).map_or(0, u16::from_le_bytes) +} +fn le32(b: &[u8], o: usize) -> u32 { + b.get(o..o.saturating_add(4)).and_then(|s| s.try_into().ok()).map_or(0, u32::from_le_bytes) +} +fn read_range(source: &impl ByteSource, off: u64, len: usize) -> Result> { + let mut bytes = vec![0; len]; + source.read_at(off, &mut bytes)?; + Ok(bytes) +} + +/// A PCM WAVE file held by an arbitrary random-access source. +pub struct WavRange { + source: S, + /// Number of complete sample frames. + pub frames: u64, + /// Channel count. + pub channels: u16, + /// Sample rate in Hz. + pub rate: u32, + /// Container bits per sample. + pub bits: u16, + /// Whether samples are floating point. + pub float: bool, + /// BWF time reference in samples, from bext or iXML. + pub time_reference: Option, + data_off: u64, +} + +impl WavRange { + /// Open with caller-selected bounds on channel count and sample rate. + pub fn open(source: S, max_channels: u32, max_rate: u32) -> Result { + let len = source.len(); + let mut pos: u64 = 12; + let mut fmt = None; + let mut data = None; + let mut bext_tr = None; + let mut ixml_tr = None; + let mut ds64_data = None; + for _ in 0..MAX_CHUNKS { + let Some(body) = pos.checked_add(8).filter(|&b| b <= len) else { break }; + let mut hdr = [0u8; 8]; + source.read_at(pos, &mut hdr)?; + let id = &hdr[0..4]; + let mut clen = u64::from(le32(&hdr, 4)); + let rest = len - body; + if id == b"data" { + if clen == 0xFFFF_FFFF { + clen = ds64_data.unwrap_or(rest); + } + clen = clen.min(rest); + } + if clen > rest { + break; + } + match id { + b"fmt " if clen >= 16 => { + let b = read_range(&source, body, clen.min(40) as usize)?; + let mut tag = le16(&b, 0); + if tag == 0xFFFE && clen >= 40 { + tag = le16(&b, 24); + } + fmt = Some((tag, le16(&b, 2), le32(&b, 4), le16(&b, 14))); + } + b"ds64" if clen >= 16 => { + let b = read_range(&source, body + 8, 8)?; + ds64_data = Some(u64::from(le32(&b, 0)) | u64::from(le32(&b, 4)) << 32); + } + b"data" => data = Some((body, clen)), + b"bext" if clen >= 346 => { + let b = read_range(&source, body + 338, 8)?; + bext_tr = Some(u64::from(le32(&b, 0)) | u64::from(le32(&b, 4)) << 32); + } + b"iXML" => { + let b = read_range(&source, body, clen.min(IXML_MAX) as usize)?; + ixml_tr = ixml_time_reference(&b); + } + _ => {} + } + pos = body.saturating_add(clen).saturating_add(clen & 1); + } + let (tag, channels, rate, bits) = fmt.ok_or_else(|| AudioError::Malformed("missing fmt chunk".into()))?; + let (data_off, dlen) = data.ok_or_else(|| AudioError::Malformed("missing data chunk".into()))?; + let float = tag == 3; + if !(tag == 1 || float) + || channels == 0 + || rate == 0 + || u32::from(channels) > max_channels + || rate > max_rate + || !matches!(bits, 8 | 16 | 24 | 32 | 64) + { + return Err(AudioError::Unsupported(format!("WAV format tag {tag}, {bits} bits"))); + } + let frames = dlen / (u64::from(channels) * u64::from(bits / 8)); + Ok(Self { source, frames, channels, rate, bits, float, time_reference: bext_tr.or(ixml_tr), data_off }) + } + /// Bytes in one whole frame. + pub fn frame_bytes(&self) -> usize { + usize::from(self.channels) * usize::from(self.bits / 8) + } + /// Read the inclusive range of frames, capped to prevent unbounded allocation. + pub fn read_frames(&self, first: u64, last: u64) -> Result> { + if first > last || last >= self.frames { + return Err(AudioError::Malformed("WAV frame range outside data".into())); + } + let n = (last - first + 1).saturating_mul(self.frame_bytes() as u64); + if n > MAX_RANGE_BYTES { + return Err(AudioError::TooLarge("WAV frame range".into())); + } + let off = self.data_off.saturating_add(first.saturating_mul(self.frame_bytes() as u64)); + read_range(&self.source, off, n as usize) + } + /// Decode a channel from a buffer returned by `read_frames`. + pub fn sample(&self, block: &[u8], frame: usize, ch: usize) -> f32 { + if ch >= usize::from(self.channels) { + return 0.0; + } + let bps = usize::from(self.bits / 8); + let Some(o) = frame.checked_mul(usize::from(self.channels)).and_then(|v| v.checked_add(ch)).and_then(|v| v.checked_mul(bps)) else { + return 0.0; + }; + let Some(b) = block.get(o..o.saturating_add(bps)) else { return 0.0 }; + match (self.bits, self.float, b) { + (8, _, &[a]) => (a as f32 - 128.0) / 128.0, + (16, _, &[a, b]) => i16::from_le_bytes([a, b]) as f32 / 32768.0, + (24, _, &[a, b, c]) => (i32::from_le_bytes([0, a, b, c]) >> 8) as f32 / 8_388_608.0, + (32, false, &[a, b, c, d]) => i32::from_le_bytes([a, b, c, d]) as f32 / 2_147_483_648.0, + (32, true, &[a, b, c, d]) => f32::from_le_bytes([a, b, c, d]), + (64, true, b) => f64::from_le_bytes(b.try_into().unwrap_or([0; 8])) as f32, + _ => 0.0, + } + } +} + +fn ixml_time_reference(x: &[u8]) -> Option { + let text = String::from_utf8_lossy(x); + let field = |tag: &str| -> Option { + let open = format!("<{tag}>"); + let a = text.find(&open)? + open.len(); + let b = a + text[a..].find('<')?; + text[a..b].trim().parse().ok() + }; + let low = field("BWF_TIME_REFERENCE_LOW")?; + Some(low | field("BWF_TIME_REFERENCE_HIGH").unwrap_or(0) << 32) +} + +/// Write interleaved samples as 16-bit PCM WAVE, using symmetric 32767 scaling. +#[cfg(feature = "pcm-encode")] +pub fn write_wav16(samples: &[f32], channels: u16, rate: u32) -> Vec { + let data_len = samples.len().saturating_mul(2); + let mut v = crate::pcm_wav_header(u32::try_from(data_len).unwrap_or(u32::MAX), channels, rate, 16); + v.reserve(data_len); + for s in samples { + v.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes()); + } + v +} + +#[cfg(all(test, feature = "pcm-encode"))] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + struct Source { + bytes: Vec, + reads: Arc>>, + } + impl ByteSource for Source { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + self.reads.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((offset, buf.len())); + self.bytes.read_at(offset, buf) + } + } + #[test] + fn bounded_reads_and_pcm_values() { + let bytes = write_wav16(&[-1.0, -0.5, 0.0, 0.5, 1.0], 1, 48_000); + let reads = Arc::new(Mutex::new(Vec::new())); + let wav = WavRange::open(Source { bytes, reads: reads.clone() }, 64, 384_000).unwrap(); + assert_eq!((wav.frames, wav.channels, wav.rate, wav.bits), (5, 1, 48_000, 16)); + assert!(reads.lock().unwrap().iter().all(|(_, n)| *n <= 40)); + let data = wav.read_frames(1, 3).unwrap(); + assert_eq!(wav.sample(&data, 0, 0), -0.5); + assert_eq!(wav.sample(&data, 2, 0), 0.5); + assert!(wav.read_frames(0, 5).is_err()); + assert!(wav.read_frames(3, 1).is_err()); + assert_eq!(reads.lock().unwrap().last(), Some(&(46, 6))); + } + #[test] + fn ixml_fallback_accepts_flat_fields() { + let base = write_wav16(&[0.0], 1, 48_000); + let mut bytes = base[..36].to_vec(); + let xml = b"51"; + bytes.extend_from_slice(b"iXML"); + bytes.extend_from_slice(&(xml.len() as u32).to_le_bytes()); + bytes.extend_from_slice(xml); + if xml.len() & 1 != 0 { + bytes.push(0); + } + bytes.extend_from_slice(&base[36..]); + assert_eq!(WavRange::open(bytes.as_slice(), 64, 384_000).unwrap().time_reference, Some((1 << 32) + 5)); + } +} diff --git a/crates/audio/src/wav_stream.rs b/crates/audio/src/wav_stream.rs new file mode 100644 index 0000000000..9da2bdcc9d --- /dev/null +++ b/crates/audio/src/wav_stream.rs @@ -0,0 +1,119 @@ +//! Canonical RIFF/WAVE header and interleaved sample blocks for non-seekable sinks. +//! +//! Extracted from AniCraft's WAV writer, preserving its byte-level compatibility. +//! Unlike `FileEncoder`, these primitives do not require `Seek` and leave final lengths, +//! chunk padding and sink error handling to the caller. The caller must supply a complete +//! frame count and append exactly that many frames. For odd-length data, append a pad byte +//! (the header includes that padding in the RIFF size); current AniCraft output is always stereo (even). +//! Non-finite samples become silence, including float output. This deliberately differs +//! from the general encoder's infinity handling. Prefer `FileEncoder` for new seekable sinks. + +/// Sample formats written. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Bits { + /// Signed 16-bit PCM. + Int16, + /// Signed 24-bit PCM. + Int24, + /// IEEE 754 32-bit float. + Float32, +} + +impl Bits { + fn bytes(self) -> u16 { + match self { + Bits::Int16 => 2, + Bits::Int24 => 3, + Bits::Float32 => 4, + } + } +} + +const PCM: u16 = 1; +const FLOAT: u16 = 3; + +/// A WAV header for `frames` frames of `channels` channels. +/// Returns `None` for zero rate/channels or any size/byte-rate field overflow. +pub fn header(rate: u32, channels: u16, bits: Bits, frames: u64) -> Option> { + if rate == 0 || channels == 0 { + return None; + } + let b = bits.bytes(); + let data = u32::try_from(frames.checked_mul(u64::from(b) * u64::from(channels))?).ok()?; + let riff = data.checked_add(36)?.checked_add(data & 1)?; + let block = channels.checked_mul(b)?; + let byte_rate = rate.checked_mul(u32::from(block))?; + let tag = if bits == Bits::Float32 { FLOAT } else { PCM }; + let mut h = Vec::with_capacity(44); + h.extend_from_slice(b"RIFF"); + h.extend_from_slice(&riff.to_le_bytes()); + h.extend_from_slice(b"WAVEfmt "); + h.extend_from_slice(&16u32.to_le_bytes()); + h.extend_from_slice(&tag.to_le_bytes()); + h.extend_from_slice(&channels.to_le_bytes()); + h.extend_from_slice(&rate.to_le_bytes()); + h.extend_from_slice(&byte_rate.to_le_bytes()); + h.extend_from_slice(&block.to_le_bytes()); + h.extend_from_slice(&(b * 8).to_le_bytes()); + h.extend_from_slice(b"data"); + h.extend_from_slice(&data.to_le_bytes()); + Some(h) +} + +/// Appends samples in `bits` format. Integers are rounded and clipped to range; `x · 32768` +/// for 16-bit, so 16-bit sources read by [`crate::decode`] come back bit-identical. +pub fn append(out: &mut Vec, samples: &[f32], bits: Bits) { + out.reserve(samples.len() * usize::from(bits.bytes())); + for &s in samples { + let s = if s.is_finite() { s } else { 0.0 }; + match bits { + Bits::Int16 => out.extend_from_slice(&((s * 32_768.0).round().clamp(-32_768.0, 32_767.0) as i16).to_le_bytes()), + Bits::Int24 => { + let v = (f64::from(s) * 8_388_608.0).round().clamp(-8_388_608.0, 8_388_607.0) as i32; + out.extend_from_slice(v.to_le_bytes().get(..3).unwrap_or(&[0, 0, 0])); + } + Bits::Float32 => out.extend_from_slice(&s.to_le_bytes()), + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + + #[test] + fn canonical_header_and_odd_padding() { + let h = header(48_000, 2, Bits::Int16, 1).unwrap(); + assert_eq!(h.len(), 44); + assert_eq!(&h[..12], b"RIFF\x28\0\0\0WAVE"); + assert_eq!(&h[28..36], &[0, 238, 2, 0, 4, 0, 16, 0]); + let h = header(8_000, 1, Bits::Int24, 1).unwrap(); + assert_eq!(&h[4..8], &40u32.to_le_bytes()); + assert_eq!(&h[40..44], &3u32.to_le_bytes()); + assert!(header(0, 2, Bits::Int16, 1).is_none()); + assert!(header(48_000, 0, Bits::Int16, 1).is_none()); + assert!(header(u32::MAX, 2, Bits::Int16, 1).is_none()); + assert!(header(48_000, 2, Bits::Float32, u64::MAX).is_none()); + assert!(header(48_000, u16::MAX, Bits::Float32, 0).is_none()); + } + + #[test] + fn samples_preserve_rounding_clipping_silence_and_chunk_boundaries() { + let samples = [-2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY]; + let mut pcm = Vec::new(); + append(&mut pcm, &samples, Bits::Int16); + let expected = [-32768i16, -32768, -16384, 0, 16384, 32767, 32767, 0, 0, 0]; + assert_eq!(pcm, expected.iter().flat_map(|s| s.to_le_bytes()).collect::>()); + for bits in [Bits::Int16, Bits::Int24, Bits::Float32] { + let mut whole = Vec::new(); + append(&mut whole, &samples, bits); + let mut blocks = Vec::new(); + for block in samples.chunks(3) { + append(&mut blocks, block, bits); + } + assert_eq!(whole, blocks); + assert_eq!(&whole[whole.len() - 3 * usize::from(bits.bytes())..], vec![0; 3 * usize::from(bits.bytes())]); + } + } +} diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 0de55c394b..a2043d2797 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -9,6 +9,10 @@ mod coded; #[cfg(feature = "flac-encode")] pub(crate) mod flac; mod pcm; +#[cfg(feature = "vorbis-encode")] +mod vorbis; +#[cfg(feature = "vorbis-encode")] +pub use vorbis::{OGG_BITRATES, OggVorbisOptions, encode as encode_ogg, encode_ogg_vorbis, quality_for_bitrate}; #[cfg(feature = "pcm-encode")] mod raw; #[cfg(feature = "pcm-encode")] @@ -17,6 +21,15 @@ 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}; +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] use std::io::{Seek, Write}; /// Encode `buf` as the file `opts.format` names. Integer depths clamp samples to [-1, 1]; float @@ -51,6 +64,25 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { EncodeFormat::Flac => flac::encode(buf, opts.bit_depth, opts.dither, mask), #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 => coded::encode(buf, opts), + #[cfg(feature = "vorbis-encode")] + EncodeFormat::Ogg => { + let count = u16::try_from(buf.channels.len()).unwrap_or(u16::MAX); + let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(count)); + if layout.channels() != count { + return Err(AudioError::Unsupported(format!("a {}-channel layout for {count} channels", layout.channels()))); + } + let map = vorbis::vorbis_map(&layout)?; + let quality = match opts.rate_control { + None => vorbis::quality_for_bitrate(192, buf.channels.len()), + Some(crate::RateControl::Bitrate(bps)) => { + vorbis::quality_for_bitrate((bps / 1000).clamp(OGG_BITRATES.0, OGG_BITRATES.1), buf.channels.len()) + } + Some(crate::RateControl::Quality(q)) if q.is_nan() => return Err(AudioError::Encode("the Vorbis quality is NaN".into())), + Some(crate::RateControl::Quality(q)) => -1.0 + 11.0 * q.clamp(0.0, 1.0), + }; + let planar: Vec<&[f32]> = map.iter().filter_map(|&i| buf.channels.get(i).map(Vec::as_slice)).collect(); + vorbis::encode_planar(buf.sample_rate, &planar, &OggVorbisOptions::new(quality)) + } #[allow(unreachable_patterns)] f => Err(AudioError::Unsupported(format!("writing {f:?}"))), } @@ -62,8 +94,8 @@ fn check_built(format: EncodeFormat) -> Result<()> { } /// Every extension [`ENCODE_EXTENSIONS`] can list, and how many of them the features built give. -const fn extensions() -> ([&'static str; 12], usize) { - let mut all = [""; 12]; +const fn extensions() -> ([&'static str; 13], usize) { + let mut all = [""; 13]; let mut n = 0; macro_rules! add { ($built:expr, $($extension:literal),+) => { @@ -81,10 +113,11 @@ const fn extensions() -> ([&'static str; 12], usize) { add!(cfg!(feature = "mp3-encode"), "mp3"); add!(cfg!(feature = "ac3-encode"), "ac3"); add!(cfg!(feature = "eac3-encode"), "eac3", "ec3"); + add!(cfg!(feature = "vorbis-encode"), "ogg"); (all, n) } -const EXTENSIONS: ([&str; 12], usize) = extensions(); +const EXTENSIONS: ([&str; 13], usize) = extensions(); /// The file extensions of the formats [`encode`] can write (those whose features are on). pub const ENCODE_EXTENSIONS: &[&str] = EXTENSIONS.0.split_at(EXTENSIONS.1).0; @@ -99,7 +132,7 @@ pub const ENCODE_EXTENSIONS: &[&str] = EXTENSIONS.0.split_at(EXTENSIONS.1).0; /// use craft_audio::{EncodeFormat, encode_format_for}; /// /// assert_eq!(encode_format_for(".AIFF"), Some(EncodeFormat::Aiff)); -/// assert_eq!(encode_format_for("ogg"), None); +/// assert_eq!(encode_format_for("unknown"), None); /// # } /// ``` pub fn encode_format_for(name: &str) -> Option { @@ -122,6 +155,8 @@ pub fn encode_format_for(name: &str) -> Option { "ac3" => Some(EncodeFormat::Ac3), #[cfg(feature = "eac3-encode")] "eac3" | "ec3" => Some(EncodeFormat::Eac3), + #[cfg(feature = "vorbis-encode")] + "ogg" => Some(EncodeFormat::Ogg), _ => None, } } @@ -138,6 +173,15 @@ fn wav_mask(layout: &ChannelLayout, channels: usize) -> Result { /// The error a stream encoder returns for every call after one of its writes has failed: the /// sink may already hold a prefix of the failed block, so the encoder's counters can no longer /// describe the bytes on the sink, and later writes or `finish` must not claim success. +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] fn failed_write_error() -> AudioError { AudioError::Encode("the stream encoder already failed on an earlier write; its output is incomplete".into()) } @@ -163,12 +207,30 @@ fn failed_write_error() -> AudioError { /// assert_eq!(&flac[..4], b"fLaC"); /// # } /// ``` +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] pub struct FileEncoder { writer: Writer, format: EncodeFormat, channels: usize, } +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] impl std::fmt::Debug for FileEncoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("FileEncoder").field("format", &self.format).finish_non_exhaustive() @@ -177,6 +239,15 @@ impl std::fmt::Debug for FileEncoder { // The writers differ in size with the features built; the coded one is boxed for its encoder. #[allow(clippy::large_enum_variant)] +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] enum Writer { #[cfg(feature = "pcm-encode")] Wav(wav::Writer), @@ -188,6 +259,15 @@ enum Writer { Coded(Box>), } +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] impl FileEncoder { /// Starts a file of `channels` channels at `sample_rate` at the current position of `out`. /// `opts.layout`, when set, must have `channels` channels. @@ -317,9 +397,39 @@ impl EncodeOptions { /// The constant bit rate such a file would be written at ([`FileEncoder::bitrate`]), or the /// error [`EncodeOptions::check`] returns. pub fn bitrate(&self, sample_rate: u32, channels: u16) -> Result> { + #[cfg(feature = "vorbis-encode")] + if self.format == EncodeFormat::Ogg { + // Vorbis is whole-buffer only and VBR has no constant output bitrate. + encode(&AudioBuffer::new(sample_rate, channels, 0), self)?; + return Ok(None); + } // The encoder a file would get, on a sink that is thrown away: what it accepts and the // rate it settles on are then the writer's by construction. - Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) + #[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" + ))] + { + Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) + } + #[cfg(not(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" + )))] + { + let _ = (sample_rate, channels); + Err(AudioError::Unsupported("streaming encoders are not built".into())) + } } } diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs new file mode 100644 index 0000000000..6c19ada77e --- /dev/null +++ b/crates/audio/src/write/vorbis.rs @@ -0,0 +1,267 @@ +//! Ogg Vorbis files (Vorbis I §A, RFC 5334) from the pure-Rust [`crate::vorbis::encoder`] and +//! craft-media's Ogg page writer: 1 to 8 channels in Vorbis channel order, a quality from -1 to +//! 10 (variable bit rate), and the tags in the comment header. Builds for every target. + +use craft_media::ogg::{PageWriter, vorbis_comment}; + +use crate::vorbis::encoder::{DEFAULT_QUALITY, Encoder, EncoderConfig, Error as VorbisError}; +use crate::{AudioBuffer, AudioError, ChannelLayout, Result}; + +/// The bit rates [`encode_ogg`](crate::encode_ogg) takes, in kbit/s. Vorbis is variable: the bit rate picks a +/// quality ([`quality_for_bitrate`]), and the file comes out near it for typical music. +pub const OGG_BITRATES: (u32, u32) = (64, 500); + +/// The serial number of the stream when the options do not set one (`LCRF`): one stream per file, +/// so a constant keeps files byte-for-byte reproducible. +const SERIAL: u32 = 0x4C43_5246; + +/// Samples per channel fed to the encoder at a time. +const CHUNK: usize = 4096; + +/// What [`encode_ogg_vorbis`] writes besides the audio. +/// +/// `#[non_exhaustive]`: build it with `OggVorbisOptions::default()` or +/// [`OggVorbisOptions::new`] and the `with_*` methods. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct OggVorbisOptions { + /// -1 (smallest) to 10 (best); clamped, and NaN or infinite reads as + /// [`DEFAULT_QUALITY`] (6). + pub quality: f32, + /// The comment header's vendor string. + pub vendor: String, + /// `NAME=value` comments (Vorbis I §5), in order. A name that is empty, or holds `=` or a byte + /// outside 0x20–0x7D, is left out. + pub tags: Vec<(String, String)>, + /// The logical stream's serial number. + pub serial: u32, +} + +impl Default for OggVorbisOptions { + fn default() -> Self { + OggVorbisOptions { quality: DEFAULT_QUALITY, vendor: "craft-audio".into(), tags: Vec::new(), serial: SERIAL } + } +} + +impl OggVorbisOptions { + /// The defaults at `quality`. + pub fn new(quality: f32) -> Self { + OggVorbisOptions { quality, ..Self::default() } + } + + /// Sets [`quality`](Self::quality). + pub fn with_quality(mut self, quality: f32) -> Self { + self.quality = quality; + self + } + + /// Sets [`vendor`](Self::vendor). + pub fn with_vendor(mut self, vendor: impl Into) -> Self { + self.vendor = vendor.into(); + self + } + + /// Adds a comment ([`tags`](Self::tags)). + pub fn with_tag(mut self, name: impl Into, value: impl Into) -> Self { + self.tags.push((name.into(), value.into())); + self + } + + /// Sets [`serial`](Self::serial). + pub fn with_serial(mut self, serial: u32) -> Self { + self.serial = serial; + self + } +} + +fn encode_error(e: VorbisError) -> AudioError { + AudioError::Encode(format!("Vorbis: {e}")) +} + +/// Encode `buf` as an Ogg Vorbis file with `opts`. The channels are in Vorbis channel order +/// (Vorbis I §4.3.9: L C R for three, L C R Ls Rs LFE for 5.1, L C R Ls Rs Rl Rr LFE for 7.1). +/// The last granule position is the buffer's length, so a decoder returns exactly its frames. +/// +/// ``` +/// use craft_audio::{AudioBuffer, OggVorbisOptions, encode_ogg_vorbis}; +/// +/// let buf = AudioBuffer::new(48_000, 6, 4_800); // 0.1 s of 5.1 silence +/// let opts = OggVorbisOptions::new(4.0).with_tag("TITLE", "Silence"); +/// let ogg = encode_ogg_vorbis(&buf, &opts).unwrap(); +/// assert!(ogg.starts_with(b"OggS")); +/// ``` +pub fn encode_ogg_vorbis(buf: &AudioBuffer, opts: &OggVorbisOptions) -> Result> { + let planar: Vec<&[f32]> = buf.channels.iter().map(Vec::as_slice).collect(); + encode_planar(buf.sample_rate, &planar, opts) +} + +/// [`encode_ogg_vorbis`] over channels already in Vorbis order. +pub(crate) fn encode_planar(sample_rate: u32, planar: &[&[f32]], opts: &OggVorbisOptions) -> Result> { + if !(1..=8).contains(&planar.len()) { + return Err(AudioError::Unsupported(format!("Ogg Vorbis holds 1 to 8 channels, not {}", planar.len()))); + } + let frames = planar.first().map_or(0, |c| c.len()); + if planar.iter().any(|c| c.len() != frames || c.iter().any(|s| !s.is_finite())) { + return Err(AudioError::Encode("Vorbis samples must be finite and channels equally long".into())); + } + if sample_rate == 0 { + return Err(AudioError::Encode("there is no audio to encode".into())); + } + let mut enc = Encoder::new(EncoderConfig::new(sample_rate, planar.len(), opts.quality)).map_err(encode_error)?; + let mut pages = PageWriter::new(opts.serial); + let tags: Vec<(&str, &str)> = opts.tags.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); + let mut out = pages.header(&enc.identification()); + out.extend(pages.header(&vorbis_comment(&opts.vendor, &tags))); + out.extend(pages.header(&enc.setup())); + // The first audio packet (which outputs nothing) gets a page of its own: a stream whose first + // audio page is also its last would leave decoders to choose between start and end trimming + // (Vorbis I §A.2), and ffmpeg then plays the padding. + let mut first = true; + let mut add = |packets: Vec<(Vec, i64)>, out: &mut Vec| { + for (packet, granule) in packets { + out.extend(pages.packet(&packet, granule)); + if std::mem::take(&mut first) { + out.extend(pages.flush()); + } + } + }; + let mut at = 0; + loop { + let end = (at + CHUNK).min(frames); + let chunk: Vec<&[f32]> = planar.iter().map(|c| c.get(at..end).unwrap_or_default()).collect(); + add(enc.encode(&chunk).map_err(encode_error)?, &mut out); + at = end; + if at >= frames { + break; + } + } + add(enc.finish().map_err(encode_error)?, &mut out); + out.extend(pages.finish(None)); + Ok(out) +} + +/// Nominal kbit/s per channel at each whole quality from -1 to 10: this encoder's rate on +/// music-like test signals at 48 kHz (harmonic chords with noise), averaged. +const KBPS_PER_CHANNEL: [f32; 12] = [18.0, 23.0, 31.0, 43.0, 58.0, 75.0, 89.0, 100.0, 111.0, 121.0, 130.0, 140.0]; + +/// The quality whose nominal bit rate is `kbps` kbit/s for `channels` channels (clamped to -1..=10). +/// Vorbis is variable: the bit rate of a file depends on the audio. +pub fn quality_for_bitrate(kbps: u32, channels: usize) -> f32 { + let per = kbps as f32 / channels.max(1) as f32; + let mut q = -1.0; + for pair in KBPS_PER_CHANNEL.windows(2) { + if let [lo, hi] = *pair + && per <= hi + { + return q + ((per - lo) / (hi - lo)).clamp(0.0, 1.0); + } + q += 1.0; + } + 10.0 +} + +/// Encode `buf` as an Ogg Vorbis stream near `kbps` kbit/s ([`OGG_BITRATES`], clamped): the +/// quality [`quality_for_bitrate`] gives, no tags. 1 to 8 channels in Vorbis channel order. +/// `Err` says why there is nothing. +pub fn encode(buf: &AudioBuffer, kbps: u32) -> Result> { + let kbps = kbps.clamp(OGG_BITRATES.0, OGG_BITRATES.1); + encode_ogg_vorbis(buf, &OggVorbisOptions::new(quality_for_bitrate(kbps, buf.channels.len()))) +} + +/// WAV-order speakers ([`crate::EncodeFormat::layout_masks`]) to Vorbis order, per channel count. +const VORBIS_ORDER: [&[usize]; 8] = + [&[0], &[0, 1], &[0, 2, 1], &[0, 1, 2, 3], &[0, 2, 1, 3, 4], &[0, 2, 1, 4, 5, 3], &[0, 2, 1, 5, 6, 4, 3], &[0, 2, 1, 6, 7, 4, 5, 3]]; + +/// For each Vorbis channel, the channel of audio in `layout` it comes from. +pub(crate) fn vorbis_map(layout: &ChannelLayout) -> Result> { + let n = layout.channels(); + let mask = crate::EncodeFormat::Ogg.layout_masks(n).first().copied(); + let order = usize::from(n).checked_sub(1).and_then(|i| VORBIS_ORDER.get(i)).copied(); + match (mask, order) { + (Some(mask), Some(order)) => crate::layout::channel_map(mask, Some(order), layout) + .ok_or_else(|| AudioError::Unsupported(format!("Vorbis has no layout of {n} channels with these speakers"))), + _ => Err(AudioError::Unsupported(format!("Ogg Vorbis holds 1 to 8 channels, not {n}"))), + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::{OGG_BITRATES, OggVorbisOptions, encode, encode_ogg_vorbis, quality_for_bitrate, vorbis_map}; + use crate::{AudioBuffer, AudioError, ChannelLayout}; + + #[test] + fn rejects_unsupported_or_malformed_channels_without_dropping_audio() { + for channels in [0, 9] { + assert!(matches!(encode(&AudioBuffer::new(48_000, channels, 16), 192), Err(AudioError::Unsupported(_)))); + } + let ragged = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; 16], vec![0.0; 15]] }; + assert!(encode(&ragged, 192).is_err()); + assert!(encode(&AudioBuffer::new(0, 1, 16), 192).is_err()); + let invalid = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::NAN]] }; + assert!(encode(&invalid, 192).is_err()); + let infinite = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::INFINITY]] }; + assert!(encode(&infinite, 192).is_err()); + } + + #[test] + fn generic_and_direct_encoders_write_one_to_eight_channels() { + for channels in 1..=8 { + let audio = AudioBuffer::new(48_000, channels, 512); + let opts = crate::EncodeOptions::new(crate::EncodeFormat::Ogg); + assert!(opts.check(48_000, channels).is_ok()); + assert_eq!(opts.bitrate(48_000, channels).unwrap(), None); + let direct = encode(&audio, 192).unwrap(); + assert!(direct.starts_with(b"OggS")); + // silence: the channel order changes nothing, so the generic path writes the same file + let generic = crate::encode(&audio, &opts.with_bitrate(192_000)).unwrap(); + assert_eq!(direct, generic, "{channels} channels"); + #[cfg(feature = "decode")] + { + let (info, decoded) = crate::decode(&generic, Some("ogg")).unwrap(); + assert_eq!(info.channels, channels); + assert_eq!(decoded.frames(), audio.frames()); + } + } + } + + #[test] + fn the_quality_follows_the_bit_rate() { + assert_eq!(quality_for_bitrate(0, 2), -1.0); + assert_eq!(quality_for_bitrate(10_000, 2), 10.0); + assert!((quality_for_bitrate(200, 2) - 6.0).abs() < 1e-6); + assert!((quality_for_bitrate(600, 6) - 6.0).abs() < 1e-6); + let mut last = -2.0; + for kbps in OGG_BITRATES.0..=OGG_BITRATES.1 { + let q = quality_for_bitrate(kbps, 2); + assert!(q >= last && (-1.0..=10.0).contains(&q)); + last = q; + } + assert!(quality_for_bitrate(192, 0).is_finite()); + } + + #[test] + fn layouts_map_to_vorbis_order() { + // 5.1 in WAV order (L R C LFE Ls Rs) is written L C R Ls Rs LFE + assert_eq!(vorbis_map(&ChannelLayout::SURROUND_5_1).unwrap(), [0, 2, 1, 4, 5, 3]); + assert_eq!(vorbis_map(&ChannelLayout::SURROUND_5_1_SIDE).unwrap(), [0, 2, 1, 4, 5, 3]); + assert_eq!(vorbis_map(&ChannelLayout::from_mask(0x63F)).unwrap(), [0, 2, 1, 6, 7, 4, 5, 3]); + assert_eq!(vorbis_map(&ChannelLayout::from_mask(0x7)).unwrap(), [0, 2, 1]); + assert_eq!(vorbis_map(&ChannelLayout::STEREO).unwrap(), [0, 1]); + assert!(vorbis_map(&ChannelLayout::from_mask(0xC)).is_err()); + assert!(vorbis_map(&ChannelLayout::unordered(9)).is_err()); + assert!(vorbis_map(&ChannelLayout::unordered(0)).is_err()); + } + + #[test] + fn options_build_and_tags_reach_the_comment_header() { + let opts = OggVorbisOptions::default().with_quality(2.0).with_vendor("v").with_tag("TITLE", "t").with_tag("bad=name", "x").with_serial(9); + assert_eq!((opts.quality, opts.vendor.as_str(), opts.serial, opts.tags.len()), (2.0, "v", 9, 2)); + let ogg = encode_ogg_vorbis(&AudioBuffer::new(44_100, 1, 100), &opts).unwrap(); + let file = craft_media::ogg::open(&ogg).unwrap(); + let s = &file.streams[0]; + assert_eq!((s.serial, s.saw_eos, s.headers.len()), (9, true, 3)); + assert_eq!(s.headers[1], craft_media::ogg::vorbis_comment("v", &[("TITLE", "t")])); + assert_eq!(s.last_granule, Some(100)); + } +} diff --git a/crates/audio/tests/audio/decode_extensions.rs b/crates/audio/tests/audio/decode_extensions.rs index 27a5573deb..fc961cc393 100644 --- a/crates/audio/tests/audio/decode_extensions.rs +++ b/crates/audio/tests/audio/decode_extensions.rs @@ -77,6 +77,6 @@ fn every_encode_format_has_an_extension_it_is_written_and_read_under() { assert!(format.mime_type().starts_with("audio/"), "{format:?}"); } let extensions: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.extension()).collect(); - assert_eq!(extensions, ["wav", "aif", "flac", "m4a", "m4a", "mp3", "ac3", "eac3"]); + assert_eq!(extensions, ["wav", "aif", "flac", "m4a", "m4a", "mp3", "ac3", "eac3", "ogg"]); assert_eq!(EncodeFormat::Aiff.mime_type(), "audio/aiff"); } diff --git a/crates/audio/tests/audio/encode_format.rs b/crates/audio/tests/audio/encode_format.rs index 7713f37a5a..72749df044 100644 --- a/crates/audio/tests/audio/encode_format.rs +++ b/crates/audio/tests/audio/encode_format.rs @@ -14,7 +14,15 @@ fn only_formats_the_encoder_writes_are_named() { for name in craft_audio::ENCODE_EXTENSIONS { assert!(encode_format_for(name).is_some(), "{name}"); } - for other in ["ogg", "opus", "aac", "mp4", "xyz", ""] { + for other in ["opus", "aac", "mp4", "xyz", ""] { assert_eq!(encode_format_for(other), None, "{other}"); } } + +#[test] +fn ogg_names_follow_the_feature() { + let built = cfg!(feature = "vorbis-encode"); + assert_eq!(EncodeFormat::Ogg.is_built(), built); + assert_eq!(encode_format_for("ogg"), built.then_some(EncodeFormat::Ogg)); + assert_eq!(craft_audio::ENCODE_EXTENSIONS.contains(&"ogg"), built); +} diff --git a/crates/audio/tests/audio/main.rs b/crates/audio/tests/audio/main.rs index 8c37256d69..52e1d17f4b 100644 --- a/crates/audio/tests/audio/main.rs +++ b/crates/audio/tests/audio/main.rs @@ -10,3 +10,4 @@ mod raw_pcm; mod roundtrip; mod stream; mod wav_empty_data; +mod wav_ixml; diff --git a/crates/audio/tests/audio/wav_ixml.rs b/crates/audio/tests/audio/wav_ixml.rs new file mode 100644 index 0000000000..88e0cfcbf5 --- /dev/null +++ b/crates/audio/tests/audio/wav_ixml.rs @@ -0,0 +1,87 @@ +//! iXML timestamp parity with FilmCraft's streaming WAV reader, including hostile metadata. +use std::io::Cursor; + +use craft_audio::{DecodeOptions, Decoder}; +use craft_media::ReadSeekSource; + +fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(body); + if !body.len().is_multiple_of(2) { + out.push(0); + } + out +} + +fn wav(metadata: &[Vec]) -> Vec { + let mut out = b"RIFF\0\0\0\0WAVE".to_vec(); + out.extend(chunk(b"fmt ", &[1, 0, 1, 0, 0x80, 0xbb, 0, 0, 0, 0x77, 1, 0, 2, 0, 16, 0])); + for m in metadata { + out.extend(m); + } + out.extend(chunk(b"data", &[0, 0, 1, 0])); + let len = (out.len() - 8) as u32; + out[4..8].copy_from_slice(&len.to_le_bytes()); + out +} + +fn xml(low: &str, high: Option<&str>) -> Vec { + let high = high.map(|v| format!("{v}")).unwrap_or_default(); + chunk(b"iXML", format!("{low}{high}").as_bytes()) +} + +fn check(file: Vec, expected: Option) { + let options = DecodeOptions::default(); + let mut bytes = Decoder::from_bytes(&file, Some("wav"), &options).unwrap(); + assert_eq!(bytes.info().bwf.as_ref().map(|b| b.time_reference), expected); + let source = ReadSeekSource::new(Cursor::new(file.clone())).unwrap(); + let mut stream = Decoder::open(source, Some("wav"), &options).unwrap(); + assert_eq!(stream.info().bwf.as_ref().map(|b| b.time_reference), expected); + assert_eq!(bytes.info().frames, 2); + assert_eq!(stream.next_block().unwrap().unwrap().frames(), 2); + assert_eq!(bytes.next_block().unwrap().unwrap().frames(), 2); +} + +#[test] +fn ixml_fallback_preserves_large_timestamps_and_optional_high_word() { + check(wav(&[xml(" 5 ", Some("1"))]), Some((1 << 32) + 5)); + check(wav(&[xml("0", None)]), Some(0)); + check(wav(&[xml("4294967295", Some("4294967295"))]), Some(u64::MAX)); +} + +#[test] +fn bext_wins_in_either_chunk_order_including_timestamp_zero() { + let bext = chunk(b"bext", &[0; 602]); + let ixml = xml("5", Some("1")); + check(wav(&[bext.clone(), ixml.clone()]), Some(0)); + check(wav(&[ixml.clone(), bext.clone()]), Some(0)); + check(wav(&[bext, chunk(b"bext", &[0; 12]), ixml.clone()]), Some(0)); + check(wav(&[chunk(b"bext", &[0; 12]), ixml]), Some((1 << 32) + 5)); +} + +#[test] +fn invalid_metadata_never_fabricates_a_timestamp_or_blocks_audio() { + for low in ["4294967296", "-1", "+1", "", "1.5", "5"] { + check(wav(&[xml(low, Some("0"))]), None); + } + for high in ["4294967296", "-1", "", "oops"] { + check(wav(&[xml("5", Some(high))]), None); + } + for text in [ + "5", + "", + "56", + "5", + ] { + check(wav(&[chunk(b"iXML", text.as_bytes())]), None); + } + check(wav(&[chunk(b"iXML", &vec![b' '; (1 << 20) + 1])]), None); + let deep = format!("{}{}", "".repeat(40), "".repeat(40)); + check(wav(&[chunk(b"iXML", deep.as_bytes())]), None); +} + +#[test] +fn only_first_ixml_document_is_considered() { + check(wav(&[xml("5", None), xml("6", None)]), Some(5)); +} diff --git a/crates/audio/tests/codecs/file_formats.rs b/crates/audio/tests/codecs/file_formats.rs index 53947df123..82edf72aa0 100644 --- a/crates/audio/tests/codecs/file_formats.rs +++ b/crates/audio/tests/codecs/file_formats.rs @@ -397,12 +397,15 @@ fn the_formats_are_named() { for name in ENCODE_EXTENSIONS { assert!(encode_format_for(name).is_some(), "{name}"); } - assert_eq!(ENCODE_EXTENSIONS.len(), 12); + assert_eq!(ENCODE_EXTENSIONS.len(), 13); for format in CODED { assert!(EncodeFormat::ALL.contains(&format) && format.is_built()); } let features: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.feature()).collect(); - assert_eq!(features, ["pcm-encode", "pcm-encode", "flac-encode", "alac-encode", "aac-encode", "mp3-encode", "ac3-encode", "eac3-encode"]); + assert_eq!( + features, + ["pcm-encode", "pcm-encode", "flac-encode", "alac-encode", "aac-encode", "mp3-encode", "ac3-encode", "eac3-encode", "vorbis-encode"] + ); } /// ffmpeg's decode of `file` as interleaved `f32`, split into `channels` channels. @@ -495,6 +498,10 @@ fn the_format_queries_agree_with_the_writer() { let layouts = masks.iter().map(|&mask| ChannelLayout::from_mask(mask)).chain((1..=9).map(ChannelLayout::unordered)); for layout in layouts { for &format in EncodeFormat::ALL { + // Vorbis is whole-buffer-only; its direct/generic API and options are tested separately. + if format == EncodeFormat::Ogg { + continue; + } // 24 bits is a depth every format has. let opts = EncodeOptions::new(format).with_layout(layout); for &sample_rate in &rates { @@ -520,7 +527,7 @@ fn the_format_queries_agree_with_the_writer() { // The most channels is the most: one more is refused, by the layouts of a format that has // a fixed set and by the writer of one that has not. let most: Vec = EncodeFormat::ALL.iter().map(|f| f.max_channels()).collect(); - assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8]); + assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8, 8]); for &format in EncodeFormat::ALL { let most = format.max_channels(); match format.fixed_layouts(most) { @@ -569,3 +576,16 @@ fn the_bit_rate_used_can_be_asked_for() { assert_eq!(encode(&buf, &opts).unwrap().len() as u32, 43 * 1152 / 8 * opts.bitrate(48_000, 2).unwrap().unwrap() / 48_000); assert!(is_unsupported(EncodeOptions::new(EncodeFormat::Mp3).bitrate(48_000, 6))); } + +#[test] +fn vorbis_is_whole_buffer_only_and_validates_layouts() { + let opts = EncodeOptions::new(EncodeFormat::Ogg).with_layout(ChannelLayout::STEREO); + assert!(opts.check(48_000, 2).is_ok()); + assert_eq!(opts.bitrate(48_000, 2).unwrap(), None); + assert!(FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, 2).is_err()); + let buf = craft_audio::AudioBuffer::new(48_000, 2, 512); + assert!(craft_audio::encode(&buf, &opts).unwrap().starts_with(b"OggS")); + let wrong = opts.with_layout(ChannelLayout::from_mask(0xC)); + assert!(wrong.check(48_000, 2).is_err()); + assert!(craft_audio::encode(&buf, &wrong).is_err()); +} diff --git a/crates/audio/tests/codecs/main.rs b/crates/audio/tests/codecs/main.rs index c1c9e2131b..41829be5c9 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -20,3 +20,5 @@ mod opus; mod opusenc; mod routing_oracle; mod track_decoder; +#[cfg(feature = "vorbis-encode")] +mod vorbis_encoder_oracle; diff --git a/crates/audio/tests/codecs/vorbis_encoder_oracle.rs b/crates/audio/tests/codecs/vorbis_encoder_oracle.rs new file mode 100644 index 0000000000..342f4fd9a1 --- /dev/null +++ b/crates/audio/tests/codecs/vorbis_encoder_oracle.rs @@ -0,0 +1,131 @@ +//! ffmpeg as an external oracle for the pure-Rust Vorbis encoder: both of its decoders (its own +//! and libvorbis) read every file exactly as long as the input, surround comes out on the right +//! speakers, and the tags reach ffprobe. Skipped when ffmpeg is not installed. + +use std::path::Path; +use std::process::Command; + +use craft_audio::{AudioBuffer, ChannelLayout, EncodeFormat, EncodeOptions, OggVorbisOptions, encode, encode_ogg_vorbis}; + +/// A different tone on every channel, so each output channel can be traced to its input. +fn tones(rate: u32, channels: usize, frames: usize) -> AudioBuffer { + let channels = (0..channels) + .map(|c| { + let f = 220.0 * (c + 1) as f32; + (0..frames).map(|i| (std::f32::consts::TAU * f * i as f32 / rate as f32).sin() * 0.3).collect() + }) + .collect(); + AudioBuffer { sample_rate: rate, channels } +} + +/// Decodes `file` with ffmpeg's `decoder`; planar output in ffmpeg's (WAV) channel order. +fn ffmpeg_decode(ff: &Path, decoder: &str, file: &[u8], channels: usize, tag: &str) -> Vec> { + let path = crate::testkit::fixtures_dir("vorbis-encoder").join(format!("{tag}.ogg")); + std::fs::write(&path, file).unwrap(); + let out = Command::new(ff) + .args(["-v", "error", "-xerror", "-c:a", decoder, "-i"]) + .arg(&path) + .args(["-f", "f32le", "-c:a", "pcm_f32le", "-"]) + .output() + .unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{tag} {decoder}: {}", String::from_utf8_lossy(&out.stderr)); + let pcm: Vec = out.stdout.as_chunks::<4>().0.iter().map(|&b| f32::from_le_bytes(b)).collect(); + (0..channels).map(|c| pcm.iter().skip(c).step_by(channels).copied().collect()).collect() +} + +/// ffmpeg's decoders to check: its own `vorbis` always, and `libvorbis` when ffmpeg has it. +fn decoders(ff: &Path) -> Vec<&'static str> { + let list = + Command::new(ff).args(["-hide_banner", "-decoders"]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default(); + if list.lines().any(|l| l.split_whitespace().nth(1) == Some("libvorbis")) { + vec!["vorbis", "libvorbis"] + } else { + eprintln!("SKIPPED (libvorbis decoder): this ffmpeg has no libvorbis; checking its own decoder only"); + vec!["vorbis"] + } +} + +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + ab += f64::from(x) * f64::from(y); + aa += f64::from(x) * f64::from(x); + bb += f64::from(y) * f64::from(y); + } + ab / (aa * bb).sqrt().max(1e-20) +} + +/// Vorbis order (§4.3.9) of the WAV-order layouts the test writes, per channel count. +const VORBIS_ORDER: [&[usize]; 8] = + [&[0], &[0, 1], &[0, 2, 1], &[0, 1, 2, 3], &[0, 2, 1, 3, 4], &[0, 2, 1, 4, 5, 3], &[0, 2, 1, 5, 6, 4, 3], &[0, 2, 1, 6, 7, 4, 5, 3]]; + +/// 1 to 8 channels through `encode` with a WAV-order layout, at exactly the input's length out of +/// both decoders: ffmpeg's own puts every channel back on its WAV speaker, and libvorbis (through +/// ffmpeg, which passes its order through) gives the file's Vorbis order. +#[test] +fn every_channel_count_decodes_on_the_right_speakers() { + let ff = require_ffmpeg!(); + for channels in 1..=8u16 { + let layout = if channels == 7 { ChannelLayout::from_mask(0x70F) } else { ChannelLayout::default_for(channels) }; + let buf = tones(48_000, channels.into(), 24_000 + 77); + let opts = EncodeOptions::new(EncodeFormat::Ogg).with_layout(layout).with_quality(0.6); + let file = encode(&buf, &opts).unwrap(); + for decoder in decoders(&ff) { + let out = ffmpeg_decode(&ff, decoder, &file, channels.into(), &format!("tones{channels}-{decoder}")); + for (j, got) in out.iter().enumerate() { + let c = if decoder == "libvorbis" { VORBIS_ORDER[usize::from(channels) - 1][j] } else { j }; + assert_eq!(got.len(), buf.frames(), "{channels} ch {decoder}: channel {j} length"); + let best = (0..buf.channels.len()).max_by(|&a, &b| { + correlation(&buf.channels[a][2048..], &got[2048..]).total_cmp(&correlation(&buf.channels[b][2048..], &got[2048..])) + }); + assert_eq!(best, Some(c), "{channels} ch {decoder}: output channel {c} carries input {best:?}"); + let r = correlation(&buf.channels[c][2048..], &got[2048..]); + assert!(r > 0.95, "{channels} ch {decoder}: channel {c} correlation {r:.3}"); + } + } + } +} + +/// The comment header's tags, UTF-8 values included, are what ffprobe reports; a name that is not +/// a valid field name is left out. +#[test] +fn tags_reach_ffprobe() { + let Some(probe) = crate::common::tool("ffprobe").or_else(|| crate::common::skip("ffprobe not found")) else { return }; + let opts = OggVorbisOptions::new(3.0) + .with_tag("TITLE", "Smörgåsbord ✓") + .with_tag("ARTIST", "Craft") + .with_tag("bad=name", "dropped") + .with_vendor("craft-audio test"); + let file = encode_ogg_vorbis(&tones(44_100, 2, 44_100), &opts).unwrap(); + let path = crate::testkit::fixtures_dir("vorbis-encoder").join("tags.ogg"); + std::fs::write(&path, &file).unwrap(); + let out = Command::new(probe).args(["-v", "error", "-of", "json", "-show_streams", "-show_format"]).arg(&path).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let j: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + let s = &j["streams"][0]; + assert_eq!((s["codec_name"].as_str(), s["channels"].as_u64(), s["sample_rate"].as_str()), (Some("vorbis"), Some(2), Some("44100"))); + let tags = &s["tags"]; + assert_eq!((tags["TITLE"].as_str(), tags["ARTIST"].as_str()), (Some("Smörgåsbord ✓"), Some("Craft"))); + assert!(tags.as_object().unwrap().keys().all(|k| !k.contains("bad")), "{tags}"); + assert_eq!(j["format"]["duration"].as_str().map(|d| d.parse::().unwrap()), Some(1.0)); +} + +/// The lowest and highest qualities and the bit-rate path decode at the exact length, mono at +/// 44.1 kHz and stereo at 22.05 kHz. +#[test] +fn quality_extremes_and_rates_decode_exactly() { + let ff = require_ffmpeg!(); + for (rate, channels, quality) in [(44_100u32, 1usize, -1.0f32), (44_100, 1, 10.0), (22_050, 2, -1.0), (22_050, 2, 10.0), (96_000, 2, 5.0)] { + let buf = tones(rate, channels, rate as usize / 2 + 13); + let file = encode_ogg_vorbis(&buf, &OggVorbisOptions::new(quality)).unwrap(); + for decoder in decoders(&ff) { + let out = ffmpeg_decode(&ff, decoder, &file, channels, &format!("q{quality}-{rate}-{channels}-{decoder}")); + assert!(out.iter().all(|c| c.len() == buf.frames()), "q{quality} {rate} Hz {decoder}: {}", out[0].len()); + let r = correlation(&buf.channels[0][2048..], &out[0][2048..]); + assert!(r > 0.9, "q{quality} {rate} Hz {decoder}: correlation {r:.3}"); + } + } + let low = craft_audio::encode_ogg(&tones(48_000, 2, 48_000), craft_audio::OGG_BITRATES.0).unwrap(); + let high = craft_audio::encode_ogg(&tones(48_000, 2, 48_000), craft_audio::OGG_BITRATES.1).unwrap(); + assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len()); +} diff --git a/crates/audio/tests/flac_decode.rs b/crates/audio/tests/flac_decode.rs new file mode 100644 index 0000000000..a1895789b2 --- /dev/null +++ b/crates/audio/tests/flac_decode.rs @@ -0,0 +1,211 @@ +//! The native FLAC decoder: round trips through this crate's encoder over bit depths, channel +//! counts, block sizes and effort levels; hostile input; and ffmpeg as the reference (oracle; +//! skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`) for files +//! ffmpeg's encoder writes at every compression level. + +use craft_audio::flac::{DecodeError, Decoder, Encoder, EncoderConfig, STREAMINFO_OFFSET, StreamInfo, decode}; +use std::process::Command; + +fn signal(channels: usize, frames: usize, bits: u32, seed: u32) -> Vec> { + let max = if bits == 32 { i32::MAX as f64 } else { ((1i64 << (bits - 1)) - 1) as f64 }; + let mut s = seed; + (0..channels) + .map(|c| { + (0..frames) + .map(|i| { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + let t = i as f64; + let v = match (i / 3000) % 4 { + 0 => (t * (0.01 + 0.007 * c as f64)).sin() * 0.6 + (t * 0.31).sin() * 0.1, + 1 => (f64::from(s) / f64::from(u32::MAX) - 0.5) * 1.8, + 2 => 0.0, + _ => { + if (i / 40) % 2 == 0 { + 0.99 + } else { + -0.99 + } + } + }; + (v * max).round() as i32 + }) + .collect() + }) + .collect() +} + +fn encode(channels: &[Vec], rate: u32, bits: u8, block: u16, level: u8) -> Vec { + let mut cfg = EncoderConfig::new(rate, channels.len() as u8, bits); + cfg.block_size = block; + cfg.level = level; + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut file = enc.header(&[]); + let refs: Vec<&[i32]> = channels.iter().map(Vec::as_slice).collect(); + file.extend(enc.encode(&refs).expect("encode")); + file.extend(enc.finish()); + let at = STREAMINFO_OFFSET as usize; + file[at..at + 34].copy_from_slice(&enc.streaminfo()); + file +} + +#[test] +fn round_trips_through_the_encoder() { + for (channels, bits) in [(1usize, 8u8), (2, 8), (1, 12), (2, 16), (2, 20), (3, 24), (6, 24), (8, 16), (2, 32), (1, 32)] { + for (block, level) in [(4096u16, 5u8), (16, 0), (1000, 8), (65535, 3), (576, 1)] { + let frames = 9000 + usize::from(block % 97); + let src = signal(channels, frames, u32::from(bits), 0x1234_5679 + u32::from(bits)); + let file = encode(&src, 44_100, bits, block, level); + let got = decode(&file).unwrap_or_else(|e| panic!("{channels}ch {bits}-bit block {block} level {level}: {e}")); + assert_eq!((got.info.channels as usize, got.info.bits_per_sample, got.info.sample_rate), (channels, bits, 44_100)); + assert_eq!(got.channels, src, "{channels}ch {bits}-bit block {block} level {level}"); + } + } +} + +#[test] +fn frames_decode_one_at_a_time() { + let src = signal(2, 10_000, 16, 7); + let file = encode(&src, 48_000, 16, 4096, 5); + let info = StreamInfo::parse(&file[STREAMINFO_OFFSET as usize..]).expect("streaminfo"); + let dec = Decoder::new(info); + // The first frame follows the metadata blocks; find the first position a frame decodes at. + let at = (42..file.len()).find(|&p| dec.decode_frame(&file[p..]).is_ok()).expect("a frame"); + let first = dec.decode_frame(&file[at..]).expect("frame"); + assert_eq!((first.block_size, first.number, first.sample_rate, first.bits_per_sample), (4096, 0, 48_000, 16)); + assert_eq!(first.channels[0], src[0][..4096]); + // Without the STREAMINFO a frame that spells out its own rate and depth still decodes. + let _ = Decoder::without_streaminfo().decode_frame(&file[at..]); +} + +#[test] +fn hostile_input_is_an_error_not_a_panic() { + let src = signal(2, 6000, 16, 11); + let file = encode(&src, 44_100, 16, 1152, 5); + for n in 0..file.len().min(3000) { + let _ = decode(&file[..n]); + } + // A cut file is truncated, not silently shorter. + assert!(decode(&file[..file.len() - 5]).is_err()); + // Every bit flip in the first frames is caught by a CRC or another check, never a panic. + for i in 0..file.len().min(2500) { + for bit in 0..8 { + let mut c = file.clone(); + c[i] ^= 1 << bit; + let _ = decode(&c); + } + } + // A sample limit stops a stream that claims too much. + assert_eq!(craft_audio::flac::decode_with_limit(&file, 1000), Err(DecodeError::TooLarge)); + assert!(decode(b"nope").is_err()); + assert!(decode(b"fLaC").is_err()); +} + +// ---- ffmpeg ---- + +/// Little-endian 16- or 32-bit samples of raw PCM. +fn pcm_values(raw: &[u8], bytes: usize) -> Vec { + if bytes == 2 { + raw.as_chunks::<2>().0.iter().map(|b| i32::from(i16::from_le_bytes(*b))).collect() + } else { + raw.as_chunks::<4>().0.iter().map(|b| i32::from_le_bytes(*b)).collect() + } +} + +/// Planar channels as interleaved samples. +fn interleave(channels: &[Vec]) -> Vec { + let frames = channels.first().map_or(0, Vec::len); + (0..frames).flat_map(|i| channels.iter().map(move |c| c[i])).collect() +} + +fn ffmpeg_run(ff: &std::path::Path, args: &[&str]) -> Vec { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); + out.stdout +} + +#[test] +fn ffmpeg_files_decode_to_ffmpegs_samples() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("flac_decode"); + let tones = "aevalsrc=exprs=0.4*sin(2*PI*441*t)+0.2*sin(2*PI*3100*t)|0.3*sin(2*PI*660*t)*sin(2*PI*3*t):s=44100:d=1.3"; + let noise = "anoisesrc=d=1.3:c=white:r=44100:a=0.5:s=3"; + for (src, name) in [(tones, "tones"), (noise, "noise")] { + for channels in [1usize, 2, 6] { + for (fmt, bytes, bits) in [("s16", 2usize, 16u32), ("s32", 4, 24)] { + for level in [0, 3, 5, 8, 12] { + let file = dir.join(format!("ffmpeg_{name}_{channels}ch_{bits}_l{level}.flac")); + let f = file.to_str().expect("path"); + let (ch, lv) = (channels.to_string(), level.to_string()); + ffmpeg_run(&ff, &["-f", "lavfi", "-i", src, "-ac", &ch, "-sample_fmt", fmt, "-compression_level", &lv, "-c:a", "flac", f]); + let theirs = ffmpeg_run(&ff, &["-i", f, "-f", if bits == 16 { "s16le" } else { "s32le" }, "-"]); + let got = + decode(&std::fs::read(&file).expect("read")).unwrap_or_else(|e| panic!("{name} {channels}ch {bits}-bit level {level}: {e}")); + assert_eq!(got.info.channels as usize, channels); + let frames = got.channels[0].len(); + assert_eq!(theirs.len(), frames * channels * bytes, "{name} {channels}ch {bits} l{level}: length"); + // ffmpeg returns 24-bit audio left-aligned in 32 bits. + let shift = if bits == 24 { 8 } else { 0 }; + let mine: Vec = interleave(&got.channels).into_iter().map(|v| v << shift).collect(); + let ok = mine == pcm_values(&theirs, bytes); + assert!(ok, "{name} {channels}ch {bits}-bit level {level}: samples differ from ffmpeg's decode"); + } + } + } + } +} + +#[test] +fn ffmpeg_decodes_our_files_to_our_samples() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("flac_decode"); + for (channels, bits) in [(1usize, 16u8), (2, 16), (2, 24), (6, 16)] { + let src = signal(channels, 20_000, u32::from(bits), 99); + let file = dir.join(format!("ours_{channels}ch_{bits}.flac")); + std::fs::write(&file, encode(&src, 44_100, bits, 4096, 5)).expect("write"); + let theirs = ffmpeg_run(&ff, &["-i", file.to_str().expect("path"), "-f", if bits == 16 { "s16le" } else { "s32le" }, "-"]); + let got = decode(&std::fs::read(&file).expect("read")).expect("decode"); + let bytes = if bits == 16 { 2 } else { 4 }; + let shift = if bytes == 4 { 8 } else { 0 }; + let want: Vec = pcm_values(&theirs, bytes).into_iter().map(|v| v >> shift).collect(); + assert!(interleave(&got.channels) == want, "{channels}ch {bits}-bit: samples differ from ffmpeg's decode"); + } +} + +#[test] +fn rejects_unknown_length_corruption_and_streaminfo_format_mismatch() { + let src = signal(1, 100, 16, 7); + let original = encode(&src, 44_100, 16, 4096, 5); + let at = STREAMINFO_OFFSET as usize; + // STREAMINFO is not CRC-covered. Clear only the 36-bit total sample count. + let mut unknown = original.clone(); + unknown[at + 13] &= 0xf0; + unknown[at + 14..at + 18].fill(0); + assert_eq!(decode(&unknown).unwrap().channels, src); + for tail in [vec![0xff], vec![0x00, 0x00]] { + let mut broken = unknown.clone(); + broken.extend(tail); + assert!(decode(&broken).is_err()); + } + // The encoder spells these in frame headers, independent of STREAMINFO. + let mut wrong_rate = original.clone(); + let mut packed = u64::from_be_bytes(wrong_rate[at + 10..at + 18].try_into().unwrap()); + packed = (packed & ((1u64 << 44) - 1)) | (48_000u64 << 44); + wrong_rate[at + 10..at + 18].copy_from_slice(&packed.to_be_bytes()); + assert!(decode(&wrong_rate).is_err()); + let mut wrong_depth = original; + wrong_depth[at + 12] = (wrong_depth[at + 12] & !1) | 1; + wrong_depth[at + 13] = (wrong_depth[at + 13] & 0x0f) | 0x70; + assert!(decode(&wrong_depth).is_err()); +} + +#[test] +fn caller_constructed_streaminfo_is_validated_before_decoding() { + let file = encode(&signal(1, 100, 16, 9), 44_100, 16, 4096, 5); + let info = StreamInfo::parse(&file[STREAMINFO_OFFSET as usize..]).unwrap(); + for bits in [0, 1, 3, 33, 64, 255] { + let invalid = StreamInfo { bits_per_sample: bits, ..info }; + assert!(matches!(Decoder::new(invalid).decode_frame(&[]), Err(DecodeError::Invalid(_)))); + } +} diff --git a/crates/audio/tests/qoa_oracle.rs b/crates/audio/tests/qoa_oracle.rs new file mode 100644 index 0000000000..7b5ac26741 --- /dev/null +++ b/crates/audio/tests/qoa_oracle.rs @@ -0,0 +1,62 @@ +//! QOA against ffmpeg's decoder as the reference (oracle; skipped when ffmpeg is absent, a failure +//! with `CRAFT_MEDIA_REQUIRE_ORACLES=1`): ffmpeg decodes the files our encoder writes to exactly +//! the samples our decoder returns for them, over several sizes (partial slices, partial frames, +//! several frames), channel counts and rates. + +use craft_audio::qoa::{decode, encode}; +use std::process::Command; + +fn signal(channels: usize, frames: usize) -> Vec> { + let mut seed = 0x2545_F491u32; + (0..channels) + .map(|c| { + (0..frames) + .map(|i| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let tone = ((i as f64) * (0.02 + 0.013 * c as f64)).sin() * 9000.0; + // Tones, noise bursts, silence and full-scale peaks. + match (i / 700) % 4 { + 0 => tone as i16, + 1 => (tone + f64::from(seed % 6000) - 3000.0) as i16, + 2 => 0, + _ => { + if i % 2 == 0 { + i16::MAX + } else { + i16::MIN + } + } + } + }) + .collect() + }) + .collect() +} + +#[test] +fn ffmpeg_decodes_our_files_to_the_same_samples() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("qoa"); + for (rate, channels, frames) in + [(44_100u32, 1usize, 1usize), (8_000, 1, 19), (48_000, 2, 5_121), (22_050, 2, 12_345), (96_000, 1, 20_000), (44_100, 4, 6_000)] + { + let src = signal(channels, frames); + let bytes = encode(rate, &src).expect("encode"); + let ours = decode(&bytes).expect("decode"); + let file = dir.join(format!("ours_{rate}_{channels}_{frames}.qoa")); + std::fs::write(&file, &bytes).expect("write fixture"); + let out = Command::new(&ffmpeg) + .args(["-v", "error", "-y", "-i"]) + .arg(&file) + .args(["-f", "s16le", "-acodec", "pcm_s16le", "-"]) + .output() + .expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg failed on {}: {}", file.display(), String::from_utf8_lossy(&out.stderr)); + let theirs: Vec = out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect(); + let interleaved: Vec = (0..frames).flat_map(|i| ours.channels.iter().map(move |ch| ch[i])).collect(); + assert_eq!(theirs.len(), interleaved.len(), "{rate} Hz, {channels} ch, {frames} frames: sample count"); + assert!(theirs == interleaved, "{rate} Hz, {channels} ch, {frames} frames: samples differ"); + } +} diff --git a/crates/ber/Cargo.toml b/crates/ber/Cargo.toml new file mode 100644 index 0000000000..fa3902e88b --- /dev/null +++ b/crates/ber/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "craft-ber" +description = "ASN.1 BER and DER (X.690): reading TLVs, BER to DER, and what an opaque signed CMS holds" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true diff --git a/crates/ber/src/lib.rs b/crates/ber/src/lib.rs new file mode 100644 index 0000000000..e97c1b0f53 --- /dev/null +++ b/crates/ber/src/lib.rs @@ -0,0 +1,432 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Reading the TLVs of ASN.1 BER and DER (X.690), and turning BER into DER where they differ in +//! what CMS writers use: indefinite lengths (which streaming signers write) and OCTET STRINGs in +//! pieces (constructed). What is DER already is kept byte for byte, an element with a definite +//! length inside an indefinite one too, so that the bytes a signature covers (signed attributes, +//! a certificate's body) are those the signer wrote. For S/MIME: `craft-smime` checks +//! signatures with it, and a message's reader takes out what an opaque signed one holds +//! ([`signed_content`]). +//! +//! The input is hostile: lengths are checked against what is there, nesting is bounded +//! ([`MAX_DEPTH`]), and the work is linear in the input (times the bounded depth). +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// CMS's id-signedData and id-data (RFC 5652 §5.1, §4), as OBJECT IDENTIFIER values. +const SIGNED_DATA: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02]; +const DATA: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01]; + +/// What the CMS `cms` holds when it is SignedData with its content inside, of type id-data: the +/// MIME entity an opaque signed message (`application/pkcs7-mime`, RFC 8551 §3.5) signed, for +/// reading as the message. Nothing is checked here (`craft-smime` checks it); `None` for any +/// other CMS (an Encrypted message's enveloped data) or bytes that aren't one. +pub fn signed_content(cms: &[u8]) -> Option> { + let der = to_der(cms)?; + let (info, rest) = read(&der)?; + if info.tag != 0x30 || !rest.is_empty() { + return None; + } + let info = children(info.value)?; + let [oid, explicit] = info.as_slice() else { return None }; + if oid.tag != 0x06 || oid.value != SIGNED_DATA || explicit.tag != 0xa0 { + return None; + } + let (signed, rest) = read(explicit.value)?; + if signed.tag != 0x30 || !rest.is_empty() { + return None; + } + let signed = children(signed.value)?; + let [version, digests, encap, tail @ ..] = signed.as_slice() else { return None }; + if version.tag != 0x02 || !matches!(version.value, [1 | 3 | 4 | 5]) || digests.tag != 0x31 || encap.tag != 0x30 { + return None; + } + if children(digests.value)?.iter().any(|algorithm| algorithm.tag != 0x30) { + return None; + } + // Certificates and revocation lists are optional, but ordered and present at most once. + let tail = if tail.first().is_some_and(|field| field.tag == 0xa0) { tail.get(1..)? } else { tail }; + let tail = if tail.first().is_some_and(|field| field.tag == 0xa1) { tail.get(1..)? } else { tail }; + let [signers] = tail else { return None }; + if signers.tag != 0x31 || children(signers.value)?.iter().any(|signer| signer.tag != 0x30) { + return None; + } + let encap = children(encap.value)?; + let [kind, content] = encap.as_slice() else { return None }; + if kind.tag != 0x06 || kind.value != DATA || content.tag != 0xa0 { + return None; + } + let (octets, rest) = read(content.value)?; + (octets.tag == 0x04 && rest.is_empty()).then(|| octets.value.to_vec()) +} + +/// How deep elements may nest. +pub const MAX_DEPTH: usize = 48; + +/// Maximum elements materialized or indexed in one parsing operation. This bounds the +/// allocation amplification from hostile, shallow input containing many empty TLVs. +pub const MAX_ELEMENTS: usize = 65_536; + +/// The universal tag of an OCTET STRING, and of one in pieces. +const OCTET_STRING: u8 = 0x04; +const OCTET_STRING_PIECES: u8 = 0x24; + +/// One element: its tag bytes, and its value (the content octets). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Tlv<'a> { + /// The tag's first byte (class, constructed bit, number below 31). + pub tag: u8, + /// The whole element, tag and length included. + pub whole: &'a [u8], + /// Its content octets. + pub value: &'a [u8], +} + +/// The tag bytes at the start of `bytes`: one, or a high tag number in up to four more. +fn tag_len(bytes: &[u8]) -> Option { + let first = *bytes.first()?; + if first & 0x1f != 0x1f { + return Some(1); + } + // High tag number: base-128 bytes, the last without its top bit. + for (i, b) in bytes.iter().enumerate().skip(1).take(4) { + if b & 0x80 == 0 { + return i.checked_add(1); + } + } + None +} + +/// The length at the start of `bytes`: `(length, bytes it took)`, `None` for an indefinite one +/// (`Some((None, 1))`) is told apart by the caller. +fn length(bytes: &[u8]) -> Option<(Option, usize)> { + let first = *bytes.first()?; + if first < 0x80 { + return Some((Some(usize::from(first)), 1)); + } + if first == 0x80 { + return Some((None, 1)); + } + let n = usize::from(first & 0x7f); + if n > 4 { + return None; + } + let digits = bytes.get(1..n.checked_add(1)?)?; + let len = digits.iter().fold(0usize, |acc, d| (acc << 8) | usize::from(*d)); + Some((Some(len), n.checked_add(1)?)) +} + +/// The element at the start of `bytes` with a definite length, and what follows it. `None` for +/// an indefinite length, or one longer than what is there. +pub fn read(bytes: &[u8]) -> Option<(Tlv<'_>, &[u8])> { + let t = tag_len(bytes)?; + let tag = *bytes.first()?; + let (len, l) = length(bytes.get(t..)?)?; + let len = len?; + let start = t.checked_add(l)?; + let end = start.checked_add(len)?; + let value = bytes.get(start..end)?; + let whole = bytes.get(..end)?; + Some((Tlv { tag, whole, value }, bytes.get(end..)?)) +} + +/// The elements of `value`, each with a definite length; `None` when one can't be read. +pub fn children(mut value: &[u8]) -> Option>> { + let mut out = Vec::new(); + while !value.is_empty() { + if out.len() >= MAX_ELEMENTS { + return None; + } + let (tlv, rest) = read(value)?; + out.push(tlv); + value = rest; + } + Some(out) +} + +/// `bytes` as DER as far as CMS needs it: indefinite lengths made definite and OCTET STRINGs in +/// pieces joined into one, everything else as it was. One element is read, and must be all of +/// `bytes` (bar trailing zero bytes, which some writers pad with). `None` when it isn't BER. +pub fn to_der(bytes: &[u8]) -> Option> { + if let Some((_, rest)) = read(bytes) + && rest.iter().all(|b| *b == 0) + && der_shaped(bytes.get(..bytes.len().saturating_sub(rest.len()))?, 0) + { + return bytes.get(..bytes.len().saturating_sub(rest.len())).map(<[u8]>::to_vec); + } + let mut out = Vec::with_capacity(bytes.len()); + let used = element(bytes, 0, &mut out)?; + let rest = bytes.get(used..)?; + rest.iter().all(|b| *b == 0).then_some(out) +} + +/// Whether the elements of `bytes` all have definite lengths and no OCTET STRING is in pieces, +/// as deep as they go: nothing to change. +fn der_shaped(mut bytes: &[u8], depth: usize) -> bool { + if depth > MAX_DEPTH { + return false; + } + while !bytes.is_empty() { + let Some((tlv, rest)) = read(bytes) else { return false }; + if tlv.tag == OCTET_STRING_PIECES || (tlv.tag & 0x20 != 0 && !der_shaped(tlv.value, depth.saturating_add(1))) { + return false; + } + bytes = rest; + } + true +} + +/// What [`measure`] found of one element: how many bytes of the input it was, and how long its +/// content is as DER. +#[derive(Clone, Copy)] +struct Size { + used: usize, + content: usize, + /// It is DER-shaped already (a definite length, and nothing in it to change): copied as it + /// is, its lengths as the writer wrote them, since a signature may cover them. + verbatim: bool, +} + +/// The sizes of the constructed elements of the input, by where each starts in it: worked out +/// once, so that writing them is one pass with no copy of a level for each level above it. +type Sizes = std::collections::HashMap; + +/// The element at `at` in `input`: how many bytes it was, and its length as DER, header and all. +fn measure(input: &[u8], at: usize, depth: usize, sizes: &mut Sizes) -> Option<(usize, usize)> { + if depth > MAX_DEPTH || sizes.len() >= MAX_ELEMENTS { + return None; + } + let bytes = input.get(at..)?; + if let Some((tlv, _)) = read(bytes) + && der_shaped(tlv.whole, depth) + { + sizes.insert(at, Size { used: tlv.whole.len(), content: tlv.value.len(), verbatim: true }); + return Some((tlv.whole.len(), tlv.whole.len())); + } + let t = tag_len(bytes)?; + let tag = *bytes.first()?; + let (len, l) = length(bytes.get(t..)?)?; + let start = t.checked_add(l)?; + if tag & 0x20 == 0 { + let used = start.checked_add(len?)?; + bytes.get(..used)?; + return Some((used, used_der(t, used.checked_sub(start)?)?)); + } + // The children, one after another, to the end of a definite length or to the end mark. + let mut content = 0usize; + let mut pos = start; + let end = match len { + Some(len) => Some(start.checked_add(len)?), + None => None, + }; + loop { + match end { + Some(end) if pos >= end => break, + None if bytes.get(pos..)?.starts_with(&[0, 0]) => { + pos = pos.checked_add(2)?; + break; + } + _ => {} + } + // (The pieces of an OCTET STRING are OCTET STRINGs, in pieces themselves or not.) + if tag == OCTET_STRING_PIECES && !matches!(bytes.get(pos), Some(&OCTET_STRING | &OCTET_STRING_PIECES)) { + return None; + } + let (n, der) = measure(input, at.checked_add(pos)?, depth.checked_add(1)?, sizes)?; + if n == 0 { + return None; + } + // An OCTET STRING in pieces is one of their contents together. + content = content.checked_add(if tag == OCTET_STRING_PIECES { der_content(input, at.checked_add(pos)?, sizes)? } else { der })?; + pos = pos.checked_add(n)?; + } + if let Some(end) = end + && pos != end + { + return None; + } + if sizes.len() >= MAX_ELEMENTS { + return None; + } + sizes.insert(at, Size { used: pos, content, verbatim: false }); + let header_tag = if tag == OCTET_STRING_PIECES { 1 } else { t }; + Some((pos, used_der(header_tag, content)?)) +} + +/// The length of a DER element with a tag of `tag` bytes and `content` bytes of content. +fn used_der(tag: usize, content: usize) -> Option { + let mut l = Vec::new(); + put_length(&mut l, content); + tag.checked_add(l.len())?.checked_add(content) +} + +/// The DER content length of the (measured) element at `at`: a primitive's own. +fn der_content(input: &[u8], at: usize, sizes: &Sizes) -> Option { + if let Some(s) = sizes.get(&at) { + return Some(s.content); + } + let bytes = input.get(at..)?; + let t = tag_len(bytes)?; + let (len, _) = length(bytes.get(t..)?)?; + len +} + +/// Write the (measured) element at `at` in `input` to `out` as DER; how many bytes it was. +fn write(input: &[u8], at: usize, sizes: &Sizes, pieces: bool, out: &mut Vec) -> Option { + if let Some(s) = sizes.get(&at).filter(|s| s.verbatim && !pieces) { + out.extend_from_slice(input.get(at..at.checked_add(s.used)?)?); + return Some(s.used); + } + let bytes = input.get(at..)?; + let t = tag_len(bytes)?; + let tag_bytes = bytes.get(..t)?; + let tag = *tag_bytes.first()?; + let (len, l) = length(bytes.get(t..)?)?; + let start = t.checked_add(l)?; + if tag & 0x20 == 0 { + let used = start.checked_add(len?)?; + let value = bytes.get(start..used)?; + // (A piece of an OCTET STRING in pieces gives its bytes alone.) + if !pieces { + out.extend_from_slice(tag_bytes); + put_length(out, value.len()); + } + out.extend_from_slice(value); + return Some(used); + } + let size = *sizes.get(&at)?; + if tag == OCTET_STRING_PIECES { + if !pieces { + out.push(OCTET_STRING); + put_length(out, size.content); + } + } else { + out.extend_from_slice(tag_bytes); + put_length(out, size.content); + } + let inner_pieces = tag == OCTET_STRING_PIECES; + let mut pos = start; + while pos < size.used { + if bytes.get(pos..)?.starts_with(&[0, 0]) && len.is_none() { + break; + } + let n = write(input, at.checked_add(pos)?, sizes, inner_pieces, out)?; + pos = pos.checked_add(n)?; + } + Some(size.used) +} + +/// Write the element at the start of `bytes` to `out` as DER; how many bytes of `bytes` it was. +fn element(bytes: &[u8], depth: usize, out: &mut Vec) -> Option { + let mut sizes = Sizes::new(); + let (used, der) = measure(bytes, 0, depth, &mut sizes)?; + out.reserve(der); + write(bytes, 0, &sizes, false, out)?; + Some(used) +} + +/// A definite length in DER's shortest form. +fn put_length(out: &mut Vec, len: usize) { + if len < 0x80 { + out.push(len as u8); + return; + } + let bytes = len.to_be_bytes(); + let skip = bytes.iter().take_while(|b| **b == 0).count(); + let digits = bytes.get(skip..).unwrap_or_default(); + out.push(0x80 | digits.len() as u8); + out.extend_from_slice(digits); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tlv(tag: u8, value: &[u8]) -> Vec { + let mut out = vec![tag]; + put_length(&mut out, value.len()); + out.extend_from_slice(value); + out + } + + fn cms(outer_tag: u8, signed_tag: u8, oid_tag: u8, long_oid: bool, trailing: bool) -> Vec { + let oid = |value: &[u8]| { + if long_oid { + let mut out = vec![oid_tag, 0x81, 9]; + out.extend_from_slice(value); + out + } else { + tlv(oid_tag, value) + } + }; + let mut encap = oid(DATA); + encap.extend(tlv(0xa0, &tlv(0x04, b"hello"))); + let mut signed = tlv(0x02, &[1]); + signed.extend(tlv(0x31, &[])); + signed.extend(tlv(0x30, &encap)); + signed.extend(tlv(0x31, &[])); + let mut signed = tlv(signed_tag, &signed); + if trailing { + signed.extend(tlv(0x05, &[])); + } + let mut info = oid(SIGNED_DATA); + info.extend(tlv(0xa0, &signed)); + tlv(outer_tag, &info) + } + + #[test] + fn extracts_content_with_der_and_ber_oid_lengths() { + for long_oid in [false, true] { + assert_eq!(signed_content(&cms(0x30, 0x30, 0x06, long_oid, false)), Some(b"hello".to_vec())); + } + } + + #[test] + fn rejects_wrong_cms_container_and_oid_tags() { + for (outer, signed, oid) in [(0x31, 0x30, 0x06), (0x30, 0x31, 0x06), (0x30, 0x30, 0x04)] { + assert_eq!(signed_content(&cms(outer, signed, oid, false, false)), None); + } + } + + #[test] + fn rejects_missing_mandatory_signed_data_fields() { + let mut encap = tlv(0x06, DATA); + encap.extend(tlv(0xa0, &tlv(0x04, b"hello"))); + for prefix in [vec![0x05, 0, 0x05, 0], vec![0x02, 1, 1, 0x31, 0]] { + let mut malformed = prefix; + malformed.extend(tlv(0x30, &encap)); + let mut info = tlv(0x06, SIGNED_DATA); + info.extend(tlv(0xa0, &tlv(0x30, &malformed))); + assert_eq!(signed_content(&tlv(0x30, &info)), None); + } + } + + #[test] + fn rejects_extra_signed_data_inside_explicit_container() { + assert_eq!(signed_content(&cms(0x30, 0x30, 0x06, false, true)), None); + } + + #[test] + fn rejects_wide_inputs_before_unbounded_metadata_allocation() { + let children_bytes = [0x05, 0].repeat(MAX_ELEMENTS + 1); + assert!(children(&children_bytes).is_none()); + let mut indefinite = vec![0x30, 0x80]; + indefinite.extend_from_slice(&children_bytes); + indefinite.extend_from_slice(&[0, 0]); + assert!(to_der(&indefinite).is_none()); + } + + #[test] + fn joins_indefinite_octet_string_pieces() { + assert_eq!(to_der(&[0x24, 0x80, 0x04, 1, b'a', 0x04, 1, b'b', 0, 0]), Some(vec![0x04, 2, b'a', b'b'])); + } + + #[test] + fn rejects_truncated_and_over_nested_input() { + assert_eq!(to_der(&[0x04, 2, b'a']), None); + let mut nested = tlv(0x04, &[]); + for _ in 0..=MAX_DEPTH { + nested = tlv(0x30, &nested); + } + assert_eq!(to_der(&nested), None); + } +} diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index df665336de..cd09f7e166 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -19,3 +19,5 @@ thiserror = { workspace = true } proptest = { workspace = true } # A second XML reader for the tests: checks of written TTML, and the comparison in tests/it/ttml_xml_views.rs. roxmltree = "0.21" +# ffmpeg as the reference for the ASS tests (tests/it/ass.rs). +craft-media-testkit = { workspace = true } diff --git a/crates/captions/README.md b/crates/captions/README.md index 0676d1d728..7380a3ce41 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -55,6 +55,7 @@ lists at most 20 characters per stream. | EBU STL `.stl` | yes | yes | EBU Tech 3264-E: GSI block + 128-byte TTI blocks, `STL25.01` (25 fps) or `STL30.01` (read/written as 29.97 fps, non-drop labels), ISO/IEC 6937 Latin text (accents as diacritic + letter), italics / underline codes as `` / ``, extension blocks for long subtitles, start-of-programme (TCP) subtracted. | | TTML `.ttml` (IMSC1) | yes | yes | Writes the IMSC1 Text profile (TTML2 namespaces) with the document's language as `xml:lang` (read back on import): `

` per cue, `
`, styled ``s for `` / `` / ``, `ttm:agent` speakers, exact frame times (`123f`) at the sequence rate. Reads any TTML (TTML1, TTML2, the 2006 `ttaf1` drafts): clock / frame / offset / tick times, `dur`, nested time containers (`body` / `div` begins offset and ends clip their contents; `seq` containers are read as `par` with a warning), timed spans, referenced styles. | | DFXP `.dfxp` | yes | yes | TTML1 with the DFXP presentation profile; clock times in milliseconds (frame-exact after `snap_to_frames`). | +| ASS / SSA `.ass`, `.ssa` | yes | yes (ASS v4+) | The `[Events]` section: `Dialogue:` lines through the file's `Format:` line, `Name` as the speaker, `\N`, `\n`, `\h` and the `\i`, `\b`, `\u` override tags kept (as ``, ``, ``); other override tags and drawing lines are dropped. Times are centiseconds. Written files have one `Default` style. | All cue times are exact `Tick`s. Milliseconds convert exactly (1 ms = 254 016 000 ticks); SCC frames map through `FrameRate::FPS_29_97`. `Document::snap_to_frames` snaps cues to a frame grid and diff --git a/crates/captions/src/ass.rs b/crates/captions/src/ass.rs new file mode 100644 index 0000000000..2d0a1df552 --- /dev/null +++ b/crates/captions/src/ass.rs @@ -0,0 +1,244 @@ +//! Advanced SubStation Alpha and SubStation Alpha (`.ass`, `.ssa`). +//! +//! Reading takes the `[Events]` section: its `Format:` line gives the field order (ASS v4+ and SSA +//! v4 differ in the first field only), each `Dialogue:` line becomes a cue; `Comment:` lines and +//! the other sections are skipped. A cue gets the `Name` field as its speaker. The text keeps what +//! the neutral model can show: `\N` and `\n` become a line break and a space, `\h` a no-break +//! space, and the override tags `\i`, `\b` and `\u` become ``, `` and ``. Every other +//! override tag (colours, fonts, positions, karaoke, animation) is dropped, and a line that draws +//! vector shapes (`\p1`) is skipped with a warning. +//! +//! Writing gives a minimal ASS v4+ file: one `Default` style, one `Dialogue:` line per cue with +//! times to the centisecond. Braces in the text, which ASS reads as override blocks, are written +//! as the full-width `ï½›` and `ï½�`. + +use crate::time::{TICKS_PER_SECOND, Tick}; +use crate::{Cue, Document, Error, Result}; + +const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100; + +/// `H:MM:SS.cc`, the form SSA and ASS use (any number of fraction digits is read). +fn parse_time(s: &str) -> Option { + let s = s.trim(); + let (hms, frac) = s.split_once('.').unwrap_or((s, "")); + let mut parts = hms.split(':'); + let (h, m, sec) = (parts.next()?, parts.next()?, parts.next()?); + if parts.next().is_some() { + return None; + } + let num = |p: &str| -> Option { (!p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit())).then(|| p.parse().ok()).flatten() }; + let (h, m, sec) = (num(h)?, num(m)?, num(sec)?); + if m >= 60 || sec >= 60 || h > 9999 { + return None; + } + let mut ticks = ((h * 60 + m) * 60 + sec) * TICKS_PER_SECOND; + if !frac.is_empty() { + if frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let d: i64 = frac.parse().ok()?; + ticks += (i128::from(d) * i128::from(TICKS_PER_SECOND) / 10i128.pow(frac.len() as u32)) as i64; + } + Some(Tick(ticks)) +} + +fn format_time(t: Tick) -> String { + let cs = (i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS); + let (h, m, s, c) = (cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100); + format!("{h}:{m:02}:{s:02}.{c:02}") +} + +/// The Text field of a Dialogue line as cue text; `None` when the line draws shapes. +fn convert_text(raw: &str) -> Option { + let mut out = String::new(); + // Open ``, ``, `` in the order they were opened. + let mut open: Vec = Vec::new(); + let mut chars = raw.chars().peekable(); + let mut drawing = false; + let mut dropped_drawing = false; + while let Some(c) = chars.next() { + match c { + '{' => { + let mut block = String::new(); + let mut closed = false; + for b in chars.by_ref() { + if b == '}' { + closed = true; + break; + } + block.push(b); + } + if !closed { + // An unterminated block is literal text. + out.push('{'); + out.push_str(&block); + continue; + } + for tag in block.split('\\').skip(1) { + let tag = tag.trim_end(); + let (name, val) = tag.split_at(tag.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(tag.len())); + match name { + "i" | "b" | "u" => { + let letter = name.chars().next().unwrap_or('i'); + let on = val.trim() != "0"; + if on && !open.contains(&letter) { + open.push(letter); + out.push_str(&format!("<{letter}>")); + } else if !on && open.contains(&letter) { + // Close back to it, reopening what was opened after. + let at = open.iter().position(|&o| o == letter).unwrap_or(0); + let after: Vec = open.split_off(at + 1); + for o in after.iter().rev() { + out.push_str(&format!("")); + } + open.pop(); + out.push_str(&format!("")); + for o in after { + open.push(o); + out.push_str(&format!("<{o}>")); + } + } + } + "p" => drawing = val.trim().parse::().unwrap_or(0) != 0, + _ => {} + } + } + } + '\\' => match chars.peek() { + Some('N') => { + chars.next(); + out.push('\n'); + } + Some('n') => { + chars.next(); + out.push(' '); + } + Some('h') => { + chars.next(); + out.push('\u{a0}'); + } + _ => out.push('\\'), + }, + c => { + if drawing { + dropped_drawing = true; + } else { + out.push(c); + } + } + } + } + if dropped_drawing && out.trim().is_empty() { + return None; + } + while let Some(o) = open.pop() { + out.push_str(&format!("")); + } + Some(out) +} + +pub fn parse(text: &str) -> Result { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let mut doc = Document::default(); + let mut in_events = false; + let mut saw_events = false; + // Column of each field in a Dialogue line. + let mut cols: Vec = + ["layer", "start", "end", "style", "name", "marginl", "marginr", "marginv", "effect", "text"].map(String::from).to_vec(); + let mut drawings = 0usize; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.starts_with('[') && line.ends_with(']') { + in_events = line.eq_ignore_ascii_case("[events]"); + saw_events |= in_events; + continue; + } + if !in_events { + continue; + } + let Some((key, rest)) = line.split_once(':') else { continue }; + let rest = rest.trim_start(); + match key.trim().to_ascii_lowercase().as_str() { + "format" => cols = rest.split(',').map(|f| f.trim().to_ascii_lowercase()).collect(), + "dialogue" => { + // The last column (Text) keeps its commas. + let fields: Vec<&str> = rest.splitn(cols.len(), ',').collect(); + let get = |name: &str| cols.iter().position(|c| c == name).and_then(|i| fields.get(i)).copied(); + let (Some(start), Some(end), Some(raw)) = (get("start").and_then(parse_time), get("end").and_then(parse_time), get("text")) else { + doc.warnings.push(format!("line {}: not a Dialogue line this reader understands", n + 1)); + continue; + }; + let Some(text) = convert_text(raw) else { + drawings += 1; + continue; + }; + let name = get("name").map(str::trim).filter(|s| !s.is_empty()); + doc.cues.push(Cue { start, end, text, speaker: name.map(str::to_string), ..Default::default() }); + } + _ => {} + } + } + if !saw_events { + return Err(Error::NotFormat("ASS")); + } + if drawings > 0 { + doc.warnings.push(format!("{drawings} vector drawing line(s) were skipped")); + } + Ok(doc) +} + +fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 8); + let mut rest = text; + while !rest.is_empty() { + if let Some(r) = rest.strip_prefix("\r\n") { + out.push_str("\\N"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\i1}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\i0}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\b1}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\b0}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\u1}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\u0}"); + rest = r; + } else if let Some(c) = rest.chars().next() { + match c { + '\n' | '\r' => out.push_str("\\N"), + // Empty override block separates a literal slash from N/n/h. + '\\' => out.push_str("\\{}"), + '{' => out.push('\u{ff5b}'), + '}' => out.push('\u{ff5d}'), + '\u{a0}' => out.push_str("\\h"), + c => out.push(c), + } + rest = &rest[c.len_utf8()..]; + } + } + out +} + +pub fn write(doc: &Document) -> String { + let mut out = String::from( + "[Script Info]\n; Written by craft-captions\nScriptType: v4.00+\nWrapStyle: 0\nScaledBorderAndShadow: yes\nPlayResX: 384\nPlayResY: 288\n\n\ + [V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n\ + Style: Default,Arial,16,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1\n\n\ + [Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n", + ); + for c in &doc.cues { + // A comma in the Name field would shift the columns; the other fields are fixed text. + let name = c.speaker.as_deref().unwrap_or("").replace([',', '\n', '\r'], " "); + out.push_str(&format!("Dialogue: 0,{},{},Default,{},0,0,0,,{}\n", format_time(c.start), format_time(c.end), name, escape(&c.text))); + } + out +} diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index 0ba9f2ba50..e8a4927229 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -4,7 +4,7 @@ //! - **Files:** [SubRip](srt) (`.srt`), [WebVTT](vtt) (`.vtt`), [Scenarist SCC](scc) (`.scc`, //! CEA-608 pop-on, roll-up and paint-on on read; pop-on on write), [MacCaption MCC](mcc) //! (`.mcc`, SMPTE ST 334-2 packets with CEA-608 and CEA-708), [EBU STL](stl) (`.stl`, EBU -//! Tech 3264) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a +//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a //! [`Document`] of [`Cue`]s and write back. Readers are forgiving (BOM, UTF-16, Windows-1252 //! fallback, CRLF/CR, missing SRT indexes, `,` or `.` milliseconds, missing hours, no blank //! line between cues); writers are strict. WebVTT cue identifiers, cue settings, `` @@ -32,6 +32,7 @@ #[doc = include_str!("../README.md")] struct ReadmeExamples; +pub mod ass; pub mod cea608; pub mod mcc; pub mod scc; @@ -69,10 +70,12 @@ pub enum Format { Ttml, /// DFXP (TTML1). Dfxp, + /// Advanced SubStation Alpha (also reads SubStation Alpha). + Ass, } impl Format { - pub const ALL: [Format; 7] = [Format::Srt, Format::WebVtt, Format::Scc, Format::Mcc, Format::Stl, Format::Ttml, Format::Dfxp]; + pub const ALL: [Format; 8] = [Format::Srt, Format::WebVtt, Format::Scc, Format::Mcc, Format::Stl, Format::Ttml, Format::Dfxp, Format::Ass]; pub fn name(self) -> &'static str { match self { Format::Srt => "SubRip (SRT)", @@ -82,6 +85,7 @@ impl Format { Format::Stl => "EBU STL", Format::Ttml => "TTML (IMSC1)", Format::Dfxp => "DFXP (TTML1)", + Format::Ass => "Advanced SubStation Alpha (ASS)", } } pub fn extension(self) -> &'static str { @@ -93,6 +97,7 @@ impl Format { Format::Stl => "stl", Format::Ttml => "ttml", Format::Dfxp => "dfxp", + Format::Ass => "ass", } } pub fn from_name(s: &str) -> Option { @@ -104,6 +109,7 @@ impl Format { "stl" | "ebu-stl" | "ebustl" | "ebu" => Some(Format::Stl), "ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml), "dfxp" => Some(Format::Dfxp), + "ass" | "ssa" => Some(Format::Ass), _ => None, } } @@ -251,6 +257,9 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.starts_with("File Format=MacCaption_MCC") { return Some(Format::Mcc); } + if head.starts_with("[Script Info]") { + return Some(Format::Ass); + } let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); if (head.starts_with('<') && (head.contains("") || head.contains(":tt "))) && (head.contains("ns/ttml") || head.contains("ttaf1")) @@ -262,7 +271,7 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { match ext.as_deref() { Some("srt") if has_arrow_timing || head.is_empty() => Some(Format::Srt), Some("vtt") if has_arrow_timing => Some(Format::WebVtt), - Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml") => None, + Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa") => None, _ if has_arrow_timing => Some(Format::Srt), _ => None, } @@ -296,6 +305,7 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result { Format::Scc => scc::parse(&text), Format::Mcc => mcc::parse(&text), Format::Ttml | Format::Dfxp => ttml::parse(&text), + Format::Ass => ass::parse(&text), Format::Stl => stl::parse(bytes), } } @@ -333,6 +343,7 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { Format::Stl => stl::write(doc, opts.rate, opts.program), Format::Ttml => ttml::write(doc, ttml::Flavor::Imsc1, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Dfxp => ttml::write(doc, ttml::Flavor::Dfxp, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), + Format::Ass => ass::write(doc).into_bytes(), } } diff --git a/crates/captions/tests/it/ass.rs b/crates/captions/tests/it/ass.rs new file mode 100644 index 0000000000..fb6d4e01ea --- /dev/null +++ b/crates/captions/tests/it/ass.rs @@ -0,0 +1,142 @@ +//! SubStation Alpha / Advanced SubStation Alpha: reading, writing, and ffmpeg as the reference +//! (oracle; skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). + +use craft_captions::{Cue, Document, Format, Tick, WriteOptions, detect, parse, write}; +use std::process::Command; + +const T: i64 = craft_captions::TICKS_PER_SECOND; + +fn cs(n: i64) -> Tick { + Tick(n * (T / 100)) +} + +const SAMPLE: &str = "\u{feff}[Script Info]\n; a comment\nTitle: Test\nScriptType: v4.00+\n\n[V4+ Styles]\nFormat: Name, Fontname\nStyle: Default,Arial\n\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nComment: 0,0:00:00.00,0:00:01.00,Default,,0,0,0,,not a cue\nDialogue: 0,0:00:01.50,0:00:03.25,Default,Bob,0,0,0,,Hello, {\\i1}world{\\i0}\\Nsecond {\\b1}line{\\b0}\nDialogue: 0,1:02:03.04,1:02:04.5,Default,,0,0,0,,{\\pos(10,20)\\c&H0000FF&}Red\\hspace\\nsoft\nDialogue: 0,0:00:09.00,0:00:10.00,Default,,0,0,0,,{\\p1}m 0 0 l 100 0 100 100{\\p0}\n"; + +#[test] +fn reads_dialogue_lines_with_commas_overrides_and_line_breaks() { + let doc = parse(SAMPLE.as_bytes(), Format::Ass).unwrap(); + assert_eq!(doc.cues.len(), 2); + assert_eq!(doc.cues[0].start, cs(150)); + assert_eq!(doc.cues[0].end, cs(325)); + assert_eq!(doc.cues[0].text, "Hello, world\nsecond line"); + assert_eq!(doc.cues[0].speaker.as_deref(), Some("Bob")); + // 1:02:03.04, a one-digit fraction, an override block dropped, \h and \n. + assert_eq!(doc.cues[1].start, Tick((3600 + 120 + 3) * T + 4 * (T / 100))); + assert_eq!(doc.cues[1].end, Tick((3600 + 120 + 4) * T + T / 2)); + assert_eq!(doc.cues[1].text, "Red\u{a0}space soft"); + assert!(doc.warnings.iter().any(|w| w.contains("vector drawing")), "{:?}", doc.warnings); +} + +#[test] +fn ssa_v4_files_read_through_their_own_format_line() { + let ssa = "[Script Info]\nScriptType: v4.00\n\n[V4 Styles]\nFormat: Name\n\n[Events]\nFormat: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nDialogue: Marked=0,0:00:01.00,0:00:02.00,*Default,,0000,0000,0000,,Old style\n"; + let doc = parse(ssa.as_bytes(), Format::Ass).unwrap(); + assert_eq!((doc.cues[0].start, doc.cues[0].end, doc.cues[0].text.as_str()), (cs(100), cs(200), "Old style")); +} + +#[test] +fn write_then_read_keeps_times_text_and_speaker() { + let cues = vec![ + Cue { start: cs(100), end: cs(250), text: "Line one\nline two".into(), speaker: Some("Ann".into()), ..Default::default() }, + Cue { + start: Tick(7200 * T + 99 * (T / 100)), + end: Tick(7203 * T), + text: "bold and under {braces}".into(), + ..Default::default() + }, + ]; + let doc = Document { cues, ..Default::default() }; + let bytes = write(&doc, Format::Ass, WriteOptions::default()); + assert_eq!(detect(&bytes, Some("ass")), Some(Format::Ass)); + let back = parse(&bytes, Format::Ass).unwrap(); + assert_eq!(back.cues[0], doc.cues[0]); + assert_eq!(back.cues[1].start, doc.cues[1].start); + // Braces are written full-width, as ASS reads `{` as the start of an override block. + assert_eq!(back.cues[1].text, "bold and under \u{ff5b}braces\u{ff5d}"); +} + +#[test] +fn files_without_an_events_section_are_not_ass() { + assert!(parse(b"[Script Info]\nTitle: x\n", Format::Ass).is_err()); + assert!(parse(b"hello", Format::Ass).is_err()); + assert_eq!(detect(b"hello", Some("ass")), None); +} + +#[test] +fn bad_lines_are_skipped_with_a_warning() { + let text = "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nDialogue: 0,garbage,0:00:02.00,Default,,0,0,0,,x\nDialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,ok\n"; + let doc = parse(text.as_bytes(), Format::Ass).unwrap(); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.warnings.len(), 1); +} + +fn ffmpeg_run(ff: &std::path::Path, args: &[&str]) { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +const SRT: &str = "1\n00:00:01,500 --> 00:00:03,250\nHello, world\nsecond line\n\n2\n00:00:04,000 --> 00:00:05,990\nPlain, with a comma\n\n3\n01:00:00,010 --> 01:00:02,999\nUnder and italic both\n"; + +#[test] +fn we_read_what_ffmpeg_writes() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("captions_ass"); + let (srt, ass) = (dir.join("in.srt"), dir.join("ffmpeg.ass")); + std::fs::write(&srt, SRT).expect("write"); + ffmpeg_run(&ff, &["-i", srt.to_str().expect("path"), ass.to_str().expect("path")]); + let from_ass = parse(&std::fs::read(&ass).expect("read"), Format::Ass).expect("parse ass"); + let from_srt = parse(SRT.as_bytes(), Format::Srt).expect("parse srt"); + assert_eq!(from_ass.cues.len(), from_srt.cues.len()); + for (a, s) in from_ass.cues.iter().zip(&from_srt.cues) { + // ASS times are centiseconds; the SRT ones round to them. + assert_eq!(a.start, cs((s.start.0 + T / 200) / (T / 100)), "start of {:?}", s.text); + assert_eq!(a.end, cs((s.end.0 + T / 200) / (T / 100)), "end of {:?}", s.text); + assert_eq!(a.text, s.text); + } +} + +#[test] +fn ffmpeg_reads_what_we_write() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("captions_ass"); + let mut doc = parse(SRT.as_bytes(), Format::Srt).expect("parse srt"); + doc.cues.push(Cue { start: cs(400_000), end: cs(400_100), text: r"C:\New\notes\hello and \N \n \h".into(), ..Default::default() }); + let (ass, srt) = (dir.join("ours.ass"), dir.join("back.srt")); + std::fs::write(&ass, write(&doc, Format::Ass, WriteOptions::default())).expect("write"); + ffmpeg_run(&ff, &["-i", ass.to_str().expect("path"), srt.to_str().expect("path")]); + let theirs = parse(&std::fs::read(&srt).expect("read"), Format::Srt).expect("parse back"); + assert_eq!(theirs.cues.len(), doc.cues.len()); + for (t, d) in theirs.cues.iter().zip(&doc.cues) { + assert_eq!(t.start, cs((d.start.0 + T / 200) / (T / 100))); + assert_eq!(t.end, cs((d.end.0 + T / 200) / (T / 100))); + assert_eq!(t.text, d.text, "text of the cue at {:?}", d.start); + } +} + +#[test] +fn literal_backslashes_survive_ass_round_trip() { + let text = r"C:\New\notes\hello and \N \n \h"; + let doc = Document { cues: vec![Cue { start: cs(100), end: cs(200), text: text.into(), ..Default::default() }], ..Default::default() }; + let bytes = write(&doc, Format::Ass, WriteOptions::default()); + assert_eq!(parse(&bytes, Format::Ass).unwrap().cues[0].text, text); +} + +#[test] +fn carriage_returns_cannot_create_dialogue_records() { + let doc = Document { + cues: vec![Cue { + start: cs(100), + end: cs(200), + text: "first\rsecond\r\nthird".into(), + speaker: Some("Ann\rOther".into()), + ..Default::default() + }], + ..Default::default() + }; + let bytes = write(&doc, Format::Ass, WriteOptions::default()); + assert!(!bytes.contains(&b'\r')); + let back = parse(&bytes, Format::Ass).unwrap(); + assert_eq!(back.cues.len(), 1); + assert_eq!(back.cues[0].text, "first\nsecond\nthird"); + assert_eq!(back.cues[0].speaker.as_deref(), Some("Ann Other")); +} diff --git a/crates/captions/tests/it/main.rs b/crates/captions/tests/it/main.rs index 16f8fcbb68..be03d2855f 100644 --- a/crates/captions/tests/it/main.rs +++ b/crates/captions/tests/it/main.rs @@ -1,3 +1,4 @@ +mod ass; mod limits; mod literal_roundtrips; mod mcc_708_timing; diff --git a/crates/cms/src/builtin.rs b/crates/cms/src/builtin.rs index ca7034286c..5a8b032289 100644 --- a/crates/cms/src/builtin.rs +++ b/crates/cms/src/builtin.rs @@ -424,6 +424,18 @@ fn shipped_cmyk(bytes: &[u8], b: Builtin) -> Profile { }) } +/// Generates the compact ICC v2.1 sRGB matrix/TRC profile used by PDFCraft. +/// +/// Unlike [`Builtin::Srgb`]'s v4 profile, this uses a 1024-sample tone curve and +/// v2 `desc`/`text` tags for consumers that require a v2 output intent. The legacy +/// description `sRGB (PdfCraft)` is retained to preserve existing document bytes. +/// The generated profile contains no external assets; callers choose where it is +/// appropriate (including their own PDF/A conformance policy). +/// All sizes are fixed; no input-controlled allocation or recursion is involved. +pub fn srgb_v2() -> Vec { + crate::builtin_v2::srgb() +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/cms/src/builtin_v2.rs b/crates/cms/src/builtin_v2.rs new file mode 100644 index 0000000000..4a9e2e25b7 --- /dev/null +++ b/crates/cms/src/builtin_v2.rs @@ -0,0 +1,143 @@ +//! A small sRGB ICC profile (version 2, display class, matrix/TRC), written from the published +//! sRGB primaries (IEC 61966-2-1) adapted to D50, with the sRGB tone curve sampled at 1024 +//! points. Used as the PDF/A output intent's destination profile. + +fn s15f16(v: f64) -> [u8; 4] { + ((v * 65536.0).round() as i32).to_be_bytes() +} + +fn xyz(x: f64, y: f64, z: f64) -> Vec { + let mut t = b"XYZ \0\0\0\0".to_vec(); + t.extend(s15f16(x)); + t.extend(s15f16(y)); + t.extend(s15f16(z)); + t +} + +fn desc(text: &str) -> Vec { + let mut t = b"desc\0\0\0\0".to_vec(); + let ascii: Vec = text.bytes().chain(std::iter::once(0)).collect(); + t.extend((ascii.len() as u32).to_be_bytes()); + t.extend(&ascii); + // No Unicode or ScriptCode descriptions. + t.extend([0u8; 4 + 4]); + t.extend([0u8; 2 + 1 + 67]); + t +} + +fn text(text: &str) -> Vec { + let mut t = b"text\0\0\0\0".to_vec(); + t.extend(text.bytes()); + t.push(0); + t +} + +fn curve() -> Vec { + const N: usize = 1024; + let mut t = b"curv\0\0\0\0".to_vec(); + t.extend((N as u32).to_be_bytes()); + for i in 0..N { + let v = i as f64 / (N - 1) as f64; + let lin = if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; + t.extend(((lin * 65535.0).round() as u16).to_be_bytes()); + } + t +} + +/// Fixed-size profile bytes; all tag sizes and loop counts are constants. +pub fn srgb() -> Vec { + // sRGB primaries, Bradford-adapted to the D50 profile connection space. + let tags: Vec<(&[u8; 4], Vec)> = vec![ + (b"desc", desc("sRGB (PdfCraft)")), + (b"cprt", text("No copyright, use freely")), + (b"wtpt", xyz(0.9642, 1.0, 0.8249)), + (b"rXYZ", xyz(0.4361, 0.2225, 0.0139)), + (b"gXYZ", xyz(0.3851, 0.7169, 0.0971)), + (b"bXYZ", xyz(0.1431, 0.0606, 0.7141)), + (b"rTRC", curve()), + ]; + // gTRC and bTRC share rTRC's data. + let count = tags.len() + 2; + let table_len = 4 + count * 12; + let mut offset = 128 + table_len; + let mut table = (count as u32).to_be_bytes().to_vec(); + let mut data = Vec::new(); + let mut trc = (0, 0); + for (sig, body) in &tags { + let len = body.len(); + table.extend(*sig); + table.extend((offset as u32).to_be_bytes()); + table.extend((len as u32).to_be_bytes()); + if *sig == b"rTRC" { + trc = (offset, len); + } + data.extend(body); + // Tags start on 4-byte boundaries. + let pad = (4 - len % 4) % 4; + data.extend(std::iter::repeat_n(0u8, pad)); + offset += len + pad; + } + for sig in [b"gTRC", b"bTRC"] { + table.extend(sig); + table.extend((trc.0 as u32).to_be_bytes()); + table.extend((trc.1 as u32).to_be_bytes()); + } + let size = 128 + table.len() + data.len(); + let mut h = Vec::with_capacity(size); + h.extend((size as u32).to_be_bytes()); + h.extend(b"\0\0\0\0"); // preferred CMM + h.extend([2, 0x10, 0, 0]); // version 2.1 + h.extend(b"mntr"); + h.extend(b"RGB "); + h.extend(b"XYZ "); + h.extend([0u8; 12]); // date + h.extend(b"acsp"); + h.extend(b"\0\0\0\0"); // platform + h.extend([0u8; 4]); // flags + h.extend([0u8; 4]); // manufacturer + h.extend([0u8; 4]); // model + h.extend([0u8; 8]); // attributes + h.extend([0, 0, 0, 0]); // perceptual intent + h.extend(s15f16(0.9642)); + h.extend(s15f16(1.0)); + h.extend(s15f16(0.8249)); + h.extend([0u8; 4]); // creator + h.resize(128, 0); + h.extend(table); + h.extend(data); + h +} + +#[cfg(test)] +mod tests { + #[test] + fn parses_as_v2_with_shared_rgb_curves() { + let bytes = super::srgb(); + let p = crate::Profile::parse(&bytes).unwrap(); + assert_eq!(p.version, (2, 0x10)); + assert_eq!(p.color_space, crate::ColorSpace::Rgb); + assert_eq!(p.pcs, crate::Pcs::Xyz); + assert_eq!(p.description, "sRGB (PdfCraft)"); + let curves = p.trc.unwrap(); + assert_eq!(curves[0], curves[1]); + assert_eq!(curves[1], curves[2]); + assert!(matches!(&curves[0], crate::Curve::Table(v) if v.len() == 1024 && v[0] == 0.0 && v[1023] == 1.0)); + assert_eq!(bytes, super::srgb()); + } + + #[test] + fn profile_is_well_formed() { + let p = super::srgb(); + assert_eq!(u32::from_be_bytes(p[0..4].try_into().unwrap()) as usize, p.len()); + assert_eq!(&p[36..40], b"acsp"); + assert_eq!(&p[12..20], b"mntrRGB "); + let n = u32::from_be_bytes(p[128..132].try_into().unwrap()) as usize; + assert_eq!(n, 9); + for i in 0..n { + let e = 132 + i * 12; + let off = u32::from_be_bytes(p[e + 4..e + 8].try_into().unwrap()) as usize; + let len = u32::from_be_bytes(p[e + 8..e + 12].try_into().unwrap()) as usize; + assert!(off.is_multiple_of(4) && off + len <= p.len(), "tag {i}"); + } + } +} diff --git a/crates/cms/src/curve.rs b/crates/cms/src/curve.rs index 5da1be8012..6615a38821 100644 --- a/crates/cms/src/curve.rs +++ b/crates/cms/src/curve.rs @@ -26,6 +26,47 @@ pub fn srgb_trc() -> Curve { } impl Curve { + /// Creates a gamma curve `y = x^g`. Returns `Identity` if `g == 1.0` (within 1e-6). + pub fn gamma(g: f64) -> Result { + if !crate::math::fits_s15f16(g) || crate::math::s15f16_round(g) <= 0.0 { + return Err(crate::CmsError::InvalidArgument("gamma must remain positive and representable in ICC fixed point".into())); + } + if (g - 1.0).abs() < 1e-6 { Ok(Curve::Identity) } else { Ok(Curve::Gamma(g)) } + } + + /// Creates an ICC parametric curve (types 0 to 4). + pub fn parametric(kind: u16, p: [f64; 7]) -> Result { + if kind > 4 { + return Err(crate::CmsError::InvalidArgument(format!("parametric curve kind {kind} must be <= 4"))); + } + let count = Self::param_count(kind); + if !p.iter().take(count).all(|&v| crate::math::fits_s15f16(v)) { + return Err(crate::CmsError::InvalidArgument("parametric curve parameters must be representable in ICC fixed point".into())); + } + Ok(Curve::Parametric { kind, p }) + } + + /// Creates a sampled lookup table curve over evenly spaced inputs in `[0, 1]`. + pub fn from_table(samples: Vec) -> Result { + if samples.len() < 2 { + return Err(crate::CmsError::InvalidArgument("sampled curve must contain at least 2 entries".into())); + } + if !samples.iter().all(|s| s.is_finite() && (0.0..=1.0).contains(s)) { + return Err(crate::CmsError::InvalidArgument("sampled curve values must be finite and within [0, 1]".into())); + } + Ok(Curve::Table(samples)) + } + + /// Validate public enum variants before a profile stores them in ICC tags. + pub(crate) fn validate_icc(&self) -> Result<(), crate::CmsError> { + match self { + Self::Identity => Ok(()), + Self::Gamma(g) => Self::gamma(*g).map(|_| ()), + Self::Parametric { kind, p } => Self::parametric(*kind, *p).map(|_| ()), + Self::Table(t) if t.len() >= 2 && u32::try_from(t.len()).is_ok() && t.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) => Ok(()), + Self::Table(_) => Err(crate::CmsError::InvalidArgument("sampled curve must contain representable finite normalized samples".into())), + } + } /// Number of parameters stored for a parametric function type. pub fn param_count(kind: u16) -> usize { match kind { diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs index 8d4f99f49e..b082f67a5b 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -20,6 +20,7 @@ #![forbid(unsafe_code)] pub mod builtin; +mod builtin_v2; pub mod clut; pub mod curve; pub mod gamut; @@ -28,11 +29,15 @@ pub mod lut3d; pub mod lutfile; pub mod math; pub mod named; +mod normalize; pub mod pipeline; pub mod profile; +pub mod sony_lut; +pub mod spi1d; pub mod synth; pub mod transform; mod write; +pub mod write_v2; pub use builtin::Builtin; pub use clut::Clut; @@ -40,7 +45,9 @@ pub use curve::Curve; pub use gamut::GamutCheck; pub use gpu_matrix_shaper::GpuMatrixShaper; pub use lut3d::Lut3d; +pub use math::Mat3; pub use named::{NamedColor, NamedColors}; +pub use normalize::normalize_for_embedding; pub use profile::{ColorSpace, Pcs, Profile, ProfileClass}; pub use transform::{SampleKind, Transform, TransformOptions, black_point, cached}; pub use write::profile_id; diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index 404b5a3156..e2e0a59800 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -150,62 +150,142 @@ fn decode_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> { } } -/// Adobe / Resolve `.cube`. 1D LUTs (`LUT_1D_SIZE`) are expanded to a 33³ table. -pub fn parse_cube(text: &str) -> Result { - let mut title = String::new(); - let (mut size3, mut size1) = (0usize, 0usize); - 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('"')) +/// A bounded, three-dimensional Cube profile with RGB rows in file order. +/// Unlike [`parse_cube`], this preserves the optional title and does not resample 1D curves. +#[derive(Clone, Debug, PartialEq)] +pub struct Cube3d { + pub title: Option, + pub size: usize, + pub data: Vec<[f32; 3]>, + pub domain_min: [f32; 3], + pub domain_max: [f32; 3], +} + +/// Read the simple 3D profile dialect used by camera-profile consumers. +/// +/// `max_size` must be in 2..=256; the row budget is checked before each allocation. +/// Whole-line comments and literal titles are preserved. Unknown alphabetic directives +/// are ignored; 1D tables are refused. Finite domains are returned unchanged so the +/// consumer retains its existing policy for equal or reversed endpoints. +/// Numeric fields must consist of exactly three finite numbers (never silently skip tokens). +pub fn parse_cube_3d(text: &str, max_size: usize) -> Result { + let p = read_cube(text, Some(max_size))?; + if p.size3 == 0 { + return err("not a 3D .cube LUT (no LUT_3D_SIZE)"); + } + let expected = p.size3.checked_pow(3).ok_or_else(|| LutError("LUT size overflow".into()))?; + if p.rows.len() != expected { + return err(format!("expected {expected} entries, found {}", p.rows.len())); + } + Ok(Cube3d { title: p.title, size: p.size3, data: p.rows, domain_min: p.min, domain_max: p.max }) +} + +struct CubeRows { + title: Option, + size3: usize, + size1: usize, + min: [f32; 3], + max: [f32; 3], + rows: Vec<[f32; 3]>, +} + +fn cube_triplet(text: &str) -> Result<[f32; 3], LutError> { + let mut it = text.split_whitespace(); + let mut row = [0.0; 3]; + for value in &mut row { + *value = it.next().and_then(|s| s.parse::().ok()).filter(|v| v.is_finite()).ok_or_else(|| LutError(format!("bad line `{text}`")))?; + } + if it.next().is_some() { + return err(format!("bad line `{text}`")); + } + Ok(row) +} + +fn read_cube(text: &str, profile_max: Option) -> Result { + if profile_max.is_some_and(|n| !(2..=256).contains(&n)) { + return err("3D profile size limit must be in 2..=256"); + } + let mut p = CubeRows { title: None, size3: 0, size1: 0, min: [0.0; 3], max: [1.0; 3], rows: Vec::new() }; + let row_limit = profile_max.unwrap_or(256).checked_pow(3).ok_or_else(|| LutError("LUT size overflow".into()))?; + for raw in text.lines() { + let profile = profile_max.is_some(); + let line = if profile { raw.trim() } else { raw.split('#').next().unwrap_or("").trim() }; + // The standard dialect protects '#' inside quoted titles; profile titles are literal. + if !profile + && let Some(quoted) = + raw.trim_start().strip_prefix("TITLE").filter(|r| r.starts_with(char::is_whitespace)).and_then(|r| r.trim_start().strip_prefix('"')) { - let Some((value, _)) = quoted.split_once('"') else { return err("unterminated quoted TITLE") }; - title = value.to_string(); + let Some((title, _)) = quoted.split_once('"') else { return err("unterminated quoted TITLE") }; + p.title = Some(title.to_string()); continue; } - let line = line.split('#').next().unwrap_or("").trim(); - if line.is_empty() { + if line.is_empty() || line.starts_with('#') { continue; } - let mut it = line.split_whitespace(); - let key = it.next().unwrap_or(""); - let nums = |it: std::str::SplitWhitespace<'_>| -> Result<[f32; 3], LutError> { - let v: Vec = it.filter_map(|s| s.parse().ok()).collect(); - if v.len() == 3 { Ok([v[0], v[1], v[2]]) } else { err(format!("bad line `{line}`")) } + let (key, rest) = if profile { + ["TITLE", "LUT_3D_SIZE", "LUT_1D_SIZE", "DOMAIN_MIN", "DOMAIN_MAX"] + .into_iter() + .find_map(|key| line.strip_prefix(key).map(|rest| (key, rest.trim()))) + .unwrap_or_else(|| line.split_once(char::is_whitespace).unwrap_or((line, ""))) + } else { + line.split_once(char::is_whitespace).map_or((line, ""), |(key, rest)| (key, rest.trim())) }; match key { - "TITLE" => title = line[5..].trim().trim_matches('"').to_string(), - "LUT_3D_SIZE" => size3 = it.next().and_then(|s| s.parse().ok()).ok_or_else(|| LutError("bad LUT_3D_SIZE".into()))?, - "LUT_1D_SIZE" => size1 = it.next().and_then(|s| s.parse().ok()).ok_or_else(|| LutError("bad LUT_1D_SIZE".into()))?, - "DOMAIN_MIN" => dmin = nums(it)?, - "DOMAIN_MAX" => dmax = nums(it)?, - "LUT_3D_INPUT_RANGE" | "LUT_1D_INPUT_RANGE" => { - let v: Vec = it.filter_map(|s| s.parse().ok()).collect(); - if v.len() == 2 { - dmin = [v[0]; 3]; - dmax = [v[1]; 3]; + "TITLE" => p.title = Some(rest.trim_matches('"').to_string()), + "LUT_3D_SIZE" => { + let value = if profile { rest } else { rest.split_whitespace().next().unwrap_or("") }; + p.size3 = value.parse().map_err(|_| LutError(format!("bad LUT_3D_SIZE `{value}`")))?; + let limit = profile_max.unwrap_or(MAX_SIZE); + if !(2..=limit).contains(&p.size3) { + return err(format!("LUT_3D_SIZE {} out of range", p.size3)); } } - 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}`")))?]; - for value in it { - v.push(value.parse::().map_err(|_| LutError(format!("bad number in `{line}`")))?); + "LUT_1D_SIZE" => { + if profile { + return err("1D LUTs are not supported (only 3D .cube files)"); } - if v.len() != 3 { - return err(format!("bad data line `{line}`")); + p.size1 = rest.split_whitespace().next().and_then(|s| s.parse().ok()).ok_or_else(|| LutError("bad LUT_1D_SIZE".into()))?; + if p.size1 > row_limit { + return err("1D LUT exceeds row budget"); + } + } + "DOMAIN_MIN" => p.min = cube_triplet(rest).map_err(|_| LutError("bad DOMAIN_MIN".into()))?, + "DOMAIN_MAX" => p.max = cube_triplet(rest).map_err(|_| LutError("bad DOMAIN_MAX".into()))?, + "LUT_3D_INPUT_RANGE" | "LUT_1D_INPUT_RANGE" if !profile => { + let mut it = rest.split_whitespace(); + let min = it.next().and_then(|s| s.parse::().ok()); + let max = it.next().and_then(|s| s.parse::().ok()); + if let (Some(min), Some(max), None) = (min, max, it.next()) { + p.min = [min; 3]; + p.max = [max; 3]; + } + } + _ => { + let numeric = key.starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '+' || c == '.'); + let nonfinite = key.parse::().is_ok(); + if numeric || nonfinite || (profile && !key.starts_with(|c: char| c.is_ascii_alphabetic())) { + let row = cube_triplet(line)?; + if p.rows.len() >= row_limit { + return err("LUT exceeds row budget"); + } + // Explicit fallible growth prevents capacity growth past the configured budget. + if p.rows.len() == p.rows.capacity() { + let grow = (p.rows.capacity().max(1)).min(row_limit - p.rows.len()); + p.rows.try_reserve_exact(grow).map_err(|_| LutError("LUT allocation failed".into()))?; + } + p.rows.push(row); } - rows.extend(v); } - // Unknown keywords (e.g. Resolve's LUT_IN_VIDEO_RANGE) are ignored, as the spec allows. - _ => {} } } + Ok(p) +} + +/// Adobe / Resolve `.cube`. 1D LUTs (`LUT_1D_SIZE`) are expanded to a 33³ table. +pub fn parse_cube(text: &str) -> Result { + let p = read_cube(text, None)?; + let (title, size3, size1, dmin, dmax) = (p.title.unwrap_or_default(), p.size3, p.size1, p.min, p.max); + let rows: Vec = p.rows.into_iter().flatten().collect(); let domain_ok = (0..3).all(|k| dmin[k] < dmax[k] && dmin[k].is_finite() && dmax[k].is_finite()); if (size3 > 0 || size1 >= 2) && !domain_ok { return err(format!("DOMAIN_MIN {:?} must lie below DOMAIN_MAX {:?}", dmin, dmax)); @@ -531,12 +611,52 @@ pub fn write_cube(l: &LutFile) -> String { s.push_str(&format!("DOMAIN_MAX {} {} {}\n", l.domain_max[0], l.domain_max[1], l.domain_max[2])); } s.push_str(&format!("LUT_3D_SIZE {}\n", l.size)); - for c in l.data.as_chunks::<3>().0 { + cube_rows(s, l.data.as_chunks::<3>().0.iter().copied()) +} + +/// Writes a `.cube` file with a creator comment, section comments and an explicit input domain. +/// +/// This layout is useful for exported LUTs; [`write_cube`] keeps its compact layout for embedded +/// tables. Values retain six decimal places, and their order and quantisation belong to the +/// caller. A default domain is written as `0.0` and `1.0` for compatibility with export consumers. +pub fn write_cube_commented(l: &LutFile, creator: &str) -> String { + let mut s = format!("#Created by: {creator}\nTITLE \"{}\"\n\n#LUT size\nLUT_3D_SIZE {}\n\n#data domain\n", l.title.replace('"', "'"), l.size); + if l.domain_is_default() { + s.push_str("DOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n"); + } else { + s.push_str(&format!("DOMAIN_MIN {} {} {}\n", l.domain_min[0], l.domain_min[1], l.domain_min[2])); + s.push_str(&format!("DOMAIN_MAX {} {} {}\n", l.domain_max[0], l.domain_max[1], l.domain_max[2])); + } + s.push_str("\n#LUT data points\n"); + cube_rows(s, l.data.as_chunks::<3>().0.iter().copied()) +} + +fn cube_rows(mut s: String, rows: impl Iterator) -> String { + for c in rows { s.push_str(&format!("{:.6} {:.6} {:.6}\n", c[0], c[1], c[2])); } s } +/// Annotated identity-domain CUBE export, streamed in red-fastest order without a table copy. +/// Callers supply exactly `size³` rows for a valid size (2..=[`MAX_SIZE`]), as with [`write_cube`]. +/// Integer-depth exports clamp/round to 1/32768 steps; floating exports clamp without rounding. +pub fn write_cube_export(creator: &str, title: &str, size: usize, integer_depth: bool, rows: impl Iterator) -> String { + let s = format!( + "#Created by: {creator}\nTITLE \"{}\"\n\n#LUT size\nLUT_3D_SIZE {size}\n\n#data domain\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n\n#LUT data points\n", + title.replace('"', "'") + ); + cube_rows( + s, + rows.map(|c| { + c.map(|v| { + let v = v.clamp(0.0, 1.0); + if integer_depth { (v * 32768.0).round() / 32768.0 } else { v } + }) + }), + ) +} + fn luma(c: [f32; 3]) -> f32 { 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] } @@ -602,6 +722,30 @@ pub fn builtin(id: &str) -> Option { mod tests { use super::*; + #[test] + fn commented_cube_preserves_export_header_and_rows() { + let mut lut = super::LutFile::identity(2).unwrap(); + lut.title = "A \"look\"".into(); + let text = super::write_cube_commented(&lut, "ExampleCraft"); + assert!(text.starts_with("#Created by: ExampleCraft\nTITLE \"A 'look'\"\n\n#LUT size\nLUT_3D_SIZE 2\n\n#data domain\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n\n#LUT data points\n")); + let parsed = super::parse_cube(&text).unwrap(); + assert_eq!(parsed.data, lut.data); + assert_eq!(parsed.title, "A 'look'"); + assert_eq!(text.lines().count(), 11 + 8); + let rows = |s: &str| s.lines().filter(|line| line.starts_with(|c: char| c.is_ascii_digit())).map(str::to_owned).collect::>(); + assert_eq!(rows(&text), rows(&super::write_cube(&lut))); + } + + #[test] + fn commented_cube_keeps_nondefault_domain_and_sample_precision() { + let mut lut = super::LutFile::identity(2).unwrap(); + lut.domain_min = [0.125, 0.25, 0.375]; + lut.domain_max = [0.625, 0.75, 0.875]; + lut.data[0] = 0.833344; + let parsed = super::parse_cube(&super::write_cube_commented(&lut, "ExampleCraft")).unwrap(); + assert_eq!(parsed, lut); + } + #[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"; @@ -1299,4 +1443,75 @@ LUT_3D_SIZE 2 assert_eq!(back.domain_min, l.domain_min, "the written table must mean the same"); assert_eq!(back.domain_max, l.domain_max); } + #[test] + fn annotated_cube_export_preserves_header_and_integer_precision() { + let mut lut = LutFile::identity(2).unwrap(); + lut.title = "My \"Look\"".into(); + lut.data[..3].copy_from_slice(&[1.0 / 6.0, 5.0 / 6.0, 160.0 / 255.0]); + let output = write_cube_export("PhotoCraft", &lut.title, lut.size, true, lut.data.as_chunks::<3>().0.iter().copied()); + assert!(output.starts_with("#Created by: PhotoCraft\nTITLE \"My 'Look'\"\n\n#LUT size\nLUT_3D_SIZE 2\n\n#data domain\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n\n#LUT data points\n0.166656 0.833344 0.627441\n")); + assert_eq!(output.lines().count(), 11 + 8); + let parsed = parse_cube(&output).unwrap(); + assert_eq!(parsed.size, 2); + assert_eq!(&parsed.data[3..], &lut.data[3..]); + let float = write_cube_export("PhotoCraft", &lut.title, lut.size, false, lut.data.as_chunks::<3>().0.iter().copied()); + assert!(float.contains("0.166667 0.833333 0.627451\n")); + } + + #[test] + fn annotated_empty_title_and_float_clamping() { + let text = write_cube_export("Exporter", "", 2, false, std::iter::repeat_n([-0.5, 0.25, 1.5], 8)); + assert!(text.contains("TITLE \"\"\n")); + let back = parse_cube(&text).unwrap(); + assert_eq!(back.data, [0.0, 0.25, 1.0].repeat(8)); + } +} + +#[cfg(test)] +mod profile_cube_tests { + use super::*; + + fn cube(prefix: &str) -> String { + format!("{prefix}\nLUT_3D_SIZE 2\n{}", "0.25 0.5 0.75\n".repeat(8)) + } + + #[test] + fn profile_preserves_optional_literal_title_and_domains() { + let no_title = parse_cube_3d(&cube(""), 256).unwrap(); + assert_eq!(no_title.title, None); + let value = parse_cube_3d(&cube("TITLE \"look # literal\"\nDOMAIN_MIN 1 0 2\nDOMAIN_MAX 0 0 1"), 256).unwrap(); + assert_eq!(value.title.as_deref(), Some("look # literal")); + assert_eq!(value.domain_min, [1.0, 0.0, 2.0]); + assert_eq!(value.domain_max, [0.0, 0.0, 1.0]); + assert_eq!(value.data, vec![[0.25, 0.5, 0.75]; 8]); + assert_eq!(parse_cube_3d(&cube("TITLE \"\""), 256).unwrap().title.as_deref(), Some("")); + assert!(parse_cube(&cube("DOMAIN_MIN 1 0 2\nDOMAIN_MAX 0 0 1")).is_err()); + } + + #[test] + fn profile_limits_are_checked_without_large_allocations() { + assert!(parse_cube_3d("LUT_3D_SIZE 256", 256).unwrap_err().0.contains("16777216")); + assert!(parse_cube_3d("LUT_3D_SIZE 257", 256).unwrap_err().0.contains("out of range")); + assert!(parse_cube_3d("LUT_3D_SIZE 256", 129).unwrap_err().0.contains("out of range")); + assert!(parse_cube_3d(&cube(""), usize::MAX).is_err()); + assert!(parse_cube_3d(&cube(""), 1).is_err()); + assert!(parse_cube_3d(&format!("{}0 0 0\n", cube("")), 2).unwrap_err().0.contains("budget")); + assert!(parse_cube_3d("LUT_1D_SIZE 2\n0 0 0\n1 1 1", 256).is_err()); + } + + #[test] + fn every_numeric_token_must_be_valid_and_finite() { + for row in ["0 ignored 0 0", "0 0 0 ignored", "NaN 0 0", "inf 0 0", "0 0 -inf", "1e39 0 0", "0 0", "0 0 0 0"] { + assert!(parse_cube_3d(&format!("LUT_3D_SIZE 2\n{row}\n{}", "0 0 0\n".repeat(7)), 256).is_err(), "{row}"); + assert!(parse_cube_3d(&cube(&format!("DOMAIN_MIN {row}")), 256).is_err(), "{row}"); + } + } + + #[test] + fn standard_reader_keeps_quoted_comments_and_1d_expansion() { + assert_eq!(parse_cube(&cube("TITLE \"look # preserved\" # comment")).unwrap().title, "look # preserved"); + let value = parse_cube("LUT_1D_SIZE 2\n0 0 0\n1 1 1").unwrap(); + assert_eq!(value.size, 33); + assert!(parse_cube_3d(&cube("DOMAIN_MIN 0 0 0 # not a whole-line comment"), 256).is_err()); + } } diff --git a/crates/cms/src/math.rs b/crates/cms/src/math.rs index dbc6865555..8601266538 100644 --- a/crates/cms/src/math.rs +++ b/crates/cms/src/math.rs @@ -216,6 +216,12 @@ pub fn d50_quantized() -> [f64; 3] { [s15f16_round(D50[0]), s15f16_round(D50[1]), s15f16_round(D50[2])] } +/// Whether ICC s15Fixed16 encoding can round this value without saturation. +pub(crate) fn fits_s15f16(v: f64) -> bool { + let scaled = (v * 65536.0).round(); + scaled.is_finite() && scaled >= f64::from(i32::MIN) && scaled <= f64::from(i32::MAX) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/cms/src/normalize.rs b/crates/cms/src/normalize.rs new file mode 100644 index 0000000000..85d6907839 --- /dev/null +++ b/crates/cms/src/normalize.rs @@ -0,0 +1,142 @@ +//! Bounded encoded ICC layout normalization, originating in LightCraft. + +use std::collections::BTreeMap; + +/// Zero the creation date, align tag payloads to four bytes, preserve shared payloads, +/// update the profile length and clear its stale profile ID. No colour tags are interpreted. +/// +/// This is a layout operation, not profile validation. Malformed tables or layouts exceeding +/// 4096 tags or 64 MiB output are returned unchanged except for the creation date. The owned +/// input is reused on failure, so rejected input does not require an additional full copy. +/// Consumers needing rejection of invalid profiles must separately use `Profile::parse`. +pub fn normalize_for_embedding(mut bytes: Vec) -> Vec { + if let Some(date) = bytes.get_mut(24..36) { + date.fill(0); + } + align(&bytes).unwrap_or(bytes) +} + +const MAX_BYTES: usize = 64 * 1024 * 1024; +const MAX_TAGS: usize = 4096; + +fn be(bytes: &[u8], at: usize) -> Option { + let s = bytes.get(at..at.checked_add(4)?)?; + usize::try_from(u32::from_be_bytes([s[0], s[1], s[2], s[3]])).ok() +} + +fn align(bytes: &[u8]) -> Option> { + if bytes.len() > MAX_BYTES { + return None; + } + let count = be(bytes, 128)?; + if count > MAX_TAGS { + return None; + } + let end = 132usize.checked_add(count.checked_mul(12)?)?; + bytes.get(..end)?; + let mut placements = BTreeMap::new(); + let mut offsets = Vec::new(); + offsets.try_reserve_exact(count).ok()?; + let mut size = end; + for index in 0..count { + let entry = 132 + index * 12; + let off = be(bytes, entry + 4)?; + let len = be(bytes, entry + 8)?; + if off < end { + return None; + } + bytes.get(off..off.checked_add(len)?)?; + let new_off = if let Some(&placed) = placements.get(&(off, len)) { + placed + } else { + let aligned = size.checked_add(3)? & !3; + size = aligned.checked_add(len)?; + if size > MAX_BYTES { + return None; + } + placements.insert((off, len), aligned); + aligned + }; + offsets.push(new_off); + } + size = size.checked_add(3)? & !3; + if size > MAX_BYTES { + return None; + } + let mut out = Vec::new(); + out.try_reserve_exact(size).ok()?; + out.resize(size, 0); + out[..end].copy_from_slice(&bytes[..end]); + for ((off, len), target) in placements { + out[target..target + len].copy_from_slice(&bytes[off..off + len]); + } + for (index, off) in offsets.into_iter().enumerate() { + let field = 132 + index * 12 + 4; + out[field..field + 4].copy_from_slice(&u32::try_from(off).ok()?.to_be_bytes()); + } + out[..4].copy_from_slice(&u32::try_from(size).ok()?.to_be_bytes()); + out[84..100].fill(0); + Some(out) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#[path = "normalize_legacy_tests.rs"] +mod legacy; + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + + #[test] + fn matches_frozen_writer_and_preserves_aliases() { + for count in 0..20usize { + let end = 132 + count * 12; + let mut bytes = vec![17; end + 31]; + bytes[128..132].copy_from_slice(&(count as u32).to_be_bytes()); + for index in 0..count { + let field = 132 + index * 12 + 4; + let off = end + index % 3; + bytes[field..field + 4].copy_from_slice(&(off as u32).to_be_bytes()); + bytes[field + 4..field + 8].copy_from_slice(&7u32.to_be_bytes()); + } + let expected = legacy::align_tags(&legacy::fixed_date(bytes.clone())); + let result = normalize_for_embedding(bytes); + assert_eq!(result, expected); + assert_eq!(normalize_for_embedding(result.clone()), result); + } + } + + #[test] + fn real_profile_preserves_color_tags_and_legacy_bytes() { + let encoded = crate::Builtin::Srgb.profile().clone().with_encoded_bytes(); + let input = encoded.to_bytes().to_vec(); + let normalized = normalize_for_embedding(input.clone()); + assert_eq!(normalized, legacy::align_tags(&legacy::fixed_date(input))); + assert_eq!(&normalized[24..36], &[0; 12]); + assert_eq!(&normalized[84..100], &[0; 16]); + assert!(crate::Profile::parse(&normalized).is_ok()); + for index in 0..be(&normalized, 128).unwrap() { + assert_eq!(be(&normalized, 136 + index * 12).unwrap() % 4, 0); + } + } + + #[test] + fn hostile_tables_return_owned_input_without_expansion() { + for len in 0..132 { + let bytes = vec![1; len]; + assert_eq!(normalize_for_embedding(bytes.clone()), legacy::fixed_date(bytes)); + } + for count in [4097u32, u32::MAX] { + let mut bytes = vec![1; 144]; + bytes[128..132].copy_from_slice(&count.to_be_bytes()); + assert_eq!(normalize_for_embedding(bytes.clone()), legacy::fixed_date(bytes)); + } + let mut bytes = vec![1; 144]; + bytes[128..132].copy_from_slice(&1u32.to_be_bytes()); + bytes[136..140].copy_from_slice(&u32::MAX.to_be_bytes()); + bytes[140..144].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(normalize_for_embedding(bytes.clone()), legacy::fixed_date(bytes)); + } +} diff --git a/crates/cms/src/normalize_legacy_tests.rs b/crates/cms/src/normalize_legacy_tests.rs new file mode 100644 index 0000000000..dae5c2770b --- /dev/null +++ b/crates/cms/src/normalize_legacy_tests.rs @@ -0,0 +1,43 @@ +//! Encoded ICC normalization extracted from LightCraft. +pub(super) fn align_tags(b: &[u8]) -> Vec { + let be = |i: usize| b.get(i..i + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize); + let Some(n) = be(128) else { return b.to_vec() }; + let table_end = 132 + 12 * n; + let tags: Option> = (0..n).map(|t| Some((be(132 + 12 * t + 4)?, be(132 + 12 * t + 8)?))).collect(); + let Some(tags) = tags.filter(|t| table_end <= b.len() && t.iter().all(|&(o, l)| o >= table_end && o + l <= b.len())) else { + return b.to_vec(); + }; + let mut out = b[..table_end].to_vec(); + let mut placed: Vec<((usize, usize), usize)> = Vec::new(); + for (t, &(off, len)) in tags.iter().enumerate() { + let new_off = match placed.iter().find(|(k, _)| *k == (off, len)) { + // tags sharing data keep sharing it + Some(&(_, o)) => o, + None => { + while !out.len().is_multiple_of(4) { + out.push(0); + } + let o = out.len(); + out.extend_from_slice(&b[off..off + len]); + placed.push(((off, len), o)); + o + } + }; + out[132 + 12 * t + 4..132 + 12 * t + 8].copy_from_slice(&(new_off as u32).to_be_bytes()); + } + while !out.len().is_multiple_of(4) { + out.push(0); + } + let size = out.len() as u32; + out[0..4].copy_from_slice(&size.to_be_bytes()); + // the profile ID (MD5) would no longer match: clear it (= "not computed") + out[84..100].fill(0); + out +} + +pub(super) fn fixed_date(mut b: Vec) -> Vec { + if let Some(date) = b.get_mut(24..36) { + date.fill(0); + } + b +} diff --git a/crates/cms/src/profile.rs b/crates/cms/src/profile.rs index 6bd83a7445..86624c1c9c 100644 --- a/crates/cms/src/profile.rs +++ b/crates/cms/src/profile.rs @@ -182,6 +182,128 @@ pub struct Profile { } impl Profile { + /// Builds a matrix/TRC display profile from an already PCS D50-adapted colorant matrix, + /// a white point, and per-channel tone reproduction curves. + /// + /// # Matrix Coordinate Space + /// In accordance with ICC.1:2010 §9.2.35–37, the colorant matrix tags (`rXYZ`, `gXYZ`, `bXYZ`) + /// stored in an ICC profile must be chromatically adapted to the D50 Profile Connection Space (PCS). + /// `pcs_matrix` must therefore be expressed relative to D50 (e.g. as read directly from ICC profile tags). + /// + /// If `white` is not D50, the profile's `chad` tag is populated with the Bradford chromatic adaptation + /// matrix mapping `white` to D50. + pub fn matrix_shaper(white: [f64; 3], pcs_matrix: Mat3, trc: [Curve; 3]) -> Result { + for curve in &trc { + curve.validate_icc()?; + } + if !white.iter().all(|&c| math::fits_s15f16(c) && math::s15f16_round(c) > 0.0) { + return Err(CmsError::InvalidArgument("white point must remain positive and representable in ICC fixed point".into())); + } + if !pcs_matrix.iter().flatten().all(|&v| v.is_finite()) { + return Err(CmsError::InvalidArgument("matrix elements must be finite".into())); + } + if math::invert(&pcs_matrix).is_none() { + return Err(CmsError::InvalidArgument("colorant matrix must be invertible".into())); + } + + let d50 = math::d50_quantized(); + let is_d50 = (white[0] - math::D50[0]).abs() < 1e-4 && (white[1] - math::D50[1]).abs() < 1e-4 && (white[2] - math::D50[2]).abs() < 1e-4; + + let chad = if is_d50 { None } else { Some(math::bradford(white, math::D50)) }; + + // Quantize and normalize to ensure (1, 1, 1) maps exactly to PCS D50 + let mut q = pcs_matrix.map(|row| row.map(math::s15f16_round)); + for (i, row) in q.iter_mut().enumerate() { + let err = d50[i] - row.iter().sum::(); + let k = (0..3).max_by(|a, b| row[*a].abs().total_cmp(&row[*b].abs())).unwrap_or(0); + row[k] = math::s15f16_round(row[k] + err); + } + if !q.iter().flatten().all(|&v| math::fits_s15f16(v)) || math::invert(&q).is_none() { + return Err(CmsError::InvalidArgument("colorant matrix is singular or unrepresentable after quantization/normalization".into())); + } + let chad_quantized = chad.map(|a| a.map(|row| row.map(math::s15f16_round))); + // Positive finite XYZ inputs can still overflow Bradford cone ratios or quantization. + // Refuse invalid stored adaptation rather than serializing nonfinite coefficients. + if chad_quantized.as_ref().is_some_and(|a| !a.iter().flatten().all(|&v| math::fits_s15f16(v)) || math::invert(a).is_none()) { + return Err(CmsError::InvalidArgument("chromatic adaptation must remain representable and invertible after quantization".into())); + } + + Ok(Profile { + version: (4, 0x30), + class: ProfileClass::Display, + color_space: ColorSpace::Rgb, + pcs: Pcs::Xyz, + rendering_intent: Intent::RelativeColorimetric, + description: "Parametric Matrix/TRC".into(), + copyright: "".into(), + white_point: if is_d50 { d50 } else { white }, + black_point: None, + chad: chad_quantized, + matrix: Some(q), + trc: Some(trc), + gray_trc: None, + a2b: [None, None, None], + b2a: [None, None, None], + bytes: None, + hash: Default::default(), + }) + } + + /// Builds a matrix/TRC display profile from unadapted source primaries relative to `white`. + /// + /// The unadapted `source_matrix` (whose columns sum to `white`) is chromatically adapted to PCS D50 + /// using the Bradford transform before storage in the profile's matrix tags. + pub fn from_source_matrix(white: [f64; 3], source_matrix: Mat3, trc: [Curve; 3]) -> Result { + if !white.iter().all(|&c| math::fits_s15f16(c) && math::s15f16_round(c) > 0.0) { + return Err(CmsError::InvalidArgument("white point must remain positive and representable in ICC fixed point".into())); + } + if !source_matrix.iter().flatten().all(|&v| v.is_finite()) { + return Err(CmsError::InvalidArgument("matrix elements must be finite".into())); + } + if math::invert(&source_matrix).is_none() { + return Err(CmsError::InvalidArgument("colorant matrix must be invertible".into())); + } + + let is_d50 = (white[0] - math::D50[0]).abs() < 1e-4 && (white[1] - math::D50[1]).abs() < 1e-4 && (white[2] - math::D50[2]).abs() < 1e-4; + let pcs_matrix = if is_d50 { + source_matrix + } else { + let adapt = math::bradford(white, math::D50); + math::mul(&adapt, &source_matrix) + }; + + Self::matrix_shaper(white, pcs_matrix, trc) + } + + /// Builds a monochrome profile from a white point and tone reproduction curve. + pub fn gray(white: [f64; 3], trc: Curve) -> Result { + trc.validate_icc()?; + if !white.iter().all(|&c| math::fits_s15f16(c) && math::s15f16_round(c) > 0.0) { + return Err(CmsError::InvalidArgument("white point must remain positive and representable in ICC fixed point".into())); + } + let is_d50 = (white[0] - math::D50[0]).abs() < 1e-4 && (white[1] - math::D50[1]).abs() < 1e-4 && (white[2] - math::D50[2]).abs() < 1e-4; + + Ok(Profile { + version: (4, 0x30), + class: ProfileClass::Display, + color_space: ColorSpace::Gray, + pcs: Pcs::Xyz, + rendering_intent: Intent::RelativeColorimetric, + description: "Parametric Gray".into(), + copyright: "".into(), + white_point: if is_d50 { math::d50_quantized() } else { white }, + black_point: None, + chad: None, + matrix: None, + trc: None, + gray_trc: Some(trc), + a2b: [None, None, None], + b2a: [None, None, None], + bytes: None, + hash: Default::default(), + }) + } + /// Parses ICC profile bytes. pub fn parse(bytes: &[u8]) -> Result { CURVE_SAMPLES_LEFT.with(|left| left.set(MAX_CURVE_SAMPLES)); diff --git a/crates/cms/src/sony_lut.rs b/crates/cms/src/sony_lut.rs new file mode 100644 index 0000000000..cc3f8fb00f --- /dev/null +++ b/crates/cms/src/sony_lut.rs @@ -0,0 +1,82 @@ +//! Sony Imageworks SPI3D and SPIMTX text readers, extracted from EffectCraft. +//! +//! These preserve the source reader's format tolerance. SPI3D sample values are not +//! clamped or sanitized; rendering policy belongs to the caller. Duplicate coordinates +//! retain their last value, and the total row count must match the lattice volume. + +/// Maximum lattice side accepted by the source reader. +pub const MAX_SIDE: usize = 129; + +/// Row-major homogeneous transform with a separate normalized code-value offset. +#[derive(Clone, Debug, PartialEq)] +pub struct Matrix { + pub matrix: [f64; 16], + pub offset: [f64; 4], +} + +/// A cubic RGB table, red coordinate varying fastest. +#[derive(Clone, Debug, PartialEq)] +pub struct Lattice { + pub size: usize, + pub values: Vec<[f32; 3]>, +} + +/// Read exactly twelve finite SPIMTX numbers, dividing the offset column by 65535. +/// Parsing uses a fixed array, not storage proportional to an oversized input. +pub fn parse_spimtx(text: &str) -> Option { + let mut words = text.split_whitespace(); + let mut v = [0.0f64; 12]; + for value in &mut v { + *value = words.next()?.parse().ok()?; + if !value.is_finite() { + return None; + } + } + if words.next().is_some() { + return None; + } + let mut matrix = [0.0; 16]; + let mut offset = [0.0; 4]; + for (r, row) in v.as_chunks::<4>().0.iter().enumerate() { + matrix[r * 4..r * 4 + 3].copy_from_slice(&row[..3]); + offset[r] = row[3] / 65535.0; + } + matrix[15] = 1.0; + Some(Matrix { matrix, offset }) +} + +/// Read a SPI3D table with a bounded 2..=129 cubic lattice and exactly six fields per row. +/// A `SPILUT` prefix is accepted and the second header line is ignored, as in EffectCraft. +pub fn parse_spi3d(text: &str) -> Option { + let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty()); + if !lines.next()?.starts_with("SPILUT") { + return None; + } + lines.next()?; + let mut sizes = lines.next()?.split_whitespace(); + let n: usize = sizes.next()?.parse().ok()?; + let g: usize = sizes.next()?.parse().ok()?; + let b: usize = sizes.next()?.parse().ok()?; + if sizes.next().is_some() || g != n || b != n || !(2..=MAX_SIDE).contains(&n) { + return None; + } + let count = n * n * n; + let mut values = vec![[0.0f32; 3]; count]; + let mut seen = 0usize; + for line in lines { + if seen == count { + return None; + } + let mut fields = line.split_whitespace(); + let r: usize = fields.next()?.parse().ok()?; + let g: usize = fields.next()?.parse().ok()?; + let b: usize = fields.next()?.parse().ok()?; + let color = [fields.next()?.parse().ok()?, fields.next()?.parse().ok()?, fields.next()?.parse().ok()?]; + if fields.next().is_some() || r >= n || g >= n || b >= n { + return None; + } + *values.get_mut(r + g * n + b * n * n)? = color; + seen += 1; + } + (seen == count).then_some(Lattice { size: n, values }) +} diff --git a/crates/cms/src/spi1d.rs b/crates/cms/src/spi1d.rs new file mode 100644 index 0000000000..ea77bdc88d --- /dev/null +++ b/crates/cms/src/spi1d.rs @@ -0,0 +1,59 @@ +//! Sony Imageworks SPI1D tables, preserving EffectCraft's permissive header syntax. +//! +//! Unknown header lines and trailing text after the closing brace are ignored. Table +//! samples are not clamped or sanitized: callers own their numerical rendering policy. +//! The declared length is validated before storing samples; surplus samples are refused. + +/// Largest accepted table (the existing EffectCraft interpolation limit). +pub const MAX_ENTRIES: usize = 1 << 24; + +/// A one-dimensional RGB lookup table and its common input domain. +#[derive(Clone, Debug, PartialEq)] +pub struct Table { + pub values: Vec<[f32; 3]>, + pub domain: [f32; 2], +} + +/// Parse a SPI1D table with one or three components, expanding monochrome samples to RGB. +/// No allocation is based only on the claimed length. At most `MAX_ENTRIES` RGB entries +/// are retained. Missing final braces remain accepted, as in the source reader. +pub fn parse(text: &str) -> Option { + let (mut from, mut len, mut comps) = ([0.0f32, 1.0], 0usize, 1usize); + let mut values = Vec::new(); + let mut body = false; + let mut sample = [0.0; 3]; + let mut channel = 0; + for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) { + if body { + if line.starts_with('}') { + break; + } + for t in line.split_whitespace() { + if values.len() == len { + return None; + } + sample[channel] = t.parse().ok()?; + channel += 1; + if channel == comps { + values.push(if comps == 1 { [sample[0]; 3] } else { sample }); + channel = 0; + } + } + continue; + } + let mut t = line.split_whitespace(); + match t.next()? { + "{" => { + if !(2..=MAX_ENTRIES).contains(&len) || !matches!(comps, 1 | 3) || from[1] <= from[0] || from.iter().any(|v| !v.is_finite()) { + return None; + } + body = true; + } + "From" => from = [t.next()?.parse().ok()?, t.next()?.parse().ok()?], + "Length" => len = t.next()?.parse().ok()?, + "Components" => comps = t.next()?.parse().ok()?, + _ => {} + } + } + (body && values.len() == len && channel == 0).then_some(Table { values, domain: from }) +} diff --git a/crates/cms/src/write_v2.rs b/crates/cms/src/write_v2.rs new file mode 100644 index 0000000000..63933c8011 --- /dev/null +++ b/crates/cms/src/write_v2.rs @@ -0,0 +1,195 @@ +//! Bounded ICC v2.1 matrix/TRC display-profile writer, extracted from TextureCraft. +//! Colour-space selection and transfer-curve sampling remain caller policy. + +const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249]; + +/// One common red/green/blue transfer curve. +#[derive(Clone, Copy)] +pub enum ToneCurve<'a> { + /// ICC gamma 1.0 (`curv` with one u8Fixed8 entry). + Linear, + /// Already quantized samples, inclusive endpoints, between 2 and 4096 entries. + Samples(&'a [u16]), +} + +/// Parameters for an ICC v2.1 RGB display profile. +pub struct MatrixProfile<'a> { + /// RGB-to-XYZ matrix already adapted to PCS D50, in row-major order. + pub matrix: [[f64; 3]; 3], + /// Common RGB transfer curve; its storage is shared by all three tags. + pub curve: ToneCurve<'a>, + /// ASCII description, at most 1024 bytes with no embedded NUL. + pub description: &'a str, + /// ASCII copyright text, at most 1024 bytes with no embedded NUL. + pub copyright: &'a str, + /// Raw ICC date fields: year, month, day, hour, minute, second. + pub date: [u16; 6], +} + +fn s15f16(v: f64) -> [u8; 4] { + ((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes() +} + +fn xyz_tag(v: [f64; 3]) -> Vec { + let mut b = b"XYZ \0\0\0\0".to_vec(); + for c in v { + b.extend_from_slice(&s15f16(c)); + } + b +} + +fn text_tag(text: &str) -> Vec { + let mut b = b"text\0\0\0\0".to_vec(); + b.extend_from_slice(text.as_bytes()); + b.push(0); + b +} + +/// `textDescriptionType` with the ASCII description only. +fn desc_tag(text: &str) -> Vec { + let mut b = b"desc\0\0\0\0".to_vec(); + b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes()); + b.extend_from_slice(text.as_bytes()); + b.push(0); + // No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler. + b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); + b +} + +fn curve_tag(curve: ToneCurve<'_>) -> Vec { + let mut b = b"curv\0\0\0\0".to_vec(); + match curve { + ToneCurve::Linear => { + b.extend_from_slice(&1u32.to_be_bytes()); + b.extend_from_slice(&0x0100u16.to_be_bytes()); + } + ToneCurve::Samples(samples) => { + b.extend_from_slice(&(samples.len() as u32).to_be_bytes()); + for sample in samples { + b.extend_from_slice(&sample.to_be_bytes()); + } + } + } + b +} + +/// Write a deterministic ICC v2.1 RGB display profile with one shared RGB TRC. +/// +/// Returns `None` for nonfinite matrix values, descriptions longer than 1024 ASCII +/// bytes or containing NUL, or sampled curves outside 2..=4096 entries. These caps +/// bound every allocation independently of caller input. Matrix values outside the +/// signed 15.16 range saturate, matching the legacy exporter. The caller owns colour +/// adaptation, transfer sampling, names and timestamp policy. +pub fn matrix_profile(params: &MatrixProfile<'_>) -> Option> { + let valid_text = |s: &str| s.len() <= 1024 && s.is_ascii() && !s.contains('\0'); + if !valid_text(params.description) + || !valid_text(params.copyright) + || !params.matrix.iter().flatten().all(|v| v.is_finite()) + || matches!(params.curve, ToneCurve::Samples(s) if !(2..=4096).contains(&s.len())) + { + return None; + } + let m = params.matrix; + let column = |c: usize| [m[0][c], m[1][c], m[2][c]]; + let curve = curve_tag(params.curve); + // The green and blue curves are the red one's entry. + let tags: [(&[u8; 4], Vec); 9] = [ + (b"desc", desc_tag(params.description)), + (b"cprt", text_tag(params.copyright)), + (b"wtpt", xyz_tag(D50_XYZ)), + (b"rXYZ", xyz_tag(column(0))), + (b"gXYZ", xyz_tag(column(1))), + (b"bXYZ", xyz_tag(column(2))), + (b"rTRC", curve.clone()), + (b"gTRC", curve.clone()), + (b"bTRC", curve), + ]; + // Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes. + let table_end = 128 + 4 + 12 * tags.len(); + let mut offsets = Vec::new(); + let mut data: Vec = Vec::new(); + for (i, (_, bytes)) in tags.iter().enumerate() { + let shared = i >= 7; + let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() }; + offsets.push(at); + if !shared { + data.extend_from_slice(bytes); + while !data.len().is_multiple_of(4) { + data.push(0); + } + } + } + let total = table_end + data.len(); + let mut out = vec![0u8; 128]; + out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes()); + out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0 + out.get_mut(12..16)?.copy_from_slice(b"mntr"); + out.get_mut(16..20)?.copy_from_slice(b"RGB "); + out.get_mut(20..24)?.copy_from_slice(b"XYZ "); + // Serialize caller-supplied ICC date fields; no calendar arithmetic. + for (i, value) in params.date.iter().enumerate() { + out.get_mut(24 + i * 2..26 + i * 2)?.copy_from_slice(&value.to_be_bytes()); + } + out.get_mut(36..40)?.copy_from_slice(b"acsp"); + for (k, v) in D50_XYZ.iter().enumerate() { + out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v)); + } + out.extend_from_slice(&(tags.len() as u32).to_be_bytes()); + for ((sig, bytes), at) in tags.iter().zip(&offsets) { + out.extend_from_slice(*sig); + out.extend_from_slice(&(*at as u32).to_be_bytes()); + out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); + } + out.extend_from_slice(&data); + Some(out) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + fn params() -> MatrixProfile<'static> { + MatrixProfile { + matrix: [[0.4361, 0.3851, 0.1431], [0.2225, 0.7169, 0.0606], [0.0139, 0.0971, 0.7141]], + curve: ToneCurve::Linear, + description: "v2", + copyright: "free", + date: [2026, 1, 1, 0, 0, 0], + } + } + + #[test] + fn valid_profile_parses_and_aliases_curves() { + for curve in [ToneCurve::Linear, ToneCurve::Samples(&[0, 32768, 65535])] { + let bytes = matrix_profile(&MatrixProfile { curve, ..params() }).unwrap(); + let p = crate::Profile::parse(&bytes).unwrap(); + assert_eq!(p.version, (2, 0x10)); + assert_eq!(p.description, "v2"); + assert_eq!(&bytes[24..28], &[7, 234, 0, 1]); + assert_eq!(&bytes[208..216], &bytes[220..228]); + assert_eq!(&bytes[208..216], &bytes[232..240]); + assert_eq!(bytes, matrix_profile(&MatrixProfile { curve, ..params() }).unwrap()); + } + } + + #[test] + fn bounded_inputs_reject_before_serializing() { + let long = "x".repeat(1025); + for description in [long.as_str(), "bad\0name", "non-ascii é"] { + assert!(matrix_profile(&MatrixProfile { description, ..params() }).is_none()); + } + for samples in [&[][..], &[0][..], &vec![0; 4097][..]] { + assert!(matrix_profile(&MatrixProfile { curve: ToneCurve::Samples(samples), ..params() }).is_none()); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut p = params(); + p.matrix[0][0] = value; + assert!(matrix_profile(&p).is_none()); + } + let samples = vec![0; 4096]; + let name = "x".repeat(1024); + let bytes = matrix_profile(&MatrixProfile { description: &name, copyright: &name, curve: ToneCurve::Samples(&samples), ..params() }).unwrap(); + assert!(bytes.len() < 12 * 1024); + } +} diff --git a/crates/cms/tests/constructors.rs b/crates/cms/tests/constructors.rs new file mode 100644 index 0000000000..aabb313ab1 --- /dev/null +++ b/crates/cms/tests/constructors.rs @@ -0,0 +1,183 @@ +use craft_cms::{Builtin, Curve, Intent, Mat3, Profile, Transform}; + +#[test] +fn test_curve_constructors() { + // Gamma + let g22 = Curve::gamma(2.2).expect("valid gamma"); + assert_eq!(g22, Curve::Gamma(2.2)); + + let g10 = Curve::gamma(1.0).expect("gamma 1.0 is identity"); + assert_eq!(g10, Curve::Identity); + + let g_near = Curve::gamma(1.0 + 1e-7).expect("near-identity gamma normalized"); + assert_eq!(g_near, Curve::Identity); + + assert!(Curve::gamma(0.0).is_err()); + assert!(Curve::gamma(-2.2).is_err()); + assert!(Curve::gamma(f64::NAN).is_err()); + assert!(Curve::gamma(f64::INFINITY).is_err()); + + // Parametric + let p0 = Curve::parametric(0, [2.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).expect("valid parametric type 0"); + assert_eq!(p0, Curve::Parametric { kind: 0, p: [2.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }); + + assert!(Curve::parametric(5, [0.0; 7]).is_err()); + assert!(Curve::parametric(0, [f64::NAN, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).is_err()); + + // Sampled table + let table = Curve::from_table(vec![0.0, 0.5, 1.0]).expect("valid sampled table"); + assert_eq!(table, Curve::Table(vec![0.0, 0.5, 1.0])); + + assert!(Curve::from_table(vec![0.5]).is_err()); + assert!(Curve::from_table(vec![0.0, f32::NAN]).is_err()); + assert!(Curve::from_table(vec![0.0, -0.1, 1.0]).is_err()); + assert!(Curve::from_table(vec![0.0, 2.0]).is_err()); + assert!(Curve::from_table(vec![0.0, 1.0001]).is_err()); +} + +#[test] +fn test_profile_constructors() { + let srgb = Builtin::Srgb.profile(); + let white_d65 = [0.95047, 1.0, 1.08883]; + + // 1. Matrix shaper with already PCS D50-adapted matrix (e.g. read from ICC tags) + let pcs_d50_matrix: Mat3 = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; + let trc = [craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc()]; + let custom_from_pcs = Profile::matrix_shaper(white_d65, pcs_d50_matrix, trc.clone()).expect("matrix shaper from PCS D50"); + assert_eq!(custom_from_pcs.color_space, craft_cms::ColorSpace::Rgb); + assert!(custom_from_pcs.same_colors(srgb), "custom profile from PCS D50 matrix should match reference sRGB"); + + // 2. Matrix shaper from unadapted D65 source primaries (undergoes single Bradford adaptation) + let source_d65_matrix: Mat3 = [[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]]; + let custom_from_source = Profile::from_source_matrix(white_d65, source_d65_matrix, trc).expect("matrix shaper from source"); + assert!(custom_from_source.same_colors(srgb), "custom profile adapted from source primaries should match reference sRGB"); + + // Evaluate transform + let xform = Transform::new(&custom_from_pcs, srgb, Intent::RelativeColorimetric, true).expect("transform from custom RGB to sRGB"); + let mut out = [0.0f32; 3]; + xform.eval(&[0.5, 0.5, 0.5], &mut out).expect("eval"); + assert!((out[0] - 0.5).abs() < 1e-2); + assert!((out[1] - 0.5).abs() < 1e-2); + assert!((out[2] - 0.5).abs() < 1e-2); + + // Invalid matrix shaper inputs + assert!(Profile::matrix_shaper([0.0, 1.0, 1.0], pcs_d50_matrix, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); + assert!(Profile::matrix_shaper([f64::NAN, 1.0, 1.0], pcs_d50_matrix, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); + let singular: Mat3 = [[0.0; 3]; 3]; + assert!(Profile::matrix_shaper(white_d65, singular, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); + + // Near-degenerate matrix that is invertible before quantization but becomes singular after + let d50 = [0.9642, 1.0, 0.8249]; + let near_degenerate: Mat3 = [[d50[0] - 0.000001, 0.000001, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, d50[2]]]; + assert!(Profile::matrix_shaper(d50, near_degenerate, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); + + // Gray profile + let gray = Profile::gray(white_d65, Curve::gamma(2.2).expect("curve")).expect("gray profile"); + assert_eq!(gray.color_space, craft_cms::ColorSpace::Gray); + + let gray_to_srgb = Transform::new(&gray, srgb, Intent::RelativeColorimetric, true).expect("transform from gray to sRGB"); + let mut srgb_out = [0.0f32; 3]; + gray_to_srgb.eval(&[0.5], &mut srgb_out).expect("eval"); + assert!((srgb_out[0] - srgb_out[1]).abs() < 1e-3); + assert!((srgb_out[1] - srgb_out[2]).abs() < 1e-3); +} + +#[test] +fn test_matrix_constructors_against_independent_moxcms_oracle() { + use moxcms::{ColorProfile, Layout, TransformOptions as MoxOpts}; + + let srgb = Builtin::Srgb.profile(); + let white_d65 = [0.95047, 1.0, 1.08883]; + + // 1. PCS D50-adapted matrix profile + let pcs_d50_matrix: Mat3 = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; + let trc = [craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc()]; + let custom_from_pcs = Profile::matrix_shaper(white_d65, pcs_d50_matrix, trc.clone()).expect("matrix shaper from PCS D50"); + + // 2. Unadapted source matrix profile + let source_d65_matrix: Mat3 = [[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]]; + let custom_from_source = Profile::from_source_matrix(white_d65, source_d65_matrix, trc).expect("matrix shaper from source"); + + // Convert both to standard ICC bytes and parse with independent oracle moxcms + let mox_from_pcs = ColorProfile::new_from_slice(&custom_from_pcs.to_bytes()).expect("moxcms parse custom PCS profile"); + let mox_from_source = ColorProfile::new_from_slice(&custom_from_source.to_bytes()).expect("moxcms parse custom source profile"); + let mox_dst_srgb = ColorProfile::new_from_slice(&srgb.to_bytes()).expect("moxcms parse builtin sRGB"); + + let test_pixels: Vec = (0..512u32).flat_map(|i| [(i * 17 % 256) as u8, (i * 53 % 256) as u8, (i * 97 % 256) as u8]).collect(); + + // Verify 1: moxcms transforming custom_from_pcs -> builtin sRGB produces identity (diff <= 1) + let mox_xform_pcs = mox_from_pcs.create_transform_8bit(Layout::Rgb, &mox_dst_srgb, Layout::Rgb, MoxOpts::default()).unwrap(); + let mut mox_out_pcs = vec![0u8; test_pixels.len()]; + mox_xform_pcs.transform(&test_pixels, &mut mox_out_pcs).unwrap(); + let max_diff_pcs = test_pixels.iter().zip(&mox_out_pcs).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap(); + assert!(max_diff_pcs <= 1, "moxcms PCS-adapted profile -> sRGB max diff was {max_diff_pcs}"); + + // Verify 2: moxcms transforming custom_from_source -> builtin sRGB produces identity (diff <= 1) + let mox_xform_src = mox_from_source.create_transform_8bit(Layout::Rgb, &mox_dst_srgb, Layout::Rgb, MoxOpts::default()).unwrap(); + let mut mox_out_src = vec![0u8; test_pixels.len()]; + mox_xform_src.transform(&test_pixels, &mut mox_out_src).unwrap(); + let max_diff_src = test_pixels.iter().zip(&mox_out_src).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap(); + assert!(max_diff_src <= 1, "moxcms source-adapted profile -> sRGB max diff was {max_diff_src}"); + + // Verify 3: craft_cms and moxcms agree when converting from custom_from_source to DisplayP3 + let p3 = Builtin::DisplayP3.profile(); + let mox_dst_p3 = ColorProfile::new_from_slice(&p3.to_bytes()).expect("moxcms parse Display P3"); + let mox_xform_p3 = mox_from_source.create_transform_8bit(Layout::Rgb, &mox_dst_p3, Layout::Rgb, MoxOpts::default()).unwrap(); + let mut mox_p3_out = vec![0u8; test_pixels.len()]; + mox_xform_p3.transform(&test_pixels, &mut mox_p3_out).unwrap(); + + let ours_xform_p3 = Transform::new(&custom_from_source, p3, Intent::RelativeColorimetric, false).unwrap(); + let mut ours_p3_out = vec![0u8; test_pixels.len()]; + ours_xform_p3.convert_u8(&test_pixels, 3, &mut ours_p3_out, 3, false).unwrap(); + + let max_p3_diff = ours_p3_out.iter().zip(&mox_p3_out).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap(); + assert!(max_p3_diff <= 1, "craft_cms vs moxcms custom source profile -> P3 max diff was {max_p3_diff}"); +} + +#[test] +fn constructor_never_returns_a_nonfinite_adaptation() { + let matrix = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; + for white in [[f64::MAX; 3], [f64::MIN_POSITIVE; 3], [1.0, 1.0, (0.8951 + 0.2664) / 0.1614]] { + if let Ok(profile) = Profile::matrix_shaper(white, matrix, [Curve::Identity, Curve::Identity, Curve::Identity]) { + assert!(profile.chad.unwrap().iter().flatten().all(|v| v.is_finite()), "nonfinite adaptation for {white:?}"); + } + } +} + +#[test] +fn constructors_reject_values_that_saturate_icc_fixed_point() { + assert!(Profile::gray([f64::MAX; 3], Curve::Identity).is_err()); + assert!(Profile::gray([f64::MIN_POSITIVE; 3], Curve::Identity).is_err()); + assert!(Curve::gamma(32768.0).is_err()); + assert!(Curve::gamma(f64::MIN_POSITIVE).is_err()); + assert!(Curve::parametric(0, [32768.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).is_err()); + let matrix = [[40000.0, -39999.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + assert!(Profile::matrix_shaper([0.9642, 1.0, 0.8249], matrix, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); +} + +#[test] +fn profile_constructors_validate_direct_curve_variants() { + let white = [0.9642, 1.0, 0.8249]; + let matrix = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; + for curve in [ + Curve::Gamma(f64::NAN), + Curve::Gamma(32768.0), + Curve::Parametric { kind: 5, p: [0.0; 7] }, + Curve::Table(vec![0.0, f32::NAN]), + Curve::Table(vec![]), + ] { + assert!(Profile::gray(white, curve.clone()).is_err()); + assert!(Profile::matrix_shaper(white, matrix, [curve.clone(), Curve::Identity, Curve::Identity]).is_err()); + assert!(Profile::from_source_matrix(white, matrix, [Curve::Identity, Curve::Identity, curve]).is_err()); + } +} + +#[test] +fn icc_fixed_point_boundaries_remain_accepted() { + let max = f64::from(i32::MAX) / 65536.0; + let min = f64::from(i32::MIN) / 65536.0; + assert!(Curve::gamma(max).is_ok()); + assert!(Curve::gamma(1.0 / 65536.0).is_ok()); + assert!(Curve::parametric(4, [1.0, 1.0, min, max, 0.0, 0.0, 0.0]).is_ok()); + assert!(Profile::gray([max; 3], Curve::Identity).is_ok()); +} diff --git a/crates/cms/tests/sony_lut.rs b/crates/cms/tests/sony_lut.rs new file mode 100644 index 0000000000..065792a270 --- /dev/null +++ b/crates/cms/tests/sony_lut.rs @@ -0,0 +1,46 @@ +use craft_cms::sony_lut::{MAX_SIDE, parse_spi3d, parse_spimtx}; + +#[test] +fn spimtx_is_finite_exact_and_scales_offsets() { + let m = parse_spimtx("2 0 0 6553.5\n0 3 0 -65535\n0 0 4 0").unwrap(); + assert_eq!(m.matrix, [2.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + assert_eq!(m.offset, [0.1, -1.0, 0.0, 0.0]); + for bad in ["", "1 0 0 0", "NaN 0 0 0 0 1 0 0 0 0 1 0", "inf 0 0 0 0 1 0 0 0 0 1 0", "1 0 0 0 0 1 0 0 0 0 1 0 9"] { + assert!(parse_spimtx(bad).is_none()); + } +} + +fn table() -> String { + let mut text = String::from("SPILUT 1.0\n3 3\n2 2 2\n"); + // Reverse row order to prove coordinates, rather than row order, determine storage. + for i in (0..8).rev() { + let (r, g, b) = (i & 1, (i >> 1) & 1, i >> 2); + text.push_str(&format!("{r} {g} {b} {r} {g} {b}\n")); + } + text +} + +#[test] +fn spi3d_red_fast_coordinates_and_limits() { + let text = table(); + let lut = parse_spi3d(&text).unwrap(); + assert_eq!(lut.size, 2); + for (i, row) in lut.values.iter().enumerate() { + assert_eq!(*row, [(i & 1) as f32, ((i >> 1) & 1) as f32, (i >> 2) as f32]); + } + assert!(parse_spi3d(&format!("{text}0 0 0 0 0 0\n")).is_none()); + assert!(parse_spi3d("SPILUT 1.0\n3 3\n2 2 2\n0 0 0 0 0 0\n").is_none()); + assert!(parse_spi3d(&format!("SPILUT 1.0\n3 3\n{0} {0} {0}\n", MAX_SIDE + 1)).is_none()); + assert!(parse_spi3d(&text.replace("2 2 2", "2 2 3")).is_none()); + assert!(parse_spi3d(&text.replace("0 0 0 0 0 0", "2 0 0 0 0 0")).is_none()); + assert!(parse_spi3d(&text.replace("0 0 0 0 0 0", "0 0 0 0 0 0 extra")).is_none()); +} + +#[test] +fn inherited_tolerance_is_explicit() { + let text = "SPILUT alternative\nignored\n2 2 2\n".to_owned() + &"0 0 0 -1 2 NaN\n".repeat(8); + let lut = parse_spi3d(&text).unwrap(); + assert_eq!(&lut.values[0][..2], &[-1.0, 2.0]); + assert!(lut.values[0][2].is_nan()); + assert_eq!(lut.values[1], [0.0; 3]); +} diff --git a/crates/cms/tests/spi1d.rs b/crates/cms/tests/spi1d.rs new file mode 100644 index 0000000000..f4e27d0518 --- /dev/null +++ b/crates/cms/tests/spi1d.rs @@ -0,0 +1,32 @@ +use craft_cms::spi1d::{MAX_ENTRIES, Table, parse}; + +#[test] +fn monochrome_and_three_component_samples_preserve_domain() { + assert_eq!( + parse("Version 1\nFrom -1 2\nLength 2\nComponents 1\n{\n-2\n3\n}"), + Some(Table { values: vec![[-2.0; 3], [3.0; 3]], domain: [-1.0, 2.0] }) + ); + assert_eq!( + parse("Length 2\nComponents 3\n{\n0 1\n2 3 4 5\n}"), + Some(Table { values: vec![[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]], domain: [0.0, 1.0] }) + ); +} + +#[test] +fn legacy_header_and_eof_tolerance_is_preserved() { + let table = parse("Ignored arbitrary header\nLength 2 extra\n{\n0 1"); + assert!(table.is_some()); + assert_eq!(table, parse("Length 2\n{\n0 1\n} ignored\ninvalid trailing text")); + assert!(parse("Length 2\n{\nNaN inf\n}").is_some(), "sample sanitization belongs to the caller"); +} + +#[test] +fn invalid_headers_partial_and_surplus_tables_are_refused() { + for header in ["Length 1", "Length 2\nComponents 2", "Length 2\nFrom 2 1", "Length 2\nFrom NaN 1"] { + assert!(parse(&format!("{header}\n{{\n0 1\n}}")).is_none()); + } + assert!(parse(&format!("Length {}\n{{\n0 1", MAX_ENTRIES + 1)).is_none()); + assert!(parse("Length 2\nComponents 3\n{\n0 1 2 3 4").is_none()); + assert!(parse("Length 2\n{\n0 1 2").is_none()); + assert!(parse("Length 2\n{\n").is_none()); +} diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml new file mode 100644 index 0000000000..44578baede --- /dev/null +++ b/crates/color/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-color" +description = "Colour tags, Y'CbCr matrices, transfer functions and HDR static metadata for compositor and display frames" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs new file mode 100644 index 0000000000..dfbdf17872 --- /dev/null +++ b/crates/color/src/lib.rs @@ -0,0 +1,440 @@ +//! Colour tags and the conversions compositor and display frames need. +//! +//! This is the slim colour-metadata layer used by craft-frame and by media +//! `MediaInfo`: [`ColorInfo`] (matrix, transfer, primaries, range), [`HdrMetadata`], Y'CbCr +//! matrices, transfer functions, and a few helpers (sRGB tables, HSL, hex). It is not a +//! colour-managed pipeline: LUTs, camera log, grade and tone mapping stay out. +//! +//! Came from FilmCraft's `filmcraft-color` (the metadata and transfer part of that crate). +//! Distinct from `craft-video`'s decoder colour tags (`ColorTags` in #1231 / #1768). + +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +use serde::{Deserialize, Serialize}; +use std::sync::OnceLock; + +/// HDR reference white in cd/m² (ITU-R BT.2408). +pub const REFERENCE_WHITE_NITS: f64 = 203.0; + +/// YUV ↔ RGB matrix coefficients. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Matrix { + Bt601, + #[default] + Bt709, + Bt2020Ncl, +} + +impl Matrix { + /// (Kr, Kb) luma coefficients. + pub fn kr_kb(self) -> (f32, f32) { + match self { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020Ncl => (0.2627, 0.0593), + } + } + /// From an ISO/IEC 23091-2 `matrix_coefficients` code. + pub fn from_code(c: u8) -> Option { + match c { + 1 => Some(Matrix::Bt709), + 5 | 6 => Some(Matrix::Bt601), + // H.273 table 4: code 10 is constant luminance, not this matrix. + 9 => Some(Matrix::Bt2020Ncl), + _ => None, + } + } +} + +/// Transfer characteristics. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Transfer { + /// BT.709 display, approximated with the sRGB curve by this slim conversion layer. + /// This is not a pure-gamma BT.1886 decode. + #[default] + Bt709, + Srgb, + Linear, + /// SMPTE ST 2084. + Pq, + /// ARIB STD-B67. + Hlg, +} + +impl Transfer { + /// From an ISO/IEC 23091-2 `transfer_characteristics` code. + pub fn from_code(c: u8) -> Option { + match c { + 1 | 6 | 14 | 15 => Some(Transfer::Bt709), + 13 => Some(Transfer::Srgb), + 8 => Some(Transfer::Linear), + 16 => Some(Transfer::Pq), + 18 => Some(Transfer::Hlg), + _ => None, + } + } +} + +/// Chromaticity primaries. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Primaries { + #[default] + Bt709, + Bt601_625, + Bt601_525, + Bt2020, + P3D65, +} + +/// Quantisation range of integer Y'CbCr samples. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Range { + /// 16–235 (8-bit) "video" range. + #[default] + Limited, + Full, +} + +/// Colour metadata attached to a compositor or display frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ColorInfo { + pub matrix: Matrix, + pub transfer: Transfer, + pub primaries: Primaries, + pub range: Range, +} + +impl ColorInfo { + pub const SRGB_FULL: ColorInfo = ColorInfo { matrix: Matrix::Bt709, transfer: Transfer::Srgb, primaries: Primaries::Bt709, range: Range::Full }; + pub const REC709: ColorInfo = ColorInfo { matrix: Matrix::Bt709, transfer: Transfer::Bt709, primaries: Primaries::Bt709, range: Range::Limited }; +} + +/// HDR static metadata of a stream: SMPTE ST 2086 mastering display luminance and the CTA-861.3 +/// content light levels (MaxCLL / MaxFALL), in cd/m². Read from `mdcv` / `clli` (MP4 / MOV) and +/// Matroska `MasteringMetadata` / `MaxCLL` / `MaxFALL`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HdrMetadata { + pub mastering_max_nits: Option, + pub mastering_min_nits: Option, + pub max_cll: Option, + pub max_fall: Option, +} + +impl HdrMetadata { + /// The content's peak for tone mapping: MaxCLL when signalled (the brightest pixel actually + /// in the content), else the mastering display's peak; `None` when neither is (0 means + /// unknown in both). Never below HDR reference white. + pub fn peak_nits(&self) -> Option { + let known = |v: Option| v.filter(|n| *n > 0.0); + let p = match (known(self.max_cll), known(self.mastering_max_nits)) { + (Some(c), _) => c, + (None, m) => m?, + }; + Some(p.clamp(REFERENCE_WHITE_NITS as f32, 10_000.0)) + } +} + +/// Convert normalised Y'CbCr (Y in 0..1, Cb/Cr in -0.5..0.5) to non-linear R'G'B'. +#[inline] +pub fn ycbcr_to_rgb(y: f32, cb: f32, cr: f32, m: Matrix) -> [f32; 3] { + let (kr, kb) = m.kr_kb(); + let kg = 1.0 - kr - kb; + let r = y + 2.0 * (1.0 - kr) * cr; + let b = y + 2.0 * (1.0 - kb) * cb; + let g = (y - kr * r - kb * b) / kg; + [r, g, b] +} + +/// Convert non-linear R'G'B' to normalised Y'CbCr. +#[inline] +pub fn rgb_to_ycbcr(r: f32, g: f32, b: f32, m: Matrix) -> [f32; 3] { + let (kr, kb) = m.kr_kb(); + let kg = 1.0 - kr - kb; + let y = kr * r + kg * g + kb * b; + [y, (b - y) / (2.0 * (1.0 - kb)), (r - y) / (2.0 * (1.0 - kr))] +} + +/// Unsupported integer sample depth. Normalization supports 8 through 16 bits. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidBitDepth(pub u32); + +impl std::fmt::Display for InvalidBitDepth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "unsupported sample bit depth {}; expected 8..=16", self.0) + } +} +impl std::error::Error for InvalidBitDepth {} + +/// Normalise an integer luma code value to 0..1 given bit depth and range. +#[inline] +pub fn normalize_y(v: u32, bits: u32, range: Range) -> Result { + if !(8..=16).contains(&bits) { + return Err(InvalidBitDepth(bits)); + } + let scale = (1u32 << (bits - 8)) as f32; + Ok(match range { + Range::Limited => (v as f32 - 16.0 * scale) / (219.0 * scale), + Range::Full => v as f32 / ((1u32 << bits) - 1) as f32, + }) +} + +/// Normalise an integer chroma code value to −0.5..0.5 given bit depth and range. +#[inline] +pub fn normalize_c(v: u32, bits: u32, range: Range) -> Result { + if !(8..=16).contains(&bits) { + return Err(InvalidBitDepth(bits)); + } + let scale = (1u32 << (bits - 8)) as f32; + Ok(match range { + Range::Limited => (v as f32 - 128.0 * scale) / (224.0 * scale), + Range::Full => (v as f32 - (1u32 << (bits - 1)) as f32) / ((1u32 << bits) - 1) as f32, + }) +} + +/// sRGB electro-optical transfer (encoded → linear). +#[inline] +pub fn srgb_to_linear(v: f32) -> f32 { + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +/// sRGB inverse EOTF (linear → encoded). +#[inline] +pub fn linear_to_srgb(v: f32) -> f32 { + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +/// Encoded → linear for a transfer function (display-referred; PQ normalised to 100 nits = 1.0). +pub fn to_linear(v: f32, t: Transfer) -> f32 { + match t { + Transfer::Srgb => srgb_to_linear(v), + // Rec.709 is treated as display gamma 2.4; the sRGB curve is visually identical for + // previews and keeps round-trips exact. + Transfer::Bt709 => srgb_to_linear(v), + Transfer::Linear => v, + Transfer::Pq => pq_eotf(v) * 100.0, + Transfer::Hlg => hlg_inverse_oetf(v), + } +} + +/// Linear → encoded for a transfer function (the inverse of [`to_linear`]). +pub fn from_linear(v: f32, t: Transfer) -> f32 { + match t { + Transfer::Srgb | Transfer::Bt709 => linear_to_srgb(v), + Transfer::Linear => v, + Transfer::Pq => pq_inverse_eotf(v / 100.0), + Transfer::Hlg => hlg_oetf(v), + } +} + +/// SMPTE ST 2084 EOTF, output normalised to 10 000 nits = 1.0. +pub fn pq_eotf(e: f32) -> f32 { + let (m1, m2) = (0.159_301_76_f32, 78.84375_f32); + let (c1, c2, c3) = (0.835_937_5_f32, 18.851_563_f32, 18.6875_f32); + let p = e.max(0.0).powf(1.0 / m2); + ((p - c1).max(0.0) / (c2 - c3 * p)).powf(1.0 / m1) +} + +/// Inverse of [`pq_eotf`]. +pub fn pq_inverse_eotf(y: f32) -> f32 { + let (m1, m2) = (0.159_301_76_f32, 78.84375_f32); + let (c1, c2, c3) = (0.835_937_5_f32, 18.851_563_f32, 18.6875_f32); + let p = y.max(0.0).powf(m1); + ((c1 + c2 * p) / (1.0 + c3 * p)).powf(m2) +} + +/// ARIB STD-B67 HLG OETF. +pub fn hlg_oetf(l: f32) -> f32 { + let (a, b, c) = (0.178_832_77_f32, 0.284_668_92_f32, 0.559_910_7_f32); + if l <= 1.0 / 12.0 { (3.0 * l.max(0.0)).sqrt() } else { a * (12.0 * l - b).ln() + c } +} + +/// Inverse of [`hlg_oetf`]. +pub fn hlg_inverse_oetf(e: f32) -> f32 { + let (a, b, c) = (0.178_832_77_f32, 0.284_668_92_f32, 0.559_910_7_f32); + if e <= 0.5 { e * e / 3.0 } else { (((e - c) / a).exp() + b) / 12.0 } +} + +/// 256-entry table: sRGB-encoded u8 → linear f32. +pub fn srgb_u8_to_linear_table() -> &'static [f32; 256] { + static T: OnceLock<[f32; 256]> = OnceLock::new(); + T.get_or_init(|| std::array::from_fn(|i| srgb_to_linear(i as f32 / 255.0))) +} + +/// 4096-entry table: linear (0..1, quantised to 12 bits) → sRGB-encoded u8. +pub fn linear_to_srgb_u8_table() -> &'static [u8; 4096] { + static T: OnceLock<[u8; 4096]> = OnceLock::new(); + T.get_or_init(|| std::array::from_fn(|i| (linear_to_srgb(i as f32 / 4095.0) * 255.0 + 0.5).clamp(0.0, 255.0) as u8)) +} + +/// Linear 0..1 to an sRGB-encoded u8, via [`linear_to_srgb_u8_table`]. +#[inline] +pub fn linear_to_srgb_u8(v: f32) -> u8 { + let i = (v.clamp(0.0, 1.0) * 4095.0 + 0.5) as usize; + linear_to_srgb_u8_table()[i] +} + +/// Rec.709 luma of a linear or encoded RGB triple. +#[inline] +pub fn luma709(r: f32, g: f32, b: f32) -> f32 { + 0.2126 * r + 0.7152 * g + 0.0722 * b +} + +/// RGB (0..1) → HSL (h in 0..1). +pub fn rgb_to_hsl(r: f32, g: f32, b: f32) -> [f32; 3] { + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let l = (max + min) / 2.0; + if (max - min).abs() < 1e-7 { + return [0.0, 0.0, l]; + } + let d = max - min; + let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; + let h = if max == r { + (g - b) / d + if g < b { 6.0 } else { 0.0 } + } else if max == g { + (b - r) / d + 2.0 + } else { + (r - g) / d + 4.0 + }; + [h / 6.0, s, l] +} + +/// Inverse of [`rgb_to_hsl`]. +pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] { + if s <= 0.0 { + return [l, l, l]; + } + let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; + let p = 2.0 * l - q; + let f = |mut t: f32| { + t = t.rem_euclid(1.0); + if t < 1.0 / 6.0 { + p + (q - p) * 6.0 * t + } else if t < 0.5 { + q + } else if t < 2.0 / 3.0 { + p + (q - p) * (2.0 / 3.0 - t) * 6.0 + } else { + p + } + }; + [f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)] +} + +/// Parse `#rrggbb` / `#rrggbbaa` into 0..1 floats. +pub fn parse_hex(s: &str) -> Option<[f32; 4]> { + let s = s.trim(); + let s = s.strip_prefix('#').unwrap_or(s); + if !s.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0); + match s.len() { + 6 => Some([b(0)?, b(2)?, b(4)?, 1.0]), + 8 => Some([b(0)?, b(2)?, b(4)?, b(6)?]), + _ => None, + } +} + +/// The inverse of [`parse_hex`], lowercase, omitting alpha when it is 1. +pub fn to_hex(c: [f32; 4]) -> String { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if c[3] >= 0.999 { + format!("#{:02x}{:02x}{:02x}", q(c[0]), q(c[1]), q(c[2])) + } else { + format!("#{:02x}{:02x}{:02x}{:02x}", q(c[0]), q(c[1]), q(c[2]), q(c[3])) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_hex_rejects_signs() { + assert_eq!(parse_hex("#+f+f+f"), None); + assert_eq!(parse_hex("#-f-f-f"), None); + assert_eq!(parse_hex("##0f0f0f"), None); + assert_eq!(parse_hex("#0f0f0"), None); + assert!(parse_hex("#0f0f0f").is_some()); + assert!(parse_hex("0f0f0f80").is_some()); + } + + #[test] + fn ycbcr_roundtrip() { + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + let rgb = [0.8, 0.3, 0.1]; + let y = rgb_to_ycbcr(rgb[0], rgb[1], rgb[2], m); + let back = ycbcr_to_rgb(y[0], y[1], y[2], m); + for k in 0..3 { + assert!((rgb[k] - back[k]).abs() < 1e-5); + } + } + } + + #[test] + fn invalid_bit_depths_are_errors_not_shifts() { + for bits in [0, 1, 7, 17, 31, 32, u32::MAX] { + assert_eq!(normalize_y(0, bits, Range::Full), Err(InvalidBitDepth(bits))); + assert_eq!(normalize_c(0, bits, Range::Limited), Err(InvalidBitDepth(bits))); + } + } + + #[test] + fn limited_range_levels() { + assert_eq!(normalize_y(16, 8, Range::Limited).unwrap(), 0.0); + assert_eq!(normalize_y(235, 8, Range::Limited).unwrap(), 1.0); + assert_eq!(normalize_y(940, 10, Range::Limited).unwrap(), 1.0); + assert_eq!(normalize_c(128, 8, Range::Limited).unwrap(), 0.0); + } + + #[test] + fn transfer_roundtrips() { + for t in [Transfer::Srgb, Transfer::Pq, Transfer::Hlg, Transfer::Linear] { + for v in [0.0, 0.1, 0.5, 0.9] { + let l = to_linear(v, t); + assert!((from_linear(l, t) - v).abs() < 1e-3, "{t:?} {v}"); + } + } + assert_eq!(linear_to_srgb_u8(1.0), 255); + assert_eq!(linear_to_srgb_u8(0.0), 0); + assert_eq!(linear_to_srgb_u8(srgb_u8_to_linear_table()[128]), 128); + } + + #[test] + fn hsl_roundtrip() { + let c = [0.2, 0.6, 0.9]; + let h = rgb_to_hsl(c[0], c[1], c[2]); + let b = hsl_to_rgb(h[0], h[1], h[2]); + for k in 0..3 { + assert!((c[k] - b[k]).abs() < 1e-5); + } + } + + #[test] + fn hex() { + assert_eq!(parse_hex("#ff8000"), Some([1.0, 128.0 / 255.0, 0.0, 1.0])); + assert_eq!(to_hex([1.0, 0.0, 0.0, 1.0]), "#ff0000"); + } + + #[test] + fn hdr_peak_nits() { + assert_eq!(HdrMetadata::default().peak_nits(), None); + assert_eq!(HdrMetadata { max_cll: Some(4000.0), mastering_max_nits: Some(1000.0), ..HdrMetadata::default() }.peak_nits(), Some(4000.0)); + assert_eq!(HdrMetadata { max_cll: Some(1000.0), mastering_max_nits: Some(4000.0), ..HdrMetadata::default() }.peak_nits(), Some(1000.0)); + assert_eq!(HdrMetadata { max_cll: Some(0.0), mastering_max_nits: Some(400.0), ..HdrMetadata::default() }.peak_nits(), Some(400.0)); + // never below reference white + assert_eq!(HdrMetadata { max_cll: Some(100.0), ..HdrMetadata::default() }.peak_nits(), Some(REFERENCE_WHITE_NITS as f32)); + } + + #[test] + fn codes() { + assert_eq!(Matrix::from_code(9), Some(Matrix::Bt2020Ncl)); + assert_eq!(Matrix::from_code(10), None); + assert_eq!(Matrix::from_code(1), Some(Matrix::Bt709)); + assert_eq!(Matrix::from_code(6), Some(Matrix::Bt601)); + assert_eq!(Transfer::from_code(16), Some(Transfer::Pq)); + assert_eq!(Transfer::from_code(99), None); + } +} diff --git a/crates/control-protocol/Cargo.toml b/crates/control-protocol/Cargo.toml new file mode 100644 index 0000000000..f00bbc1c66 --- /dev/null +++ b/crates/control-protocol/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "craft-control-protocol" +description = "Authenticated bounded JSON-lines control protocol" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde_json = { workspace = true } +subtle = "2" diff --git a/crates/control-protocol/src/lib.rs b/crates/control-protocol/src/lib.rs new file mode 100644 index 0000000000..8bdb08d660 --- /dev/null +++ b/crates/control-protocol/src/lib.rs @@ -0,0 +1,234 @@ +//! Authenticated JSON-lines request framing and dispatch for local control services. +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] +use serde_json::{Value, json}; +use std::io::{BufRead, BufReader, Read, Write}; +use subtle::ConstantTimeEq; + +/// Whether a session token has the control protocol's 64 hexadecimal character form. +pub fn valid_token(token: &str) -> bool { + token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Encode one client request, including its terminating newline. +pub fn request_line(id: u64, token: Option<&str>, method: &str, params: &Value) -> String { + format!("{}\n", json!({"id": id, "token": token, "method": method, "params": params})) +} + +/// Extract the result or application error from a parsed control reply. +pub fn reply_result(reply: &Value) -> Result { + if reply.get("ok").and_then(Value::as_bool) == Some(true) { + Ok(reply.get("result").cloned().unwrap_or(Value::Null)) + } else { + Err(reply.get("error").and_then(Value::as_str).unwrap_or("error").to_owned()) + } +} + +/// One parsed line. +enum Line { + Request { + id: Value, + method: String, + params: Value, + }, + Blank, + /// Not a request: reply with this error and close the connection. + Reject(String), +} + +fn parse_line(bytes: &[u8], token: &str) -> Line { + let Ok(text) = std::str::from_utf8(bytes) else { + return Line::Reject("not a control request (invalid UTF-8); closing the connection".into()); + }; + let text = text.trim(); + if text.is_empty() { + return Line::Blank; + } + let msg = match serde_json::from_str::(text) { + Ok(v) => v, + Err(e) => return Line::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")), + }; + let Some(obj) = msg.as_object() else { + return Line::Reject("not a control request (expected a JSON object); closing the connection".into()); + }; + let Some(method) = obj.get("method").and_then(Value::as_str) else { + return Line::Reject("not a control request (missing string `method`); closing the connection".into()); + }; + // Authenticate every request before constructing or enqueueing a ControlRequest. A valid + // earlier request must not authorize a later one with a missing or incorrect credential. + let authenticated = obj.get("token").and_then(Value::as_str).is_some_and(|supplied| bool::from(supplied.as_bytes().ct_eq(token.as_bytes()))); + if !authenticated { + return Line::Reject("control authentication failed; closing the connection".into()); + } + Line::Request { + id: obj.get("id").cloned().unwrap_or(Value::Null), + method: method.to_string(), + params: obj.get("params").cloned().unwrap_or(json!({})), + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum ReadFailure { + Timeout, + Rejected(String), +} + +/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped). +/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails. +pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) -> Result { + buf.clear(); + // `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`. + let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); + let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() { + std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => ReadFailure::Timeout, + _ => ReadFailure::Rejected(e.to_string()), + })?; + if n == 0 { + return Ok(false); + } + if buf.last() == Some(&b'\n') { + buf.pop(); + if buf.last() == Some(&b'\r') { + buf.pop(); + } + return Ok(true); + } + if buf.len() > max { + return Err(ReadFailure::Rejected(format!("request line longer than {max} bytes; closing the connection"))); + } + // Last line without a newline, then end of stream. + Ok(true) +} + +/// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is +/// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and +/// returns the reply object (the request's `id` is added here). +pub fn serve_lines(read: R, mut out: W, token: &str, max_line: usize, mut handle: impl FnMut(String, Value) -> Option) { + let mut reader = BufReader::new(read); + let mut buf = Vec::new(); + loop { + let reject = match read_bounded_line(&mut reader, &mut buf, max_line) { + Ok(false) => return, + // Expiration is not a request: a pooled client must see EOF and reconnect, rather + // than read a stale error reply. A partial line must not be parsed on timeout. + Err(ReadFailure::Timeout) => return, + Err(ReadFailure::Rejected(e)) => e, + Ok(true) => match parse_line(&buf, token) { + Line::Blank => continue, + Line::Reject(e) => e, + Line::Request { id, method, params } => { + let Some(mut r) = handle(method, params) else { return }; + if let Some(o) = r.as_object_mut() { + o.insert("id".into(), id); + } + if writeln!(out, "{r}").and_then(|()| out.flush()).is_err() { + return; + } + continue; + } + }, + }; + let _ = writeln!(out, "{}", json!({"ok": false, "error": reject})).and_then(|()| out.flush()); + return; + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn rejects_bad_request_shapes_without_dispatching() { + for input in [&b"\xff\n"[..], &b"[]\n"[..], &b"{}\n"[..]] { + let mut out = Vec::new(); + serve_lines(input, &mut out, "secret", 1024, |_, _| panic!("must not dispatch")); + let reply: Value = serde_json::from_slice(&out).unwrap(); + assert_eq!(reply["ok"], false); + assert!(reply["error"].as_str().unwrap().contains("closing the connection")); + } + } + #[test] + fn timeout_after_partial_line_never_dispatches() { + struct Partial(bool); + impl Read for Partial { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if !self.0 { + self.0 = true; + buf[..2].copy_from_slice(b"{\""); + return Ok(2); + } + Err(std::io::ErrorKind::TimedOut.into()) + } + } + let mut out = Vec::new(); + serve_lines(Partial(false), &mut out, "secret", 1024, |_, _| panic!("must not dispatch")); + assert!(out.is_empty()); + } + #[test] + fn line_boundaries_and_closed_dispatch_are_preserved() { + let mut buf = Vec::new(); + assert_eq!(read_bounded_line(&mut &b"abc\r\n"[..], &mut buf, 4), Ok(true)); + assert_eq!(buf, b"abc"); + assert_eq!(read_bounded_line(&mut &b"abcd\n"[..], &mut buf, 4), Ok(true)); + assert_eq!(buf, b"abcd"); + let mut out = Vec::new(); + serve_lines(&b"{\"method\":\"x\",\"token\":\"s\"}\n"[..], &mut out, "s", 1024, |_, _| None); + assert!(out.is_empty()); + } + #[test] + fn output_failure_stops_following_requests() { + struct Closed; + impl Write for Closed { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let input = b"{\"method\":\"x\",\"token\":\"s\"}\n{\"method\":\"y\",\"token\":\"s\"}\n"; + let mut calls = 0; + serve_lines(&input[..], Closed, "s", 1024, |_, _| { + calls += 1; + Some(json!({"ok": true})) + }); + assert_eq!(calls, 1); + } + #[test] + fn client_request_and_reply_keep_optional_fields() { + let line = request_line(7, None, "status", &json!({"a": 1})); + assert_eq!(serde_json::from_str::(&line).unwrap(), json!({"id": 7, "token": null, "method": "status", "params": {"a": 1}})); + assert_eq!(reply_result(&json!({"ok": true})).unwrap(), Value::Null); + assert_eq!(reply_result(&json!({"ok": false, "error": "busy"})).unwrap_err(), "busy"); + } + #[test] + fn validates_session_token_shape() { + assert!(valid_token(&"aB09".repeat(16))); + assert!(!valid_token(&"a".repeat(63))); + assert!(!valid_token(&"g".repeat(64))); + } + #[test] + fn authenticates_each_request_and_closes_after_failure() { + let input = + b"{\"id\":1,\"method\":\"first\",\"token\":\"secret\"}\n{\"id\":2,\"method\":\"second\"}\n{\"method\":\"third\",\"token\":\"secret\"}\n"; + let mut output = Vec::new(); + let mut calls = Vec::new(); + serve_lines(&input[..], &mut output, "secret", 4096, |method, _| { + calls.push(method); + Some(json!({"ok": true})) + }); + assert_eq!(calls, ["first"]); + let lines: Vec = std::str::from_utf8(&output).unwrap().lines().map(|s| serde_json::from_str(s).unwrap()).collect(); + assert_eq!(lines[0], json!({"ok": true, "id": 1})); + assert_eq!(lines[1]["error"], "control authentication failed; closing the connection"); + } + #[test] + fn bounds_requests_and_preserves_last_unterminated_line() { + let mut buf = Vec::new(); + assert_eq!(read_bounded_line(&mut &b"abc"[..], &mut buf, 3), Ok(true)); + assert_eq!(buf, b"abc"); + assert!(matches!(read_bounded_line(&mut &b"abcd"[..], &mut buf, 3), Err(ReadFailure::Rejected(_)))); + let mut out = Vec::new(); + serve_lines(&b"{broken}\n"[..], &mut out, "secret", 1024, |_, _| panic!("must not dispatch")); + let reply: Value = serde_json::from_slice(&out).unwrap(); + assert!(reply["error"].as_str().unwrap().starts_with("bad JSON (")); + } +} diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml new file mode 100644 index 0000000000..0a18ccc99c --- /dev/null +++ b/crates/control/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "craft-control" +description = "The control channel any app may share: token files, the loopback server, and its requests; no UI toolkit" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } + +# The loopback server is for desktop apps; the web app is driven through the page instead. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0). +getrandom = "0.3" + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/control/src/auth.rs b/crates/control/src/auth.rs new file mode 100644 index 0000000000..bb2cef86b3 --- /dev/null +++ b/crates/control/src/auth.rs @@ -0,0 +1,673 @@ +//! The control channel's per-launch token (docs/control-protocol.md). An app listening for +//! control makes a random token, writes it to a file only the user can read +//! ([`App::token_path`]) and refuses every connection whose first request doesn't carry it, so +//! other users on the same machine (loopback is shared, on Windows across remote-desktop sessions +//! too) can't drive the app. Clients find it with [`App::client_token`]. Next to it, `.pid` +//! names the process that wrote it, so a client refused with a leftover token can say the file is +//! stale. + +use std::ffi::OsString; +use std::io::{Error, ErrorKind, Read, Result, Write}; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// Shortest token accepted from the app's `CONTROL_TOKEN` variable (hex characters). +pub const MIN_TOKEN_LEN: usize = 32; + +/// Ports tried from the app's default port upward when it is taken (a second window, another +/// program). +pub const PORT_TRIES: u16 = 16; + +/// Which app a control channel belongs to: where its token files live, its environment and its +/// name in messages. +#[derive(Clone, Copy)] +pub struct App { + /// The app's name in messages ("restart SolidCraft"). + pub name: &'static str, + /// The per-user data folder; the token files go in its `control` folder. + pub data_dir: fn() -> Option, + /// The app's environment variable `name` (`CONTROL_DIR`, `CONTROL_TOKEN`), with the app's prefix. + pub env: fn(&str) -> Option, + /// A time in seconds since the Unix epoch, as the app writes UTC times in messages. + pub utc: fn(u64) -> String, + /// The port the control channel tries first when the launch gives none. Below the ephemeral + /// ranges of Linux (32768+) and Windows/macOS (49152+), so the system never hands it to an + /// outgoing connection. + pub default_port: u16, +} + +/// Where the control channel listens, from the launch's `--control`/environment port and the app's +/// allow-agents setting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Listen { + /// Exactly this port (`--control PORT`, the app's `CONTROL_PORT`); no fallback. + Exact(u16), + /// The app's [`App::default_port`], or the next free one of [`PORT_TRIES`]. + Default, +} + +/// What a launch listens on. An explicit port wins over the app's allow-agents setting +/// (`enabled`), so a scripted launch works with the setting off; with the setting off and no port, +/// nothing listens. +pub fn plan(explicit: Option, enabled: bool) -> Option { + match explicit { + Some(port) => Some(Listen::Exact(port)), + None if enabled => Some(Listen::Default), + None => None, + } +} + +/// Bind a loopback-only listener on `first`, or on the next free port when it is taken, up to +/// `tries` ports in all. +pub fn bind_with_fallback(first: u16, tries: u16) -> Result { + let mut last = Error::new(ErrorKind::AddrInUse, "no port to try"); + for port in (first..=u16::MAX).take(usize::from(tries.max(1))) { + match std::net::TcpListener::bind(("127.0.0.1", port)) { + Ok(l) => return Ok(l), + // In use; Windows reports a port another program holds exclusively as denied. + Err(e) if matches!(e.kind(), ErrorKind::AddrInUse | ErrorKind::PermissionDenied) => last = e, + Err(e) => return Err(e), + } + } + Err(last) +} + +impl App { + /// The folder of the token files: `/control` (the app's `CONTROL_DIR` replaces it). + fn control_dir(&self) -> Option { + match self.custom_control_dir() { + Some(d) => Some(PathBuf::from(d)), + None => Some((self.data_dir)()?.join("control")), + } + } + + /// The folder the app's `CONTROL_DIR` names in place of the default one. + fn custom_control_dir(&self) -> Option { + (self.env)("CONTROL_DIR").filter(|d| !d.is_empty()) + } + + /// The token file of the app listening on `port`: `/control/.token` + /// (the app's `CONTROL_DIR` replaces the folder). + pub fn token_path(&self, port: u16) -> Option { + Some(self.control_dir()?.join(format!("{port}.token"))) + } + + /// The discovery file: the port of the most recently started app, so a client with no port + /// finds it. It holds only the port; the token stays in its own file. + pub fn current_port_path(&self) -> Option { + Some(self.control_dir()?.join("current.port")) + } + + /// Record `port` as the running app's, readable only by the user like the token files. + pub fn write_current_port(&self, port: u16) -> Result { + let path = self.current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?; + self.write_token_file(&path, &port.to_string())?; + Ok(path) + } + + /// The port the discovery file names, if there is one. + pub fn read_current_port(&self) -> Option { + parse_port(&std::fs::read_to_string(self.current_port_path()?).ok().filter(|t| t.len() <= 64)?) + } + + /// Remove the discovery file (and its process file) at exit, unless a later app has taken it + /// over: it names another port, or another launch now holds this port's token file. Under + /// Flatpak every instance has its own loopback, so two windows can listen on the same port + /// number and write the same file names; the one closing first must leave the other's (#8794). + /// Run it after [`remove_token_file`], which takes this launch's own token file away first. + pub fn remove_current_port(&self, port: u16, token: &str) { + if let (Some(current), Some(file)) = (self.current_port_path(), self.token_path(port)) { + remove_discovery(¤t, &file, port, token); + } + } + + /// A token set on purpose with the app's `CONTROL_TOKEN` (test harnesses, sandboxed packages + /// whose data folder the client can't see), if it is long enough. + pub fn env_token(&self) -> Option { + (self.env)("CONTROL_TOKEN").and_then(|v| v.into_string().ok()).map(|t| t.trim().to_string()).filter(|t| t.len() >= MIN_TOKEN_LEN) + } + + /// The token a client sends to the app on `port`: `explicit` (`--token`), else the app's + /// `CONTROL_TOKEN`, else the app's token file. + pub fn client_token(&self, port: u16, explicit: Option<&str>) -> Option { + if let Some(t) = explicit.map(str::trim).filter(|t| !t.is_empty()) { + return Some(ClientToken { token: t.to_string(), file: None, app: *self }); + } + if let Some(t) = self.env_token() { + return Some(ClientToken { token: t, file: None, app: *self }); + } + // Read directly, not through any agent's file scope: the app's own file. + read_token_file(&self.token_path(port)?, *self) + } + + /// Write `token` to `path`, readable and writable only by the user: the folder is made `0700` + /// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one + /// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file + /// is removed and no token is written. A file left by an earlier launch is replaced. The process + /// file beside it ([`pid_path`]) records this process, best effort. + pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> { + #[cfg(windows)] + let restrict = |p: &Path| restrict_to_user(p, self.custom_control_dir().is_some()); + #[cfg(not(windows))] + let restrict = |_: &Path| Ok(()); + write_token_file_with(path, token, restrict) + } +} + +fn parse_port(text: &str) -> Option { + text.trim().parse::().ok().filter(|p| *p != 0) +} + +/// [`App::remove_current_port`] on given files: `current` is the discovery file, `file` the token +/// file of `port`. +fn remove_discovery(current: &Path, file: &Path, port: u16, token: &str) { + let named = std::fs::read_to_string(current).ok().filter(|t| t.len() <= 64).and_then(|t| parse_port(&t)); + if named != Some(port) || held_by_another(file, token) { + return; + } + let _ = std::fs::remove_file(current); + let _ = std::fs::remove_file(pid_path(current)); +} + +/// A client token and, when it came from a token file, where that file is. +pub struct ClientToken { + pub token: String, + pub file: Option, + /// The app it is for, named in an explanation. + pub app: App, +} + +/// The token file a client read: its path, when it was written and the process that wrote it. +pub struct TokenSource { + pub path: PathBuf, + pub modified: Option, + /// From `.pid`: the writer's process id and, on Linux, its start time. + pub writer: Option<(u32, Option)>, +} + +impl ClientToken { + /// The app's `error`, and for a refused token read from a file, which file it was, when it + /// was written and whether the instance that wrote it has exited. Never the token itself. + pub fn explain_error(&self, error: &str) -> String { + let Some(src) = &self.file else { return error.to_string() }; + if !error.starts_with("unauthorized") { + return error.to_string(); + } + let written = src + .modified + .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) + .map(|t| (self.app.utc)(t.as_secs())) + .unwrap_or_else(|| "at an unknown time".into()); + let age = src.modified.and_then(|t| t.elapsed().ok()).map(|d| format!(" ({} s ago)", d.as_secs())).unwrap_or_default(); + let path = src.path.display(); + let name = self.app.name; + match src.writer.filter(|(pid, start)| writer_exited(*pid, *start)) { + Some((pid, _)) => format!( + "{error}; stale token file from an instance that exited (process {pid}): {path}, written {written}{age}; delete that file or restart {name}" + ), + None => format!("{error}; token from {path}, written {written}{age}; if {name} was force-quit, restart it or delete that file"), + } + } +} + +/// Files bigger than this are not token files. +const MAX_TOKEN_FILE: u64 = 4096; + +fn read_token_file(path: &Path, app: App) -> Option { + let f = std::fs::File::open(path).ok()?; + let modified = f.metadata().ok().and_then(|m| m.modified().ok()); + let mut text = String::new(); + f.take(MAX_TOKEN_FILE + 1).read_to_string(&mut text).ok()?; + if text.len() as u64 > MAX_TOKEN_FILE { + return None; + } + let token = text.trim(); + if token.is_empty() { + return None; + } + let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let writer = read_pid_file(&pid_path(&path)); + Some(ClientToken { token: token.to_string(), file: Some(TokenSource { path, modified, writer }), app }) +} + +/// The process file beside the token file `path`: `7878.token` → `7878.pid`. +pub fn pid_path(path: &Path) -> PathBuf { + path.with_extension("pid") +} + +/// ` []`; anything else (or no file) is no information. +fn read_pid_file(path: &Path) -> Option<(u32, Option)> { + let mut text = String::new(); + std::fs::File::open(path).ok()?.take(256).read_to_string(&mut text).ok()?; + let mut fields = text.split_whitespace(); + let pid = fields.next()?.parse::().ok().filter(|&pid| pid > 0)?; + Some((pid, fields.next().and_then(|s| s.parse().ok()))) +} + +/// Whether the process that wrote a token file is known to be gone: not running, or its id now +/// belongs to a process that started at another time. Unknown counts as running. +fn writer_exited(pid: u32, start: Option) -> bool { + process_running(pid) == Some(false) || start.zip(process_start(pid)).is_some_and(|(saved, now)| saved != now) +} + +/// Whether process `pid` runs; `None` when that can't be found out. +fn process_running(pid: u32) -> Option { + #[cfg(target_os = "linux")] + { + if !Path::new("/proc/self").exists() { + return None; + } + match std::fs::metadata(format!("/proc/{pid}")) { + Ok(_) => Some(true), + Err(e) if e.kind() == ErrorKind::NotFound => Some(false), + Err(_) => None, + } + } + #[cfg(all(unix, not(target_os = "linux")))] + { + let output = std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "pid="]).output().ok()?; + if output.status.success() { + return Some(true); + } + (output.status.code() == Some(1) && output.stdout.iter().all(u8::is_ascii_whitespace)).then_some(false) + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + let output = std::process::Command::new("tasklist") + .args(["/FI", &format!("PID eq {pid}"), "/FO", "CSV", "/NH"]) + .creation_flags(0x0800_0000) + .output() + .ok()?; + if !output.status.success() || output.stdout.is_empty() { + return None; + } + // `"image","pid",…` per process; with no match, a message line without a pid. + let text = String::from_utf8_lossy(&output.stdout); + Some(text.lines().any(|line| line.split("\",\"").nth(1).and_then(|s| s.trim_matches('"').parse::().ok()) == Some(pid))) + } + #[cfg(not(any(unix, windows)))] + { + let _ = pid; + None + } +} + +/// Linux: the process's start time (clock ticks after boot), which tells a reused id apart. +fn process_start(pid: u32) -> Option { + #[cfg(target_os = "linux")] + { + let mut stat = String::new(); + std::fs::File::open(format!("/proc/{pid}/stat")).ok()?.take(4096).read_to_string(&mut stat).ok()?; + stat.rsplit_once(')')?.1.split_whitespace().nth(19)?.parse().ok() + } + #[cfg(not(target_os = "linux"))] + { + let _ = pid; + None + } +} + +/// `a == b`, taking the same time wherever they differ. +pub fn tokens_match(a: &str, b: &str) -> bool { + let (a, b) = (a.as_bytes(), b.as_bytes()); + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// [`App::write_token_file`], with `restrict` limiting the new file to the user (Windows). +fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> { + let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?; + std::fs::create_dir_all(dir)?; + let _ = std::fs::remove_file(path); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; + opts.mode(0o600); + } + let opened = opts.open(path)?; + // On a refusal the file goes with the closure, so it is closed before it is removed. + let mut f = match restrict(path).map(|()| opened) { + Ok(f) => f, + Err(e) => { + let _ = std::fs::remove_file(path); + return Err(e); + } + }; + f.write_all(token.as_bytes())?; + f.write_all(b"\n")?; + f.sync_all()?; + let pid = std::process::id(); + let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n")); + let _ = std::fs::write(pid_path(path), line); + Ok(()) +} + +/// Remove a token file this launch wrote, and its process file, while it still holds `token`. +/// Another launch may have written the same file since (a second window on the same port, +/// #8794); its file stays. The process id can't tell the two apart, as every Flatpak instance +/// has the same one, but each launch's token is its own. +pub fn remove_token_file(path: &Path, token: &str) { + if read_token(path).is_some_and(|held| tokens_match(&held, token.trim())) { + let _ = std::fs::remove_file(path); + let _ = std::fs::remove_file(pid_path(path)); + } +} + +/// The token a token file holds, trimmed; `None` when there is no readable token file. +fn read_token(path: &Path) -> Option { + let mut text = String::new(); + std::fs::File::open(path).ok()?.take(MAX_TOKEN_FILE + 1).read_to_string(&mut text).ok()?; + let token = text.trim(); + (text.len() as u64 <= MAX_TOKEN_FILE && !token.is_empty()).then(|| token.to_string()) +} + +/// Whether the token file at `path` holds a token other than `token`: another launch's. +fn held_by_another(path: &Path, token: &str) -> bool { + read_token(path).is_some_and(|held| !tokens_match(&held, token.trim())) +} + +/// How long `icacls` may take (#6145). It finishes at once; on some computers the new process +/// is left suspended (security software holding it), and waiting on it without a limit froze +/// the app. +#[cfg(windows)] +const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5); + +/// How a run of `icacls` ended. +#[cfg(any(windows, test))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum IcaclsEnd { + Succeeded, + Failed, + /// It didn't finish within [`ICACLS_LIMIT`] and was ended. + TimedOut, +} + +/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is +/// in the folder the app's `CONTROL_DIR` names. A timeout is accepted only in the default folder, +/// the user's own local app data, which other users can't read by default; nothing is known about +/// the permissions of any other folder. +#[cfg(any(windows, test))] +fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> { + match end { + IcaclsEnd::Succeeded => Ok(()), + IcaclsEnd::TimedOut if !custom_folder => Ok(()), + IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))), + IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))), + } +} + +/// Windows: drop inherited entries and grant only the current user full access. An `icacls` +/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means. +#[cfg(windows)] +fn restrict_to_user(path: &Path, custom_folder: bool) -> Result<()> { + use std::os::windows::process::CommandExt; + let user = std::env::var("USERNAME").map_err(|_| Error::other("USERNAME is not set"))?; + let domain = std::env::var("USERDOMAIN").ok().filter(|d| !d.is_empty()); + let who = domain.map_or(user.clone(), |d| format!("{d}\\{user}")); + let child = std::process::Command::new("icacls") + .arg(path) + .args(["/inheritance:r", "/grant:r", &format!("{who}:F")]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .creation_flags(0x0800_0000) + .spawn()?; + let end = match wait_within(child, ICACLS_LIMIT)? { + Some(status) if status.success() => IcaclsEnd::Succeeded, + Some(_) => IcaclsEnd::Failed, + None => IcaclsEnd::TimedOut, + }; + restriction_result(end, custom_folder, path) +} + +/// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it +/// hasn't finished by then. +#[cfg(any(windows, test))] +fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Result> { + let start = std::time::Instant::now(); + loop { + if let Some(status) = child.try_wait()? { + return Ok(Some(status)); + } + if start.elapsed() >= limit { + // Not waited for afterwards: a suspended process may not end at once. + let _ = child.kill(); + return Ok(None); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } +} + +/// Removes the token file (path, token) when the app ends, while it still holds that token. +pub struct TokenFile(pub PathBuf, pub String); + +impl Drop for TokenFile { + fn drop(&mut self) { + remove_token_file(&self.0, &self.1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An app with no data folder and no environment, whose times read `t`. + const TEST: App = App { name: "TestCraft", data_dir: || None, env: |_| None, utc: |secs| format!("t{secs}"), default_port: 27878 }; + + /// #6145: a child that doesn't finish in time is given up on, not waited for forever. + #[cfg(unix)] + #[test] + fn a_slow_child_is_waited_for_only_so_long() { + use std::time::{Duration, Instant}; + let start = Instant::now(); + let slow = std::process::Command::new("sleep").arg("30").spawn().unwrap(); + assert!(wait_within(slow, Duration::from_millis(200)).unwrap().is_none()); + assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed()); + let quick = std::process::Command::new("true").spawn().unwrap(); + assert!(wait_within(quick, Duration::from_secs(5)).unwrap().is_some_and(|s| s.success())); + let failing = std::process::Command::new("false").spawn().unwrap(); + assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success())); + } + + /// #6145's freeze fix stays in the default folder, the user's own; a folder picked with + /// the app's `CONTROL_DIR` gets no token unless the file was really restricted. + #[test] + fn only_the_default_folder_accepts_an_icacls_that_timed_out() { + let path = Path::new("control/7878.token"); + for custom in [false, true] { + assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok()); + assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err()); + } + assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok()); + let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::TimedOut); + assert!(e.to_string().contains("7878.token"), "{e}"); + } + + /// A file that couldn't be restricted is removed, empty and with no process file beside it, and + /// the error goes to the caller. A restricted one gets its token. + #[test] + fn a_token_file_that_could_not_be_restricted_is_removed() { + let dir = std::env::temp_dir().join(format!("craft-control-restrict-{}", std::process::id())); + let path = dir.join("7879.token"); + let e = write_token_file_with(&path, "secret-token", |p| { + assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in"); + restriction_result(IcaclsEnd::TimedOut, true, p) + }) + .unwrap_err(); + assert_eq!(e.kind(), ErrorKind::TimedOut); + assert!(!path.exists() && !pid_path(&path).exists()); + write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap(); + assert_eq!(read_token(&path).as_deref(), Some("secret-token")); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn tokens_compare_whole() { + assert!(tokens_match("abc123", "abc123")); + assert!(!tokens_match("abc123", "abc124")); + assert!(!tokens_match("abc123", "abc12")); + assert!(!tokens_match("", "a")); + } + + /// The preference starts the listener by default, off it doesn't, and a port given on the + /// command line or in the environment wins over it either way. + #[test] + fn the_preference_decides_unless_a_port_is_given() { + assert_eq!(plan(None, true), Some(Listen::Default)); + assert_eq!(plan(None, false), None); + assert_eq!(plan(Some(7878), false), Some(Listen::Exact(7878))); + assert_eq!(plan(Some(7878), true), Some(Listen::Exact(7878))); + } + + /// A taken port falls through to the next free one, on loopback only; a run of taken ports + /// is an error, not a hang. + #[test] + fn a_taken_port_falls_back_to_the_next_free_one() { + let first = bind_with_fallback(TEST.default_port, PORT_TRIES).unwrap(); + let a = first.local_addr().unwrap(); + assert!(a.ip().is_loopback() && (TEST.default_port..TEST.default_port + PORT_TRIES).contains(&a.port()), "{a}"); + let second = bind_with_fallback(a.port(), PORT_TRIES).unwrap(); + assert!(second.local_addr().unwrap().port() > a.port()); + assert!(bind_with_fallback(a.port(), 1).is_err()); + } + + #[test] + fn the_discovery_file_holds_a_port() { + assert_eq!(parse_port("27879\n"), Some(27879)); + assert_eq!(parse_port("0"), None); + assert_eq!(parse_port("70000"), None); + assert_eq!(parse_port("nope"), None); + let dir = std::env::temp_dir().join(format!("solidcraft-current-port-{}", std::process::id())); + let path = dir.join("current.port"); + TEST.write_token_file(&path, "27881").unwrap(); + assert_eq!(parse_port(&std::fs::read_to_string(&path).unwrap()), Some(27881)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A one-line token file (and one with no process file) still reads. + #[test] + fn a_token_file_reads_with_and_without_its_process_file() { + let dir = std::env::temp_dir().join(format!("craft-control-read-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("7879.token"); + std::fs::write(&path, "legacy-token\n").unwrap(); + let client = read_token_file(&path, TEST).unwrap(); + assert_eq!(client.token, "legacy-token"); + let src = client.file.as_ref().unwrap(); + assert_eq!(src.path, std::fs::canonicalize(&path).unwrap()); + assert!(src.modified.is_some() && src.writer.is_none()); + std::fs::write(pid_path(&path), "not a pid\n").unwrap(); + assert!(read_token_file(&path, TEST).unwrap().file.unwrap().writer.is_none()); + std::fs::write(&path, "x".repeat(4097)).unwrap(); + assert!(read_token_file(&path, TEST).is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A refused token's explanation names the app and writes the time as the app does. + #[test] + fn an_explanation_names_the_app() { + let file = Some(TokenSource { path: PathBuf::from("7878.token"), modified: Some(UNIX_EPOCH), writer: None }); + let client = ClientToken { token: "secret-token".into(), file, app: TEST }; + let error = client.explain_error("unauthorized"); + assert!(error.contains("written t0 (") && error.contains("if TestCraft was force-quit"), "{error}"); + assert!(!error.contains("secret-token"), "{error}"); + let explicit = TEST.client_token(0, Some("explicit-token")).unwrap(); + assert!(explicit.token == "explicit-token" && explicit.file.is_none()); + assert_eq!(explicit.explain_error("unauthorized"), "unauthorized"); + } + + /// A process file naming a process that has exited marks the token file stale. + /// Where the process inspector cannot run (a sandboxed test runner), the exit + /// is unknown, and the explanation must not claim it. + #[cfg(any(unix, windows))] + #[test] + fn a_token_file_from_an_exited_process_is_stale() { + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "auth::tests::tokens_compare_whole"]) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap(); + let pid = child.id(); + assert!(child.wait().unwrap().success()); + let source = |writer| Some(TokenSource { path: PathBuf::from("7878.token"), modified: None, writer }); + let stale = ClientToken { token: "secret-token".into(), file: source(Some((pid, None))), app: TEST }; + let error = stale.explain_error("unauthorized"); + match process_running(pid) { + Some(false) => { + assert!(error.contains(&format!("stale token file from an instance that exited (process {pid}): 7878.token")), "{error}"); + } + None => assert!(!error.contains("stale") && error.contains("restart it or delete that file"), "{error}"), + Some(true) => panic!("the reaped child {pid} is reported as running"), + } + assert!(!error.contains("secret-token")); + let live = ClientToken { token: "t".into(), file: source(Some((std::process::id(), process_start(std::process::id())))), app: TEST }; + assert!(!live.explain_error("unauthorized").contains("stale")); + #[cfg(target_os = "linux")] + { + let reused = process_start(std::process::id()).map(|s| s + 1); + let reused = ClientToken { token: "t".into(), file: source(Some((std::process::id(), reused))), app: TEST }; + assert!(reused.explain_error("unauthorized").contains("stale token file")); + } + } + + /// The token file is the user's alone, and a client reads it back. + #[cfg(unix)] + #[test] + fn the_token_file_is_private_to_the_user() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("craft-control-auth-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("control/7878.token"); + std::fs::create_dir_all(dir.join("control")).unwrap(); + std::fs::write(&path, "stale").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + TEST.write_token_file(&path, "0123456789abcdef0123456789abcdef").unwrap(); + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&path), 0o600); + assert_eq!(mode(path.parent().unwrap()), 0o700); + assert_eq!(std::fs::read_to_string(&path).unwrap().trim(), "0123456789abcdef0123456789abcdef"); + let writer = read_token_file(&path, TEST).unwrap().file.unwrap().writer; + assert_eq!(writer.map(|(pid, _)| pid), Some(std::process::id())); + drop(TokenFile(path.clone(), "0123456789abcdef0123456789abcdef".into())); + assert!(!path.exists() && !pid_path(&path).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// #8794: under Flatpak two windows can listen on the same port number (each has its own + /// loopback) and write the same files. The one closing first leaves the other's token, process + /// and discovery files; the last one takes them all away, `current.pid` too. + #[test] + fn a_closing_launch_leaves_another_launchs_files() { + let dir = std::env::temp_dir().join(format!("craft-control-two-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (file, current) = (dir.join("27878.token"), dir.join("current.port")); + let (first, second) = ("a".repeat(64), "b".repeat(64)); + // The first window, then the second on the same port, each writing both files. + for token in [&first, &second] { + TEST.write_token_file(&file, token).unwrap(); + TEST.write_token_file(¤t, "27878").unwrap(); + } + // The first closes: the second's files stay. + remove_token_file(&file, &first); + remove_discovery(¤t, &file, 27878, &first); + assert_eq!(read_token(&file).as_deref(), Some(second.as_str())); + assert!(pid_path(&file).exists() && current.exists() && pid_path(¤t).exists()); + // Another port named in the discovery file is another app's too. + remove_discovery(¤t, &file, 27879, &second); + assert!(current.exists()); + // The second closes: nothing of either is left. + remove_token_file(&file, &format!(" {second}\n")); + remove_discovery(¤t, &file, 27878, &second); + assert!(!file.exists() && !pid_path(&file).exists() && !current.exists() && !pid_path(¤t).exists()); + // With no token file left (removed by hand, or never written), the discovery file of the + // port still goes; a missing file is no error. + TEST.write_token_file(¤t, "27878").unwrap(); + remove_token_file(&file, &second); + remove_discovery(¤t, &file, 27878, &second); + assert!(!current.exists()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/control/src/cancel.rs b/crates/control/src/cancel.rs new file mode 100644 index 0000000000..e030523078 --- /dev/null +++ b/crates/control/src/cancel.rs @@ -0,0 +1,118 @@ +//! Where a control request is, so the connection that sent it can cancel it (`control.cancel`, +//! #1989): shared between the window, which moves it along, and the connection. Whoever changes +//! it first wins. + +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::{Mutex, PoisonError}; + +/// A request's place in the app, and how to stop the work computing it. +#[derive(Default)] +pub struct Ticket { + state: AtomicU8, + /// It is an export computing on a copy, whose worker writes its file. + writes_file: AtomicBool, + /// Tells its worker to stop: set by the window when it hands the request to one. + stopper: Mutex>>, +} + +impl std::fmt::Debug for Ticket { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Ticket").field("state", &self.state).field("writes_file", &self.writes_file).finish_non_exhaustive() + } +} + +/// Waiting its turn (sent, or held behind another request). +const WAITING: u8 = 0; +/// Running on the window thread (or handed to something that can't stop it, such as the file +/// loader). +const RUNNING: u8 = 1; +/// Computing off the window thread. +const COMPUTING: u8 = 2; +const CANCELLED: u8 = 3; + +/// What [`Ticket::cancel`] did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cancel { + /// It was waiting its turn: it will not run. + Removed, + /// It was computing off the window thread: it is answered as stopped and nothing of it is + /// applied. An export's worker may still write its file. + Stopped { writes_file: bool }, + /// It runs on the window thread: it will finish. + Running, + /// It was cancelled or stopped before. + Already, +} + +impl Ticket { + /// Cancel the request, unless it already runs on the window thread. + pub fn cancel(&self) -> Cancel { + let mut state = self.state.load(Ordering::Acquire); + loop { + let done = match state { + WAITING => Cancel::Removed, + COMPUTING => Cancel::Stopped { writes_file: self.writes_file.load(Ordering::Acquire) }, + CANCELLED => return Cancel::Already, + _ => return Cancel::Running, + }; + match self.state.compare_exchange(state, CANCELLED, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + self.stop_worker(); + return done; + } + Err(now) => state = now, + } + } + } + + pub fn is_cancelled(&self) -> bool { + self.state.load(Ordering::Acquire) == CANCELLED + } + + /// The window takes the request to run it: false when it was cancelled. + pub fn take(&self) -> bool { + self.moves(WAITING, RUNNING) + } + + /// The work computing it stops on `stop` (a worker's own stop flag). Cancelled already, it is + /// stopped at once. + pub fn on_stop(&self, stop: impl Fn() + Send + Sync + 'static) { + *self.stopper.lock().unwrap_or_else(PoisonError::into_inner) = Some(Box::new(stop)); + if self.is_cancelled() { + self.stop_worker(); + } + } + + /// The window hands it to a worker (`writes_file`: an export on a copy). + pub fn computing(&self, writes_file: bool) { + self.writes_file.store(writes_file, Ordering::Release); + let _ = self.moves(RUNNING, COMPUTING) || self.moves(WAITING, COMPUTING); + } + + /// Its worker is done and it runs on the window thread now (or it never left): false when it + /// was cancelled meanwhile. Only the window moves it on from running, so running stays running. + pub fn back(&self) -> bool { + self.moves(COMPUTING, RUNNING) || self.state.load(Ordering::Acquire) == RUNNING + } + + /// Computed, but it waits its turn again (a file opening meanwhile): false when cancelled. + pub fn wait_again(&self) -> bool { + self.moves(COMPUTING, WAITING) + } + + /// The person at the app stopped it (Stop): its worker stops too. + pub fn stop(&self) { + self.state.store(CANCELLED, Ordering::Release); + self.stop_worker(); + } + + fn stop_worker(&self) { + if let Some(stop) = self.stopper.lock().unwrap_or_else(PoisonError::into_inner).as_ref() { + stop(); + } + } + + fn moves(&self, from: u8, to: u8) -> bool { + self.state.compare_exchange(from, to, Ordering::AcqRel, Ordering::Acquire).is_ok() + } +} diff --git a/crates/control/src/client.rs b/crates/control/src/client.rs new file mode 100644 index 0000000000..cbad788504 --- /dev/null +++ b/crates/control/src/client.rs @@ -0,0 +1,616 @@ +//! The control channel's client (docs/control-protocol.md): a connection to an app's loopback +//! control port, with the app's token ([`App::client_token`]) on every request, one bounded +//! round trip per request, a fresh connection after one is lost, and the wait for a request the +//! app says is still running (#1618), through `control.pending`. Its errors tell an app that is +//! not running from one that went away during a call ([`CallError`]). What a request means, and +//! anything an app adds to its parameters, is the caller's. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpStream, ToSocketAddrs}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use crate::Effect; +use crate::auth::App; + +/// Longest reply line accepted from the app. +pub const MAX_REPLY: u64 = 64 << 20; + +/// How long a reply may take: kernel operations (booleans, fillets) on big parts can take a while. +pub const READ_TIMEOUT: Duration = Duration::from_secs(300); + +/// How long the app may take to answer a request sent [`Request::once`]: a little longer than its +/// control server waits for a long request (3600 s), so its "still running" reply arrives first. +pub const ONCE_TIMEOUT: Duration = Duration::from_secs(3720); + +/// How long connecting to the app may take. +const CONNECT_TIMEOUT: Duration = Duration::from_millis(800); + +/// How often a long wait is reported ([`Connection::with_progress`]). +const PROGRESS_EVERY: Duration = Duration::from_secs(30); + +/// How an error starts when a request is still running in the app after the wait: the request +/// was not cancelled and its reply waits on the connection; [`Connection::pending`] gets it. +pub use crate::STILL_RUNNING; + +/// How long to wait for a request the app says is still running. +#[derive(Clone, Copy, Debug)] +pub struct Waits { + /// How long a call goes on waiting, asking `control.pending`, after the app said its request + /// is still running (the app says so after 60 s), before it says so itself. + pub pending: Duration, + /// How long a later call, or [`Connection::pending`], waits for a request still running from + /// an earlier call. + pub settle: Duration, + /// How often `control.pending` is asked while waiting. + pub poll: Duration, +} + +impl Default for Waits { + fn default() -> Self { + Waits { pending: Duration::from_secs(240), settle: Duration::from_secs(60), poll: Duration::from_millis(500) } + } +} + +/// Why a call has no result. Each holds the message for the caller (an agent reads it). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CallError { + /// Nothing listens at the address: the app is not running, or it quit before the call was + /// sent. The message says how to start it. + NotRunning(String), + /// The app went away or did not answer during the call, after running it or not. + Lost(String), + /// The request is still running in the app after the wait (it starts with [`STILL_RUNNING`]), + /// or an earlier one is and this one was not sent. + StillRunning(String), + /// The app answered with an error (a refused token says which token file it came from). + Refused(String), + /// The reply was not a control reply. + BadReply(String), +} + +impl CallError { + /// The message. + pub fn message(&self) -> &str { + match self { + CallError::NotRunning(m) | CallError::Lost(m) | CallError::StillRunning(m) | CallError::Refused(m) | CallError::BadReply(m) => m, + } + } +} + +impl std::fmt::Display for CallError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.message()) + } +} + +impl std::error::Error for CallError {} + +impl From for String { + fn from(e: CallError) -> String { + e.message().to_string() + } +} + +/// A request: its method and parameters, how messages name it and what it does if it is still +/// running when its call returns. +#[derive(Clone, Debug)] +pub struct Request { + pub method: String, + pub params: Value, + /// The request in messages ("`engine.execute` (solid.fillet)"). + pub what: String, + /// What it still does when it finishes after its wait. + pub effect: Effect, + /// Never sent twice: on a fresh connection, waiting up to [`ONCE_TIMEOUT`], and once it is + /// being written any error is final, as the app may have run it. Otherwise a request that + /// finds its connection lost is sent once more on a fresh one (the app may have restarted). + pub once: bool, +} + +impl Request { + /// `method` with `params`, named "`method`" in messages, taken to change the document, sent + /// again once on a fresh connection when its connection was lost. + pub fn new(method: &str, params: Value) -> Self { + Request { method: method.to_string(), params, what: format!("`{method}`"), effect: Effect::Changes, once: false } + } +} + +/// A control reply as a call's result: its `result`, or its `error`. +pub fn outcome(v: &Value) -> Result { + if v.get("ok").and_then(Value::as_bool) == Some(true) { + Ok(v.get("result").cloned().unwrap_or(Value::Null)) + } else { + Err(v.get("error").and_then(Value::as_str).unwrap_or("error").to_string()) + } +} + +/// A request the app said is still running. Its reply will come on this connection, through +/// `control.pending`, so the connection is kept for it. +struct Outstanding { + what: String, + /// What it does when it finishes; `None`: not known (a request this client did not send). + effect: Option, + since: Instant, +} + +impl Outstanding { + fn secs(&self) -> u64 { + self.since.elapsed().as_secs() + } +} + +/// What became of a request still running when its call returned, once a later call waited it +/// out: kept for [`Connection::pending`]. +enum Settled { + Finished { what: String, reply: Value }, + Lost { what: String }, +} + +/// The end of a wait for an outstanding request. +enum Waited { + /// It finished: its own reply. + Done(Value), + /// The app holds nothing (any more) for this connection. + Nothing, + /// Still running when the wait ran out. + Running, +} + +/// A connection to the app listening at an address. It connects when a call needs it, so a +/// client started before the app reaches it once it runs. +pub struct Connection { + app: App, + /// What the app calls its document in messages ("design"). + document: &'static str, + addr: String, + port: u16, + conn: Option<(BufReader, TcpStream)>, + /// Counts the connections made, so a caller can tell a fresh one from the one it asked. + serial: u64, + next_id: u64, + /// The token given, when one was. Otherwise each request looks the token up again, since + /// every launch of the app makes a new one. + explicit_token: Option, + /// A request still running in the app; its reply waits on `conn`. + outstanding: Option, + /// An outstanding request's end, once a later call waited for it (for `pending`). + settled: Option, + waits: Waits, + /// Where a long wait is reported. + progress: fn(&str), +} + +impl Connection { + /// A connection to `app` at `addr` (`host:port`), with `token` when given, else the app's + /// token found the usual way ([`App::client_token`]); not connected yet. + pub fn new(app: App, addr: &str, token: Option<&str>) -> Self { + let port = addr.rsplit(':').next().and_then(|p| p.parse::().ok()).unwrap_or(0); + Self { + app, + document: "design", + addr: addr.to_string(), + port, + conn: None, + serial: 0, + next_id: 1, + explicit_token: token.map(str::to_string), + outstanding: None, + settled: None, + waits: Waits::default(), + progress: |_| {}, + } + } + + /// What the app calls its document in messages ("design", the default). + #[must_use] + pub fn with_document(mut self, document: &'static str) -> Self { + self.document = document; + self + } + + /// Report a long wait for a request still running to `progress`, every 30 s. + #[must_use] + pub fn with_progress(mut self, progress: fn(&str)) -> Self { + self.progress = progress; + self + } + + /// How long to wait for a request still running. + pub fn set_waits(&mut self, waits: Waits) { + self.waits = waits; + } + + /// The address it connects to. + pub fn addr(&self) -> &str { + &self.addr + } + + /// The port of the address (0 when it names none). + pub fn port(&self) -> u16 { + self.port + } + + /// The token given, if one was. + pub fn explicit_token(&self) -> Option<&str> { + self.explicit_token.as_deref() + } + + /// Whether a connection is open now. + pub fn is_connected(&self) -> bool { + self.conn.is_some() + } + + /// The number of connections made so far: the same number while the same connection stays + /// open. + pub fn serial(&self) -> u64 { + self.serial + } + + /// Whether a request of this connection is still running in the app. + pub fn has_outstanding(&self) -> bool { + self.outstanding.is_some() + } + + /// Close the connection. A request still running loses its reply with it. + pub fn disconnect(&mut self) { + self.conn = None; + if let Some(o) = self.outstanding.take() { + self.settled = Some(Settled::Lost { what: o.what }); + } + } + + /// Connect afresh. Failing to reach the app at all is `NotConnected`, so [`Connection::explain`] + /// can tell it from a connection lost during a call. + /// + /// # Errors + /// `NotConnected` when nothing listens at the address (or it does not resolve). + pub fn connect(&mut self) -> std::io::Result<()> { + self.disconnect(); + let not_connected = |e: std::io::Error| std::io::Error::new(std::io::ErrorKind::NotConnected, e); + let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr)); + for sa in self.addr.to_socket_addrs().map_err(not_connected)? { + match TcpStream::connect_timeout(&sa, CONNECT_TIMEOUT) { + Ok(s) => { + s.set_nodelay(true).ok(); + s.set_read_timeout(Some(READ_TIMEOUT)).ok(); + let read = s.try_clone()?; + self.conn = Some((BufReader::new(read), s)); + self.serial += 1; + return Ok(()); + } + Err(e) => last = e, + } + } + Err(not_connected(last)) + } + + /// See whether the app is there now; the error says why not. The connection doesn't stay + /// open: the app closes one that shows no token within a few seconds, and the first call may + /// be long away. That call connects again. + /// + /// # Errors + /// As [`Connection::connect`]. + pub fn try_connect(&mut self) -> std::io::Result<()> { + self.connect()?; + self.disconnect(); + Ok(()) + } + + /// The error for a failed exchange: whether the app is not running (and how to start it) or + /// went away during the call. + pub fn explain(&self, e: &std::io::Error) -> CallError { + let (addr, port, name, document) = (&self.addr, self.port, self.app.name, self.document); + let start = format!("{} --control {port}", name.to_lowercase()); + if e.kind() == std::io::ErrorKind::NotConnected { + CallError::NotRunning(format!( + "no {name} app is listening at {addr} ({e}): it is not running, or it quit. Start it with `{start}` (or ask the user to); the \ + next call connects to it" + )) + } else { + CallError::Lost(format!( + "the {name} app at {addr} did not answer ({e}): it may have quit or crashed during this call, after running it or not. Inspect \ + the {document} before sending a change again; if the app quit, start it with `{start}`" + )) + } + } + + /// The request line for `method`: a fresh id and the app's token (looked up again for every + /// request: an app restarted mid-session has a new one). + pub fn request_line(&mut self, method: &str, params: Value) -> String { + let id = self.next_id; + self.next_id += 1; + let mut msg = json!({"id": id, "method": method, "params": params}); + if let Some(t) = self.app.client_token(self.port, self.explicit_token.as_deref()) { + msg["token"] = json!(t.token); + } + msg.to_string() + } + + /// One request line out and one reply line back, at most [`MAX_REPLY`] long, connecting + /// first when not connected. Any failure closes the connection (a timed-out read leaves a + /// late reply on the stream). + fn roundtrip(&mut self, line: &str) -> std::io::Result { + if self.conn.is_none() { + self.connect()?; + } + let Some((reader, writer)) = self.conn.as_mut() else { return Err(std::io::Error::other("not connected")) }; + // One write: a request that loses its newline still reaches the app as a request. + let sent = writer.write_all(format!("{line}\n").as_bytes()).and_then(|()| writer.flush()); + if let Err(e) = sent { + self.disconnect(); + return Err(e); + } + let mut reply = String::new(); + let n = match reader.by_ref().take(MAX_REPLY).read_line(&mut reply) { + Ok(n) => n, + Err(e) => { + self.disconnect(); + return Err(e); + } + }; + if n == 0 || !reply.ends_with('\n') { + self.disconnect(); + return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "connection closed")); + } + Ok(reply) + } + + fn set_read_timeout(&self, t: Duration) { + if let Some((_, writer)) = &self.conn { + writer.set_read_timeout(Some(t)).ok(); + } + } + + /// A reply line as JSON. + fn parse(reply: &str) -> Result { + serde_json::from_str(reply).map_err(|e| CallError::BadReply(format!("bad reply from the app: {e}"))) + } + + /// A control reply as a call's result; a refused token says which token file it came from + /// (and whether it is stale). + /// + /// # Errors + /// [`CallError::Refused`] with the app's error. + pub fn outcome(&self, v: &Value) -> Result { + outcome(v).map_err(|error| { + CallError::Refused( + self.app.client_token(self.port, self.explicit_token.as_deref()).map_or_else(|| error.clone(), |t| t.explain_error(&error)), + ) + }) + } + + /// `method` with `params`, at once and once: not behind a request still running on this + /// connection, no second try. The app's whole reply (`ok`, `result` or `error`, and anything + /// it adds), for a request the app answers at once on any connection + /// (`control.capabilities`, `control.running`). + /// + /// # Errors + /// As [`Connection::explain`]; [`CallError::BadReply`]. + pub fn ask(&mut self, method: &str, params: Value) -> Result { + let line = self.request_line(method, params); + let reply = self.roundtrip(&line).map_err(|e| self.explain(&e))?; + Self::parse(&reply) + } + + /// `method` with `params`, waiting at most `timeout` for the reply and never behind a request + /// still running: for a request the app answers within a frame, asked again later when the + /// app is busy. One try. + /// + /// # Errors + /// [`CallError::StillRunning`] when a request of this connection is still running; as + /// [`Connection::ask`] and [`Connection::outcome`]. + pub fn quick(&mut self, method: &str, params: Value, timeout: Duration) -> Result { + if self.outstanding.is_some() { + return Err(CallError::StillRunning("a request is still running in the app".into())); + } + if self.conn.is_none() { + self.connect().map_err(|e| self.explain(&e))?; + } + let line = self.request_line(method, params); + self.set_read_timeout(timeout); + let reply = self.roundtrip(&line); + self.set_read_timeout(READ_TIMEOUT); + let reply = reply.map_err(|e| self.explain(&e))?; + let v = Self::parse(&reply)?; + self.outcome(&v) + } + + /// Ask the app, on this connection only, about the request it still runs for it. + fn ask_pending(&mut self) -> Result { + if self.conn.is_none() { + self.disconnect(); + return Err(CallError::Lost("the connection to the app was lost".into())); + } + let v = self.ask("control.pending", json!({}))?; + outcome(&v).map_err(CallError::Refused).inspect_err(|_| self.disconnect()) + } + + /// `control.cancel` for the request still running on this connection. Sent at once, without + /// waiting for that request first, and never on a fresh connection, which has nothing to + /// cancel. Once the app no longer holds it (removed, stopped or finished), later calls don't + /// wait for it. + /// + /// # Errors + /// As [`Connection::ask`]; [`CallError::Refused`]. + pub fn cancel(&mut self, params: Value) -> Result { + if self.conn.is_none() { + return Ok(json!({"cancelled": null, "note": "nothing to cancel: no request of this client is running in the app"})); + } + let v = self.ask("control.cancel", params)?; + let r = outcome(&v).map_err(CallError::Refused); + if r.is_ok() { + self.outstanding = None; + } + r + } + + /// Wait up to `limit` for the outstanding request, asking `control.pending` now and then and + /// reporting how long it takes. An error: the connection, and so the reply, was lost. + fn wait_outstanding(&mut self, limit: Duration) -> Result { + let start = Instant::now(); + let mut told = start; + loop { + let Some(o) = &self.outstanding else { return Ok(Waited::Nothing) }; + let what = o.what.clone(); + let r = self.ask_pending()?; + if r.get("pending").is_none_or(Value::is_null) { + self.outstanding = None; + return Ok(Waited::Nothing); + } + if r.get("done").and_then(Value::as_bool) == Some(true) { + self.outstanding = None; + return Ok(Waited::Done(r.get("reply").cloned().unwrap_or(Value::Null))); + } + let waited = start.elapsed(); + if waited >= limit { + return Ok(Waited::Running); + } + if told.elapsed() >= PROGRESS_EVERY { + let secs = self.outstanding.as_ref().map_or(0, Outstanding::secs); + (self.progress)(&format!("{what} is still running in the app ({secs} s); waiting for it")); + told = Instant::now(); + } + std::thread::sleep(self.waits.poll.min(limit.saturating_sub(waited))); + } + } + + /// The error for the outstanding request still running after its wait. + fn still_running(&self, earlier: bool) -> CallError { + let Some(o) = &self.outstanding else { return CallError::StillRunning(format!("{STILL_RUNNING} a request is still running in the app")) }; + let document = self.document; + let effect = + o.effect.map_or_else(|| format!("it was not cancelled and may still change the {document} when it finishes"), |e| e.when_done(document)); + let settle = self.waits.settle.as_secs(); + CallError::StillRunning(if earlier { + format!( + "{STILL_RUNNING} an earlier request, {}, is still running in the app ({} s; {effect}), so this call was not sent. Call the \ + `pending` tool to wait for its result, then send this call again", + o.what, + o.secs() + ) + } else { + format!( + "{STILL_RUNNING} {} is still running in the app after {} s ({effect}); don't send it again. Call the `pending` tool to \ + wait for its result (up to {settle} s per call); other calls wait for it first", + o.what, + o.secs() + ) + }) + } + + /// Before a new request: wait for one still running from an earlier call, keeping its end for + /// `pending`. Still running after the wait: the new request is not sent. + fn settle_earlier(&mut self) -> Result<(), CallError> { + let Some(what) = self.outstanding.as_ref().map(|o| o.what.clone()) else { return Ok(()) }; + match self.wait_outstanding(self.waits.settle) { + Ok(Waited::Done(reply)) => self.settled = Some(Settled::Finished { what, reply }), + Ok(Waited::Nothing) => {} + Ok(Waited::Running) => return Err(self.still_running(true)), + // The connection was lost, and the earlier reply with it (`pending` says so): the new + // request goes on a fresh connection. + Err(_) => {} + } + Ok(()) + } + + /// `control.pending` for the client: the end of the request still running from an earlier + /// call, waiting for it up to the settle wait: `{pending: what | null, done?, reply?, lost?, + /// running_s?}`. Never sent on a fresh connection, which has nothing pending. + pub fn pending(&mut self) -> Value { + if let Some(s) = self.settled.take() { + return match s { + Settled::Finished { what, reply } => json!({"pending": what, "done": true, "reply": reply}), + Settled::Lost { what } => json!({"pending": what, "lost": true}), + }; + } + let Some(what) = self.outstanding.as_ref().map(|o| o.what.clone()) else { return json!({"pending": null}) }; + match self.wait_outstanding(self.waits.settle) { + Ok(Waited::Done(reply)) => json!({"pending": what, "done": true, "reply": reply}), + Ok(Waited::Nothing) => json!({"pending": null}), + Ok(Waited::Running) => json!({"pending": what, "done": false, "running_s": self.outstanding.as_ref().map_or(0, Outstanding::secs)}), + Err(_) => { + self.settled = None; + json!({"pending": what, "lost": true}) + } + } + } + + /// Send `request` and wait for its reply: the app's whole reply (`ok`, `result` or `error`, + /// and anything it adds). First a request still running from an earlier call is waited for + /// (except for `control.running`, which the app answers at once); a request the app says is + /// still running is waited for through `control.pending`; a request refused unrun as busy + /// behind one this client did not know of is sent once more after that one, when + /// `retry_busy`. + /// + /// # Errors + /// As [`Connection::explain`]: a request whose connection is lost is sent once more on a fresh + /// one (unless [`Request::once`]), and when nothing listens any more the app went away, maybe + /// while running it ([`CallError::Lost`]); [`CallError::StillRunning`]; [`CallError::BadReply`]. + pub fn exchange(&mut self, request: Request, retry_busy: bool) -> Result { + let Request { method, params, what, effect, once } = request; + if method != "control.running" { + self.settle_earlier()?; + } + let again = retry_busy.then(|| params.clone()); + let sent = Instant::now(); + let line = self.request_line(&method, params); + let reply = if once { + // A fresh connection (an idle one may have been closed by an app restart; connecting + // again sends nothing). + self.connect().or_else(|_| self.connect()).and_then(|()| { + self.set_read_timeout(ONCE_TIMEOUT); + let r = self.roundtrip(&line); + self.set_read_timeout(READ_TIMEOUT); + r + }) + } else { + self.roundtrip(&line).or_else(|lost| { + self.roundtrip(&line).map_err(|e| if e.kind() == std::io::ErrorKind::NotConnected && lost.kind() != e.kind() { lost } else { e }) + }) + } + .map_err(|e| self.explain(&e))?; + let v = Self::parse(&reply)?; + // Timed out in the app, still running: wait for its result on this connection. + if v.get("running").and_then(Value::as_bool) == Some(true) { + self.outstanding = Some(Outstanding { what: what.clone(), effect: Some(effect), since: sent }); + (self.progress)(&format!( + "{what} is still running in the app after {} s; waiting up to {} s more for it", + sent.elapsed().as_secs(), + self.waits.pending.as_secs() + )); + let document = self.document; + return match self.wait_outstanding(self.waits.pending)? { + Waited::Done(reply) => Ok(reply), + Waited::Nothing => Err(CallError::Lost(format!( + "{what} timed out in the app, which kept no result for it: inspect the {document} before sending it again" + ))), + Waited::Running => Err(self.still_running(false)), + }; + } + // Refused unrun behind a request this client did not know of: wait for that one, then + // send this one once more. + if v.get("busy").and_then(Value::as_bool) == Some(true) + && let Some(params) = again + { + self.outstanding = Some(Outstanding { what: "an earlier request".into(), effect: None, since: Instant::now() }); + self.settle_earlier()?; + return self.exchange(Request { method, params, what, effect, once }, false); + } + Ok(v) + } + + /// [`Connection::exchange`] (retrying a busy refusal once) and the reply's result. + /// + /// # Errors + /// As [`Connection::exchange`] and [`Connection::outcome`]. + pub fn call(&mut self, request: Request) -> Result { + let v = self.exchange(request, true)?; + self.outcome(&v) + } +} + +#[cfg(test)] +#[path = "client_tests.rs"] +mod tests; diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs new file mode 100644 index 0000000000..f5af19a004 --- /dev/null +++ b/crates/control/src/client_tests.rs @@ -0,0 +1,190 @@ +//! The client against the shared server ([`crate::server::Hub`]) on an ephemeral loopback port. + +use super::*; +use crate::ControlRequest; +use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits}; +use std::ffi::OsString; +use std::net::TcpListener; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::mpsc::channel; + +const TOKEN: &str = "0123456789abcdef0123456789abcdef"; + +fn no_dir() -> Option { + None +} + +fn no_env(_: &str) -> Option { + None +} + +fn utc(secs: u64) -> String { + secs.to_string() +} + +/// An app with no token files and no environment: a client sends only the token it is given. +const APP: App = App { name: "Probe", data_dir: no_dir, env: no_env, utc, default_port: 0 }; + +/// An app whose requests all may change its document. +struct Probe; + +impl Protocol for Probe { + fn summary(&self, method: &str, _: &Value) -> Summary { + Summary { what: format!("`{method}`"), effect: Effect::Changes, command: None, steps: None, long: false } + } + fn document(&self) -> &'static str { + "design" + } + fn change_event(&self) -> &'static str { + "design.changed" + } + fn revision_method(&self) -> &'static str { + "document.revision" + } + fn docs(&self) -> &'static str { + "docs/control-protocol.md" + } + fn capabilities(&self) -> Value { + json!({}) + } +} + +/// The app on `port` (0: an ephemeral one) behind [`TOKEN`]: its window answers each request after +/// `delay` with the request's method and parameters, and the server says a request is still +/// running after `wait`. +fn serve(port: u16, delay: Duration, wait: Duration) -> Stop { + // A port just closed may take a moment to be free again on a loaded machine. + let started = Instant::now(); + let mut bound = TcpListener::bind(("127.0.0.1", port)); + while bound.is_err() && started.elapsed() < Duration::from_secs(2) { + std::thread::sleep(Duration::from_millis(10)); + bound = TcpListener::bind(("127.0.0.1", port)); + } + let listener = bound.unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + std::thread::sleep(delay); + let _ = req.reply.send(json!({"ok": true, "result": {"method": req.method, "params": req.params}})); + } + }); + let waits = ServerWaits { short: wait, long: wait, token: Duration::from_secs(5) }; + let hub = Arc::new(Hub::new(Probe, || {}, 1 << 20).with_waits(waits)); + hub.listen_stoppable(listener, TOKEN.into(), tx, false).unwrap() +} + +fn addr(port: u16) -> String { + format!("127.0.0.1:{port}") +} + +/// A port nothing listens on. +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +#[test] +fn a_call_is_one_round_trip_with_the_token() { + let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)); + assert!(!c.is_connected()); + let r = c.call(Request::new("document.inspect", json!({"a": 1}))).unwrap(); + assert_eq!(r, json!({"method": "document.inspect", "params": {"a": 1}})); + assert!(c.is_connected()); + let serial = c.serial(); + // the next call goes on the same connection + c.call(Request::new("document.inspect", json!({}))).unwrap(); + assert_eq!(c.serial(), serial); + // `try_connect` sees the app there and leaves no connection open + let mut fresh = Connection::new(APP, &addr(app.port()), Some(TOKEN)); + fresh.try_connect().unwrap(); + assert!(!fresh.is_connected()); +} + +#[test] +fn a_wrong_token_or_none_is_refused() { + let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + for token in [Some("fedcba9876543210fedcba9876543210"), None] { + let mut c = Connection::new(APP, &addr(app.port()), token); + match c.call(Request::new("document.inspect", json!({}))) { + Err(CallError::Refused(e)) => assert!(e.starts_with("unauthorized"), "{token:?}: {e}"), + other => panic!("{token:?}: {other:?}"), + } + } +} + +#[test] +fn an_app_not_running_says_how_to_start_it() { + let port = free_port(); + let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); + let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err(); + let CallError::NotRunning(m) = &e else { panic!("{e:?}") }; + assert!(m.starts_with(&format!("no Probe app is listening at 127.0.0.1:{port}")), "{m}"); + assert!(m.contains(&format!("`probe --control {port}`")), "{m}"); + assert_eq!(c.try_connect().unwrap_err().kind(), std::io::ErrorKind::NotConnected); +} + +/// An app that goes away during a call is lost, not "not running"; the next call says it is not +/// running, and once it runs again the next call reaches it. +#[test] +fn an_app_gone_during_a_call_is_lost_and_reached_again_once_back() { + let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let port = app.port(); + let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); + c.call(Request::new("document.inspect", json!({}))).unwrap(); + app.stop(); + let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err(); + let CallError::Lost(m) = &e else { panic!("{e:?}") }; + assert!(m.contains("may have quit") && m.contains("Inspect the design") && m.contains(&format!("`probe --control {port}`")), "{m}"); + assert!(matches!(c.call(Request::new("document.inspect", json!({}))), Err(CallError::NotRunning(_)))); + let _back = serve(port, Duration::ZERO, Duration::from_secs(10)); + assert_eq!(c.call(Request::new("ui.view", json!({}))).unwrap()["method"], json!("ui.view")); +} + +/// A server that reads a request and closes the connection without a reply: the call is lost +/// (after one more try on a fresh connection), and the reply is never taken for "not running". +#[test] +fn a_connection_closed_without_a_reply_is_lost() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let mut line = String::new(); + let _ = BufReader::new(stream).read_line(&mut line); + } + }); + let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); + let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err(); + assert!(matches!(e, CallError::Lost(_)), "{e:?}"); + assert!(!c.is_connected()); +} + +/// A request the app says is still running is waited for through `control.pending`, on the same +/// connection, and its own reply is the call's result. +#[test] +fn a_request_still_running_is_waited_for_through_pending() { + let app = serve(0, Duration::from_millis(400), Duration::from_millis(50)); + let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)); + c.set_waits(Waits { pending: Duration::from_secs(10), settle: Duration::from_secs(10), poll: Duration::from_millis(5) }); + let r = c.call(Request::new("solid.slow", json!({"n": 2}))).unwrap(); + assert_eq!(r, json!({"method": "solid.slow", "params": {"n": 2}})); + assert!(!c.has_outstanding()); + assert_eq!(c.pending(), json!({"pending": null})); +} + +/// Past the wait, the call says the request is still running, and `pending` later has its end. +#[test] +fn a_request_still_running_past_the_wait_is_reported_and_its_end_kept() { + let app = serve(0, Duration::from_millis(400), Duration::from_millis(20)); + let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)); + c.set_waits(Waits { pending: Duration::from_millis(30), settle: Duration::from_secs(10), poll: Duration::from_millis(5) }); + let mut slow = Request::new("solid.slow", json!({})); + slow.what = "`solid.slow` (now)".into(); + let e = c.call(slow).unwrap_err(); + let CallError::StillRunning(m) = &e else { panic!("{e:?}") }; + assert!(m.starts_with(STILL_RUNNING) && m.contains("`solid.slow` (now)") && m.contains("will still apply"), "{m}"); + assert!(c.has_outstanding()); + let end = c.pending(); + assert_eq!(end["done"], json!(true), "{end}"); + assert_eq!(end["reply"]["result"]["method"], json!("solid.slow"), "{end}"); +} diff --git a/crates/control/src/effect.rs b/crates/control/src/effect.rs new file mode 100644 index 0000000000..aed5cbe596 --- /dev/null +++ b/crates/control/src/effect.rs @@ -0,0 +1,27 @@ +//! What a client is told about a control request that outlasts its wait (docs/control-protocol.md, +//! #1618): the app's control server and a bridged client both say what the request still does when +//! it finishes. Which requests do what is the app's to say. + +/// What a request still running does when it finishes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Effect { + /// It only reads (the document, the window or the command list): nothing changes. + ReadsOnly, + /// It writes a file (an export, a save, a render to a path); the document stays as it is. + WritesFile, + /// It changes the document (or may: anything not known to read or only write a file). + Changes, +} + +impl Effect { + /// What happens when the request finishes, for a message: "it only reads: nothing changes", + /// "it was not cancelled and will still write the file when it finishes; the design does not + /// change", … `document` is what the app calls its document ("design"). + pub fn when_done(self, document: &str) -> String { + match self { + Effect::ReadsOnly => "it only reads: nothing changes".into(), + Effect::WritesFile => format!("it was not cancelled and will still write the file when it finishes; the {document} does not change"), + Effect::Changes => "it was not cancelled and will still apply when it finishes".into(), + } + } +} diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs new file mode 100644 index 0000000000..26727a97c8 --- /dev/null +++ b/crates/control/src/lib.rs @@ -0,0 +1,26 @@ +//! The control channel any app may share (docs/control-protocol.md): the per-launch token and its +//! files ([`auth`]), the loopback server that admits a connection by the token and hands each +//! request to the window ([`server`]), the client that talks to it ([`client`]), the request the +//! window answers ([`ControlRequest`]), the document watch subscribed connections wait on +//! ([`DocumentWatch`]), and what a request still running does when it finishes ([`Effect`]). It +//! needs no UI toolkit; the window's own requests over egui (`ui.screenshot`, `ui.resize`) are +//! `craft-control-egui`. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +pub mod auth; +mod cancel; +#[cfg(not(target_arch = "wasm32"))] +pub mod client; +mod effect; +mod request; +#[cfg(not(target_arch = "wasm32"))] +pub mod server; + +pub use cancel::{Cancel, Ticket}; +pub use effect::Effect; +pub use request::{ControlRequest, ControlResponse, DOCUMENT_WATCH, DocumentWatch, Subscriber, cancelled_chat_response, chat_turn_cancelled}; + +/// How an error from the client (`client`, native only) starts when a request is still running +/// in the app after the wait. Outside the client so callers on every target can test for it. +pub const STILL_RUNNING: &str = "still running:"; diff --git a/crates/control/src/request.rs b/crates/control/src/request.rs new file mode 100644 index 0000000000..b97c90b76c --- /dev/null +++ b/crates/control/src/request.rs @@ -0,0 +1,125 @@ +//! A control request as the window gets it, and the design watch subscribed connections wait on. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::Sender; +use std::sync::{Condvar, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use serde_json::{Value, json}; + +pub type ControlResponse = Value; + +pub struct ControlRequest { + pub method: String, + pub params: Value, + pub reply: Sender, + /// Set once the window starts on it; until then it waits its turn (`control.running`, #3654). + pub started: std::sync::Arc, + /// Chat requests already admitted by the gate may outlive a tab switch. This turn's + /// validity follows them through queues, computation and cursor animation. + pub chat_turn: Option>, + /// Where the request is, shared with the connection that sent it so it can cancel it + /// (`control.cancel`, #1989). + pub ticket: std::sync::Arc, + /// Told apart from every other request of this run: names its row while it waits. + pub serial: u64, +} + +impl ControlRequest { + pub fn new(method: impl Into, params: Value) -> (Self, std::sync::mpsc::Receiver) { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let (tx, rx) = std::sync::mpsc::channel(); + let serial = NEXT.fetch_add(1, Ordering::Relaxed); + (Self { method: method.into(), params, reply: tx, started: Default::default(), chat_turn: None, ticket: Default::default(), serial }, rx) + } + + /// Answer a request whose agent chat turn has ended, and say so: such a request is not run. + pub fn refuse_cancelled_chat(&self) -> bool { + if chat_turn_cancelled(self.chat_turn.as_deref()) { + let _ = self.reply.send(cancelled_chat_response()); + true + } else { + false + } + } +} + +/// Whether the agent chat turn a request belongs to has ended (`None`: it belongs to none). +pub fn chat_turn_cancelled(turn: Option<&std::sync::atomic::AtomicBool>) -> bool { + turn.is_some_and(|active| !active.load(std::sync::atomic::Ordering::Relaxed)) +} + +/// The reply to a request whose agent chat turn has ended. +pub fn cancelled_chat_response() -> Value { + json!({"ok": false, "error": "not run: the agent chat turn ended or its document tab was left"}) +} + +/// The active design's id and revision for control connections that sent `control.subscribe` +/// (#6985): the window publishes them each frame while one is subscribed, and each such +/// connection waits for them to move, then sends the app's change event (`Protocol::change_event`). +#[derive(Default)] +pub struct DocumentWatch { + subscribers: AtomicUsize, + now: Mutex>, + moved: Condvar, +} + +/// The app's [`DocumentWatch`]. +pub static DOCUMENT_WATCH: DocumentWatch = DocumentWatch::new(); + +impl DocumentWatch { + pub const fn new() -> Self { + DocumentWatch { subscribers: AtomicUsize::new(0), now: Mutex::new(None), moved: Condvar::new() } + } + + fn now(&self) -> MutexGuard<'_, Option<(String, u64)>> { + self.now.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The design as last published (`None` before anything was). + pub fn current(&self) -> Option<(String, u64)> { + self.now().clone() + } + + /// The design as it is now; waiters wake only when it moved. Only the latest is kept, so + /// changes made faster than a connection sends them go out as one. + pub fn publish(&self, document_id: &str, revision: u64) { + let mut now = self.now(); + if now.as_ref().is_some_and(|(id, r)| id == document_id && *r == revision) { + return; + } + *now = Some((document_id.to_string(), revision)); + self.moved.notify_all(); + } + + /// Whether a connection is subscribed: the window publishes only then. + pub fn subscribed(&self) -> bool { + self.subscribers.load(Ordering::Relaxed) > 0 + } + + /// Count a subscribed connection until the returned guard is dropped. + pub fn join(&'static self) -> Subscriber { + self.subscribers.fetch_add(1, Ordering::Relaxed); + Subscriber(self) + } + + /// Wait up to `wait` for the design to differ from `seen`, or for `stop`; the design then + /// (`None` before anything was published). + pub fn wait(&self, seen: &(String, u64), stop: &AtomicBool, wait: Duration) -> Option<(String, u64)> { + let unmoved = |now: &mut Option<(String, u64)>| now.as_ref() == Some(seen) && !stop.load(Ordering::Relaxed); + let (now, _) = self.moved.wait_timeout_while(self.now(), wait, unmoved).unwrap_or_else(PoisonError::into_inner); + now.clone() + } +} + +/// A subscribed connection, counted by its [`DocumentWatch`] while this lives. +pub struct Subscriber(&'static DocumentWatch); + +impl Drop for Subscriber { + fn drop(&mut self) { + self.0.subscribers.fetch_sub(1, Ordering::Relaxed); + // Under the lock, so a connection about to wait sees its `stop` set before it does. + let _now = self.0.now(); + self.0.moved.notify_all(); + } +} diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs new file mode 100644 index 0000000000..85664a1aa9 --- /dev/null +++ b/crates/control/src/server.rs @@ -0,0 +1,1433 @@ +//! The loopback JSON-lines control server: one request per line, one reply per line, behind the +//! launch's token (docs/control-protocol.md). Agents and tests drive an app through it (adapted +//! from CADCraft, MIT OR Apache-2.0). What the app's requests mean is the app's [`Protocol`]; the +//! window answers them from the [`ControlRequest`]s it is sent. + +use std::io::{BufRead, BufReader, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use crate::Effect; +use crate::auth::tokens_match; +use crate::cancel::{Cancel, Ticket}; +use crate::request::{ControlRequest, DOCUMENT_WATCH, DocumentWatch, Subscriber}; + +/// What the server needs to know of a request before it sends it to the window: how to name it +/// in messages, what it does if it outlasts its wait, and what `control.running` shows of it. +#[derive(Clone, Debug)] +pub struct Summary { + /// The request in messages ("`engine.execute` (solid.fillet)"). + pub what: String, + /// What it still does when it finishes after its wait. + pub effect: Effect, + /// The command it runs, for `control.running` (never its parameters). + pub command: Option<&'static str>, + /// The number of steps it runs, for `control.running`. + pub steps: Option, + /// It may take as long as a batch. + pub long: bool, +} + +/// What an app's requests mean to its control server. +pub trait Protocol: Send + Sync { + fn summary(&self, method: &str, params: &Value) -> Summary; + /// What the app calls its document in messages ("design"). + fn document(&self) -> &'static str; + /// The event a subscribed connection is sent when the document moves ("design.changed"). + fn change_event(&self) -> &'static str; + /// The method that answers the document's id and revision now ("document.revision"). + fn revision_method(&self) -> &'static str; + /// Where a client reads how to talk to the channel, named when its token is refused + /// ("docs/control-protocol.md"). + fn docs(&self) -> &'static str; + /// The `control.capabilities` result: what this app's channel does beyond the methods every + /// version has, for a client to find out before it relies on it (an older app answers + /// `control.capabilities` with "unknown method"). + fn capabilities(&self) -> Value; +} + +/// An app's control server: its [`Protocol`], how it wakes the window for a request, and the +/// requests every connection of its listeners has the window running (`control.running`). +pub struct Hub { + protocol: Box, + wake: Box, + /// Longest request line accepted. + max_line: usize, + waits: Waits, + watch: &'static DocumentWatch, + running: Arc, + open: AtomicUsize, +} + +impl Hub { + /// A server for `protocol`'s requests; `wake` makes the window look at its requests now. + pub fn new(protocol: impl Protocol + 'static, wake: impl Fn() + Send + Sync + 'static, max_line: usize) -> Self { + Hub { + protocol: Box::new(protocol), + wake: Box::new(wake), + max_line, + waits: Waits::default(), + watch: &DOCUMENT_WATCH, + running: Arc::new(Running::new()), + open: AtomicUsize::new(0), + } + } + + /// Other waits (tests). + pub fn with_waits(mut self, waits: Waits) -> Self { + self.waits = waits; + self + } + + /// Another document watch than the app's [`DOCUMENT_WATCH`] (tests). + pub fn with_watch(mut self, watch: &'static DocumentWatch) -> Self { + self.watch = watch; + self + } + + /// Serve `listener` with `token` on threads of their own, at most [`MAX_CONNECTIONS`] + /// connections at once. `patient`: every request may wait as long as a batch (a person decides + /// on it). A listener that is not on a loopback address is refused: the channel never goes on + /// the network. + pub fn listen(self: &Arc, listener: TcpListener, token: String, requests: Sender, patient: bool) -> std::io::Result<()> { + self.listen_stoppable(listener, token, requests, patient).map(drop) + } + + /// [`Hub::listen`], and a [`Stop`] that closes the listener and the connections it accepted + /// (a channel turned off in the app's settings). Dropping the [`Stop`] leaves it serving. + pub fn listen_stoppable( + self: &Arc, + listener: TcpListener, + token: String, + requests: Sender, + patient: bool, + ) -> std::io::Result { + let addr = listener.local_addr()?; + if !addr.ip().is_loopback() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("the control channel listens on loopback only, not {addr}"))); + } + let hub = Arc::clone(self); + let token = Arc::new(token); + let shared = Arc::new(Accepted::default()); + let (closed_tx, closed) = channel::<()>(); + let stop = Stop { addr, shared: Arc::clone(&shared), closed }; + std::thread::spawn(move || { + // Dropped when this thread ends, with the listener: `Stop::stop` waits for that. + let _closed = closed_tx; + for stream in listener.incoming().flatten() { + if shared.stopped.load(Ordering::SeqCst) { + break; + } + if hub.open.fetch_add(1, Ordering::Relaxed) >= MAX_CONNECTIONS { + hub.open.fetch_sub(1, Ordering::Relaxed); + let mut refused = stream; + let _ = send(&mut refused, &json!({"ok": false, "error": "too many connections"})); + continue; + } + let id = shared.next.fetch_add(1, Ordering::Relaxed); + if let Ok(copy) = stream.try_clone() { + shared.lock().push((id, copy)); + } + // Stopped while this one was being accepted: it is closed with the rest. + if shared.stopped.load(Ordering::SeqCst) { + shared.close_all(); + } + let (hub, tx, token, shared) = (Arc::clone(&hub), requests.clone(), Arc::clone(&token), Arc::clone(&shared)); + std::thread::spawn(move || { + hub.serve(stream, &token, tx, patient); + hub.open.fetch_sub(1, Ordering::Relaxed); + shared.lock().retain(|(i, _)| *i != id); + }); + } + // A captured value drops after the body's locals, so without this `_closed` would tell + // `Stop::stop` the port is free while the listener still holds it (#14752). + drop(listener); + }); + Ok(stop) + } +} + +/// The connections a stoppable listener accepted, so stopping it can close them too. +#[derive(Default)] +struct Accepted { + stopped: AtomicBool, + next: AtomicU64, + streams: Mutex>, +} + +impl Accepted { + fn lock(&self) -> MutexGuard<'_, Vec<(u64, TcpStream)>> { + self.streams.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn close_all(&self) { + for (_, stream) in self.lock().drain(..) { + let _ = stream.shutdown(std::net::Shutdown::Both); + } + } +} + +/// Stops a listener started with [`Hub::listen_stoppable`]. +pub struct Stop { + addr: std::net::SocketAddr, + shared: Arc, + closed: Receiver<()>, +} + +impl Stop { + /// The port the listener is on. + pub fn port(&self) -> u16 { + self.addr.port() + } + + /// Stop accepting, close the port and end every connection it accepted. Returns once the + /// port is closed (at most a couple of seconds), so the same port can be bound again at once. + pub fn stop(self) { + self.shared.stopped.store(true, Ordering::SeqCst); + // The listener waits in `accept`: a connection of our own wakes it to see the flag. + let _ = TcpStream::connect_timeout(&self.addr, Duration::from_secs(1)); + let _ = self.closed.recv_timeout(Duration::from_secs(2)); + self.shared.close_all(); + } +} + +/// Connections served at once, so a flood must not be able to spawn threads without end. +pub const MAX_CONNECTIONS: usize = 16; +/// Lines that are not JSON before the connection is closed, so garbage cannot loop forever. +const MAX_BAD_LINES: usize = 8; +/// How long a subscribed connection waits after a `design.changed` line before the next: what +/// changes meanwhile (a parameter dragged) goes out as one line, the latest (#6985). +const EVENT_GAP: Duration = Duration::from_millis(100); +/// How long a new connection has to show the token. A client connects when it has a request to +/// send, so this is plenty; one that doesn't send it loses the connection, and its seat among +/// [`MAX_CONNECTIONS`] goes to someone else. +const TOKEN_WAIT: Duration = Duration::from_secs(5); + +/// A new random token: 32 bytes from the operating system, as hex. +pub fn new_token() -> Option { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).ok()?; + Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} + +/// One line without its newline, or `None` at the end of the stream. A client that sends +/// gigabytes with no newline would otherwise make this thread allocate until the process is +/// killed, so the line is refused as soon as it passes `max`. +fn read_line(r: &mut impl BufRead, max: usize) -> std::io::Result>> { + let mut line = Vec::new(); + loop { + let (done, used) = { + let available = r.fill_buf()?; + if available.is_empty() { + return Ok((!line.is_empty()).then_some(line)); + } + match available.iter().position(|b| *b == b'\n') { + Some(i) => { + line.extend_from_slice(available.get(..i).unwrap_or(&[])); + (true, i + 1) + } + None => { + line.extend_from_slice(available); + (false, available.len()) + } + } + }; + r.consume(used); + if done { + return Ok(Some(line)); + } + if line.len() > max { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "request too large")); + } + } +} + +/// A reply line, written to the socket at once. `writeln!` with a JSON value hands the socket each +/// of its pieces apart, a system call for every string, number and comma: half a second for a +/// design's component tree when it has thousands of components. +fn send(out: &mut impl Write, reply: &Value) -> std::io::Result<()> { + let mut line = serde_json::to_vec(reply).map_err(std::io::Error::other)?; + line.push(b'\n'); + out.write_all(&line) +} + +/// The `"token"` of a request line that is a JSON object, read without building the rest of it. +/// Until a connection shows the token, a line costs only its own bytes: parsed whole, a 16 MiB +/// line of `[0,0,…]` is hundreds of MB, and 16 such connections could exhaust memory before any +/// token was checked. +fn token_of(line: &str) -> Option { + struct Token; + impl<'de> serde::de::Visitor<'de> for Token { + type Value = Option; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a request object") + } + fn visit_map>(self, mut map: A) -> Result { + let mut token = None; + while let Some(key) = map.next_key::()? { + if key == "token" { + token = Some(map.next_value::()?); + } else { + map.next_value::()?; + } + } + Ok(token) + } + } + let mut de = serde_json::Deserializer::from_str(line); + let token = serde::Deserializer::deserialize_map(&mut de, Token).ok()?; + de.end().ok()?; + token +} + +/// The reply to a connection that didn't show the token, naming the app's `docs`; the +/// connection is then closed. +fn unauthorized(docs: &str) -> Value { + json!({"ok": false, "error": format!("unauthorized: send the control token as \"token\" (see {docs})")}) +} + +/// Refuse the connection: the reply, then the end of what we send, then what the client had +/// already sent read and dropped (a little, briefly). Closing a socket with unread input resets +/// the connection, and a reset can reach the client before it has read the refusal. +fn refuse(out: &mut TcpStream, reader: &mut BufReader, docs: &str) { + use std::io::Read; + let _ = send(out, &unauthorized(docs)); + let _ = out.shutdown(std::net::Shutdown::Write); + reader.get_mut().deadline = Some(Instant::now() + Duration::from_millis(500)); + let _ = std::io::copy(&mut reader.by_ref().take(64 * 1024), &mut std::io::sink()); +} + +/// What a client sends. Until it shows the token, all of its reads share one deadline, so neither +/// blank lines nor a line sent a byte at a time buy it more time. After that it may stay idle as +/// long as it likes. +struct ClientInput { + socket: TcpStream, + deadline: Option, +} + +impl ClientInput { + /// No deadline any more: the client showed the token. + fn admit(&mut self) -> std::io::Result<()> { + self.deadline = None; + self.socket.set_read_timeout(None) + } +} + +impl std::io::Read for ClientInput { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if let Some(deadline) = self.deadline { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.socket.set_read_timeout(Some(left))?; + } + self.socket.read(buf) + } +} + +/// How long a request waits for the app's reply: most requests, and a batch (or every request, +/// on a patient connection); and how long a new connection has to show the token. +#[derive(Clone, Copy, Debug)] +pub struct Waits { + pub short: Duration, + pub long: Duration, + pub token: Duration, +} + +impl Default for Waits { + fn default() -> Self { + Waits { short: Duration::from_secs(60), long: Duration::from_secs(3600), token: TOKEN_WAIT } + } +} + +/// A request that timed out but is still running in the app (#1618): its id and method, and where +/// its reply will land. +struct Pending { + id: Value, + method: String, + /// The request in messages ("`engine.execute` (solid.fillet)"). + what: String, + reply: Receiver, + /// Where it is in the app, to cancel it (`control.cancel`). + job: Arc, +} + +/// `control.cancel {id?}`: cancel the request this connection still waits for (the one +/// `control.pending` reports; `id`, when given, must name it). A connection can only cancel its +/// own requests. Waiting its turn, it is removed; computing off the window thread, it is stopped +/// as the app's Stop stops it. Either way nothing of it is applied and the connection is free. +/// One that runs on the window thread can't be cancelled; one that finished is answered. +fn cancel(pending: &mut Option, late: Option, id: Option<&Value>, document: &str) -> Value { + let id = id.filter(|v| !v.is_null()); + let mine = pending.as_ref().filter(|p| id.is_none_or(|id| *id == p.id)); + let Some(p) = mine else { + return match id { + None => json!({"ok": true, "result": {"cancelled": null, "note": "nothing to cancel: no request of this connection is running"}}), + Some(id) => json!({"ok": false, "error": format!( + "nothing to cancel: request {} is not running on this connection (a connection can only cancel its own requests)", + id.to_string().chars().take(64).collect::() + )}), + }; + }; + let (what, id) = (format!("request {} ({})", p.id, p.what), p.id.clone()); + let finished = |p: Pending, reply: Value| { + json!({"ok": true, "result": {"cancelled": null, "pending": p.id, "method": p.method, "done": true, "reply": reply, + "note": format!("nothing to cancel: {what} had already finished; its reply is here")}}) + }; + if let Some(reply) = late { + return pending.take().map_or(Value::Null, |p| finished(p, reply)); + } + let outcome = p.job.cancel(); + let note = match outcome { + Cancel::Removed => format!("cancelled: {what} was still waiting its turn and will not run; nothing was applied"), + Cancel::Stopped { writes_file: false } => format!("stopped: {what} was computing off the window thread; nothing was applied"), + Cancel::Stopped { writes_file: true } => { + format!("stopped: {what} was computing on a copy of the {document}, which is unchanged; its worker may still write the file") + } + Cancel::Already => format!("{what} was already cancelled or stopped; nothing of it was applied"), + Cancel::Running => { + // It may have just finished. + if let Some(reply) = pending.as_ref().and_then(|p| p.reply.try_recv().ok()) { + return pending.take().map_or(Value::Null, |p| finished(p, reply)); + } + return json!({"ok": false, "cancellable": false, "error": format!( + "cannot be cancelled: {what} already runs in the app (on its window thread, or as a file it opens) and will \ + still finish; ask `control.pending` for its result. Only a request still waiting its turn, or a change or \ + export computing off the window thread, can be cancelled" + )}); + } + }; + let method = pending.take().map(|p| p.method); + let how = match outcome { + Cancel::Removed => "removed", + Cancel::Stopped { .. } => "stopped", + _ => "already", + }; + json!({"ok": true, "result": {"cancelled": id, "method": method, "outcome": how, "note": note}}) +} + +/// Every request the app has been sent and not answered yet, from every connection, for +/// `control.running` (#3654). Each connection's own thread answers that, so it never waits behind +/// a running request. +struct Running { + list: Mutex>, + connections: AtomicU64, + keys: AtomicU64, +} + +/// What `control.running` says about a request: never its parameters beyond the command id. +struct InFlight { + key: u64, + connection: u64, + id: Value, + method: String, + command: Option<&'static str>, + steps: Option, + since: Instant, + started: Arc, +} + +impl Running { + fn new() -> Self { + Running { list: Mutex::new(Vec::new()), connections: AtomicU64::new(0), keys: AtomicU64::new(0) } + } + + fn lock(&self) -> MutexGuard<'_, Vec> { + self.list.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// List `req`, sent on `connection`, until the returned ticket is dropped; `command` and + /// `steps` as the app's [`Protocol`] summarised it. + fn add(self: &Arc, connection: u64, id: &Value, req: &ControlRequest, command: Option<&'static str>, steps: Option) -> Listing { + let key = self.keys.fetch_add(1, Ordering::Relaxed); + // Ids and methods come from the client: only short ones are repeated to the others. + let id = match id { + Value::Number(_) => id.clone(), + Value::String(s) if s.len() <= 64 => id.clone(), + _ => Value::Null, + }; + let method = req.method.chars().take(64).collect(); + let started = req.started.clone(); + self.lock().push(InFlight { key, connection, id, method, command, steps, since: Instant::now(), started }); + Listing { running: Arc::clone(self), key } + } + + /// The `control.running` result, as `asker`'s connection sees it. + fn result(&self, asker: u64) -> Value { + let rows: Vec = self + .lock() + .iter() + .map(|e| { + let mut r = json!({ + "connection": e.connection, + "id": e.id, + "method": e.method, + "running_s": (e.since.elapsed().as_secs_f64() * 10.0).round() / 10.0, + "queued": !e.started.load(Ordering::Relaxed), + }); + if let Some(c) = e.command { + r["command"] = json!(c); + } + if let Some(n) = e.steps { + r["steps"] = json!(n); + } + if e.connection == asker { + r["self"] = json!(true); + } + r + }) + .collect(); + json!({"running": rows}) + } +} + +/// A listed request; dropped when its reply arrives. +struct Listing { + running: Arc, + key: u64, +} + +impl Drop for Listing { + fn drop(&mut self) { + let key = self.key; + self.running.lock().retain(|e| e.key != key); + } +} + +/// The reply to a timed-out request, received on a thread of its own so the request stays listed +/// until the app answers, also once its connection has closed (#3654). +fn watch(reply: Receiver, ticket: Listing) -> Receiver { + let (late_tx, late_rx) = channel(); + // A small thread per timed-out request (each connection has at most one). If none can be + // made, the reply is lost and `control.pending` says the app ended the request without one. + // The reply is passed on before the request leaves the list: once `control.running` no longer + // shows it, its connection's `control.pending` has it. + let _ = std::thread::Builder::new().stack_size(64 * 1024).spawn(move || { + if let Ok(v) = reply.recv() { + let _ = late_tx.send(v); + } + drop(late_tx); + drop(ticket); + }); + late_rx +} + +/// The reply text for a request that outlasts its wait. A request that only reads changes +/// nothing when it finishes; an export or a save still writes its file, and any other request +/// still applies, as it was not cancelled. +pub fn timeout_message(what: &str, effect: Effect, document: &str) -> String { + match effect { + Effect::ReadsOnly => { + format!("timeout: {what} is still running in the app ({}); ask `control.pending` for its answer", effect.when_done(document)) + } + Effect::WritesFile => format!( + "timeout: {what} is still running in the app and will still write the file when it finishes (it was not cancelled: \ + don't send it again; the {document} does not change); ask `control.pending` for its result, or `control.cancel` to \ + cancel it" + ), + Effect::Changes => format!( + "timeout: {what} is still running in the app and will still apply when it finishes (it was not cancelled: don't send it \ + again); ask `control.pending` for its result, or `control.cancel` to cancel it" + ), + } +} + +/// The reply text for a request refused because an earlier one on the connection still runs. +fn busy_message(p: &Pending, method: &str) -> String { + let method: String = method.chars().take(128).collect(); + format!( + "busy: request {} ({}) is still running, so `{method}` was not run; ask `control.pending` for that request's result, then \ + send this one again", + p.id, p.what + ) +} + +/// A subscribed connection's socket, for its replies and its events: each line is written whole +/// and alone, so an event never lands inside a reply (#6985). +struct Lines { + socket: TcpStream, + turn: Mutex<()>, +} + +impl Lines { + fn send(&self, line: &Value) -> std::io::Result<()> { + let _turn = self.turn.lock().unwrap_or_else(PoisonError::into_inner); + send(&mut &self.socket, line) + } +} + +/// A subscribed connection's seat on the watch: it leaves exactly once, whichever thread sees +/// the connection's end first — the connection's own thread at the end of the stream, or the +/// events thread at the first write a closed client refuses. The seat used to wait for the +/// events thread alone, and that thread only leaves its wait when the design moves, so the +/// count could outlive the connection by a second or more (#8315). +struct Seat(Mutex>); + +impl Seat { + fn new(counted: Subscriber) -> Self { + Seat(Mutex::new(Some(counted))) + } + + /// Leave the watch now: the seat goes once, whoever gets here first. + fn release(&self) { + let counted = self.0.lock().unwrap_or_else(PoisonError::into_inner).take(); + drop(counted); + } +} + +impl Drop for Seat { + fn drop(&mut self) { + self.release(); + } +} + +/// A connection's `control.subscribe` (#6985): its `design.changed` lines, sent from a thread of +/// their own until the connection ends. +struct Subscription { + lines: Arc, + stop: Arc, + seat: Arc, +} + +impl Subscription { + /// Write `reply`, the window's answer to `control.subscribe` naming the design `seen`, on + /// `out`, then send `design`'s changes after it: the reply goes out before any event. `None`, + /// with nothing written, when no thread or socket was left for the events. + fn start( + watch: &'static DocumentWatch, + event: &'static str, + counted: Subscriber, + out: &TcpStream, + seen: (String, u64), + reply: &Value, + ) -> Option<(Self, std::io::Result<()>)> { + let lines = Arc::new(Lines { socket: out.try_clone().ok()?, turn: Mutex::new(()) }); + let stop = Arc::new(AtomicBool::new(false)); + let seat = Arc::new(Seat::new(counted)); + let first = lines.turn.lock().unwrap_or_else(PoisonError::into_inner); + let (l, s, watch_seat) = (lines.clone(), stop.clone(), Arc::clone(&seat)); + // The connection's seat on the watch rides the events thread: it leaves when the thread + // does, so the next failed write to a closed client retires it even while the connection's + // own thread is slow to see the end of the stream (#7226). The connection's own thread + // leaves it too, so a closed connection stops counting at once (#8315). + std::thread::Builder::new().stack_size(64 * 1024).spawn(move || send_events(watch, event, &l, &s, seen, watch_seat)).ok()?; + let sent = send(&mut &lines.socket, reply); + drop(first); + Some((Subscription { lines, stop, seat }, sent)) + } +} + +/// The design a `control.subscribe` reply names. +fn document_of(reply: &Value) -> Option<(String, u64)> { + let result = reply.get("result")?; + Some((result.get("document_id")?.as_str()?.to_string(), result.get("revision")?.as_u64()?)) +} + +impl Drop for Subscription { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + // The seat on the watch goes now: the connection is over, and nothing counts it any more + // (#8315). + self.seat.release(); + // The socket closes now, not when the thread next looks; a line blocked on a client that + // stopped reading ends too. + let _ = self.lines.socket.shutdown(std::net::Shutdown::Both); + } +} + +/// The `design.changed` lines of a subscribed connection, each time the design differs from the +/// last one it was told of (`seen`), until `stop`. Holds the connection's seat on the watch +/// (`seat`), which it leaves when the thread ends: on `stop`, or on the first write a closed +/// client refuses (#7226). +fn send_events(watch: &DocumentWatch, event: &str, lines: &Lines, stop: &AtomicBool, mut seen: (String, u64), seat: Arc) { + while !stop.load(Ordering::Relaxed) { + let Some(now) = watch.wait(&seen, stop, Duration::from_secs(1)).filter(|now| *now != seen) else { continue }; + if lines.send(&json!({"event": event, "params": {"document_id": now.0, "revision": now.1}})).is_err() { + break; + } + seen = now; + std::thread::sleep(EVENT_GAP); + } + // The client is gone: it is not counted on the watch any more, whatever the connection's own + // thread still has to notice (#8315). + seat.release(); +} + +/// Write `reply` on the connection: through its subscription once it has one. +fn answer(out: &mut TcpStream, events: Option<&Subscription>, reply: &Value) -> std::io::Result<()> { + match events { + Some(e) => e.lines.send(reply), + None => send(out, reply), + } +} + +impl Hub { + /// Serve one connection until it closes: the token first, then one request per line, each + /// sent to the window on `requests` and its reply written back. + pub fn serve(&self, stream: TcpStream, token: &str, requests: Sender, patient: bool) { + let (waits, running, documents, tx) = (self.waits, &self.running, self.watch, requests); + let connection = running.connections.fetch_add(1, Ordering::Relaxed) + 1; + let Ok(read) = stream.try_clone() else { return }; + let mut out = stream; + let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(Instant::now() + waits.token) }); + let mut bad = 0usize; + let mut authenticated = false; + let mut pending: Option = None; + let mut events: Option = None; + loop { + // A first `control.subscribe` on its way to the window (#6985). + let mut joining = None; + let line = match read_line(&mut reader, self.max_line) { + Ok(Some(l)) => String::from_utf8_lossy(&l).into_owned(), + Ok(None) => break, + // Closed without a word: a client that connected early and only now sends its first + // request would read a line here as the reply to it. It finds the connection closed + // and opens another. + Err(e) if !authenticated && matches!(e.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock) => break, + Err(e) => { + let _ = answer(&mut out, events.as_ref(), &json!({"ok": false, "error": e.to_string()})); + break; + } + }; + if line.trim().is_empty() { + continue; + } + // The first request must carry the token; later ones on the same connection may. + if !authenticated { + match token_of(&line) { + Some(t) if tokens_match(&t, token) => { + if reader.get_mut().admit().is_err() { + break; + } + authenticated = true; + } + _ => { + refuse(&mut out, &mut reader, self.protocol.docs()); + break; + } + } + } + let reply = match serde_json::from_str::(&line) { + Ok(msg) => { + let id = msg.get("id").cloned().unwrap_or(Value::Null); + let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string(); + let params = msg.get("params").cloned().unwrap_or(json!({})); + // A request that timed out may have finished since (#1618). `control.running` and + // `control.capabilities` only look, so they leave that reply where it is. + let late = pending.as_ref().filter(|_| !matches!(method.as_str(), "control.running" | "control.capabilities")).and_then(|p| { + match p.reply.try_recv() { + Ok(reply) => Some(reply), + Err(TryRecvError::Disconnected) => Some(json!({"ok": false, "error": "the app ended the request without a reply"})), + Err(TryRecvError::Empty) => None, + } + }); + let mut r = if method == "control.running" { + json!({"ok": true, "result": running.result(connection)}) + } else if method == "control.capabilities" { + json!({"ok": true, "result": self.protocol.capabilities()}) + } else if method == "control.cancel" { + let r = cancel(&mut pending, late, params.get("id"), self.protocol.document()); + (self.wake)(); + r + } else if method == "control.pending" { + match (pending.take(), late) { + (None, _) => json!({"ok": true, "result": {"pending": null}}), + (Some(p), Some(reply)) => { + json!({"ok": true, "result": {"pending": p.id, "method": p.method, "done": true, "reply": reply}}) + } + (Some(p), None) => { + let r = json!({"ok": true, "result": {"pending": p.id, "method": p.method, "done": false}}); + pending = Some(p); + r + } + } + } else if let Some(p) = pending.as_ref().filter(|_| late.is_none()) { + // Nothing more is queued behind it, to run unseen when it ends. + json!({"ok": false, "busy": true, "error": busy_message(p, &method)}) + } else if method == "control.subscribe" && events.is_some() { + if late.is_some() { + // As below: finished, and the client moved on without asking. + pending = None; + } + // Its events already say how the design moves; a second answer could only + // arrive behind a newer one. + { + let (event, revision, document) = + (self.protocol.change_event(), self.protocol.revision_method(), self.protocol.document()); + json!({"ok": false, "error": format!("already subscribed: this connection is sent {event} lines; ask {revision} for the {document} now")}) + } + } else { + if late.is_some() { + // Finished, and the client moved on without asking: it is dropped. + pending = None; + } + // A batch replaces many short requests: the whole of it may take long (#743). + let Summary { what, effect, command, steps, long } = self.protocol.summary(&method, ¶ms); + let wait = if patient || long { waits.long } else { waits.short }; + // Counted before the window answers, so it publishes every change from its + // answer on. + joining = (method == "control.subscribe").then(|| documents.join()); + let (req, rrx) = ControlRequest::new(method.clone(), params); + let job = Arc::clone(&req.ticket); + let ticket = running.add(connection, &id, &req, command, steps); + if tx.send(req).is_err() { + break; + } + (self.wake)(); + match rrx.recv_timeout(wait) { + Ok(r) => r, + Err(_) => { + let r = json!({"ok": false, "running": true, "error": timeout_message(&what, effect, self.protocol.document())}); + pending = Some(Pending { id: id.clone(), method, what, reply: watch(rrx, ticket), job }); + r + } + } + }; + if let Some(o) = r.as_object_mut() { + o.insert("id".into(), id); + } + r + } + Err(e) => { + bad += 1; + json!({"ok": false, "error": format!("bad JSON: {e}")}) + } + }; + // Subscribed once the window named the design (not when it refused or timed out). + let sent = match joining.zip(document_of(&reply)) { + Some((counted, seen)) => match Subscription::start(documents, self.protocol.change_event(), counted, &out, seen, &reply) { + Some((subscription, sent)) => { + events = Some(subscription); + sent + } + None => send( + &mut out, + &json!({"id": reply.get("id"), "ok": false, "error": "not subscribed: no thread or socket left for the events"}), + ), + }, + None => answer(&mut out, events.as_ref(), &reply), + }; + if sent.is_err() { + break; + } + if bad >= MAX_BAD_LINES { + break; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The longest request line, as an app might accept. + const MAX_LINE: usize = 16 << 20; + + /// An app whose requests all may change its document and take the short wait. + struct Plain; + + impl Protocol for Plain { + fn summary(&self, method: &str, _: &Value) -> Summary { + Summary { what: format!("`{method}`"), effect: Effect::Changes, command: None, steps: None, long: false } + } + fn document(&self) -> &'static str { + "design" + } + fn change_event(&self) -> &'static str { + "design.changed" + } + fn revision_method(&self) -> &'static str { + "document.revision" + } + fn docs(&self) -> &'static str { + "docs/control-protocol.md" + } + fn capabilities(&self) -> Value { + json!({}) + } + } + + /// A server for [`Plain`] with these waits and this document watch. + fn hub(waits: Waits, watch: &'static DocumentWatch) -> Arc { + Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_watch(watch)) + } + + /// The channel never goes on the network: a listener on any address but loopback is refused, + /// and nothing is served on it. + #[test] + fn a_listener_off_loopback_is_refused() { + let (tx, _rx) = channel::(); + let open = TcpListener::bind("0.0.0.0:0").unwrap(); + let e = hub(Waits::default(), &DOCUMENT_WATCH).listen(open, "0123456789abcdef0123456789abcdef".into(), tx.clone(), false).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{e}"); + assert!(e.to_string().contains("loopback only"), "{e}"); + let local = TcpListener::bind("127.0.0.1:0").unwrap(); + assert!(hub(Waits::default(), &DOCUMENT_WATCH).listen(local, "0123456789abcdef0123456789abcdef".into(), tx, false).is_ok()); + } + + /// A connection that doesn't show the token in time is closed without a word, however it fills + /// the time. One that does keeps working when it idles for longer than that. + #[test] + fn the_token_has_a_time_limit_and_an_authenticated_client_may_idle() { + use std::io::Read; + let token = "0123456789abcdef0123456789abcdef"; + let limit = Duration::from_millis(500); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + let waits = Waits { short: Duration::from_secs(10), long: Duration::from_secs(10), token: limit }; + let hub = hub(waits, &DOCUMENT_WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let open = || { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + s + }; + // Sends `drip` every 50 ms until the server closes; what it read, and when it closed. + let closed_after = |drip: &[u8]| { + let mut s = open(); + let start = Instant::now(); + s.set_read_timeout(Some(Duration::from_millis(50))).unwrap(); + let mut got = Vec::new(); + loop { + let mut buf = [0u8; 256]; + match s.read(&mut buf) { + Ok(0) => break, + Ok(n) => got.extend_from_slice(buf.get(..n).unwrap()), + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { + assert!(start.elapsed() < Duration::from_secs(20), "still open"); + let _ = s.write_all(drip); + } + Err(_) => break, + } + } + (got, start.elapsed()) + }; + for drip in [&b""[..], b"\n", b"\r\n \n", b" ", b"{"] { + let (got, took) = closed_after(drip); + assert!(got.is_empty(), "{drip:?} was answered: {}", String::from_utf8_lossy(&got)); + assert!(took >= limit.saturating_sub(Duration::from_millis(50)), "{drip:?} closed after {took:?}"); + } + + let mut s = open(); + let mut lines = BufReader::new(s.try_clone().unwrap()); + let mut ask = |line: Value| -> Value { + writeln!(s, "{line}").unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + assert_eq!(ask(json!({"id": 1, "method": "ui.view", "token": token}))["ok"], true); + std::thread::sleep(limit * 3); + assert_eq!(ask(json!({"id": 2, "method": "ui.view"}))["ok"], true, "idle for longer than the limit"); + + // A wrong token is still answered, at once. + let mut wrong = open(); + writeln!(wrong, "{}", json!({"id": 1, "method": "ui.view", "token": "nope"})).unwrap(); + let mut l = String::new(); + BufReader::new(wrong).read_line(&mut l).unwrap(); + assert!(l.contains("unauthorized"), "{l}"); + } + + /// #1989: `control.cancel` cancels the connection's own outstanding request. One still + /// waiting its turn is removed and never runs, and the connection is free at once; one that + /// already runs in the app can't be, and says so; another connection's request is refused; + /// with nothing outstanding there is nothing to cancel. + #[test] + fn control_cancel_cancels_only_this_connections_request() { + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + let (gate_tx, gate_rx) = channel::<()>(); + let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let seen = ran.clone(); + // A stand-in for the window thread: `queued` waits behind the others (never taken until + // `slow` is done), `slow` runs until the gate opens. + std::thread::spawn(move || { + let mut held = Vec::new(); + for req in rx { + if req.method == "queued" { + held.push(req); + continue; + } + if !req.ticket.take() { + continue; + } + seen.lock().unwrap().push(req.method.clone()); + if req.method == "slow" { + let _ = gate_rx.recv(); + } + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + if req.method == "slow" { + for req in held.drain(..) { + if req.ticket.take() { + seen.lock().unwrap().push(req.method.clone()); + } + } + } + } + }); + let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; + let hub = hub(waits, &DOCUMENT_WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let connect = || { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let out = s.try_clone().unwrap(); + (out, BufReader::new(s)) + }; + let ask = |(out, lines): &mut (TcpStream, BufReader), v: Value| -> Value { + writeln!(out, "{v}").unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + let mut a = connect(); + let mut b = connect(); + let r = ask(&mut b, json!({"id": 1, "method": "control.cancel", "token": token})); + assert!(r["ok"] == true && r["result"]["cancelled"].is_null(), "nothing to cancel: {r}"); + + // Waiting its turn: removed, never run, and the connection is free. + let r = ask(&mut a, json!({"id": 1, "method": "queued", "token": token})); + assert_eq!(r["running"], true, "{r}"); + let r = ask(&mut a, json!({"id": 2, "method": "control.cancel", "params": {"id": 1}})); + assert_eq!((&r["ok"], &r["result"]["cancelled"], &r["result"]["outcome"]), (&json!(true), &json!(1), &json!("removed")), "{r}"); + assert!(r["result"]["note"].as_str().is_some_and(|n| n.contains("will not run")), "{r}"); + let r = ask(&mut a, json!({"id": 3, "method": "control.pending"})); + assert_eq!(r["result"]["pending"], Value::Null, "{r}"); + + // Already running in the app: it can't be, and it still answers. + let r = ask(&mut a, json!({"id": 4, "method": "slow"})); + assert_eq!(r["running"], true, "{r}"); + let r = ask(&mut b, json!({"id": 2, "method": "control.cancel", "params": {"id": 4}})); + assert!(r["ok"] == false && r["error"].as_str().is_some_and(|e| e.contains("its own requests")), "another connection's: {r}"); + let r = ask(&mut a, json!({"id": 5, "method": "control.cancel", "params": {"id": 99}})); + assert!(r["ok"] == false && r["error"].as_str().is_some_and(|e| e.starts_with("nothing to cancel")), "{r}"); + let r = ask(&mut a, json!({"id": 6, "method": "control.cancel"})); + assert!(r["ok"] == false && r["cancellable"] == false, "{r}"); + assert!(r["error"].as_str().is_some_and(|e| e.starts_with("cannot be cancelled") && e.contains("control.pending")), "{r}"); + gate_tx.send(()).unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + let r = loop { + let r = ask(&mut a, json!({"id": 7, "method": "control.pending"})); + if r["result"]["done"] == true || Instant::now() > deadline { + break r; + } + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!(r["result"]["reply"]["result"], "slow", "{r}"); + let r = ask(&mut a, json!({"id": 8, "method": "control.cancel"})); + assert!(r["ok"] == true && r["result"]["cancelled"].is_null(), "{r}"); + assert_eq!(*ran.lock().unwrap(), ["slow"], "the cancelled request never ran"); + } + + /// #1618: a request that outlasts its wait says it is still running; the connection keeps its + /// reply for `control.pending`, and refuses other requests as `busy` until it lands, so none + /// is queued to run unseen behind it. + #[test] + fn a_timed_out_request_can_be_asked_for_later() { + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + // The slow request is held until the test has seen it time out, so the test does not + // race the clock on a loaded machine. + let (gate_tx, gate_rx) = channel::<()>(); + let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let seen = ran.clone(); + std::thread::spawn(move || { + for req in rx { + seen.lock().unwrap().push(req.method.clone()); + if req.method == "slow" { + let _ = gate_rx.recv(); + } + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; + let hub = hub(waits, &DOCUMENT_WATCH); + std::thread::spawn(move || { + if let Some(stream) = listener.incoming().flatten().next() { + hub.serve(stream, token, tx, false); + } + }); + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut out = s.try_clone().unwrap(); + let mut lines = BufReader::new(s); + let mut ask = |v: Value| -> Value { + writeln!(out, "{v}").unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + let r = ask(json!({"id": 1, "method": "slow", "token": token})); + assert!(r["ok"] == false && r["running"] == true && r["error"].as_str().is_some_and(|e| e.starts_with("timeout")), "{r}"); + let r = ask(json!({"id": 2, "method": "ui.view"})); + assert!(r["busy"] == true && r["id"] == 2, "{r}"); + let r = ask(json!({"id": 3, "method": "control.pending"})); + assert_eq!((&r["result"]["pending"], &r["result"]["done"]), (&json!(1), &json!(false)), "{r}"); + gate_tx.send(()).unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + let r = loop { + let r = ask(json!({"id": 4, "method": "control.pending"})); + if r["result"]["done"] == true || std::time::Instant::now() > deadline { + break r; + } + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!( + (&r["result"]["pending"], &r["result"]["done"], &r["result"]["reply"]["result"]), + (&json!(1), &json!(true), &json!("slow")), + "{r}" + ); + let r = ask(json!({"id": 5, "method": "control.pending"})); + assert_eq!(r["result"]["pending"], Value::Null, "{r}"); + let r = ask(json!({"id": 6, "method": "ui.view"})); + assert_eq!((&r["ok"], &r["result"]), (&json!(true), &json!("ui.view")), "{r}"); + assert_eq!(*ran.lock().unwrap(), ["slow", "ui.view"], "the busy request never reached the app"); + } + + /// #6985: a connection that sends `control.subscribe` gets the design in the reply, then a + /// `design.changed` line each time the window publishes another: never before the reply, + /// none for the same design, the latest after a burst, each line whole between its replies. + /// A second subscribe is refused without reaching the window. A connection that did not + /// subscribe gets no events, and one that closed is no longer counted. + #[test] + fn subscribed_connections_are_told_of_design_changes() { + static WATCH: DocumentWatch = DocumentWatch::new(); + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + // The window: it answers `control.subscribe` as the app does, publishing the design first; + // then the design changes at once, before the reply may have been written. + std::thread::spawn(move || { + for req in rx { + if req.method == "control.subscribe" { + WATCH.publish("d-1", 3); + let _ = req.reply.send(json!({"ok": true, "result": {"document_id": "d-1", "revision": 3}})); + WATCH.publish("d-1", 4); + } else { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + } + }); + let hub = hub(Waits::default(), &WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let open = || { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + (s.try_clone().unwrap(), BufReader::new(s)) + }; + let next = |lines: &mut BufReader| -> Value { + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + let changed = |id: &str, revision: u64| json!({"event": "design.changed", "params": {"document_id": id, "revision": revision}}); + + let (mut quiet_out, mut quiet) = open(); + writeln!(quiet_out, "{}", json!({"id": 1, "method": "ui.view", "token": token})).unwrap(); + assert_eq!(next(&mut quiet)["id"], 1); + + let (mut out, mut lines) = open(); + writeln!(out, "{}", json!({"id": 1, "method": "control.subscribe", "token": token})).unwrap(); + assert_eq!(next(&mut lines), json!({"id": 1, "ok": true, "result": {"document_id": "d-1", "revision": 3}})); + assert_eq!(next(&mut lines), changed("d-1", 4), "the change after the window's answer comes after the reply"); + assert!(WATCH.subscribed()); + // The design it was told of is no news; another revision is. + WATCH.publish("d-1", 4); + WATCH.publish("d-1", 5); + assert_eq!(next(&mut lines), changed("d-1", 5)); + // A burst ends with its latest. + for revision in 6..=10 { + WATCH.publish("d-1", revision); + } + let mut last = 5; + while last < 10 { + let e = next(&mut lines); + let revision = e["params"]["revision"].as_u64().unwrap(); + assert!(e["event"] == "design.changed" && revision > last, "{e} after {last}"); + last = revision; + } + // Another tab: another id, whatever its revision. + WATCH.publish("d-2", 2); + assert_eq!(next(&mut lines), changed("d-2", 2)); + // Subscribed already: refused here (the window would have published d-1 again). + writeln!(out, "{}", json!({"id": 2, "method": "control.subscribe"})).unwrap(); + let r = next(&mut lines); + assert!(r["id"] == 2 && r["ok"] == false && r["error"].as_str().is_some_and(|e| e.starts_with("already subscribed")), "{r}"); + // Replies still come, whole, and nothing else was sent meanwhile. + writeln!(out, "{}", json!({"id": 3, "method": "ui.view"})).unwrap(); + assert_eq!(next(&mut lines), json!({"id": 3, "ok": true, "result": "ui.view"})); + writeln!(quiet_out, "{}", json!({"id": 2, "method": "ui.view"})).unwrap(); + assert_eq!(next(&mut quiet), json!({"id": 2, "ok": true, "result": "ui.view"}), "no events without subscribing"); + // Closed, it is no longer counted. Each publish asks the events thread for one more line, + // and its write to the closed connection is what retires the seat; that keeps the wait off + // the connection's own thread, which anything else this process is doing may hold up past + // the deadline (#7226). + drop((out, lines)); + let mut revision = 11; + let deadline = Instant::now() + Duration::from_secs(10); + while WATCH.subscribed() && Instant::now() < deadline { + WATCH.publish("d-1", revision); + revision += 1; + std::thread::sleep(Duration::from_millis(20)); + } + assert!(!WATCH.subscribed()); + } + + /// #8315: a closed connection leaves the watch at once. The seat of a subscribed connection + /// goes when the connection's own thread sees the end of the stream, not only when the + /// events thread notices: that thread waits for the design to move, so a connection that + /// closed while the design stood still kept the watch counting it for a second or more. + #[test] + fn a_closed_connection_leaves_the_watch_at_once() { + static WATCH: DocumentWatch = DocumentWatch::new(); + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + // The window names the design once and then leaves it alone: nothing moves it, so the + // events thread has nothing to write and only the end of the connection can retire it. + std::thread::spawn(move || { + for req in rx { + if req.method == "control.subscribe" { + WATCH.publish("d-1", 3); + let _ = req.reply.send(json!({"ok": true, "result": {"document_id": "d-1", "revision": 3}})); + } else { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + } + }); + let hub = hub(Waits::default(), &WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut out = s.try_clone().unwrap(); + let mut lines = BufReader::new(s); + writeln!(out, "{}", json!({"id": 1, "method": "control.subscribe", "token": token})).unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + let reply: Value = serde_json::from_str(&l).unwrap(); + assert!(reply["ok"] == true, "{reply}"); + assert!(WATCH.subscribed(), "the connection is subscribed"); + // Let the events thread settle into its wait: the design stands still, so it has nothing + // to write, and only the end of the connection can retire it. + std::thread::sleep(Duration::from_millis(200)); + // The client goes away without asking anything else. + drop((out, lines)); + let deadline = Instant::now() + Duration::from_millis(400); + while WATCH.subscribed() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(!WATCH.subscribed(), "a closed connection is not counted on the watch"); + } + + /// The token is read from a request object without building the rest of it: other fields, + /// however large or nested, are only skipped. Anything but an object with a string token is + /// no token. + #[test] + fn token_is_read_without_parsing_the_request() { + assert_eq!(token_of(r#"{"id":1,"token":"abc","params":{"a":[1,[2,{"b":null}]]}}"#).as_deref(), Some("abc")); + let flood = format!(r#"{{"params":[{}0],"token":"t"}}"#, "0,".repeat(1 << 20)); + assert_eq!(token_of(&flood).as_deref(), Some("t")); + for no in [r#"["abc"]"#, r#"{"token":5}"#, r#"{"token":"a"} x"#, r#"{"id":1}"#, "GET / HTTP/1.1", r#""token""#] { + assert_eq!(token_of(no), None, "{no}"); + } + } + + /// #205: a connection runs nothing until a request carries the launch's token; a wrong or + /// missing token, or garbage, is refused and the connection closed. Once shown, the token + /// need not be repeated on that connection. + #[test] + fn requests_run_only_after_the_token() { + use std::io::Read; + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let seen = ran.clone(); + std::thread::spawn(move || { + for req in rx { + seen.lock().unwrap().push(req.method.clone()); + let _ = req.reply.send(json!({"ok": true, "result": null})); + } + }); + let hub = hub(Waits::default(), &DOCUMENT_WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let session = |lines: &[String]| { + let mut s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + for l in lines { + let _ = writeln!(s, "{l}"); + } + let _ = s.shutdown(std::net::Shutdown::Write); + let mut text = String::new(); + let _ = s.read_to_string(&mut text); + text.lines().map(|l| serde_json::from_str::(l).unwrap()).collect::>() + }; + for first in [ + json!({"id": 1, "method": "app.quit", "params": {"force": true}}).to_string(), + json!({"id": 1, "method": "app.quit", "token": "0123456789abcdef0123456789abcdee"}).to_string(), + json!({"id": 1, "method": "app.quit", "token": "0123"}).to_string(), + json!({"id": 1, "method": "app.quit", "token": 7}).to_string(), + "not json".to_string(), + ] { + let replies = session(&[first.clone(), json!({"id": 2, "method": "app.quit", "token": token}).to_string()]); + assert_eq!(replies.len(), 1, "{first}: closed after refusing: {replies:?}"); + assert!(replies[0]["error"].as_str().is_some_and(|e| e.starts_with("unauthorized")), "{first}: {replies:?}"); + } + assert!(ran.lock().unwrap().is_empty(), "nothing ran without the token"); + let replies = session(&[ + json!({"id": 1, "method": "ui.inspect", "token": token}).to_string(), + json!({"id": 2, "method": "engine.commands"}).to_string(), + ]); + assert_eq!(replies.len(), 2, "{replies:?}"); + assert!(replies.iter().all(|r| r["ok"] == true), "{replies:?}"); + assert_eq!(*ran.lock().unwrap(), ["ui.inspect", "engine.commands"]); + } + + /// A request longer than the cap is refused instead of allocated. + #[test] + fn lines_past_the_cap_are_refused() { + let flood = vec![b'A'; MAX_LINE + 2]; + let mut r = BufReader::new(flood.as_slice()); + let e = read_line(&mut r, MAX_LINE).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + assert!(e.to_string().contains("request too large"), "{e}"); + } + + /// Ordinary framing: lines split on newlines, blank lines kept, no trailing newline needed. + #[test] + fn lines_split_on_newlines() { + let text = b"{\"a\":1}\n\n{\"b\":2}\nlast".to_vec(); + let mut r = BufReader::new(text.as_slice()); + let mut got = Vec::new(); + while let Some(line) = read_line(&mut r, MAX_LINE).unwrap() { + got.push(String::from_utf8(line).unwrap()); + } + assert_eq!(got, vec!["{\"a\":1}", "", "{\"b\":2}", "last"]); + assert!(read_line(&mut r, MAX_LINE).unwrap().is_none()); + } + + /// A line that spans several reads of the underlying stream still arrives whole. + #[test] + fn lines_longer_than_one_buffer_arrive_whole() { + let long = "x".repeat(200_000); + let text = format!("{long}\n{long}\n").into_bytes(); + let mut r = BufReader::with_capacity(64, text.as_slice()); + assert_eq!(read_line(&mut r, MAX_LINE).unwrap().unwrap().len(), long.len()); + assert_eq!(read_line(&mut r, MAX_LINE).unwrap().unwrap().len(), long.len()); + assert!(read_line(&mut r, MAX_LINE).unwrap().is_none()); + // The same line against a smaller cap is refused. + let mut r = BufReader::with_capacity(64, text.as_slice()); + assert!(read_line(&mut r, 1000).is_err()); + } + + /// A large reply reaches the socket in one write, not one per JSON piece (a component tree of + /// thousands of components took half a second to send), and reads back as it was. + #[test] + fn a_large_reply_is_written_at_once() { + struct Counted { + writes: usize, + bytes: Vec, + } + impl Write for Counted { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.writes += 1; + self.bytes.extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let components: Vec = (0..2000).map(|i| json!({"id": i, "name": format!("Part {i}"), "bodies": ["a", "b"], "parent": 0})).collect(); + let reply = json!({"ok": true, "id": 7, "result": {"components": components}}); + let mut out = Counted { writes: 0, bytes: Vec::new() }; + send(&mut out, &reply).unwrap(); + assert_eq!(out.writes, 1); + assert_eq!(out.bytes.last(), Some(&b'\n')); + assert_eq!(serde_json::from_slice::(&out.bytes).unwrap(), reply); + } + + /// A stopped listener frees its port at once and ends the connections it had, so a channel + /// turned off in the settings leaves nothing listening and can be turned on again on the + /// same port. + #[test] + fn a_stopped_listener_closes_its_port_and_its_connections() { + use std::io::Read; + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + let (tx, _rx) = channel(); + let stop = hub(Waits::default(), &DOCUMENT_WATCH).listen_stoppable(listener, "0123456789abcdef0123456789abcdef".into(), tx, false).unwrap(); + assert_eq!(stop.port(), port); + let mut client = TcpStream::connect(("127.0.0.1", port)).unwrap(); + client.set_read_timeout(Some(Duration::from_secs(4))).unwrap(); + // Wait until the server holds the connection, so stopping has one to close. + let held = Instant::now(); + while stop.shared.lock().is_empty() && held.elapsed() < Duration::from_secs(4) { + std::thread::sleep(Duration::from_millis(5)); + } + let started = Instant::now(); + stop.stop(); + let mut byte = [0u8; 1]; + match client.read(&mut byte) { + Ok(n) => assert_eq!(n, 0, "the connection ends"), + Err(e) => { + assert!(!matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), "the connection ends, not waits: {e}") + } + } + assert!(started.elapsed() < Duration::from_secs(3), "before the token wait runs out"); + // The listener thread closes its socket when it notices the stop; on a loaded machine that can + // take a moment after `stop()` returns. Wait for the port to be free, not for one instant. + let freed = Instant::now(); + let mut bound = TcpListener::bind(("127.0.0.1", port)); + while bound.is_err() && freed.elapsed() < Duration::from_secs(2) { + std::thread::sleep(Duration::from_millis(10)); + bound = TcpListener::bind(("127.0.0.1", port)); + } + assert!(bound.is_ok(), "the port is free again: {:?}", bound.err()); + } +} diff --git a/crates/csv/README.md b/crates/csv/README.md index 6369ce8b47..bfd525c8cf 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -11,7 +11,7 @@ mapping a SYLK sheet onto a document are the caller's work. | Function | What it does | |---|---| | `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 | -| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 non-blank records in a 64 KiB sample; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | +| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 non-blank records in a 64 KiB sample; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record counts the delimiters of the first record up to the end of the sample, or up to a quoted field still open there, and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | | `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text | | `records(text, delim, quote, max_records, max_fields)` | the same, collected | | `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing | diff --git a/crates/csv/src/lib.rs b/crates/csv/src/lib.rs index 0aec971ac1..70f6148a6e 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -34,8 +34,13 @@ pub use decode::{decode_text, decode_utf8}; /// Quotes start only at a candidate field boundary; candidates with incoherent quoted fields /// are discarded when another coherent candidate separates the records. Ties prefer tab, /// then comma, then semicolon. Comma is the fallback when no candidate separates the text. +/// Only the first 64 KiB are read. A record cut off at the end of that sample is left out, +/// except when no candidate finds coherent complete records with a delimiter in each. Then a candidate +/// that finds no complete record counts the delimiters read so far in the first record, and that +/// record is incoherent when it has a quote inside a field that does not start with one. When one +/// of those candidates ends the sample inside a quoted field, each of them counts only up to that +/// field's opening quote. pub fn sniff_delimiter(text: &str, quote: char) -> u8 { - let mut candidates = [(b'\t', 0usize, 0usize, true), (b',', 0, 0, true), (b';', 0, 0, true)]; const SAMPLE_BYTES: usize = 64 * 1024; let mut sample_end = text.len().min(SAMPLE_BYTES); while !text.is_char_boundary(sample_end) { @@ -43,78 +48,46 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { } let sample = &text[..sample_end]; let truncated = sample_end < text.len(); - for (delimiter, min_count, total, coherent) in &mut candidates { - let mut counts = Vec::new(); - let mut count = 0usize; - let mut quoted = false; - let mut after_quote = false; - let mut field_start = true; - let mut record_has_content = false; - let mut record_coherent = true; - let mut candidate_coherent = true; - let mut reached_record_limit = false; - let mut chars = sample.chars().peekable(); - while let Some(ch) = chars.next() { - if quoted { - if ch == quote { - if chars.peek() == Some("e) { - chars.next(); - record_has_content = true; - } else { - quoted = false; - after_quote = true; - } - } else if !ch.is_whitespace() { - record_has_content = true; - } + let mut scans = b"\t,;".map(|delimiter| scan_delimiter(sample, delimiter, quote)); + if truncated { + if scans.iter().any(|scan| scan.coherent && scan.counts.iter().min().is_some_and(|&min| min > 0)) { + return pick_delimiter(scans); + } + // Every quote in the scans is at a char boundary, so the cut is one too. + let cut = scans.iter().filter(|scan| scan.counts.is_empty()).filter_map(|scan| scan.open_quote).min().unwrap_or(sample_end); + for scan in &mut scans { + if !scan.counts.is_empty() { continue; } - if ch == '\r' || ch == '\n' { - if ch == '\r' && chars.peek() == Some(&'\n') { - chars.next(); - } - if record_has_content { - counts.push(count); - candidate_coherent &= record_coherent; - if counts.len() >= 20 { - reached_record_limit = true; - break; - } - } - count = 0; - quoted = false; - after_quote = false; - field_start = true; - record_has_content = false; - record_coherent = true; + if cut < sample_end { + let before_cut = scan_delimiter(&sample[..cut], scan.delimiter, quote); + (scan.count, scan.record_has_content, scan.record_coherent, scan.record_bare_quote) = + (before_cut.count, before_cut.record_has_content, before_cut.record_coherent, before_cut.record_bare_quote); + } + if scan.record_has_content { + scan.coherent &= scan.record_coherent && !scan.record_bare_quote; + scan.counts.push(scan.count); + } + } + } else { + for scan in &mut scans { + if scan.reached_record_limit { continue; } - if ch == quote && field_start { - quoted = true; - field_start = false; - record_has_content = true; - } else if ch == char::from(*delimiter) { - count += 1; - field_start = true; - after_quote = false; - } else { - record_coherent &= !after_quote || ch.is_whitespace(); - record_has_content |= !ch.is_whitespace(); - field_start = false; + if scan.open_quote.is_some() { + scan.coherent = false; + } else if scan.record_has_content { + scan.coherent &= scan.record_coherent; + scan.counts.push(scan.count); } } - if !reached_record_limit && !truncated { - if quoted { - candidate_coherent = false; - } else if record_has_content { - candidate_coherent &= record_coherent; - counts.push(count); - } - } - *coherent &= candidate_coherent; - *min_count = counts.iter().copied().min().unwrap_or(0); - *total = counts.iter().sum(); } + pick_delimiter(scans) +} + +fn pick_delimiter(scans: [DelimiterScan; 3]) -> u8 { + let candidates = + scans.map(|scan| (scan.delimiter, scan.counts.iter().copied().min().unwrap_or(0), scan.counts.iter().sum::(), scan.coherent)); let prefer_coherent = candidates.iter().any(|(_, min, _, coherent)| *min > 0 && *coherent); let mut best = (b',', 0usize, 0usize); for (delimiter, min, total, coherent) in candidates { @@ -125,6 +98,93 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { best.0 } +/// One candidate delimiter's pass over the sample in [`sniff_delimiter`]. +struct DelimiterScan { + delimiter: u8, + /// Delimiter counts of the complete non-blank records, at most 20. + counts: Vec, + /// Whether every counted record had coherent quoted fields. + coherent: bool, + reached_record_limit: bool, + /// The record still open at the end of the sample: its delimiter count so far, whether it + /// has content, and whether its quoted fields so far are coherent. + count: usize, + record_has_content: bool, + record_coherent: bool, + /// Whether the open record has a quote inside a field that does not start with one. + record_bare_quote: bool, + /// The byte offset of the quote that opens a field still unterminated at the end. + open_quote: Option, +} + +fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan { + let mut scan = DelimiterScan { + delimiter, + counts: Vec::new(), + coherent: true, + reached_record_limit: false, + count: 0, + record_has_content: false, + record_coherent: true, + record_bare_quote: false, + open_quote: None, + }; + let mut after_quote = false; + let mut field_start = true; + let mut chars = sample.char_indices().peekable(); + while let Some((at, ch)) = chars.next() { + if scan.open_quote.is_some() { + if ch == quote { + if chars.peek().map(|&(_, next)| next) == Some(quote) { + chars.next(); + scan.record_has_content = true; + } else { + scan.open_quote = None; + after_quote = true; + } + } else if !ch.is_whitespace() { + scan.record_has_content = true; + } + continue; + } + if ch == '\r' || ch == '\n' { + if ch == '\r' && chars.peek().map(|&(_, next)| next) == Some('\n') { + chars.next(); + } + if scan.record_has_content { + scan.counts.push(scan.count); + scan.coherent &= scan.record_coherent; + if scan.counts.len() >= 20 { + scan.reached_record_limit = true; + break; + } + } + scan.count = 0; + after_quote = false; + field_start = true; + scan.record_has_content = false; + scan.record_coherent = true; + scan.record_bare_quote = false; + continue; + } + if ch == quote && field_start { + scan.open_quote = Some(at); + field_start = false; + scan.record_has_content = true; + } else if ch == char::from(delimiter) { + scan.count += 1; + field_start = true; + after_quote = false; + } else { + scan.record_coherent &= !after_quote || ch.is_whitespace(); + scan.record_bare_quote |= ch == quote; + scan.record_has_content |= !ch.is_whitespace(); + field_start = false; + } + } + scan +} + /// Splits delimited text into records of fields and hands each to `on_record`, which returns /// whether to go on. A record ends at CR, LF or CRLF; a blank line is a record with one empty /// field. A field that starts with `quote` runs to the closing quote (a doubled quote is one @@ -309,6 +369,40 @@ mod tests { assert_eq!(sniff_delimiter(&text, '"'), b'\t'); } + #[test] + fn delimiter_sniffing_counts_a_first_record_longer_than_the_sample() { + let wide = |field: &str, delimiter: char| { + let mut record = String::new(); + while record.len() <= 64 * 1024 { + record.push_str(field); + record.push(delimiter); + } + record + }; + assert_eq!(sniff_delimiter(&format!("{}end\n1;2\n", wide("cell", ';')), '"'), b';'); + assert_eq!(sniff_delimiter(&format!("{}end\n1\t2\n", wide("cell", '\t')), '"'), b'\t'); + // Delimiters inside quoted fields of the long record are text. + assert_eq!(sniff_delimiter(&format!("{}end\n", wide("\"a,b\tc\"", ';')), '"'), b';'); + assert_eq!(sniff_delimiter(&format!("{}end\n", wide("\"a;b\tc\"", ',')), '"'), b','); + // A candidate that reads a quoted field as text inside an unquoted one is incoherent. + assert_eq!(sniff_delimiter(&format!("a,\"{}\",{}", "x;y".repeat(20_000), "z".repeat(10_000)), '"'), b','); + // The sample ends inside a quoted field: the delimiters before that field count. + let text = format!("a;b;c;\"{}\"\n1;2;3;4\n", "long text ".repeat(8_000)); + assert_eq!(sniff_delimiter(&text, '"'), b';'); + // Candidates without a complete record do not count delimiters after that quote, also + // when they read it as text. + assert_eq!(sniff_delimiter(&format!("a,\"{}\"\n1,2\n", "x;y".repeat(30_000)), '"'), b','); + assert_eq!(sniff_delimiter(&format!("a;b;\"{}\"\n1;2;3\n", "x,y\t".repeat(20_000)), '"'), b';'); + // A line break inside the open quoted field gives the other candidates a record without + // a delimiter, which does not stop the first record from counting. + assert_eq!(sniff_delimiter(&format!("a;b;\"hello\n{}\"\n", "x".repeat(70_000)), '"'), b';'); + assert_eq!(sniff_delimiter(&format!("\"a\";b;\"hello,\n{}\"\n", "x".repeat(70_000)), '"'), b';'); + // When a candidate finds coherent complete records with a delimiter in each, a record cut + // off at the end is left out. + assert_eq!(sniff_delimiter(&format!("a;\"hello,\";b\n{}", "x;y;z\n".repeat(12_000)), '"'), b';'); + assert_eq!(sniff_delimiter(&format!("a,b,c;\"hello,\";d\n{}", "x;y;z\n".repeat(12_000)), '"'), b';'); + } + #[test] fn parser_stops_collecting_fields_at_the_cap() { let (max, extra) = (16_384usize, 50); diff --git a/crates/csv/src/sylk.rs b/crates/csv/src/sylk.rs index f9a74405a8..53283cb912 100644 --- a/crates/csv/src/sylk.rs +++ b/crates/csv/src/sylk.rs @@ -219,12 +219,13 @@ fn position(arg: &str, max: u32) -> Option { arg.trim().parse::().ok().filter(|n| (1..=max).contains(n)).map(|n| n - 1) } -/// A `K` value: `"text"` (everything between the first and the last quote, as written), a -/// boolean, a number, or other text (an error value when it starts with `#`). +/// A `K` value: `"text"` (everything between the first and the last quote, with Excel's +/// character escapes decoded), a boolean, a number, or other text (an error value when it starts +/// with `#`). fn parse_value(arg: &str) -> Value { if let Some(text) = arg.strip_prefix('"') { let text = text.strip_suffix('"').unwrap_or(text); - return Value::Text(text.to_string()); + return Value::Text(decode_escapes(text)); } if arg.eq_ignore_ascii_case("TRUE") || arg.eq_ignore_ascii_case("FALSE") { return Value::Bool(arg.eq_ignore_ascii_case("TRUE")); @@ -238,6 +239,149 @@ fn parse_value(arg: &str) -> Value { } } +/// ISO 6937's diacritics (codes 0xC1–0xCF): each code, its combining mark, and the letters it +/// composes with, as pairs of letter and precomposed letter (from Unicode's canonical composition). +/// A diacritic on a SPACE is the spacing accent (`´`, `¨`, `ˇ`, ...), as in glibc's ISO_6937 map; the +/// grave, circumflex and tilde have none, since `` ` ``, `^` and `~` are plain ASCII. +const ISO6937_DIACRITICS: [(u8, char, &str); 13] = [ + (0xC1, '\u{0300}', "AÀaàEÈeèIÃŒiìNǸnǹOÃ’oòUÙuùWẀwáº�YỲyỳ"), // grave + (0xC2, '\u{0301}', " ´AÃ�aáCĆcćEÉeéGÇ´gǵIÃ�iíKḰkḱLĹlĺMḾmḿNŃnÅ„OÓoóPá¹”pṕRÅ”rÅ•SÅšsÅ›UÚuúWẂwẃYÃ�yýZŹzź"), // acute + (0xC3, '\u{0302}', "AÂaâCĈcĉEÊeêGÄœgÄ�HĤhÄ¥IÃŽiîJÄ´jĵOÔoôSÅœsÅ�UÛuûWÅ´wŵYŶyÅ·Záº�zẑ"), // circumflex + (0xC4, '\u{0303}', "AÃaãEẼeẽIĨiÄ©NÑnñOÕoõUŨuÅ©Vá¹¼vá¹½YỸyỹ"), // tilde + (0xC5, '\u{0304}', " ¯AÄ€aÄ�EÄ’eÄ“GḠgḡIĪiÄ«OÅŒoÅ�UŪuÅ«YȲyȳ"), // macron + (0xC6, '\u{0306}', " ˘AÄ‚aăEÄ”eÄ•GÄžgÄŸIĬiÄ­OÅŽoÅ�UŬuÅ­"), // breve + (0xC7, '\u{0307}', " Ë™AȦaȧBḂbḃCÄŠcÄ‹DḊdḋEÄ–eÄ—FḞfḟGÄ gÄ¡HḢhḣIİMá¹€má¹�NṄná¹…OÈ®oȯPá¹–pá¹—RṘrá¹™Sá¹ sṡTṪtṫWẆwẇXẊxẋYẎyáº�ZÅ»zż"), // dot above + (0xC8, '\u{0308}', " ¨AÄaäEËeëHḦhḧIÃ�iïOÖoötẗUÜuüWẄwẅXẌxáº�YŸyÿ"), // diaeresis + (0xCA, '\u{030a}', " ËšAÃ…aÃ¥UÅ®uůwẘyẙ"), // ring + (0xCB, '\u{0327}', " ¸CÇcçDá¸�dḑEȨeÈ©GÄ¢gÄ£HḨhḩKĶkÄ·LÄ»lļNÅ…nņRÅ–rÅ—SÅžsÅŸTÅ¢tÅ£"), // cedilla + (0xCD, '\u{030b}', " Ë�OÅ�oÅ‘UŰuű"), // double acute + (0xCE, '\u{0328}', " Ë›AÄ„aÄ…EĘeÄ™IÄ®iįOǪoÇ«UŲuų"), // ogonek + (0xCF, '\u{030c}', " ˇAÇ�aÇŽCÄŒcÄ�DÄŽdÄ�EÄšeÄ›GǦgǧHÈžhÈŸIÇ�iÇ�jǰKǨkÇ©LĽlľNŇnňOÇ‘oÇ’RŘrÅ™SÅ sÅ¡TŤtÅ¥UÇ“uÇ”ZŽzž"), // caron +]; + +/// ISO 6937's spacing characters above ASCII (codes 0xA1–0xFE that aren't diacritics). +const ISO6937_SPACING: [(u8, char); 71] = [ + (0xA1, '¡'), + (0xA2, '¢'), + (0xA3, '£'), + (0xA5, 'Â¥'), + (0xA7, '§'), + (0xA8, '¤'), + (0xA9, '‘'), + (0xAA, '“'), + (0xAB, '«'), + (0xAC, 'â†�'), + (0xAD, '↑'), + (0xAE, '→'), + (0xAF, '↓'), + (0xB0, '°'), + (0xB1, '±'), + (0xB2, '²'), + (0xB3, '³'), + (0xB4, '×'), + (0xB5, 'µ'), + (0xB6, '¶'), + (0xB7, '·'), + (0xB8, '÷'), + (0xB9, '’'), + (0xBA, 'â€�'), + (0xBB, '»'), + (0xBC, '¼'), + (0xBD, '½'), + (0xBE, '¾'), + (0xBF, '¿'), + (0xD0, '―'), + (0xD1, '¹'), + (0xD2, '®'), + (0xD3, '©'), + (0xD4, 'â„¢'), + (0xD5, '♪'), + (0xD6, '¬'), + (0xD7, '¦'), + (0xDC, 'â…›'), + (0xDD, 'â…œ'), + (0xDE, 'â…�'), + (0xDF, 'â…ž'), + (0xE0, 'Ω'), + (0xE1, 'Æ'), + (0xE2, 'Ä�'), + (0xE3, 'ª'), + (0xE4, 'Ħ'), + (0xE6, 'IJ'), + (0xE7, 'Ä¿'), + (0xE8, 'Å�'), + (0xE9, 'Ø'), + (0xEA, 'Å’'), + (0xEB, 'º'), + (0xEC, 'Þ'), + (0xED, 'Ŧ'), + (0xEE, 'ÅŠ'), + (0xEF, 'ʼn'), + (0xF0, 'ĸ'), + (0xF1, 'æ'), + (0xF2, 'Ä‘'), + (0xF3, 'ð'), + (0xF4, 'ħ'), + (0xF5, 'ı'), + (0xF6, 'ij'), + (0xF7, 'Å€'), + (0xF8, 'Å‚'), + (0xF9, 'ø'), + (0xFA, 'Å“'), + (0xFB, 'ß'), + (0xFC, 'þ'), + (0xFD, 'ŧ'), + (0xFE, 'Å‹'), +]; + +/// Text with Excel's SYLK character escapes decoded. Excel writes a character outside ASCII as +/// `ESC N` and one byte, the character's ISO 6937 code less 0x80. A diacritic's code is followed +/// by the letter it goes on (`ESC N H o` is `ö`, `ESC N {` is `ß`). A code ISO 6937 doesn't define, +/// or an `ESC` that isn't followed by `N` and a code, is kept as written. +fn decode_escapes(text: &str) -> String { + if !text.contains('\u{1b}') { + return text.to_string(); + } + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + let mut ahead = chars.clone(); + let code = (c == '\u{1b}' && ahead.next() == Some('N')) + .then(|| ahead.next()) + .flatten() + .and_then(|b| u8::try_from(b).ok()) + .filter(|b| (0x20..0x80).contains(b)); + let Some(code) = code.map(|b| b + 0x80) else { + out.push(c); + continue; + }; + if let Some(&(_, mark, pairs)) = ISO6937_DIACRITICS.iter().find(|(d, _, _)| *d == code) { + // The letter it goes on: precomposed where Unicode has the pair, else letter and mark. + // The base is an ordinary character: another escape (or any control character) after a + // diacritic leaves this escape as written, and the next one is decoded on its own. + let Some(base) = ahead.next().filter(|b| !b.is_control()) else { + out.push(c); + continue; + }; + let letters: Vec = pairs.chars().collect(); + match letters.chunks(2).find(|p| p.first() == Some(&base)).and_then(|p| p.get(1)) { + Some(&composed) => out.push(composed), + None => { + out.push(base); + out.push(mark); + } + } + } else if let Some(&(_, ch)) = ISO6937_SPACING.iter().find(|(s, _)| *s == code) { + out.push(ch); + } else { + out.push(c); + continue; + } + chars = ahead; + } + out +} + /// One part of an R1C1 reference: `R`/`C` followed by an absolute number, a bracketed offset or /// nothing (the cell's own row or column). #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/csv/tests/sylk.rs b/crates/csv/tests/sylk.rs index 7635089832..de3c38d0bc 100644 --- a/crates/csv/tests/sylk.rs +++ b/crates/csv/tests/sylk.rs @@ -115,3 +115,36 @@ fn survives_huge_relative_offsets_and_width_floods() { let _ = read(&b); } } + +#[test] +fn decodes_excels_character_escapes_in_text() { + // storytold/gridcraft#4321: Excel writes `Größe für Köln` with `ESC N` escapes (ISO 6937 codes + // less 0x80: `H` is the diaeresis, put on the next letter; `{` is ß). + let file = "ID;PWXL;N;E\r\nC;Y1;X1;K\"Gr\u{1b}NHo\u{1b}N{e f\u{1b}NHur K\u{1b}NHoln\"\r\nC;Y2;X1;K\"Plain ASCII 123\"\r\n\ + C;Y3;X1;K\"\u{1b}NBe \u{1b}NAa \u{1b}NCa \u{1b}NKc \u{1b}NOs \u{1b}NMo \u{1b}NJa \u{1b}NDn\"\r\n\ + C;Y4;X1;K\"\u{1b}NAa \u{1b}NAZ\"\r\nC;Y5;X1;K\"\u{1b}Nq \u{1b}NyStra\u{1b}N{e \u{1b}Na\u{1b}Ni\"\r\n\ + C;Y6;X1;K\"\u{1b}NHq \u{1b}N\u{1b}NHo end\u{1b}N\"\r\nC;Y7;X1;K\"\u{1b}N\u{7f} \u{1b}NL \u{1b}X\"\r\nC;Y8;X1;K\"\u{1b}NH\u{1b}NHo \u{1b}NB\tx\"\r\n\ + C;Y9;X1;K\"\u{1b}NB |\u{1b}NE |\u{1b}NF |\u{1b}NG |\u{1b}NH |\u{1b}NJ |\u{1b}NK |\u{1b}NM |\u{1b}NN |\u{1b}NO |\u{1b}NA |\u{1b}NC \"\r\nE\r\n"; + let sh = read(file.as_bytes()).unwrap(); + let value = |a: &str| sh.cells.get(&at(a)).map(|c| c.value.clone()).unwrap_or_default(); + let text = |s: &str| Value::Text(s.into()); + assert_eq!(value("A1"), text("Größe für Köln")); + assert_eq!(value("A2"), text("Plain ASCII 123"), "plain ASCII is unchanged"); + // Acute, grave, circumflex, cedilla, caron, double acute, ring, tilde. + assert_eq!(value("A3"), text("é à â ç Å¡ Å‘ Ã¥ ñ")); + // A letter the mark has no precomposed form with keeps the combining mark. + assert_eq!(value("A4"), text("à Z\u{300}")); + // Spacing characters, one code each: `q` æ, `y` ø, `{` ß, `a` Æ, `i` Ø. + assert_eq!(value("A5"), text("æ øStraße ÆØ")); + // A diacritic on a letter with no precomposed form, and a stray `ESC N` before an escape. + assert_eq!(value("A6"), text("q\u{308} \u{1b}Nö end\u{1b}N")); + // Codes ISO 6937 doesn't define (0xFF, 0xCC) and an `ESC` without `N` stay as written. + assert_eq!(value("A7"), text("\u{1b}N\u{7f} \u{1b}NL \u{1b}X")); + // A diacritic followed by another escape (or a control character) is kept as written, and the + // next escape still decodes. + assert_eq!(value("A8"), text("\u{1b}NHö \u{1b}NB\tx")); + // A diacritic on a SPACE is the spacing accent: acute, macron, breve, dot above, diaeresis, ring, + // cedilla, double acute, ogonek, caron. The grave and circumflex have none (`` ` `` and `^` are + // ASCII), so they stay a space with the combining mark. + assert_eq!(value("A9"), text("´|¯|˘|Ë™|¨|Ëš|¸|Ë�|Ë›|ˇ| \u{300}| \u{302}")); +} diff --git a/crates/dds/Cargo.toml b/crates/dds/Cargo.toml new file mode 100644 index 0000000000..f93e8cbcc9 --- /dev/null +++ b/crates/dds/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-dds" +description = "DirectDraw Surface (DDS) textures: uncompressed and BC1-BC5 block compression, read and write, without dependencies" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = [] +# Encode and decode rows of blocks (and mip levels) on several threads. +parallel = ["dep:rayon"] + +[dependencies] +rayon = { workspace = true, optional = true } diff --git a/crates/dds/README.md b/crates/dds/README.md new file mode 100644 index 0000000000..2dae26bc10 --- /dev/null +++ b/crates/dds/README.md @@ -0,0 +1,64 @@ +# craft-dds + +DirectDraw Surface (DDS) textures, after Microsoft's public DDS and block-compression +documentation, with no dependencies. `craft-image-codecs` reads and writes DDS through this +crate and re-exports its `DdsCompression` and `DdsOptions`; an app that only needs DDS (a texture +exporter, say) can depend on it alone and leave out the other codecs and their licences. + +```toml +craft-dds = { git = "https://github.com/storytold/craft-libs", rev = "" } +``` + +| | Read | Write | +|---|---|---| +| Uncompressed | 8, 16, 24 or 32 bits per pixel described by channel masks, RGB or luminance, with or without alpha; padded rows (`DDSD_PITCH`); 16 bits per channel: `R16_UNORM`, `R16G16_UNORM`, `R16G16B16A16_UNORM` (DXGI 56, 35, 11 and their typeless forms; legacy FourCC 36) | BGRA, BGRX, luminance, luminance with alpha; from 16-bit pixels `R16_UNORM`, `R16G16_UNORM`, `R16G16B16A16_UNORM` | +| Block-compressed | BC1, BC2, BC3 (DXT1, DXT3, DXT5); unsigned BC4 (ATI1, BC4U, DXGI 79 and 80) and BC5 (ATI2, BC5U, DXGI 82 and 83) | BC1, BC2, BC3, BC4, BC5 | +| Headers | legacy and DX10 | legacy; DX10 for BC4, BC5 and the 16-bit formats | +| Mip levels | the top level only | optional full chain, box-filtered | + +Cubemaps, texture arrays, volume textures, premultiplied-alpha textures (DXT2/DXT4, or DX10 alpha mode 2), signed (SNORM) BC4/BC5 and +the other DXGI formats (BC6H, BC7, float, signed or integer 16-bit) are refused with `DdsError::Unsupported` rather than read +in part. + +Pixels are 8 bits per channel (`encode`, `Texture::decode`) or 16 bits per channel (`encode16`, +`Texture::decode16`), interleaved and top row first, in one of four `Layout`s (`Gray`, +`GrayA`, `Rgb`, `Rgba`). BC1 to BC3 are written from RGBA, BC4 from gray and BC5 from RGB +(`DdsCompression::layout` names it). BC4 reads back as gray. BC5 stores red and green only, so it +reads back as RGB with blue 0: for a tangent-space normal map, X and Y, with Z left to the +renderer. ATI2 files are read as Microsoft's tools read them (red in the first block), not with +the two blocks swapped as FFmpeg does. + +From 16-bit pixels, uncompressed textures keep 16 bits per channel: gray as `R16_UNORM`, gray +and alpha (or any two channels, such as a normal map's X and Y) as `R16G16_UNORM`, RGB (alpha +65535) and RGBA as `R16G16B16A16_UNORM`, all with the DX10 header; they read back as gray, gray +and alpha, and RGBA. BC4 and BC5 keep 8-bit endpoints, as the formats store them, but pick them +and the indices against the 16-bit values, so a smooth height or normal map has less error than +when its 8-bit rounding is compressed. BC1 to BC3 round the pixels to 8 bits first. +`Texture::decode` rounds 16-bit formats to 8 bits; `Texture::decode16` returns them exactly, +rescales channel-mask fields from their own width (a 16-bit luminance field exactly), +interpolates BC4 and BC5 at 16 bits, and scales BC1 to BC3 by 257. `craft-image-codecs` still +reads DDS at 8 bits. + +```rust +use craft_dds::{DdsCompression, DdsOptions, Layout, Texture}; + +let pixels = [10, 20, 30, 255].repeat(6 * 5); +let file = craft_dds::encode(6, 5, Layout::Rgba, &pixels, DdsOptions { compression: DdsCompression::Bc1, mipmaps: true })?; +// The header first: the size and layout are known before anything is allocated. +let texture = Texture::parse(&file)?; +assert_eq!((texture.width(), texture.height(), texture.layout()), (6, 5, Layout::Rgba)); +let decoded = texture.decode()?; +``` + +`Texture::parse` requires a complete header and nonzero dimensions. `Texture::decode` bounds its output buffer to 1 GiB; use `decode_with_limit(max_bytes)` for an explicit per-buffer budget. Allocation is fallible. This is not a total process memory limit. The `craft-image-codecs` adapter forwards its own existing `Limits::max_alloc` instead of imposing the standalone default. + +The block encoder is our own: RGB565 endpoints fitted along each block's principal axis and +refined by least squares, indices picked against the palette the reader decodes; BC1 turns texels +under half opacity into its transparent black, and BC3, BC4 and BC5 pick whichever mode of their +value blocks fits. The block functions don't depend on the DDS header, so other containers of +the same blocks can share them. + +## Features + +- `parallel`: encodes and decodes rows of blocks (and mip levels) on several threads with rayon. + `craft-image-codecs` turns it on for native targets. diff --git a/crates/dds/src/bc.rs b/crates/dds/src/bc.rs new file mode 100644 index 0000000000..7000a09e41 --- /dev/null +++ b/crates/dds/src/bc.rs @@ -0,0 +1,613 @@ +//! BC1 to BC5 (DXT1, DXT3, DXT5, ATI1, ATI2) blocks, after Microsoft's public block compression +//! documentation ("Block Compression (Direct3D 10)" and "Texture Block Compression in Direct3D +//! 11"): the block decoders and the block encoder the DDS reader and writer use. Nothing here +//! knows about DDS headers, so other containers of the same blocks can use it. +//! +//! BC4 is one block of 16 single-channel values, the same block BC3 stores its alpha in; BC5 is +//! two of them, red then green. [`value_block`] and [`decode_values`] serve all three; +//! [`value_block16`] and [`decode_values16`] are the same blocks for 16-bit values (BC4 and BC5 +//! from 16-bit sources). +//! +//! The encoder fits a block's colours with two RGB565 endpoints along their principal axis, +//! refines them by least squares, and scores every candidate against the exact palette the +//! reader rebuilds, so the indices it picks are the best ones for what a decoder shows. + +/// The 16 texels of a 4×4 block, row by row, as RGBA. +pub(crate) type Block = [[u8; 4]; 16]; + +/// Bit `t` set for each texel `t` of a block that counts: edge blocks of a texture whose size is +/// not a multiple of four have texels outside the image. +pub(crate) type Mask = u16; + +pub(crate) fn rgb565(c: u16) -> [u8; 3] { + let scale = |v: u16, max: u16| ((u32::from(v) * 255 + u32::from(max) / 2) / u32::from(max)) as u8; + [scale(c >> 11, 31), scale((c >> 5) & 63, 63), scale(c & 31, 31)] +} + +/// The colours a colour block's indices select. Four-colour mode (BC1 with `c0 > c1`, and every +/// BC2 and BC3 block) adds two colours at thirds; three-colour mode adds the midpoint and +/// transparent black. +pub(crate) fn colour_palette(c0: u16, c1: u16, four: bool) -> [[u8; 4]; 4] { + let (a, b) = (rgb565(c0), rgb565(c1)); + let mix = |wa: u32, wb: u32| { + let d = wa + wb; + let at = |i: usize| ((wa * u32::from(a[i]) + wb * u32::from(b[i]) + d / 2) / d) as u8; + [at(0), at(1), at(2), 255] + }; + if four { + [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(2, 1), mix(1, 2)] + } else { + [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(1, 1), [0; 4]] + } +} + +/// A value block's eight values: six interpolated at sevenths when `a0 > a1`, else four +/// interpolated at fifths followed by 0 and 255. +pub(crate) fn alpha_palette(a0: u8, a1: u8) -> [u8; 8] { + let (a0, a1) = (u32::from(a0), u32::from(a1)); + let mut palette = [a0, a1, 0, 0, 0, 0, 0, 255]; + if a0 > a1 { + for (k, v) in palette.iter_mut().enumerate().skip(2) { + let k = k as u32; + *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7; + } + } else { + for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) { + let k = k as u32; + *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5; + } + } + palette.map(|v| v as u8) +} + +/// A colour block's 16 texels as RGBA. BC2 and BC3 colour blocks always have four colours +/// (`one_bit_alpha` false); only BC1's `c0 <= c1` order selects three colours and transparent +/// black. Missing bytes read as 0. +pub(crate) fn decode_colour(block: &[u8], one_bit_alpha: bool) -> Block { + let byte = |i: usize| block.get(i).copied().unwrap_or(0); + let (c0, c1) = (u16::from_le_bytes([byte(0), byte(1)]), u16::from_le_bytes([byte(2), byte(3)])); + let palette = colour_palette(c0, c1, c0 > c1 || !one_bit_alpha); + let indices = u32::from_le_bytes([byte(4), byte(5), byte(6), byte(7)]); + std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) +} + +/// [`alpha_palette`] at 16 bits: the same eight values before they are rounded to 8 bits, as a +/// decoder that interpolates at a higher precision shows them (endpoints scaled by 257, so 255 +/// is 65535). +pub(crate) fn alpha_palette16(a0: u8, a1: u8) -> [u16; 8] { + let (a0, a1) = (u32::from(a0) * 257, u32::from(a1) * 257); + let mut palette = [a0, a1, 0, 0, 0, 0, 0, 65535]; + if a0 > a1 { + for (k, v) in palette.iter_mut().enumerate().skip(2) { + let k = k as u32; + *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7; + } + } else { + for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) { + let k = k as u32; + *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5; + } + } + palette.map(|v| v as u16) +} + +/// BC2's alpha: four explicit bits per texel. +pub(crate) fn decode_bc2_alpha(block: &[u8]) -> [u8; 16] { + let bits = u64::from_le_bytes(std::array::from_fn(|i| block.get(i).copied().unwrap_or(0))); + std::array::from_fn(|t| ((bits >> (4 * t)) & 0xf) as u8 * 17) +} + +/// A value block (BC3's alpha, BC4, either half of BC5): two endpoints and a 3-bit index per +/// texel into eight values, or into six plus 0 and 255 when `a0 <= a1`. Missing bytes read as 0. +pub(crate) fn decode_values(block: &[u8]) -> [u8; 16] { + let byte = |i: usize| block.get(i).copied().unwrap_or(0); + let palette = alpha_palette(byte(0), byte(1)); + let bits = u64::from_le_bytes([byte(2), byte(3), byte(4), byte(5), byte(6), byte(7), 0, 0]); + std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize]) +} + +/// [`decode_values`] at 16 bits, from [`alpha_palette16`]. +pub(crate) fn decode_values16(block: &[u8]) -> [u16; 16] { + let byte = |i: usize| block.get(i).copied().unwrap_or(0); + let palette = alpha_palette16(byte(0), byte(1)); + let bits = u64::from_le_bytes([byte(2), byte(3), byte(4), byte(5), byte(6), byte(7), 0, 0]); + std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize]) +} + +/// A BC1 block. Texels under half opacity become BC1's transparent black, which needs the +/// three-colour mode; an opaque block takes whichever mode fits its colours better. +pub(crate) fn encode_bc1(block: &Block, inside: Mask) -> [u8; 8] { + let transparent = select(block, inside, |t| t[3] < 128); + colour_block(block, inside & !transparent, transparent, true) +} + +/// A BC2 block: four bits of alpha per texel, then a four-colour block. +pub(crate) fn encode_bc2(block: &Block, inside: Mask) -> [u8; 16] { + let bits = block.iter().enumerate().fold(0u64, |bits, (t, texel)| bits | ((u64::from(texel[3]) * 15 + 127) / 255) << (4 * t)); + join(bits.to_le_bytes(), colour_block(block, inside, 0, false)) +} + +/// A BC3 block: an interpolated alpha block, then a four-colour block. +pub(crate) fn encode_bc3(block: &Block, inside: Mask) -> [u8; 16] { + let alphas = std::array::from_fn(|t| block[t][3]); + join(value_block(&alphas, inside), colour_block(block, inside, 0, false)) +} + +fn join(a: [u8; 8], b: [u8; 8]) -> [u8; 16] { + std::array::from_fn(|i| if i < 8 { a.get(i) } else { b.get(i - 8) }.copied().unwrap_or(0)) +} + +/// The texels of `inside` for which `f` holds. +fn select(block: &Block, inside: Mask, f: impl Fn(&[u8; 4]) -> bool) -> Mask { + block.iter().enumerate().filter(|(t, texel)| inside >> t & 1 != 0 && f(texel)).fold(0, |m, (t, _)| m | 1 << t) +} + +fn rgb_of(texel: &[u8; 4]) -> [f32; 3] { + [f32::from(texel[0]), f32::from(texel[1]), f32::from(texel[2])] +} + +/// RGB565 of a colour, rounding each channel to the nearest level. +fn to565(c: [f32; 3]) -> u16 { + let q = |v: f32, max: f32| (v.clamp(0.0, 255.0) * max / 255.0).round() as u16; + q(c[0], 31.0) << 11 | q(c[1], 63.0) << 5 | q(c[2], 31.0) +} + +fn distance(a: &[u8; 4], b: &[u8; 4]) -> u32 { + let d = |i: usize| u32::from(a[i].abs_diff(b[i])).pow(2); + d(0) + d(1) + d(2) +} + +/// The index of the first of `palette`'s entries nearest by `distance`, and that distance: the +/// entry `Iterator::min_by_key` picks, found without the iterator (a texel equal to an entry +/// stops the search, as no later entry can be nearer and an equal one doesn't win). +fn nearest(palette: &[T], distance: impl Fn(&T) -> u32) -> (usize, u32) { + let mut best = (0, u32::MAX); + for (i, p) in palette.iter().enumerate() { + let d = distance(p); + if d < best.1 { + best = (i, d); + if d == 0 { + break; + } + } + } + if palette.is_empty() { (0, 0) } else { best } +} + +/// A colour block (endpoints, then 2-bit indices) for the `opaque` texels' colours, with the +/// `transparent` ones on BC1's transparent index. `bc1` allows the three-colour mode; BC2 and +/// BC3 always decode four colours. +fn colour_block(block: &Block, opaque: Mask, transparent: Mask, bc1: bool) -> [u8; 8] { + // The opaque texels' colours in texel order, on the stack (after storytold/photocraft#10669, + // which took the per-block allocations out of PhotoCraft's copy of this encoder). + let mut buffer = [[0f32; 3]; 16]; + let mut n = 0; + for (t, texel) in block.iter().enumerate() { + if opaque >> t & 1 != 0 + && let Some(slot) = buffer.get_mut(n) + { + *slot = rgb_of(texel); + n += 1; + } + } + let colours = buffer.get(..n).unwrap_or_default(); + let Some((first, rest)) = colours.split_first() else { + // Nothing visible: every texel on the transparent index (or index 0 of black). + let indices = if transparent != 0 { u32::MAX } else { 0 }; + return pack(0, 0, indices); + }; + // One colour has no axis: `principal_endpoints` returns that colour (their mean) for both + // ends, so it is skipped. Everything after it runs as for any block. + let (lo, hi) = if rest.iter().all(|c| c == first) { (*first, *first) } else { principal_endpoints(colours) }; + let mut candidate = (to565(lo), to565(hi)); + // The endpoint pairs fitted so far: at most one per round. + let mut fitted = [candidate; 3]; + let mut count = 1; + let modes: &[bool] = if transparent != 0 { + &[false] + } else if bc1 { + &[true, false] + } else { + &[true] + }; + let mut best: Option<(u32, [u8; 8])> = None; + // Each refinement starts from the best block so far: its indices give the least-squares + // endpoints, which become one more candidate. + for round in 0..3 { + let (e0, e1) = candidate; + for &four in modes { + let (bytes, error) = fit(block, opaque, transparent, e0, e1, four); + if best.is_none_or(|(e, _)| error < e) { + best = Some((error, bytes)); + } + } + let Some((error, bytes)) = best else { break }; + if error == 0 || round == 2 { + break; + } + let Some(next) = least_squares(block, opaque, &bytes) else { break }; + // A pair fitted before (in either order: `fit` orders the endpoints itself) fits the same + // again and can't beat the best block, which then gives the same pair again: the rounds + // left would change nothing. + let seen = fitted.get(..count).unwrap_or_default(); + if seen.iter().any(|&(a, b)| (a, b) == next || (b, a) == next) { + break; + } + if let Some(slot) = fitted.get_mut(count) { + *slot = next; + count += 1; + } + candidate = next; + } + best.map_or([0; 8], |(_, bytes)| bytes) +} + +/// Orders endpoints `e0`, `e1` for the mode (`c0 > c1` for four colours, `c0 <= c1` for three) +/// and picks each texel's nearest palette colour. Returns the block and its squared error. +fn fit(block: &Block, opaque: Mask, transparent: Mask, e0: u16, e1: u16, four: bool) -> ([u8; 8], u32) { + let (c0, c1) = if four == (e0 >= e1) { (e0, e1) } else { (e1, e0) }; + // Equal endpoints can't be in four-colour order; the palette is then one colour either way. + let palette = colour_palette(c0, c1, four && c0 > c1); + let choices = if four && c0 > c1 { 4 } else { 3 }; + let mut indices = 0u32; + let mut error = 0u32; + for (t, texel) in block.iter().enumerate() { + let index = if transparent >> t & 1 != 0 { + 3 + } else if opaque >> t & 1 != 0 { + let (i, d) = nearest(palette.get(..choices).unwrap_or_default(), |p| distance(texel, p)); + error += d; + i as u32 + } else { + 0 + }; + indices |= index << (2 * t); + } + (pack(c0, c1, indices), error) +} + +fn pack(c0: u16, c1: u16, indices: u32) -> [u8; 8] { + let (c0, c1, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes()); + [c0[0], c0[1], c1[0], c1[1], i[0], i[1], i[2], i[3]] +} + +/// The ends of the colours' spread along their principal axis (the covariance's dominant +/// eigenvector, by power iteration), clamped to the RGB cube. +fn principal_endpoints(colours: &[[f32; 3]]) -> ([f32; 3], [f32; 3]) { + let n = colours.len().max(1) as f32; + let mean = [0, 1, 2].map(|i| colours.iter().map(|c| c[i]).sum::() / n); + let mut cov = [[0f32; 3]; 3]; + for c in colours { + let d = [c[0] - mean[0], c[1] - mean[1], c[2] - mean[2]]; + for (i, row) in cov.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v += d[i] * d[j]; + } + } + } + let times = |a: [f32; 3]| [0, 1, 2].map(|i| cov[i][0] * a[0] + cov[i][1] * a[1] + cov[i][2] * a[2]); + let iterate = |start: usize| { + let mut axis = [0f32; 3]; + axis[start] = 1.0; + for _ in 0..8 { + let next = times(axis); + let len = next.iter().map(|v| v * v).sum::().sqrt(); + if !len.is_normal() { + break; + } + let normalised = next.map(|v| v / len); + // A step that returns the same axis, bit for bit, returns it on every later step too: + // stopping there gives the very axis the remaining steps would. Kept only if timing + // shows the comparison pays for itself. + if normalised.map(f32::to_bits) == axis.map(f32::to_bits) { + break; + } + axis = normalised; + } + axis + }; + // From each channel's axis, keeping the one the colours spread along most: a channel that + // varies on its own is already an eigenvector, so a single start there would never leave it + // even when the others vary more together. + let spread = |a: [f32; 3]| times(a).iter().zip(a).map(|(x, y)| x * y).sum::(); + let axis = [0, 1, 2].map(iterate).into_iter().max_by(|&a, &b| spread(a).total_cmp(&spread(b))).unwrap_or([1.0, 0.0, 0.0]); + let along = |c: &[f32; 3]| (c[0] - mean[0]) * axis[0] + (c[1] - mean[1]) * axis[1] + (c[2] - mean[2]) * axis[2]; + let (lo, hi) = colours.iter().map(along).fold((f32::MAX, f32::MIN), |(lo, hi), t| (lo.min(t), hi.max(t))); + let at = |t: f32| [0, 1, 2].map(|i| (mean[i] + t * axis[i]).clamp(0.0, 255.0)); + if lo > hi { (mean, mean) } else { (at(lo), at(hi)) } +} + +/// The endpoints that minimise the squared error for the indices `bytes` already chose: each +/// texel's index fixes its weights between the endpoints, giving 2×2 normal equations per +/// channel. `None` when the indices don't constrain both endpoints. +fn least_squares(block: &Block, opaque: Mask, bytes: &[u8; 8]) -> Option<(u16, u16)> { + let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); + let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); + let four = c0 > c1; + // How much of c0 each index holds. + let weight = |i: u32| match (four, i) { + (_, 0) => Some(1.0f32), + (_, 1) => Some(0.0), + (true, 2) => Some(2.0 / 3.0), + (true, _) => Some(1.0 / 3.0), + (false, 2) => Some(0.5), + (false, _) => None, + }; + let (mut aa, mut ab, mut bb) = (0f32, 0f32, 0f32); + let (mut ax, mut bx) = ([0f32; 3], [0f32; 3]); + for (t, texel) in block.iter().enumerate() { + if opaque >> t & 1 == 0 { + continue; + } + let Some(a) = weight(indices >> (2 * t) & 3) else { continue }; + let b = 1.0 - a; + let c = rgb_of(texel); + aa += a * a; + ab += a * b; + bb += b * b; + for ((x0, x1), v) in ax.iter_mut().zip(bx.iter_mut()).zip(c) { + *x0 += a * v; + *x1 += b * v; + } + } + let det = aa * bb - ab * ab; + if det.abs() < 1e-3 { + return None; + } + let e0 = [0, 1, 2].map(|i| (ax[i] * bb - bx[i] * ab) / det); + let e1 = [0, 1, 2].map(|i| (bx[i] * aa - ax[i] * ab) / det); + Some((to565(e0), to565(e1))) +} + +/// A block of 16 single-channel values (BC3's alpha, BC4, either half of BC5): whichever of the two modes +/// (eight values between the extremes, or six between the extremes other than 0 and 255, plus +/// exact 0 and 255) fits better. Only the values of `inside` count. +pub(crate) fn value_block(values: &[u8; 16], inside: Mask) -> [u8; 8] { + // Both ranges in one pass: of all values, and of those other than 0 and 255. + let mut all: Option<(u8, u8)> = None; + let mut mid = all; + let widen = |r: Option<(u8, u8)>, v: u8| Some(r.map_or((v, v), |(lo, hi)| (lo.min(v), hi.max(v)))); + for (t, &v) in values.iter().enumerate() { + if inside >> t & 1 != 0 { + all = widen(all, v); + if !matches!(v, 0 | 255) { + mid = widen(mid, v); + } + } + } + let (lo, hi) = all.unwrap_or((0, 0)); + // Eight values need a0 > a1; equal ends fall to the six-value mode, which starts with a0 too. + let eight = value_fit(values, inside, hi, lo); + let (mid_lo, mid_hi) = mid.unwrap_or((0, 0)); + let six = value_fit(values, inside, mid_lo, mid_hi); + if six.1 < eight.1 { six.0 } else { eight.0 } +} + +fn value_fit(values: &[u8; 16], inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) { + let palette = alpha_palette(a0, a1); + let mut bits = 0u64; + let mut error = 0u32; + for (t, &v) in values.iter().enumerate() { + if inside >> t & 1 == 0 { + continue; + } + let (i, d) = nearest(&palette, |&p| u32::from(p.abs_diff(v)).pow(2)); + error += d; + bits |= (i as u64) << (3 * t); + } + let b = bits.to_le_bytes(); + ([a0, a1, b[0], b[1], b[2], b[3], b[4], b[5]], error) +} + +/// [`value_block`] for 16-bit values: the endpoints are still 8 bits, but each end of each mode +/// tries the 8-bit levels just below and above the 16-bit extreme, and every candidate is scored +/// against the 16-bit palette ([`alpha_palette16`]). A block that spans less than one 8-bit level +/// is flat from 8-bit values but gets the interpolated steps between two adjacent levels here. +pub(crate) fn value_block16(values: &[u16; 16], inside: Mask) -> [u8; 8] { + let mut all: Option<(u16, u16)> = None; + let mut mid = all; + let widen = |r: Option<(u16, u16)>, v: u16| Some(r.map_or((v, v), |(lo, hi)| (lo.min(v), hi.max(v)))); + for (t, &v) in values.iter().enumerate() { + if inside >> t & 1 != 0 { + all = widen(all, v); + if !matches!(v, 0 | 65535) { + mid = widen(mid, v); + } + } + } + let (lo, hi) = all.unwrap_or((0, 0)); + let (mid_lo, mid_hi) = mid.unwrap_or((0, 0)); + let (down, up) = (|v: u16| (v / 257) as u8, |v: u16| v.div_ceil(257) as u8); + // The eight-value mode's pairs first (a0 the high end), then the six-value mode's: on a tie + // the eight-value mode wins, as in `value_block`. Each pair's palette follows its order, so a + // pair that lands in the other mode is still scored as the decoder reads it. + let candidates = [ + (up(hi), down(lo)), + (up(hi), up(lo)), + (down(hi), down(lo)), + (down(hi), up(lo)), + (down(mid_lo), down(mid_hi)), + (down(mid_lo), up(mid_hi)), + (up(mid_lo), down(mid_hi)), + (up(mid_lo), up(mid_hi)), + ]; + let mut best: Option<([u8; 8], u64)> = None; + for (a0, a1) in candidates { + let fit = value_fit16(values, inside, a0, a1); + if best.is_none_or(|(_, e)| fit.1 < e) { + best = Some(fit); + } + } + best.map_or([0; 8], |(bytes, _)| bytes) +} + +fn value_fit16(values: &[u16; 16], inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u64) { + let palette = alpha_palette16(a0, a1); + let mut bits = 0u64; + let mut error = 0u64; + for (t, &v) in values.iter().enumerate() { + if inside >> t & 1 == 0 { + continue; + } + let (i, d) = nearest(&palette, |&p| u32::from(p.abs_diff(v)).pow(2)); + error += u64::from(d); + bits |= (i as u64) << (3 * t); + } + let b = bits.to_le_bytes(); + ([a0, a1, b[0], b[1], b[2], b[3], b[4], b[5]], error) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn solid_blocks_land_on_the_nearest_565_colour() { + for colour in [[0, 0, 0, 255], [255, 255, 255, 255], [12, 200, 77, 255]] { + let block = [colour; 16]; + let out = decode_colour(&encode_bc1(&block, u16::MAX), true); + for texel in out { + assert!(texel.iter().zip(colour).all(|(a, b)| a.abs_diff(b) <= 4), "{texel:?} for {colour:?}"); + } + } + } + + #[test] + fn two_colour_blocks_are_exact_when_the_colours_are_565() { + let (a, b) = ([255, 0, 0, 255], [0, 0, 255, 255]); + let block: Block = std::array::from_fn(|t| if t % 3 == 0 { a } else { b }); + for bc1 in [true, false] { + let bytes = if bc1 { encode_bc1(&block, u16::MAX) } else { colour_block(&block, u16::MAX, 0, false) }; + assert_eq!(decode_colour(&bytes, bc1), block); + } + } + + #[test] + fn bc1_punches_through_texels_under_half_alpha() { + let block: Block = std::array::from_fn(|t| if t < 8 { [200, 100, 50, 255] } else { [9, 9, 9, 127] }); + let bytes = encode_bc1(&block, u16::MAX); + let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); + assert!(c0 <= c1, "three-colour mode"); + let out = decode_colour(&bytes, true); + assert!(out[..8].iter().all(|t| t[3] == 255) && out[8..].iter().all(|t| *t == [0; 4]), "{out:?}"); + } + + #[test] + fn four_colour_blocks_keep_c0_above_c1() { + // A ramp needs all four colours; BC2 and BC3 blocks must not rely on the order, but + // older decoders read c0 <= c1 as three colours, so the encoder never writes that. + let block: Block = std::array::from_fn(|t| [(t * 16) as u8, 0, 0, 255]); + let bytes = colour_block(&block, u16::MAX, 0, false); + assert!(u16::from_le_bytes([bytes[0], bytes[1]]) > u16::from_le_bytes([bytes[2], bytes[3]])); + } + + #[test] + fn alpha_blocks_pick_the_mode_that_keeps_0_and_255() { + // 0, 255 and a cluster in between: the six-value mode stores 0 and 255 exactly. + let block: Block = std::array::from_fn(|t| [0, 0, 0, [0, 255, 100, 110][t % 4]]); + let bytes = value_block(&block.map(|t| t[3]), u16::MAX); + assert!(bytes[0] <= bytes[1], "six-value mode"); + let palette = alpha_palette(bytes[0], bytes[1]); + let bits = u64::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], 0, 0]); + for (t, texel) in block.iter().enumerate() { + let got = palette[(bits >> (3 * t)) as usize & 7]; + assert!(got.abs_diff(texel[3]) <= 2, "texel {t}: {got} for {}", texel[3]); + } + } + + #[test] + fn the_principal_axis_is_found_when_one_channel_varies_on_its_own() { + // Red alternates on its own (variance 64); green and blue alternate together (variance 49 + // each, 98 along their shared axis), uncorrelated with red. Starting on red alone would + // keep red's axis and flatten green and blue; the block must do better than its bounding box. + let block: Block = std::array::from_fn(|t| { + let gb = if (t / 2) % 2 == 0 { 121 } else { 135 }; + [if t % 2 == 0 { 120 } else { 136 }, gb, gb, 255] + }); + let error = |bytes: &[u8; 8]| decode_colour(bytes, false).iter().zip(&block).map(|(a, b)| distance(a, b)).sum::(); + let (_, bounding_box) = fit(&block, u16::MAX, 0, to565([120.0, 121.0, 121.0]), to565([136.0, 135.0, 135.0]), true); + let ours = error(&colour_block(&block, u16::MAX, 0, false)); + assert!(ours < bounding_box, "{ours} vs the bounding box's {bounding_box}"); + } + + #[test] + fn value_blocks_decode_the_frozen_vectors() { + // Eight-value mode (a0 = 200 > a1 = 50), every index 0. + assert_eq!(decode_values(&[0xc8, 0x32, 0, 0, 0, 0, 0, 0]), [200; 16]); + // Six-value mode (a0 = 10 <= a1 = 250), every index 1. + assert_eq!(decode_values(&[0x0a, 0xfa, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24]), [250; 16]); + // Six-value mode's indices 6 and 7 are 0 and 255 whatever the endpoints. + let bits: u64 = (0..16).fold(0, |b, t| b | (6 + (t % 2)) << (3 * t)); + let b = bits.to_le_bytes(); + let got = decode_values(&[10, 250, b[0], b[1], b[2], b[3], b[4], b[5]]); + assert_eq!(got, std::array::from_fn(|t| if t % 2 == 0 { 0 } else { 255 })); + } + + #[test] + fn value_blocks_round_trip_ramps_and_solids() { + for values in [[200u8; 16], [0; 16], [255; 16], std::array::from_fn(|t| (t * 17) as u8), std::array::from_fn(|t| 100 + t as u8)] { + let back = decode_values(&value_block(&values, u16::MAX)); + let worst = values.iter().zip(back).map(|(a, b)| a.abs_diff(b)).max().unwrap_or(0); + // Within half a step of either mode: 255 / 7 apart in the eight-value mode, about + // 221 / 5 in the six-value one. + assert!(worst <= 23, "{values:?} -> {back:?}"); + } + assert_eq!(decode_values(&value_block(&[200; 16], u16::MAX)), [200; 16]); + } + + #[test] + fn nearest_picks_what_min_by_key_picks() { + // Ties (equal entries, entries equally far on both sides) and exact hits included. + let mut seed = 0x2545_f491u32; + for _ in 0..2000 { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let palette = [seed as u8 & 0xf0, (seed >> 8) as u8 & 0xf0, (seed >> 16) as u8 & 0xf0, (seed >> 24) as u8 & 0xf0]; + let v = (seed >> 4) as u8 & 0xf8; + let d = |p: &u8| u32::from(p.abs_diff(v)).pow(2); + let want = palette.iter().enumerate().map(|(i, p)| (i, d(p))).min_by_key(|&(_, d)| d).unwrap(); + assert_eq!(nearest(&palette, d), want, "{palette:?} {v}"); + } + assert_eq!(nearest::(&[], |_| 7), (0, 0)); + } + + #[test] + fn value_blocks_decode_the_frozen_vectors_at_16_bits() { + // Eight-value mode (200 > 50): index 2 is (6 * 200 + 50) / 7 of 255 at 16 bits, which + // the 8-bit palette rounds to 179. + let bits: u64 = (0..16).fold(0, |b, t| b | 2 << (3 * t)); + let b = bits.to_le_bytes(); + let block = [200, 50, b[0], b[1], b[2], b[3], b[4], b[5]]; + assert_eq!(decode_values16(&block), [(((6 * 200 + 50) * 257 + 3) / 7_u32) as u16; 16]); + assert_eq!(decode_values(&block), [179; 16]); + // Six-value mode's indices 6 and 7 are 0 and 65535. + let bits: u64 = (0..16).fold(0, |b, t| b | (6 + (t % 2)) << (3 * t)); + let b = bits.to_le_bytes(); + let got = decode_values16(&[10, 250, b[0], b[1], b[2], b[3], b[4], b[5]]); + assert_eq!(got, std::array::from_fn(|t| if t % 2 == 0 { 0 } else { 65535 })); + } + + #[test] + fn value_blocks_from_16_bits_step_between_two_8_bit_levels() { + // A ramp across 0.8 of one 8-bit level: from 8 bits it is one or two flat values; from 16 + // bits the endpoints straddle it and the steps between them follow the ramp. + let values: [u16; 16] = std::array::from_fn(|t| 25_700 + (t as u16) * 13); + let error = |got: [u16; 16]| values.iter().zip(got).map(|(a, b)| u64::from(a.abs_diff(b)).pow(2)).sum::(); + let ours = error(decode_values16(&value_block16(&values, u16::MAX))); + let from_8_bits = error(decode_values16(&value_block(&values.map(|v| ((u32::from(v) + 128) / 257) as u8), u16::MAX))); + assert!(ours * 4 < from_8_bits, "{ours} vs {from_8_bits} from 8 bits"); + // Values outside the image don't count. + let solid = value_block16(&std::array::from_fn(|t| if t == 0 { 1000 } else { 60_000 }), 1); + assert!(decode_values16(&solid)[0].abs_diff(1000) < 129); + } + + #[test] + fn texels_outside_the_image_are_ignored() { + // Only the top-left texel is inside: its colour alone decides the endpoints. + let mut block: Block = [[0, 255, 0, 255]; 16]; + block[0] = [255, 0, 255, 255]; + let out = decode_colour(&encode_bc1(&block, 1), true); + assert_eq!(out[0], [255, 0, 255, 255]); + } +} diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs new file mode 100644 index 0000000000..183ec4fa14 --- /dev/null +++ b/crates/dds/src/lib.rs @@ -0,0 +1,1425 @@ +//! DirectDraw Surface (DDS) textures, after Microsoft's public DDS documentation ("DDS", +//! "DDS_HEADER", "DDS_PIXELFORMAT", "DDS_HEADER_DXT10"). +//! +//! Reading: the top mip level of a 2D texture, either uncompressed (8 to 32 bits per pixel +//! described by channel masks, RGB or luminance, or 16 bits per channel: `R16_UNORM`, +//! `R16G16_UNORM`, `R16G16B16A16_UNORM`) or block-compressed BC1/BC2/BC3 +//! (DXT1/DXT3/DXT5) or unsigned BC4/BC5 (ATI1/ATI2), with or without the DX10 header. BC4 opens +//! as gray and BC5 as RGB with blue 0: BC5 stores only red and green, and a normal map's Z is +//! left for the caller to reconstruct. Cubemaps, texture arrays and volume textures are refused +//! rather than flattened to one face or slice, and signed (SNORM) BC4/BC5 is refused too. +//! +//! Writing: a 2D texture, uncompressed (BGRA or BGRX, luminance with or without alpha), +//! BC1/BC2/BC3 or BC4/BC5, optionally with its full mip chain. The legacy header describes all +//! but BC4, BC5 and the 16-bit formats, which are written with the DX10 header (`BC4_UNORM`, `BC5_UNORM`): their +//! legacy FourCCs are vendor names that programs read differently (ATI2's two blocks are swapped +//! by some). BC6H, BC7 and sRGB formats aren't written. +//! +//! Pixels are 8 bits per channel ([`encode`], [`Texture::decode`]) or 16 bits per channel +//! ([`encode16`], [`Texture::decode16`]), interleaved, top row first, in one of the [`Layout`]s. +//! Uncompressed 16-bit pixels are written with the DX10 header as `R16_UNORM` (gray), +//! `R16G16_UNORM` (gray and alpha, or any two channels such as a normal map's X and Y) or +//! `R16G16B16A16_UNORM` (RGB, with alpha 65535, and RGBA). BC4 and BC5 fit their 8-bit endpoints +//! and their indices to the 16-bit values; BC1 to BC3 round the pixels to 8 bits first. The +//! crate has no dependencies; the `parallel` feature encodes and decodes rows of blocks (and mip +//! levels) on several threads with rayon. +//! +//! ``` +//! use craft_dds::{DdsCompression, DdsOptions, Layout}; +//! +//! let pixels = [10, 20, 30, 255].repeat(6 * 5); +//! let options = DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }; +//! let file = craft_dds::encode(6, 5, Layout::Rgba, &pixels, options)?; +//! let texture = craft_dds::Texture::parse(&file)?; +//! assert_eq!((texture.width(), texture.height(), texture.layout()), (6, 5, Layout::Rgba)); +//! assert_eq!(texture.decode()?.len(), 6 * 5 * 4); +//! # Ok::<(), craft_dds::DdsError>(()) +//! ``` +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod bc; + +use std::borrow::Cow; +use std::fmt; + +use bc::{Block, Mask}; + +/// The channels of a pixel, 8 or 16 bits each, in this order. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Layout { + Gray, + /// Gray, then straight (not premultiplied) alpha. + GrayA, + Rgb, + /// Red, green, blue, then straight alpha. + Rgba, +} + +impl Layout { + /// Samples per pixel. + pub fn channels(self) -> usize { + match self { + Layout::Gray => 1, + Layout::GrayA => 2, + Layout::Rgb => 3, + Layout::Rgba => 4, + } + } +} + +/// Why a texture could not be read or written. More kinds may be added, so a `match` on it needs +/// a wildcard arm. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum DdsError { + /// The file is damaged or not a DDS file. + Malformed(String), + /// A valid texture in a form this crate doesn't read (a cubemap, an array, a compression it + /// doesn't decode). + Unsupported(String), + /// The pixels can't be written with the options given. + Encode(String), + /// An output buffer of this many bytes could not be allocated. + Alloc(usize), + /// The decoded output exceeds the caller-selected per-buffer byte limit. + LimitExceeded { required: usize, limit: u64 }, +} + +impl fmt::Display for DdsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + DdsError::Malformed(reason) => write!(f, "malformed DDS: {reason}"), + DdsError::Unsupported(reason) => write!(f, "unsupported DDS: {reason}"), + DdsError::Encode(reason) => write!(f, "DDS encode failed: {reason}"), + DdsError::Alloc(len) => write!(f, "cannot allocate {len} bytes for the texture"), + DdsError::LimitExceeded { required, limit } => write!(f, "decoded texture requires {required} bytes, exceeding limit {limit}"), + } + } +} + +impl std::error::Error for DdsError {} + +/// How a DDS texture stores its pixels. More compressions may be added, so a `match` on it needs +/// a wildcard arm. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[non_exhaustive] +pub enum DdsCompression { + /// Uncompressed, 8 bits per channel: BGRA (BGRX without alpha), or luminance with or + /// without alpha for grayscale. From [`encode16`], 16 bits per channel instead. Lossless. + #[default] + None, + /// BC1 (DXT1): 4 bits per pixel. Alpha is on or off: texels under half opacity become + /// transparent black. + Bc1, + /// BC2 (DXT3): 8 bits per pixel, with 4 bits of explicit alpha per texel. + Bc2, + /// BC3 (DXT5): 8 bits per pixel, with smooth interpolated alpha. + Bc3, + /// BC4 (ATI1): 4 bits per pixel, one channel: gray, for roughness, metallic, height or + /// ambient-occlusion maps. Written from gray pixels. + Bc4, + /// BC5 (ATI2): 8 bits per pixel, two channels: red and green, for tangent-space normal maps + /// (X and Y; Z is reconstructed by the renderer). Written from RGB pixels, blue dropped. + Bc5, +} + +impl DdsCompression { + pub const ALL: [DdsCompression; 6] = + [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3, DdsCompression::Bc4, DdsCompression::Bc5]; + + /// The name scripts and the CLI use: `none`, `bc1`, `bc2`, `bc3`, `bc4` or `bc5`. + pub fn name(self) -> &'static str { + match self { + DdsCompression::None => "none", + DdsCompression::Bc1 => "bc1", + DdsCompression::Bc2 => "bc2", + DdsCompression::Bc3 => "bc3", + DdsCompression::Bc4 => "bc4", + DdsCompression::Bc5 => "bc5", + } + } + + /// [`Self::name`] back to a compression, also taking the DXT and ATI names (`dxt1`, `dxt3`, + /// `dxt5`, `ati1`, `ati2`), in any case. Anything else is `None`. + pub fn from_name(name: &str) -> Option { + match name.to_ascii_lowercase().as_str() { + "none" => Some(DdsCompression::None), + "bc1" | "dxt1" => Some(DdsCompression::Bc1), + "bc2" | "dxt3" => Some(DdsCompression::Bc2), + "bc3" | "dxt5" => Some(DdsCompression::Bc3), + "bc4" | "ati1" => Some(DdsCompression::Bc4), + "bc5" | "ati2" => Some(DdsCompression::Bc5), + _ => None, + } + } + + /// The pixel layout the compression is written from: gray for BC4, RGB for BC5, RGBA for + /// the other block compressions. `None` for uncompressed textures, which take every layout. + pub fn layout(self) -> Option { + match self { + DdsCompression::None => None, + DdsCompression::Bc4 => Some(Layout::Gray), + DdsCompression::Bc5 => Some(Layout::Rgb), + DdsCompression::Bc1 | DdsCompression::Bc2 | DdsCompression::Bc3 => Some(Layout::Rgba), + } + } + + /// A block compression (lossy), not uncompressed pixels. + pub fn is_block(self) -> bool { + self != DdsCompression::None + } +} + +/// What a DDS file is written with. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DdsOptions { + pub compression: DdsCompression, + /// Write the full mip chain down to 1×1, each level a box filter of the one above. + pub mipmaps: bool, +} + +/// `DDS ` plus the 124-byte DDS_HEADER. +const HEADER: usize = 128; +/// DDS_HEADER_DXT10, present when the FourCC is `DX10`. +const DX10_HEADER: usize = 20; + +const DDSD_DEPTH: u32 = 0x80_0000; +const DDPF_ALPHAPIXELS: u32 = 0x1; +const DDPF_FOURCC: u32 = 0x4; +const DDPF_RGB: u32 = 0x40; +const DDPF_LUMINANCE: u32 = 0x2_0000; +const DDSCAPS2_CUBEMAP: u32 = 0x200; +const DDSCAPS2_CUBEMAP_FACES: u32 = 0xfc00; +const DDSCAPS2_VOLUME: u32 = 0x20_0000; +const DIMENSION_TEXTURE2D: u32 = 3; +const MISC_TEXTURECUBE: u32 = 0x4; +/// The legacy FourCC (a number, not text) of 16-bit RGBA. +const D3DFMT_A16B16G16R16: u32 = 36; + +fn bad(reason: impl fmt::Display) -> DdsError { + DdsError::Malformed(reason.to_string()) +} +fn unsupported(reason: impl Into) -> DdsError { + DdsError::Unsupported(reason.into()) +} +fn le32(b: &[u8], at: usize) -> Result { + let bytes = b.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).ok_or_else(|| bad("truncated header"))?; + Ok(u32::from_le_bytes(bytes)) +} + +/// Whether the header declares more than the one image a reader takes: further mip levels, +/// cubemap faces, volume slices or array textures, even without their presence flags. +pub fn has_additional_images(bytes: &[u8]) -> Result { + let depth = le32(bytes, 24)?; + let mips = le32(bytes, 28)?; + let faces = (le32(bytes, 112)? & DDSCAPS2_CUBEMAP_FACES).count_ones(); + let dx10 = le32(bytes, 80)? & DDPF_FOURCC != 0 && bytes.get(84..88) == Some(b"DX10"); + let (cube, array) = if dx10 { (le32(bytes, 136)? & MISC_TEXTURECUBE != 0, le32(bytes, 140)?) } else { (false, 0) }; + Ok(depth > 1 || mips > 1 || faces > 1 || cube || array > 1) +} + +/// A FourCC as text when it is printable, else as the number legacy writers store there. +fn fourcc_name(fourcc: u32) -> String { + let bytes = fourcc.to_le_bytes(); + if bytes.iter().all(|c| c.is_ascii_graphic() || *c == b' ') { bytes.iter().map(|&c| char::from(c)).collect() } else { fourcc.to_string() } +} + +/// One channel of an uncompressed pixel: where it sits and its largest value. +#[derive(Clone, Copy)] +struct Field { + shift: u32, + max: u32, +} + +impl Field { + /// `None` for an empty mask; an error for one with gaps or wider than the pixel. + fn new(mask: u32, bits: u32) -> Result, DdsError> { + if mask == 0 { + return Ok(None); + } + let shift = mask.trailing_zeros(); + let max = mask >> shift; + if max & max.wrapping_add(1) != 0 || (bits < 32 && mask >> bits != 0) { + return Err(bad(format!("channel mask {mask:#x} is not a contiguous field of a {bits}-bit pixel"))); + } + Ok(Some(Field { shift, max })) + } + + fn get(self, pixel: u32) -> u8 { + let v = u64::from((pixel >> self.shift) & self.max); + let max = u64::from(self.max); + ((v * 255 + max / 2) / max) as u8 + } + + fn get16(self, pixel: u32) -> u16 { + let v = u64::from((pixel >> self.shift) & self.max); + let max = u64::from(self.max); + ((v * 65535 + max / 2) / max) as u16 + } +} + +#[derive(Clone, Copy)] +enum Encoding { + /// Uncompressed: bytes per pixel, then red (or luminance), green, blue and alpha. + Masks { + bytes: usize, + gray: bool, + fields: [Option; 4], + }, + Bc1, + Bc2, + Bc3, + /// 16 bits per channel, little-endian: gray, gray and alpha (or red and green), or RGBA. + Unorm16 { + channels: usize, + }, + /// One value block: gray. + Bc4, + /// Two value blocks: red, then green. + Bc5, +} + +impl Encoding { + fn masks(bits: u32, masks: [u32; 4], gray: bool) -> Result { + if !matches!(bits, 8 | 16 | 24 | 32) { + return Err(bad(format!("{bits} bits per pixel is not 8, 16, 24 or 32"))); + } + let mut fields = [None; 4]; + for (field, mask) in fields.iter_mut().zip(masks) { + *field = Field::new(mask, bits)?; + } + let colour = if gray { fields[0].is_some() } else { fields[..3].iter().any(Option::is_some) }; + if !colour { + return Err(bad("the pixel format has no colour channel masks")); + } + Ok(Encoding::Masks { bytes: bits as usize / 8, gray, fields }) + } + + fn layout(&self) -> Layout { + match self { + Encoding::Masks { gray: true, fields, .. } if fields[3].is_some() => Layout::GrayA, + Encoding::Masks { gray: true, .. } => Layout::Gray, + Encoding::Masks { fields, .. } if fields[3].is_none() => Layout::Rgb, + Encoding::Unorm16 { channels: 1 } => Layout::Gray, + Encoding::Unorm16 { channels: 2 } => Layout::GrayA, + Encoding::Bc4 => Layout::Gray, + Encoding::Bc5 => Layout::Rgb, + _ => Layout::Rgba, + } + } + + /// Bytes per 4×4 block; 0 for uncompressed pixels. + fn block_size(&self) -> usize { + match self { + Encoding::Masks { .. } | Encoding::Unorm16 { .. } => 0, + Encoding::Bc1 | Encoding::Bc4 => 8, + Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc5 => 16, + } + } + + /// Stored row stride and byte size of the top mip level (block rows for BC). + fn level_layout(&self, width: u32, height: u32, pitch: Option) -> Result<(usize, usize), DdsError> { + let overflow = || bad("pixel data size overflow"); + let (w, h) = (usize::try_from(width).map_err(|_| overflow())?, usize::try_from(height).map_err(|_| overflow())?); + let pixel_bytes = match self { + Encoding::Masks { bytes, .. } => Some(*bytes), + Encoding::Unorm16 { channels } => Some(2 * channels), + _ => None, + }; + let (row_bytes, rows) = match pixel_bytes { + Some(bytes) => { + let packed = w.checked_mul(bytes).ok_or_else(overflow)?; + let row_bytes = match pitch { + Some(pitch) => usize::try_from(pitch).map_err(|_| overflow())?, + None => packed, + }; + if row_bytes < packed { + return Err(bad(format!("row pitch {row_bytes} is smaller than the {packed}-byte pixel row"))); + } + (row_bytes, h) + } + None => (w.div_ceil(4).checked_mul(self.block_size()).ok_or_else(overflow)?, h.div_ceil(4)), + }; + let size = row_bytes.checked_mul(rows).ok_or_else(overflow)?; + Ok((row_bytes, size)) + } +} + +/// The legacy pixel format: a FourCC, or channel masks. +fn legacy_encoding(b: &[u8]) -> Result { + let (flags, fourcc, bits) = (le32(b, 80)?, le32(b, 84)?, le32(b, 88)?); + let alpha = if flags & DDPF_ALPHAPIXELS != 0 { le32(b, 104)? } else { 0 }; + if flags & DDPF_FOURCC != 0 { + // D3DFMT_A16B16G16R16, the legacy name of R16G16B16A16_UNORM (DirectXTex writes it so). + if fourcc == D3DFMT_A16B16G16R16 { + return Ok(Encoding::Unorm16 { channels: 4 }); + } + return match &fourcc.to_le_bytes() { + b"DXT1" => Ok(Encoding::Bc1), + b"DXT3" => Ok(Encoding::Bc2), + b"DXT5" => Ok(Encoding::Bc3), + // Microsoft's mapping (DirectXTex reads ATI2 as BC5_UNORM, as Pillow does): red in + // the first block, green in the second. FFmpeg's reader swaps the two blocks of + // ATI2, after the old ATI 3Dc tools; this reader doesn't. + b"ATI1" | b"BC4U" => Ok(Encoding::Bc4), + b"ATI2" | b"BC5U" => Ok(Encoding::Bc5), + b"BC4S" | b"BC5S" => Err(unsupported(format!("signed (SNORM) `{}` textures are not supported", fourcc_name(fourcc)))), + b"DXT2" | b"DXT4" => Err(unsupported("premultiplied-alpha DXT2/DXT4 textures are not supported")), + _ => Err(unsupported(format!("compression `{}` is not supported (DXT1, DXT3, DXT5, ATI1/BC4U and ATI2/BC5U are)", fourcc_name(fourcc)))), + }; + } + if flags & DDPF_RGB != 0 { + return Encoding::masks(bits, [le32(b, 92)?, le32(b, 96)?, le32(b, 100)?, alpha], false); + } + if flags & DDPF_LUMINANCE != 0 { + return Encoding::masks(bits, [le32(b, 92)?, 0, 0, alpha], true); + } + Err(unsupported(format!("pixel format flags {flags:#x} are not RGB, luminance or a supported compression"))) +} + +/// The DX10 header's DXGI format, refusing anything but a single 2D texture. +fn dx10_encoding(b: &[u8]) -> Result { + let (dxgi, dimension, misc, array) = (le32(b, HEADER)?, le32(b, HEADER + 4)?, le32(b, HEADER + 8)?, le32(b, HEADER + 12)?); + if misc & MISC_TEXTURECUBE != 0 { + return Err(unsupported("cubemaps are not supported")); + } + if dimension != DIMENSION_TEXTURE2D { + return Err(unsupported(format!("only 2D textures are supported (resource dimension {dimension})"))); + } + if array > 1 { + return Err(unsupported(format!("texture arrays are not supported ({array} textures)"))); + } + // miscFlags2 bits 0-2 are the alpha mode; 2 is premultiplied. Only the formats with a real + // alpha channel are affected, and the legacy path refuses their DXT2/DXT4 equivalents too. + if le32(b, HEADER + 16)? & 0x7 == 2 && matches!(dxgi, 9 | 11 | 27..=29 | 73..=78 | 87 | 90 | 91) { + return Err(unsupported(format!("premultiplied-alpha DX10 textures are not supported (DXGI format {dxgi})"))); + } + const RGBA: [u32; 4] = [0xff, 0xff00, 0xff_0000, 0xff00_0000]; + const BGRA: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0xff00_0000]; + const BGRX: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0]; + match dxgi { + 27..=29 => Encoding::masks(32, RGBA, false), + // Typeless, then UNORM, as for BC4 and BC5 below. + 9 | 11 => Ok(Encoding::Unorm16 { channels: 4 }), + 33 | 35 => Ok(Encoding::Unorm16 { channels: 2 }), + 53 | 56 => Ok(Encoding::Unorm16 { channels: 1 }), + 87 | 90 | 91 => Encoding::masks(32, BGRA, false), + 88 | 92 | 93 => Encoding::masks(32, BGRX, false), + 70..=72 => Ok(Encoding::Bc1), + 73..=75 => Ok(Encoding::Bc2), + 76..=78 => Ok(Encoding::Bc3), + // Typeless, then UNORM: a typeless texture's view is unsigned unless a program says + // otherwise, and Pillow writes BC5 as typeless. + 79 | 80 => Ok(Encoding::Bc4), + 82 | 83 => Ok(Encoding::Bc5), + 81 | 84 => Err(unsupported(format!("signed (SNORM) BC4 and BC5 textures are not supported (DXGI format {dxgi})"))), + _ => Err(unsupported(format!("DXGI format {dxgi} is not supported (BC1 to BC5, 8-bit RGBA or BGRA and 16-bit R, RG or RGBA are)"))), + } +} + +/// Default per-buffer decoded output budget (1 GiB). This is not a total process memory budget. +pub const DEFAULT_MAX_DECODE_BYTES: u64 = 1024 * 1024 * 1024; + +/// A DDS file whose header has been read: its size and pixel layout are known before +/// [`Texture::decode`] allocates anything, so a caller can check them against its limits. +pub struct Texture<'a> { + bytes: &'a [u8], + flags: u32, + width: u32, + height: u32, + encoding: Encoding, + /// Where the top level's pixel data starts. + start: usize, +} + +impl<'a> Texture<'a> { + /// Reads the header, refusing what [`Texture::decode`] can't read. + pub fn parse(b: &'a [u8]) -> Result, DdsError> { + if !b.starts_with(b"DDS ") { + return Err(bad("missing the `DDS ` signature")); + } + if le32(b, 4)? != 124 { + return Err(bad("header size is not 124")); + } + let (flags, height, width, depth, caps2) = (le32(b, 8)?, le32(b, 12)?, le32(b, 16)?, le32(b, 24)?, le32(b, 112)?); + if caps2 & DDSCAPS2_CUBEMAP != 0 { + return Err(unsupported("cubemaps are not supported")); + } + if caps2 & DDSCAPS2_VOLUME != 0 || (flags & DDSD_DEPTH != 0 && depth > 1) { + return Err(unsupported("volume textures are not supported")); + } + let dx10 = le32(b, 80)? & DDPF_FOURCC != 0 && &le32(b, 84)?.to_le_bytes() == b"DX10"; + let (encoding, start) = if dx10 { (dx10_encoding(b)?, HEADER + DX10_HEADER) } else { (legacy_encoding(b)?, HEADER) }; + if b.len() < start { + return Err(bad("truncated header")); + } + if width == 0 || height == 0 { + return Err(bad("texture dimensions must be nonzero")); + } + Ok(Texture { bytes: b, flags, width, height, encoding, start }) + } + + pub fn width(&self) -> u32 { + self.width + } + + pub fn height(&self) -> u32 { + self.height + } + + /// The layout [`Texture::decode`] returns. + pub fn layout(&self) -> Layout { + self.encoding.layout() + } + + /// The top mip level's pixels in [`Texture::layout`], bounded by [`DEFAULT_MAX_DECODE_BYTES`]. + pub fn decode(&self) -> Result, DdsError> { + self.decode_with_limit(DEFAULT_MAX_DECODE_BYTES) + } + + /// Decode with an explicit per-buffer output byte budget; allocation remains fallible. + pub fn decode_with_limit(&self, max_bytes: u64) -> Result, DdsError> { + let encoding = self.encoding; + let (data, row_pitch, total) = self.top_level(1, max_bytes)?; + let (w, channels) = (self.width as usize, encoding.layout().channels()); + let row_size = w * channels; + let mut pixels = alloc_zeroed(total)?; + match encoding { + Encoding::Masks { bytes, gray, fields } => decode_masks(Masks { bytes, gray, fields }, data, row_pitch, &mut pixels, row_size), + // Each 16-bit sample rounded to the nearest 8-bit level. + Encoding::Unorm16 { .. } => rows(&mut pixels, row_size, |y, dst| { + let src = data.get(y * row_pitch..).unwrap_or_default(); + for (d, s) in dst.iter_mut().zip(src.as_chunks::<2>().0) { + *d = to8(u16::from_le_bytes(*s)); + } + }), + Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc4 | Encoding::Bc5 => { + decode_blocks(encoding, data, (w, channels), &mut pixels) + } + } + Ok(pixels) + } + + /// The top mip level's pixels in [`Texture::layout`] at 16 bits per channel, bounded by + /// [`DEFAULT_MAX_DECODE_BYTES`]. 16-bit formats come back exactly; channel-mask fields are + /// rescaled from their own width to 0..=65535 (a 16-bit luminance field exactly, an 8-bit one + /// times 257); BC4 and BC5 values are interpolated at 16 bits; BC1 to BC3 are their 8-bit + /// values times 257 (so 255 is 65535). + pub fn decode16(&self) -> Result, DdsError> { + self.decode16_with_limit(DEFAULT_MAX_DECODE_BYTES) + } + + /// [`Texture::decode16`] with an explicit per-buffer output byte budget (two bytes a sample). + pub fn decode16_with_limit(&self, max_bytes: u64) -> Result, DdsError> { + let encoding = self.encoding; + let (data, row_pitch, total) = self.top_level(2, max_bytes)?; + let (w, channels) = (self.width as usize, encoding.layout().channels()); + let row_size = w * channels; + let mut pixels = alloc_zeroed(total / 2)?; + match encoding { + Encoding::Masks { bytes, gray, fields } => decode_masks16(Masks { bytes, gray, fields }, data, row_pitch, &mut pixels, row_size), + Encoding::Unorm16 { .. } => rows(&mut pixels, row_size, |y, dst| { + let src = data.get(y * row_pitch..).unwrap_or_default(); + for (d, s) in dst.iter_mut().zip(src.as_chunks::<2>().0) { + *d = u16::from_le_bytes(*s); + } + }), + Encoding::Bc4 | Encoding::Bc5 => decode_value_blocks16(encoding, data, (w, channels), &mut pixels), + Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 => { + // The limit was checked above for the 16-bit buffer, which is twice this one. + let narrow = self.decode_with_limit(u64::MAX)?; + for (d, v) in pixels.iter_mut().zip(narrow) { + *d = u16::from(v) * 257; + } + } + } + Ok(pixels) + } + + /// The top level's stored bytes and row stride, and the decoded size in bytes at + /// `sample_bytes` a sample, checked against `max_bytes` before the stored data is. + fn top_level(&self, sample_bytes: usize, max_bytes: u64) -> Result<(&'a [u8], usize, usize), DdsError> { + let (b, flags, encoding) = (self.bytes, self.flags, self.encoding); + let (width, height) = (self.width, self.height); + // The same header field is a total level size for BC, but a row stride when DDSD_PITCH is set. + let pitch = if flags & DDSD_PITCH != 0 { Some(le32(b, 20)?) } else { None }; + let (row_pitch, size) = encoding.level_layout(width, height, pitch)?; + let (w, h) = (width as usize, height as usize); + let channels = encoding.layout().channels(); + let row_size = w.checked_mul(channels).and_then(|n| n.checked_mul(sample_bytes)).ok_or_else(|| bad("pixel size overflow"))?; + let total = row_size.checked_mul(h).ok_or_else(|| bad("pixel size overflow"))?; + if total as u64 > max_bytes { + return Err(DdsError::LimitExceeded { required: total, limit: max_bytes }); + } + let data = b.get(self.start..).and_then(|d| d.get(..size)).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?; + Ok((data, row_pitch, total)) + } +} + +/// A 16-bit sample rounded to the nearest 8-bit level. +fn to8(v: u16) -> u8 { + ((u32::from(v) + 128) / 257) as u8 +} + +/// An uncompressed pixel format: bytes per pixel, luminance or RGB, and the red (or +/// luminance), green, blue and alpha fields. +struct Masks { + bytes: usize, + gray: bool, + fields: [Option; 4], +} + +/// Uncompressed rows `row_pitch` apart into `pixels` (rows of `row_size` bytes), one row of +/// pixels per task. +fn decode_masks(m: Masks, data: &[u8], row_pitch: usize, pixels: &mut [u8], row_size: usize) { + let Masks { bytes, gray, fields } = m; + let channels = if gray { 1 + usize::from(fields[3].is_some()) } else { 3 + usize::from(fields[3].is_some()) }; + // The field each output channel comes from. + let picks = if gray { [0, 3, 0, 0] } else { [0, 1, 2, 3] }; + // An 8-bit field on a byte boundary scales to itself, so when every channel is one (or + // absent, and 0) the pixels are a byte shuffle: the byte each channel copies. + let mut at: [Option; 4] = [None; 4]; + let mut whole_bytes = true; + for (slot, &pick) in at.iter_mut().zip(&picks).take(channels) { + match fields.get(pick).copied().flatten() { + None => {} + Some(f) if f.max == 255 && f.shift % 8 == 0 => *slot = Some(f.shift as usize / 8), + Some(_) => whole_bytes = false, + } + } + // Four bytes to four channels, each present: RGBA, BGRA and the like. + let four = (whole_bytes && bytes == 4 && channels == 4 && at.iter().all(Option::is_some)).then(|| at.map(|i| i.unwrap_or(0) & 3)); + rows(pixels, row_size, |y, dst_row| { + // Stop at the output width, leaving any stored row padding unread. + let src_row = data.get(y * row_pitch..).unwrap_or_default(); + if let Some(order) = four { + let (src, dst) = (src_row.as_chunks::<4>().0, dst_row.as_chunks_mut::<4>().0); + if order == [0, 1, 2, 3] { + for (d, s) in dst.iter_mut().zip(src) { + *d = *s; + } + } else { + for (d, s) in dst.iter_mut().zip(src) { + *d = order.map(|i| s[i]); + } + } + } else if whole_bytes { + for (src, dst) in src_row.chunks_exact(bytes).zip(dst_row.chunks_exact_mut(channels)) { + for (v, i) in dst.iter_mut().zip(at) { + *v = i.and_then(|i| src.get(i)).copied().unwrap_or(0); + } + } + } else { + for (src, dst) in src_row.chunks_exact(bytes).zip(dst_row.chunks_exact_mut(channels)) { + let pixel = src.iter().rev().fold(0u32, |v, &byte| v << 8 | u32::from(byte)); + let channel = |i: usize| fields[i].map_or(0, |f| f.get(pixel)); + let values = if gray { [channel(0), channel(3), 0, 0] } else { [channel(0), channel(1), channel(2), channel(3)] }; + dst.copy_from_slice(&values[..channels]); + } + } + }); +} + +/// [`decode_masks`] at 16 bits: every field scaled to 0..=65535, so fields wider than 8 bits +/// (luminance or red and green of 16 bits) keep their precision. +fn decode_masks16(m: Masks, data: &[u8], row_pitch: usize, pixels: &mut [u16], row_size: usize) { + let Masks { bytes, gray, fields } = m; + let channels = if gray { 1 + usize::from(fields[3].is_some()) } else { 3 + usize::from(fields[3].is_some()) }; + rows(pixels, row_size, |y, dst_row| { + let src_row = data.get(y * row_pitch..).unwrap_or_default(); + for (src, dst) in src_row.chunks_exact(bytes).zip(dst_row.chunks_exact_mut(channels)) { + let pixel = src.iter().rev().fold(0u32, |v, &byte| v << 8 | u32::from(byte)); + let channel = |i: usize| fields[i].map_or(0, |f| f.get16(pixel)); + let values = if gray { [channel(0), channel(3), 0, 0] } else { [channel(0), channel(1), channel(2), channel(3)] }; + dst.copy_from_slice(&values[..channels]); + } + }); +} + +/// BC4 or BC5 blocks into 16-bit `pixels` of `width` × `channels` samples a row: gray, or red and +/// green with blue 0, interpolated at 16 bits. +fn decode_value_blocks16(encoding: Encoding, data: &[u8], (width, channels): (usize, usize), pixels: &mut [u16]) { + let block_size = encoding.block_size().max(1); + let blocks_x = width.div_ceil(4); + let row_size = width * channels; + rows(pixels, row_size.saturating_mul(4), |by, band| { + let src = data.get(by * blocks_x * block_size..).unwrap_or_default(); + for (bx, block) in src.chunks_exact(block_size).take(blocks_x).enumerate() { + let red = bc::decode_values16(block); + let green = if matches!(encoding, Encoding::Bc5) { bc::decode_values16(block.get(8..).unwrap_or_default()) } else { [0; 16] }; + let x0 = bx * 4; + for (ty, line) in band.chunks_exact_mut(row_size).enumerate() { + let dst = line.get_mut(x0 * channels..).unwrap_or_default(); + for (tx, d) in dst.chunks_exact_mut(channels).take(4).enumerate() { + let t = ty * 4 + tx; + for (c, v) in d.iter_mut().enumerate() { + *v = match c { + 0 => red[t], + 1 => green[t], + _ => 0, + }; + } + } + } + } + }); +} + +/// Block-compressed data into `pixels` of `width` × `channels` bytes a row, one row of blocks +/// per task. Blocks wholly inside the image copy whole rows of texels; only those on the right +/// edge check each texel. +fn decode_blocks(encoding: Encoding, data: &[u8], (width, channels): (usize, usize), pixels: &mut [u8]) { + let block_size = encoding.block_size().max(1); + let blocks_x = width.div_ceil(4); + let row_size = width * channels; + rows(pixels, row_size.saturating_mul(4), |by, band| { + let src = data.get(by * blocks_x * block_size..).unwrap_or_default(); + for (bx, block) in src.chunks_exact(block_size).take(blocks_x).enumerate() { + let second = block.get(8..).unwrap_or_default(); + let texels = match encoding { + Encoding::Bc1 => bc::decode_colour(block, true), + Encoding::Bc2 => with_alpha(bc::decode_colour(second, false), bc::decode_bc2_alpha(block)), + Encoding::Bc4 => values(&[bc::decode_values(block)]), + Encoding::Bc5 => values(&[bc::decode_values(block), bc::decode_values(second)]), + _ => with_alpha(bc::decode_colour(second, false), bc::decode_values(block)), + }; + let x0 = bx * 4; + // The band holds the block's rows that lie inside the image (fewer than four in the + // last band of a height that isn't a multiple of four). + for (line, row) in band.chunks_exact_mut(row_size).zip(texels.as_chunks::<4>().0) { + if x0 + 4 <= width && channels == 4 { + if let Some(dst) = line.get_mut(x0 * 4..x0 * 4 + 16) { + dst.copy_from_slice(row.as_flattened()); + } + } else { + let dst = line.get_mut(x0 * channels..).unwrap_or_default(); + for (d, texel) in dst.chunks_exact_mut(channels).zip(row) { + d.copy_from_slice(texel.get(..channels).unwrap_or_default()); + } + } + } + } + }); +} + +/// Texels whose first channels are `channels`' values, the rest 0: gray for BC4, red and green +/// (and blue 0) for BC5. +fn values(channels: &[[u8; 16]]) -> [[u8; 4]; 16] { + std::array::from_fn(|t| std::array::from_fn(|c| channels.get(c).map_or(0, |v| v[t]))) +} + +fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] { + for (texel, a) in texels.iter_mut().zip(alpha) { + texel[3] = a; + } + texels +} + +const DDSD_CAPS: u32 = 0x1; +const DDSD_HEIGHT: u32 = 0x2; +const DDSD_WIDTH: u32 = 0x4; +const DDSD_PITCH: u32 = 0x8; +const DDSD_PIXELFORMAT: u32 = 0x1000; +const DDSD_MIPMAPCOUNT: u32 = 0x2_0000; +const DDSD_LINEARSIZE: u32 = 0x8_0000; +const DDSCAPS_COMPLEX: u32 = 0x8; +const DDSCAPS_TEXTURE: u32 = 0x1000; +const DDSCAPS_MIPMAP: u32 = 0x40_0000; +const DXGI_BC4_UNORM: u32 = 80; +const DXGI_BC5_UNORM: u32 = 83; +const DXGI_R16G16B16A16_UNORM: u32 = 11; +const DXGI_R16G16_UNORM: u32 = 35; +const DXGI_R16_UNORM: u32 = 56; + +fn encode_err(reason: impl fmt::Display) -> DdsError { + DdsError::Encode(reason.to_string()) +} + +/// A zeroed buffer of `len` samples, or [`DdsError::Alloc`] (in bytes) when it can't be reserved. +fn alloc_zeroed(len: usize) -> Result, DdsError> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| DdsError::Alloc(len.saturating_mul(size_of::())))?; + v.resize(len, T::default()); + Ok(v) +} + +/// A sample of 8 or 16 bits: what the mip chain averages and the buffers hold. +trait Sample: Copy + Default + Send + Sync { + fn wide(self) -> u32; + /// An average already within the sample's range. + fn from_average(v: u32) -> Self; +} + +impl Sample for u8 { + fn wide(self) -> u32 { + u32::from(self) + } + fn from_average(v: u32) -> u8 { + v as u8 + } +} + +impl Sample for u16 { + fn wide(self) -> u32 { + u32::from(self) + } + fn from_average(v: u32) -> u16 { + v as u16 + } +} + +/// How a written texture stores its pixels. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Store { + /// 8-bit luminance. + Luminance, + /// 8-bit luminance, then 8-bit alpha. + LuminanceAlpha, + /// Blue, green, red and an unused byte (written as 255, so a reader that takes it for + /// alpha still sees an opaque texture). + Bgrx, + Bgra, + Bc1, + Bc2, + Bc3, + Bc4, + Bc5, + /// 16-bit gray (`R16_UNORM`). + R16, + /// 16-bit gray and alpha, or any two channels (`R16G16_UNORM`). + Rg16, + /// 16-bit RGB with alpha 65535 (`R16G16B16A16_UNORM`). + Rgb16, + /// 16-bit RGBA (`R16G16B16A16_UNORM`). + Rgba16, +} + +impl Store { + /// The storage for pixels of `layout`. Block compressions take their + /// [`DdsCompression::layout`] only. + fn new(compression: DdsCompression, layout: Layout) -> Result { + Ok(match (compression, layout) { + (DdsCompression::None, Layout::Gray) => Store::Luminance, + (DdsCompression::None, Layout::GrayA) => Store::LuminanceAlpha, + (DdsCompression::None, Layout::Rgb) => Store::Bgrx, + (DdsCompression::None, Layout::Rgba) => Store::Bgra, + (DdsCompression::Bc1, Layout::Rgba) => Store::Bc1, + (DdsCompression::Bc2, Layout::Rgba) => Store::Bc2, + (DdsCompression::Bc3, Layout::Rgba) => Store::Bc3, + (DdsCompression::Bc4, Layout::Gray) => Store::Bc4, + (DdsCompression::Bc5, Layout::Rgb) => Store::Bc5, + (_, layout) => return Err(encode_err(format!("{layout:?} pixels can't be written as `{}`", compression.name()))), + }) + } + + /// [`Store::new`] for 16-bit pixels: uncompressed ones keep 16 bits per channel. + fn new16(compression: DdsCompression, layout: Layout) -> Result { + Ok(match (compression, layout) { + (DdsCompression::None, Layout::Gray) => Store::R16, + (DdsCompression::None, Layout::GrayA) => Store::Rg16, + (DdsCompression::None, Layout::Rgb) => Store::Rgb16, + (DdsCompression::None, Layout::Rgba) => Store::Rgba16, + _ => Store::new(compression, layout)?, + }) + } + + /// Bytes per pixel, or per 4×4 block for a block compression. + fn unit(self) -> usize { + match self { + Store::Luminance => 1, + Store::LuminanceAlpha | Store::R16 => 2, + Store::Bgrx | Store::Bgra | Store::Rg16 => 4, + Store::Rgb16 | Store::Rgba16 => 8, + Store::Bc1 | Store::Bc4 => 8, + Store::Bc2 | Store::Bc3 | Store::Bc5 => 16, + } + } + + fn is_block(self) -> bool { + matches!(self, Store::Bc1 | Store::Bc2 | Store::Bc3 | Store::Bc4 | Store::Bc5) + } + + /// The DXGI format of the DX10 header, for the formats the legacy header can't name. + fn dxgi(self) -> Option { + match self { + Store::Bc4 => Some(DXGI_BC4_UNORM), + Store::Bc5 => Some(DXGI_BC5_UNORM), + Store::R16 => Some(DXGI_R16_UNORM), + Store::Rg16 => Some(DXGI_R16G16_UNORM), + Store::Rgb16 | Store::Rgba16 => Some(DXGI_R16G16B16A16_UNORM), + _ => None, + } + } + + /// Bytes of one row of pixels (or of 4×4 blocks) of a level `width` wide. + fn row_bytes(self, width: usize) -> Option { + if self.is_block() { width.div_ceil(4).checked_mul(self.unit()) } else { width.checked_mul(self.unit()) } + } + + fn level_bytes(self, width: usize, height: usize) -> Option { + let rows = if self.is_block() { height.div_ceil(4) } else { height }; + self.row_bytes(width)?.checked_mul(rows) + } + + /// DDS_PIXELFORMAT: flags, FourCC, bits per pixel and the red, green, blue and alpha masks. + fn pixel_format(self) -> (u32, [u8; 4], u32, [u32; 4]) { + match self { + Store::Luminance => (DDPF_LUMINANCE, [0; 4], 8, [0xff, 0, 0, 0]), + Store::LuminanceAlpha => (DDPF_LUMINANCE | DDPF_ALPHAPIXELS, [0; 4], 16, [0xff, 0, 0, 0xff00]), + Store::Bgrx => (DDPF_RGB, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0]), + Store::Bgra => (DDPF_RGB | DDPF_ALPHAPIXELS, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]), + Store::Bc1 => (DDPF_FOURCC, *b"DXT1", 0, [0; 4]), + Store::Bc2 => (DDPF_FOURCC, *b"DXT3", 0, [0; 4]), + Store::Bc3 => (DDPF_FOURCC, *b"DXT5", 0, [0; 4]), + Store::Bc4 | Store::Bc5 | Store::R16 | Store::Rg16 | Store::Rgb16 | Store::Rgba16 => (DDPF_FOURCC, *b"DX10", 0, [0; 4]), + } + } +} + +/// Levels in a full mip chain: the larger side halves down to 1. +fn mip_levels(width: u32, height: u32) -> u32 { + 32 - width.max(height).max(1).leading_zeros() +} + +fn half((w, h): (usize, usize)) -> (usize, usize) { + ((w / 2).max(1), (h / 2).max(1)) +} + +/// A DDS file of `width` × `height` `pixels` in `layout`, interleaved and top row first. +/// Block compressions take the layout [`DdsCompression::layout`] names (RGBA for BC1 to BC3, +/// gray for BC4, RGB for BC5); uncompressed textures take every layout. +pub fn encode(width: u32, height: u32, layout: Layout, pixels: &[u8], options: DdsOptions) -> Result, DdsError> { + if width == 0 || height == 0 { + return Err(encode_err("texture dimensions must be nonzero")); + } + let store = Store::new(options.compression, layout)?; + encode_levels((width, height), layout, pixels, store, options.mipmaps, write_level) +} + +/// [`encode`] for 16-bit pixels. Uncompressed, they keep 16 bits per channel: gray as +/// `R16_UNORM`, gray and alpha (or any two channels, such as a normal map's X and Y) as +/// `R16G16_UNORM`, RGB (with alpha 65535) and RGBA as `R16G16B16A16_UNORM`, all with the DX10 +/// header. BC4 and BC5 pick their endpoints and indices against the 16-bit values; BC1 to BC3 +/// round the pixels to 8 bits and write what [`encode`] writes from them. +pub fn encode16(width: u32, height: u32, layout: Layout, pixels: &[u16], options: DdsOptions) -> Result, DdsError> { + if width == 0 || height == 0 { + return Err(encode_err("texture dimensions must be nonzero")); + } + let store = Store::new16(options.compression, layout)?; + check_len((width, height), layout, pixels)?; + if matches!(store, Store::Bc1 | Store::Bc2 | Store::Bc3) { + let mut narrow = alloc_zeroed(pixels.len())?; + for (d, &v) in narrow.iter_mut().zip(pixels) { + *d = to8(v); + } + return encode(width, height, layout, &narrow, options); + } + encode_levels((width, height), layout, pixels, store, options.mipmaps, write_level16) +} + +/// Refuses a pixel buffer that isn't `width` × `height` pixels of `layout`. +fn check_len((width, height): (u32, u32), layout: Layout, pixels: &[T]) -> Result<(), DdsError> { + let expected = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(layout.channels())); + if expected != Some(pixels.len()) { + let unit = if size_of::() == 1 { "bytes" } else { "16-bit samples" }; + return Err(encode_err(format!("{} {unit} of pixels for a {width}x{height} {layout:?} texture", pixels.len()))); + } + Ok(()) +} + +/// A level writer: one level of `width` × `height` pixels (in the image's layout) into `dst`. +type WriteLevel = fn(Store, &[T], (usize, usize), &mut [u8]) -> Result<(), DdsError>; + +/// The header and every level of `pixels`, each written by `write`. +fn encode_levels( + (width, height): (u32, u32), + layout: Layout, + pixels: &[T], + store: Store, + mipmaps: bool, + write: WriteLevel, +) -> Result, DdsError> { + check_len((width, height), layout, pixels)?; + let levels = if mipmaps { mip_levels(width, height) } else { 1 }; + let top = (width as usize, height as usize); + // Every level's size, checked before anything is allocated. + let mut sizes = Vec::new(); + let mut size = top; + for _ in 0..levels { + sizes.push(store.level_bytes(size.0, size.1).ok_or_else(|| encode_err("texture size overflow"))?); + size = half(size); + } + let head = if store.dxgi().is_some() { HEADER + DX10_HEADER } else { HEADER }; + let total = sizes.iter().try_fold(head, |total, &s| total.checked_add(s)).ok_or_else(|| encode_err("texture size overflow"))?; + let header = header(width, height, store, levels, sizes.first().copied().unwrap_or(0))?; + let mut out = alloc_zeroed::(total)?; + let (Some(dst), Some(src)) = (out.get_mut(..head), header.get(..head)) else { + return Err(encode_err("output buffer too small")); + }; + dst.copy_from_slice(src); + + let channels = layout.channels(); + let mut level = Cow::Borrowed(pixels); + let (mut size, mut at) = (top, head); + for (i, &bytes) in sizes.iter().enumerate() { + let dst = out.get_mut(at..at + bytes).ok_or_else(|| encode_err("output buffer too small"))?; + write(store, &level, size, dst)?; + at += bytes; + if i + 1 < sizes.len() { + let next = half(size); + level = Cow::Owned(downsample(&level, size, next, channels)?); + size = next; + } + } + Ok(out) +} + +/// The `DDS ` signature, DDS_HEADER and, for a format only DXGI names, DDS_HEADER_DXT10 (the +/// caller keeps the first [`HEADER`] bytes otherwise). `top` is the top level's size in bytes. +fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Result<[u8; HEADER + DX10_HEADER], DdsError> { + let mut b = [0u8; HEADER + DX10_HEADER]; + let mut put = |at: usize, v: u32| { + if let Some(d) = b.get_mut(at..at + 4) { + d.copy_from_slice(&v.to_le_bytes()); + } + }; + // Uncompressed: the pitch of one row. Compressed: the whole top level (its "linear size"). + let (size_flag, pitch_or_size) = if store.is_block() { (DDSD_LINEARSIZE, Some(top)) } else { (DDSD_PITCH, store.row_bytes(width as usize)) }; + let pitch_or_size = pitch_or_size + .and_then(|v| u32::try_from(v).ok()) + .ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?; + let mipmapped = levels > 1; + put(4, 124); + put(8, DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | size_flag | if mipmapped { DDSD_MIPMAPCOUNT } else { 0 }); + put(12, height); + put(16, width); + put(20, pitch_or_size); + put(28, levels); + let (flags, fourcc, bits, masks) = store.pixel_format(); + put(76, 32); + put(80, flags); + put(84, u32::from_le_bytes(fourcc)); + put(88, bits); + for (i, mask) in masks.into_iter().enumerate() { + put(92 + 4 * i, mask); + } + put(108, DDSCAPS_TEXTURE | if mipmapped { DDSCAPS_COMPLEX | DDSCAPS_MIPMAP } else { 0 }); + if let Some(dxgi) = store.dxgi() { + // One 2D texture, no misc flags, alpha mode unknown (straight for the one format with + // alpha, RGBA16, as readers take it). + put(HEADER, dxgi); + put(HEADER + 4, DIMENSION_TEXTURE2D); + put(HEADER + 12, 1); + } + b[..4].copy_from_slice(b"DDS "); + Ok(b) +} + +/// Runs `f` on each `len`-byte row of `out` with its index, in parallel with the `parallel` +/// feature. +fn rows(out: &mut [T], len: usize, f: impl Fn(usize, &mut [T]) + Send + Sync) { + #[cfg(feature = "parallel")] + { + use rayon::prelude::*; + out.par_chunks_mut(len.max(1)).enumerate().for_each(|(i, row)| f(i, row)); + } + #[cfg(not(feature = "parallel"))] + for (i, row) in out.chunks_mut(len.max(1)).enumerate() { + f(i, row); + } +} + +/// Writes one level of `width` × `height` pixels (in the image's layout) into `dst`. +fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst: &mut [u8]) -> Result<(), DdsError> { + let row_bytes = store.row_bytes(width).ok_or_else(|| encode_err("texture size overflow"))?; + match store { + // 16-bit stores are written by `write_level16`. + Store::R16 | Store::Rg16 | Store::Rgb16 | Store::Rgba16 => return Err(encode_err("16-bit storage needs 16-bit pixels")), + Store::Luminance | Store::LuminanceAlpha => { + // The image's gray (and alpha) samples, in the same order. + let src = pixels.get(..dst.len()).ok_or_else(|| encode_err("the level is smaller than its size"))?; + dst.copy_from_slice(src); + } + Store::Bgrx | Store::Bgra => { + let channels = if store == Store::Bgra { 4 } else { 3 }; + rows(dst, row_bytes, |y, row| { + let src = pixels.get(y * width * channels..).unwrap_or_default(); + for (d, s) in row.as_chunks_mut::<4>().0.iter_mut().zip(src.chunks_exact(channels)) { + let byte = |i: usize| s.get(i).copied().unwrap_or(255); + *d = [byte(2), byte(1), byte(0), byte(3)]; + } + }); + } + Store::Bc1 | Store::Bc2 | Store::Bc3 => { + let (texels, _) = pixels.as_chunks::<4>(); + rows(dst, row_bytes, |by, row| { + for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { + let (block, inside) = gather(texels, (width, height), bx, by); + let encoded: &[u8] = match store { + Store::Bc1 => &bc::encode_bc1(&block, inside), + Store::Bc2 => &bc::encode_bc2(&block, inside), + _ => &bc::encode_bc3(&block, inside), + }; + for (d, s) in d.iter_mut().zip(encoded) { + *d = *s; + } + } + }); + } + Store::Bc4 | Store::Bc5 => { + // BC4: the gray channel; BC5: red, then green, of RGB pixels. + let channels = if store == Store::Bc4 { 1 } else { 3 }; + rows(dst, row_bytes, |by, row| { + for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { + for (c, d) in d.as_chunks_mut::<8>().0.iter_mut().enumerate() { + let (values, inside) = gather_channel(pixels, (width, height), channels, c, (bx, by)); + *d = bc::value_block(&values, inside); + } + } + }); + } + } + Ok(()) +} + +/// [`write_level`] for 16-bit pixels: little-endian samples, or BC4/BC5 blocks fitted to them. +fn write_level16(store: Store, pixels: &[u16], (width, height): (usize, usize), dst: &mut [u8]) -> Result<(), DdsError> { + let row_bytes = store.row_bytes(width).ok_or_else(|| encode_err("texture size overflow"))?; + match store { + Store::R16 | Store::Rg16 | Store::Rgba16 => { + // The image's samples, in the same order. + for (d, s) in dst.as_chunks_mut::<2>().0.iter_mut().zip(pixels) { + *d = s.to_le_bytes(); + } + } + Store::Rgb16 => rows(dst, row_bytes, |y, row| { + let src = pixels.get(y * width * 3..).unwrap_or_default(); + for (d, s) in row.as_chunks_mut::<8>().0.iter_mut().zip(src.as_chunks::<3>().0) { + let [r, g, b, a] = [s[0], s[1], s[2], u16::MAX].map(u16::to_le_bytes); + *d = [r[0], r[1], g[0], g[1], b[0], b[1], a[0], a[1]]; + } + }), + Store::Bc4 | Store::Bc5 => { + let channels = if store == Store::Bc4 { 1 } else { 3 }; + rows(dst, row_bytes, |by, row| { + for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { + for (c, d) in d.as_chunks_mut::<8>().0.iter_mut().enumerate() { + let (values, inside) = gather_channel(pixels, (width, height), channels, c, (bx, by)); + *d = bc::value_block16(&values, inside); + } + } + }); + } + // `encode16` rounds BC1 to BC3 to 8 bits; the 8-bit stores take 8-bit pixels. + _ => return Err(encode_err("8-bit storage needs 8-bit pixels")), + } + Ok(()) +} + +/// Channel `c` of block (`bx`, `by`) of pixels with `channels` channels, and which of its texels +/// lie inside the image. +fn gather_channel(pixels: &[T], (width, height): (usize, usize), channels: usize, c: usize, (bx, by): (usize, usize)) -> ([T; 16], Mask) { + let mut values = [T::default(); 16]; + let mut inside: Mask = 0; + for (t, v) in values.iter_mut().enumerate() { + let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4); + if x < width + && y < height + && let Some(&p) = pixels.get((y * width + x) * channels + c) + { + *v = p; + inside |= 1 << t; + } + } + (values, inside) +} + +/// Block (`bx`, `by`)'s texels, and which of them lie inside the image. +fn gather(texels: &[[u8; 4]], (width, height): (usize, usize), bx: usize, by: usize) -> (Block, Mask) { + let mut block = [[0u8; 4]; 16]; + // A block wholly inside the image: four rows of four texels. + let (x0, y0) = (bx * 4, by * 4); + if x0 + 4 <= width && y0 + 4 <= height { + let mut copied = 0; + for (ty, row) in block.as_chunks_mut::<4>().0.iter_mut().enumerate() { + if let Some(src) = texels.get((y0 + ty) * width + x0..).and_then(|s| s.first_chunk::<4>()) { + *row = *src; + copied += 1; + } + } + if copied == 4 { + return (block, Mask::MAX); + } + } + let mut inside: Mask = 0; + for (t, texel) in block.iter_mut().enumerate() { + let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4); + if x < width + && y < height + && let Some(p) = texels.get(y * width + x) + { + *texel = *p; + inside |= 1 << t; + } + } + (block, inside) +} + +/// The next mip level: each pixel the average of the 2×2 pixels it covers, or of 2×3, 3×2 or +/// 3×3 along the last column and row of an odd-sized level, so no pixel is dropped. +fn downsample(src: &[T], (w, h): (usize, usize), (nw, nh): (usize, usize), channels: usize) -> Result, DdsError> { + let len = nw.checked_mul(nh).and_then(|n| n.checked_mul(channels)).ok_or_else(|| encode_err("mip level size overflow"))?; + let mut dst = alloc_zeroed(len)?; + let span = |i: usize, n: usize, size: usize| 2 * i..=if i + 1 == n { size.saturating_sub(1) } else { 2 * i + 1 }; + let ch = channels.max(1); + let line = w * ch; + rows(&mut dst, nw * channels, |y, row| { + let ys = span(y, nh, h); + // Every pixel but those of the last column and row averages exactly 2×2: the same sum + // and rounding as below, from two source rows read in step. + let mut edge = 0; + if y + 1 < nh + && let (Some(r0), Some(r1)) = (src.get(2 * y * line..(2 * y + 1) * line), src.get((2 * y + 1) * line..(2 * y + 2) * line)) + { + let interior = nw.saturating_sub(1); + for ((px, a), b) in row.chunks_exact_mut(ch).zip(r0.chunks_exact(2 * ch)).zip(r1.chunks_exact(2 * ch)).take(interior) { + for (c, v) in px.iter_mut().enumerate() { + let sum = a[c].wide() + a[ch + c].wide() + b[c].wide() + b[ch + c].wide(); + *v = T::from_average((sum + 2) / 4); + } + } + edge = interior; + } + for (x, px) in row.chunks_exact_mut(ch).enumerate().skip(edge) { + let xs = span(x, nw, w); + for (c, v) in px.iter_mut().enumerate() { + let (mut sum, mut n) = (0u32, 0u32); + for sy in ys.clone() { + for sx in xs.clone() { + if let Some(&s) = src.get((sy * w + sx) * channels + c) { + sum += s.wide(); + n += 1; + } + } + } + *v = T::from_average((sum + n / 2) / n.max(1)); + } + } + }); + Ok(dst) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pixel_buffer_of_the_wrong_size_is_refused() { + let options = DdsOptions::default(); + assert!(matches!(encode(2, 2, Layout::Rgb, &[0; 11], options), Err(DdsError::Encode(_)))); + assert!(matches!(encode(2, 2, Layout::Rgb, &[0; 13], options), Err(DdsError::Encode(_)))); + assert!(encode(2, 2, Layout::Rgb, &[0; 12], options).is_ok()); + } + + #[test] + fn block_compressions_take_their_layout_only() { + let options = DdsOptions { compression: DdsCompression::Bc3, mipmaps: false }; + assert_eq!(encode(1, 1, Layout::Rgb, &[1, 2, 3], options), Err(DdsError::Encode("Rgb pixels can't be written as `bc3`".into()))); + for compression in DdsCompression::ALL { + for layout in [Layout::Gray, Layout::GrayA, Layout::Rgb, Layout::Rgba] { + let options = DdsOptions { compression, mipmaps: false }; + let written = encode(1, 1, layout, &[9; 4][..layout.channels()], options); + let takes = compression.layout().is_none_or(|l| l == layout); + assert_eq!(written.is_ok(), takes, "{compression:?} from {layout:?}"); + } + } + } + + #[test] + fn the_header_is_read_before_the_pixels() { + // A header that promises more pixel data than the file holds: its size and layout are + // known, and only decoding fails. + let file = encode(8, 8, Layout::Gray, &[7; 64], DdsOptions::default()).unwrap(); + let texture = Texture::parse(&file[..HEADER + 10]).unwrap(); + assert_eq!((texture.width(), texture.height(), texture.layout()), (8, 8, Layout::Gray)); + assert!(matches!(texture.decode(), Err(DdsError::Malformed(_)))); + assert_eq!(Texture::parse(&file).and_then(|t| t.decode()), Ok(vec![7; 64])); + } + + /// Samples spread over the whole 16-bit range, `channels` a pixel. + fn spread16(width: usize, height: usize, channels: usize) -> Vec { + (0..width * height * channels).map(|i| (i as u32 * 7919 % 65536) as u16).collect() + } + + #[test] + fn uncompressed_16_bit_pixels_round_trip_exactly() { + let (w, h) = (7, 5); + for (layout, dxgi, read_as, pixel_bytes) in [ + (Layout::Gray, 56, Layout::Gray, 2), + (Layout::GrayA, 35, Layout::GrayA, 4), + (Layout::Rgb, 11, Layout::Rgba, 8), + (Layout::Rgba, 11, Layout::Rgba, 8), + ] { + let pixels = spread16(w, h, layout.channels()); + let want: Vec = + if layout == Layout::Rgb { pixels.chunks(3).flat_map(|p| [p[0], p[1], p[2], 65535]).collect() } else { pixels.clone() }; + for mipmaps in [false, true] { + let file = encode16(w as u32, h as u32, layout, &pixels, DdsOptions { compression: DdsCompression::None, mipmaps }).unwrap(); + assert_eq!(le32(&file, HEADER).unwrap(), dxgi, "{layout:?}"); + // 7×5, then 3×2 and 1×1. + let samples = if mipmaps { 7 * 5 + 3 * 2 + 1 } else { 7 * 5 }; + assert_eq!(file.len(), HEADER + DX10_HEADER + samples * pixel_bytes); + let texture = Texture::parse(&file).unwrap(); + assert_eq!(texture.layout(), read_as); + assert_eq!(texture.decode16().unwrap(), want); + assert_eq!(texture.decode().unwrap(), want.iter().map(|&v| to8(v)).collect::>()); + if layout == Layout::Rgba { + let mut premultiplied = file.clone(); + premultiplied[HEADER + 16] = 2; + assert!(matches!(Texture::parse(&premultiplied), Err(DdsError::Unsupported(_)))); + } + } + } + } + + #[test] + fn mip_levels_of_16_bit_pixels_average_at_16_bits() { + // 1000 to 1003 average to 1002 (rounded), which 8 bits can't hold. + let file = encode16(2, 2, Layout::Gray, &[1000, 1001, 1002, 1003], DdsOptions { compression: DdsCompression::None, mipmaps: true }).unwrap(); + assert_eq!(le32(&file, 28).unwrap(), 2); + assert_eq!(file[file.len() - 2..], 1002u16.to_le_bytes()); + } + + #[test] + fn legacy_16_bit_textures_decode_at_16_bits() { + // D3DFMT_A16B16G16R16: the legacy header's numeric FourCC 36, the same pixels as the + // DX10 file. + let pixels = spread16(3, 2, 4); + let file = encode16(3, 2, Layout::Rgba, &pixels, DdsOptions::default()).unwrap(); + let mut legacy = file[..HEADER].to_vec(); + legacy[84..88].copy_from_slice(&36u32.to_le_bytes()); + legacy.extend_from_slice(&file[HEADER + DX10_HEADER..]); + let texture = Texture::parse(&legacy).unwrap(); + assert_eq!((texture.layout(), texture.decode16().unwrap()), (Layout::Rgba, pixels)); + // L16: a 16-bit luminance mask keeps its 16 bits through `decode16`. + let mut l16 = encode(2, 1, Layout::Gray, &[0, 0], DdsOptions::default()).unwrap(); + l16[20..24].copy_from_slice(&4u32.to_le_bytes()); + l16[88..92].copy_from_slice(&16u32.to_le_bytes()); + l16[92..96].copy_from_slice(&0xffffu32.to_le_bytes()); + l16.truncate(HEADER); + l16.extend([300u16, 65000].iter().flat_map(|v| v.to_le_bytes())); + let texture = Texture::parse(&l16).unwrap(); + assert_eq!(texture.decode16().unwrap(), [300, 65000]); + assert_eq!(texture.decode().unwrap(), [1, 253]); + // G16R16 as masks (red low, green high) reads as RGB at 16 bits, blue 0. + let mut g16r16 = l16[..HEADER].to_vec(); + g16r16[80..84].copy_from_slice(&DDPF_RGB.to_le_bytes()); + g16r16[20..24].copy_from_slice(&8u32.to_le_bytes()); + g16r16[88..92].copy_from_slice(&32u32.to_le_bytes()); + g16r16[96..100].copy_from_slice(&0xffff_0000u32.to_le_bytes()); + g16r16.extend([300u16, 40000, 65535, 7].iter().flat_map(|v| v.to_le_bytes())); + let texture = Texture::parse(&g16r16).unwrap(); + assert_eq!((texture.layout(), texture.decode16().unwrap()), (Layout::Rgb, vec![300, 40000, 0, 65535, 7, 0])); + } + + #[test] + fn typeless_and_padded_16_bit_textures_are_read() { + // Rows padded to 8 bytes, as other writers may store them: the padding is skipped. + let file = encode16(3, 2, Layout::Gray, &[1, 2, 3, 4, 5, 6], DdsOptions::default()).unwrap(); + let mut padded = file[..HEADER + DX10_HEADER].to_vec(); + padded[20..24].copy_from_slice(&8u32.to_le_bytes()); + for row in file[HEADER + DX10_HEADER..].chunks(6) { + padded.extend_from_slice(row); + padded.extend_from_slice(&[0xee, 0xee]); + } + assert_eq!(Texture::parse(&padded).unwrap().decode16().unwrap(), [1, 2, 3, 4, 5, 6]); + // The typeless forms read as the UNORM ones; typeless RGBA refuses premultiplied alpha too. + for (unorm, typeless, layout) in [(56u32, 53u32, Layout::Gray), (35, 33, Layout::GrayA), (11, 9, Layout::Rgba)] { + let pixels = spread16(3, 2, layout.channels()); + let file = encode16(3, 2, layout, &pixels, DdsOptions::default()).unwrap(); + assert_eq!(le32(&file, HEADER).unwrap(), unorm); + let mut retyped = file.clone(); + retyped[HEADER..HEADER + 4].copy_from_slice(&typeless.to_le_bytes()); + let texture = Texture::parse(&retyped).unwrap(); + assert_eq!((texture.layout(), texture.decode16().unwrap()), (layout, pixels)); + retyped[HEADER + 16] = 2; + assert_eq!(Texture::parse(&retyped).is_err(), layout == Layout::Rgba); + } + } + + #[test] + fn bc4_and_bc5_from_16_bits_beat_the_8_bit_rounded_source() { + // Smooth ramps, about half an 8-bit level across a block, as in height and normal maps. + // 62×61 leaves partial blocks on the right and bottom edges. + let (w, h) = (62usize, 61usize); + let at = |i: usize| (i % w, i / w); + let height: Vec = (0..w * h).map(|i| (20_000 + at(i).0 * 29 + at(i).1 * 11) as u16).collect(); + let normal: Vec = + (0..w * h).flat_map(|i| [(10_000 + at(i).0 * 23 + at(i).1 * 7) as u16, (40_000 + at(i).1 * 27 + at(i).0 * 5) as u16, 65535]).collect(); + for (compression, layout, pixels) in [(DdsCompression::Bc4, Layout::Gray, &height), (DdsCompression::Bc5, Layout::Rgb, &normal)] { + let options = DdsOptions { compression, mipmaps: true }; + let rounded: Vec = pixels.iter().map(|&v| to8(v)).collect(); + let (file16, file8) = + (encode16(w as u32, h as u32, layout, pixels, options).unwrap(), encode(w as u32, h as u32, layout, &rounded, options).unwrap()); + let from16 = Texture::parse(&file16).unwrap(); + let from8 = Texture::parse(&file8).unwrap(); + let channels = layout.channels(); + // Root-mean-square error of the stored channels (BC5: red and green), in 16-bit units. + let rms = |got: &[u16]| { + let stored = pixels.iter().zip(got).enumerate().filter(|(i, _)| i % channels < 2); + let (sum, n) = stored.fold((0f64, 0f64), |(sum, n), (_, (&a, &b))| (sum + (f64::from(a) - f64::from(b)).powi(2), n + 1.0)); + (sum / n).sqrt() + }; + let (ours, theirs) = (rms(&from16.decode16().unwrap()), rms(&from8.decode16().unwrap())); + eprintln!("{compression:?}: RMS error {ours:.1} from 16 bits, {theirs:.1} from the 8-bit rounded source (16-bit units)"); + assert!(ours * 2.0 < theirs, "{compression:?}: {ours} vs {theirs}"); + // `decode` and `decode16` read the same blocks: 8 bits are the 16-bit values rounded, + // give or take the 8-bit palette's own rounding. + for texture in [&from16, &from8] { + let (narrow, wide) = (texture.decode().unwrap(), texture.decode16().unwrap()); + assert!(narrow.iter().zip(&wide).all(|(&a, &b)| a.abs_diff(to8(b)) <= 1)); + } + } + } + + #[test] + fn bc1_to_bc3_from_16_bits_write_what_the_rounded_pixels_write() { + let pixels = spread16(6, 5, 4); + let rounded: Vec = pixels.iter().map(|&v| to8(v)).collect(); + for compression in [DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3] { + for mipmaps in [false, true] { + let options = DdsOptions { compression, mipmaps }; + assert_eq!(encode16(6, 5, Layout::Rgba, &pixels, options), encode(6, 5, Layout::Rgba, &rounded, options)); + } + } + // `encode16` takes the layouts `encode` takes, and checks the buffer size the same way. + for compression in DdsCompression::ALL { + for layout in [Layout::Gray, Layout::GrayA, Layout::Rgb, Layout::Rgba] { + let options = DdsOptions { compression, mipmaps: false }; + let n = layout.channels(); + assert_eq!( + encode16(1, 1, layout, &[9; 4][..n], options).is_ok(), + encode(1, 1, layout, &[9; 4][..n], options).is_ok(), + "{compression:?} from {layout:?}" + ); + } + } + assert!(matches!(encode16(2, 2, Layout::Rgb, &[0; 11], DdsOptions::default()), Err(DdsError::Encode(_)))); + let bc1 = DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }; + assert_eq!(encode16(1, 1, Layout::Rgba, &[0; 3], bc1), Err(DdsError::Encode("3 16-bit samples of pixels for a 1x1 Rgba texture".into()))); + // Reading BC1 to BC3 at 16 bits: their 8-bit values times 257. + let file = encode16(6, 5, Layout::Rgba, &pixels, bc1).unwrap(); + let texture = Texture::parse(&file).unwrap(); + let narrow = texture.decode().unwrap(); + assert_eq!(texture.decode16().unwrap(), narrow.iter().map(|&v| u16::from(v) * 257).collect::>()); + assert!(matches!(encode16(0, 2, Layout::Rgb, &[], DdsOptions::default()), Err(DdsError::Encode(_)))); + } + + #[test] + fn decode16_checks_its_budget_in_bytes() { + let file = encode16(4, 4, Layout::Gray, &[7; 16], DdsOptions::default()).unwrap(); + let texture = Texture::parse(&file).unwrap(); + assert!(matches!(texture.decode16_with_limit(31), Err(DdsError::LimitExceeded { required: 32, limit: 31 }))); + assert_eq!(texture.decode16_with_limit(32).unwrap(), [7; 16]); + } +} diff --git a/crates/dds/tests/boundary.rs b/crates/dds/tests/boundary.rs new file mode 100644 index 0000000000..ecd3aac112 --- /dev/null +++ b/crates/dds/tests/boundary.rs @@ -0,0 +1,46 @@ +use craft_dds::{DdsCompression, DdsOptions, Layout, Texture, encode}; +#[test] +fn metadata_requires_a_complete_header() { + for (compression, layout, channels, header) in [(DdsCompression::None, Layout::Gray, 1, 128), (DdsCompression::Bc4, Layout::Gray, 1, 148)] { + let data = encode(4, 4, layout, &vec![7; 16 * channels], DdsOptions { compression, mipmaps: false }).unwrap(); + for n in 0..header { + assert!(Texture::parse(&data[..n]).is_err(), "accepted {n}/{header} header bytes"); + } + assert!(Texture::parse(&data[..header]).is_ok()); + } +} +#[test] +fn empty_dimensions_are_not_textures() { + for (w, h) in [(0, 0), (0, 4), (4, 0)] { + assert!(encode(w, h, Layout::Gray, &[], DdsOptions::default()).is_err(), "encoded {w}x{h}"); + } +} +#[test] +fn decoded_output_respects_explicit_budget() { + let data = encode(4, 4, Layout::Rgba, &[7; 64], DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }).unwrap(); + let texture = Texture::parse(&data).unwrap(); + assert!(matches!(texture.decode_with_limit(63), Err(craft_dds::DdsError::LimitExceeded { required: 64, limit: 63 }))); + assert_eq!(texture.decode_with_limit(64).unwrap().len(), 64); + assert_eq!(texture.decode().unwrap(), texture.decode_with_limit(u64::MAX).unwrap()); +} +#[test] +fn parse_rejects_empty_dimensions() { + let valid = encode(1, 1, Layout::Gray, &[7], DdsOptions::default()).unwrap(); + for (w, h) in [(0u32, 0u32), (0, 4), (4, 0)] { + let mut data = valid.clone(); + data[12..16].copy_from_slice(&h.to_le_bytes()); + data[16..20].copy_from_slice(&w.to_le_bytes()); + assert!(Texture::parse(&data).is_err()); + } +} +#[test] +fn default_budget_rejects_oversized_header_before_payload_or_allocation() { + let mut data = encode(1, 1, Layout::Gray, &[7], DdsOptions::default()).unwrap(); + data.truncate(128); + data[12..16].copy_from_slice(&65536u32.to_le_bytes()); + data[16..20].copy_from_slice(&32768u32.to_le_bytes()); + data[20..24].copy_from_slice(&32768u32.to_le_bytes()); + let texture = Texture::parse(&data).unwrap(); + assert!(matches!(texture.decode(), Err(craft_dds::DdsError::LimitExceeded { limit: craft_dds::DEFAULT_MAX_DECODE_BYTES, .. }))); + assert!(matches!(texture.decode_with_limit(u64::MAX), Err(craft_dds::DdsError::Malformed(_)))); +} diff --git a/crates/deckcraft-format/Cargo.toml b/crates/deckcraft-format/Cargo.toml new file mode 100644 index 0000000000..d7c6b035fb --- /dev/null +++ b/crates/deckcraft-format/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "craft-deckcraft-format" +description = "The DeckCraft .deckcraft package: identity, manifest envelope, NaN-safe JSON, member names and bounded reads" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-zip = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +zip = { version = "9", default-features = false, features = ["deflate-flate2"] } diff --git a/crates/deckcraft-format/README.md b/crates/deckcraft-format/README.md new file mode 100644 index 0000000000..94f5d90e8d --- /dev/null +++ b/crates/deckcraft-format/README.md @@ -0,0 +1,25 @@ +# craft-deckcraft-format + +The DeckCraft `.deckcraft` package. A file is a ZIP that holds, in this order: + +- `mimetype`, stored: `application/vnd.storyteller.deckcraft+zip`. Files from before the + SlideCraft rename carry the legacy type, and `sniff` accepts both. +- `presentation.json`, deflated: `{"format":"deckcraft","version":1,"generator":…,"presentation":…}`. + It is compact JSON, and non-finite numbers are written as `0` (`Finite`). +- `media/` and `chart-parts/` binary members. A member whose content type is already + compressed (JPEG, PNG, video, MP3/MP4 audio, anything `zip`) is stored, and any other member is deflated. + +The presentation is a type parameter: DeckCraft owns the model, decides which media and chart +parts become members, and repairs a loaded deck. This crate owns the bytes: + +- `write(presentation, generator, members)` writes the package with `craft-zip`'s deterministic writer. +- `Package::open_manifest(bytes, max)` reads and checks the manifest. A file with no + `presentation.json` or a different `format` is `NotOurs`. `parse_manifest` reads files written + before `Finite`, where serde_json saved NaN as `null`, as 0 within fixed patch and re-parse budgets. +- `Package::read_max` refuses a member that declares more than its limit and stops one that + inflates past it. `read_charged` charges a shared budget for every byte it inflates, including + the bytes of a read that then fails its CRC. +- `Budget` and the `MAX_*` constants are the format's limits: 2 GiB per member, 4 GiB of media and + chart parts, 100,000 items and a 256 MiB manifest. + +There is no `unsafe` and no panics, and it builds for `wasm32-unknown-unknown`. diff --git a/crates/deckcraft-format/src/finite.rs b/crates/deckcraft-format/src/finite.rs new file mode 100644 index 0000000000..834108a335 --- /dev/null +++ b/crates/deckcraft-format/src/finite.rs @@ -0,0 +1,185 @@ +//! A serde serializer adapter that writes non-finite floats as 0. +//! +//! serde_json writes NaN and ±infinity as `null`, which doesn't read back as a number: a single +//! NaN anywhere in the model (a rotation, a crop, a stroke width) made a saved file fail to open +//! as "damaged". [`Finite`] wraps any `Serialize` value and replaces those floats on the way out; +//! everything else passes through unchanged. + +use serde::ser::{self, Serialize, Serializer}; + +/// `T`, serialized with non-finite floats written as 0. +pub struct Finite<'a, T: ?Sized>(pub &'a T); + +impl Serialize for Finite<'_, T> { + fn serialize(&self, s: S) -> Result { + self.0.serialize(Wrap(s)) + } +} + +struct Wrap(S); + +macro_rules! pass { + ($($m:ident($t:ty)),* $(,)?) => { + $(fn $m(self, v: $t) -> Result { self.0.$m(v) })* + }; +} + +impl Serializer for Wrap { + type Ok = S::Ok; + type Error = S::Error; + type SerializeSeq = Wrap; + type SerializeTuple = Wrap; + type SerializeTupleStruct = Wrap; + type SerializeTupleVariant = Wrap; + type SerializeMap = Wrap; + type SerializeStruct = Wrap; + type SerializeStructVariant = Wrap; + + pass!( + serialize_bool(bool), + serialize_i8(i8), + serialize_i16(i16), + serialize_i32(i32), + serialize_i64(i64), + serialize_i128(i128), + serialize_u8(u8), + serialize_u16(u16), + serialize_u32(u32), + serialize_u64(u64), + serialize_u128(u128), + serialize_char(char), + serialize_str(&str), + serialize_bytes(&[u8]), + ); + + fn serialize_f32(self, v: f32) -> Result { + self.0.serialize_f32(if v.is_finite() { v } else { 0.0 }) + } + fn serialize_f64(self, v: f64) -> Result { + self.0.serialize_f64(if v.is_finite() { v } else { 0.0 }) + } + fn serialize_none(self) -> Result { + self.0.serialize_none() + } + fn serialize_some(self, v: &T) -> Result { + self.0.serialize_some(&Finite(v)) + } + fn serialize_unit(self) -> Result { + self.0.serialize_unit() + } + fn serialize_unit_struct(self, name: &'static str) -> Result { + self.0.serialize_unit_struct(name) + } + fn serialize_unit_variant(self, name: &'static str, i: u32, variant: &'static str) -> Result { + self.0.serialize_unit_variant(name, i, variant) + } + fn serialize_newtype_struct(self, name: &'static str, v: &T) -> Result { + self.0.serialize_newtype_struct(name, &Finite(v)) + } + fn serialize_newtype_variant(self, name: &'static str, i: u32, variant: &'static str, v: &T) -> Result { + self.0.serialize_newtype_variant(name, i, variant, &Finite(v)) + } + fn serialize_seq(self, len: Option) -> Result { + self.0.serialize_seq(len).map(Wrap) + } + fn serialize_tuple(self, len: usize) -> Result { + self.0.serialize_tuple(len).map(Wrap) + } + fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result { + self.0.serialize_tuple_struct(name, len).map(Wrap) + } + fn serialize_tuple_variant(self, name: &'static str, i: u32, variant: &'static str, len: usize) -> Result { + self.0.serialize_tuple_variant(name, i, variant, len).map(Wrap) + } + fn serialize_map(self, len: Option) -> Result { + self.0.serialize_map(len).map(Wrap) + } + fn serialize_struct(self, name: &'static str, len: usize) -> Result { + self.0.serialize_struct(name, len).map(Wrap) + } + fn serialize_struct_variant( + self, + name: &'static str, + i: u32, + variant: &'static str, + len: usize, + ) -> Result { + self.0.serialize_struct_variant(name, i, variant, len).map(Wrap) + } + fn is_human_readable(&self) -> bool { + self.0.is_human_readable() + } +} + +macro_rules! compound { + ($tr:ident, $m:ident) => { + impl ser::$tr for Wrap { + type Ok = S::Ok; + type Error = S::Error; + fn $m(&mut self, v: &T) -> Result<(), S::Error> { + self.0.$m(&Finite(v)) + } + fn end(self) -> Result { + self.0.end() + } + } + }; +} +compound!(SerializeSeq, serialize_element); +compound!(SerializeTuple, serialize_element); +compound!(SerializeTupleStruct, serialize_field); +compound!(SerializeTupleVariant, serialize_field); + +impl ser::SerializeMap for Wrap { + type Ok = S::Ok; + type Error = S::Error; + fn serialize_key(&mut self, k: &T) -> Result<(), S::Error> { + self.0.serialize_key(&Finite(k)) + } + fn serialize_value(&mut self, v: &T) -> Result<(), S::Error> { + self.0.serialize_value(&Finite(v)) + } + fn end(self) -> Result { + self.0.end() + } +} + +macro_rules! fields { + ($tr:ident) => { + impl ser::$tr for Wrap { + type Ok = S::Ok; + type Error = S::Error; + fn serialize_field(&mut self, key: &'static str, v: &T) -> Result<(), S::Error> { + self.0.serialize_field(key, &Finite(v)) + } + fn skip_field(&mut self, key: &'static str) -> Result<(), S::Error> { + self.0.skip_field(key) + } + fn end(self) -> Result { + self.0.end() + } + } + }; +} +fields!(SerializeStruct); +fields!(SerializeStructVariant); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn non_finite_floats_are_written_as_zero_and_nothing_else_changes() { + #[derive(serde::Serialize)] + struct T { + a: f64, + b: Option, + c: Vec<(f32, f64)>, + d: Option, + e: std::collections::BTreeMap, + } + let t = T { a: f64::NAN, b: Some(f64::INFINITY), c: vec![(f32::NEG_INFINITY, 1.5)], d: None, e: [("k".to_string(), f64::NAN)].into() }; + let s = serde_json::to_string(&Finite(&t)).unwrap_or_default(); + assert_eq!(s, r#"{"a":0.0,"b":0.0,"c":[[0.0,1.5]],"d":null,"e":{"k":0.0}}"#); + } +} diff --git a/crates/deckcraft-format/src/lib.rs b/crates/deckcraft-format/src/lib.rs new file mode 100644 index 0000000000..b59363c99d --- /dev/null +++ b/crates/deckcraft-format/src/lib.rs @@ -0,0 +1,226 @@ +//! The native `.deckcraft` package: a ZIP holding a stored `mimetype`, `presentation.json` (the +//! manifest: format name, version, generator and the presentation, minus media bytes), and +//! `media/` and `chart-parts/` binary members. Readers ignore unknown fields, so newer +//! files open in older builds with what those builds understand. +//! +//! DeckCraft owns the presentation model and its mapping: which media and chart parts become +//! members, and how a loaded deck is repaired. This crate owns the bytes: the package identity, +//! the manifest envelope, the NaN-safe JSON writer, the reader that opens files with NaN saved as +//! `null`, member names and compression, and the bounded member reads and their budgets. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +mod finite; +mod manifest; + +#[cfg(test)] +mod tests; + +use std::io::{Cursor, Read}; + +pub use finite::Finite; +pub use manifest::parse_manifest; + +pub const MIMETYPE: &str = "application/vnd.storyteller.deckcraft+zip"; +/// Files written before the SlideCraft → DeckCraft rename (`.slidecraft`) are still read. +pub const LEGACY_MIMETYPE: &str = concat!("application/vnd.storyteller.", "slide", "craft+zip"); +pub const EXTENSION: &str = "deckcraft"; +/// The manifest's `format`. +pub const FORMAT: &str = "deckcraft"; +/// Format version written into the manifest. +pub const VERSION: u32 = 1; +/// The stored member naming the package type. +pub const MIMETYPE_ENTRY: &str = "mimetype"; +/// The manifest member. +pub const MANIFEST_ENTRY: &str = "presentation.json"; +/// Largest entry we will inflate (guards against zip bombs). +pub const MAX_ENTRY: u64 = 2 << 30; +/// All embedded media and chart sidecars together, inflated (storytold/deckcraft#393). +pub const MAX_TOTAL_MEDIA: u64 = 4 << 30; +/// Media items and chart sidecar parts one file may list. +pub const MAX_MEDIA_ITEMS: usize = 100_000; +/// Largest `presentation.json` we will inflate. The manifest holds no media bytes, so it is far +/// smaller than a media entry may be; inflating and parsing one is what dominates memory. +pub const MAX_MANIFEST: u64 = 256 << 20; + +const MEDIA_PREFIX: &str = "media/"; +const CHART_PARTS_PREFIX: &str = "chart-parts/"; + +/// What one load may inflate. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Budget { + /// Bytes all media and chart members may inflate to together. + pub total: u64, + /// Media items and chart parts the manifest may list. + pub items: usize, + /// Bytes `presentation.json` may inflate to. + pub manifest: u64, +} + +impl Default for Budget { + fn default() -> Self { + Budget { total: MAX_TOTAL_MEDIA, items: MAX_MEDIA_ITEMS, manifest: MAX_MANIFEST } + } +} + +impl Budget { + /// A media budget with the default manifest limit. + pub const fn media(total: u64, items: usize) -> Self { + Budget { total, items, manifest: MAX_MANIFEST } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum FormatError { + #[error("not a DeckCraft file: {0}")] + NotOurs(String), + #[error("damaged file: {0}")] + Damaged(String), + #[error("write failed: {0}")] + Write(String), +} + +pub type Result = std::result::Result; + +/// `presentation.json`: the envelope around the app's presentation. +#[derive(serde::Serialize, serde::Deserialize)] +pub struct Manifest { + pub format: String, + pub version: u32, + pub generator: String, + pub presentation: T, +} + +/// The member holding media item `id`'s bytes. +pub fn media_entry(id: u32) -> String { + format!("{MEDIA_PREFIX}{id}") +} + +/// The member holding the `index`th chart part a save separated out. +pub fn chart_part_entry(index: usize) -> String { + format!("{CHART_PARTS_PREFIX}{index}") +} + +/// Whether `entry` is a name [`chart_part_entry`] gives, exactly: no other member, no path +/// tricks, no leading zeros. +pub fn is_chart_part_entry(entry: &str) -> bool { + entry.strip_prefix(CHART_PARTS_PREFIX).and_then(|s| s.parse::().ok()).is_some_and(|n| entry == chart_part_entry(n)) +} + +/// Whether a member of this content type is stored rather than deflated: it is compressed already. +pub fn is_compressed(content_type: &str) -> bool { + content_type.starts_with("image/jpeg") + || content_type.starts_with("image/png") + || content_type.starts_with("video/") + || content_type.starts_with("audio/mpeg") + || content_type.starts_with("audio/mp4") + || content_type.contains("zip") +} + +/// Does this look like a `.deckcraft` file? +pub fn sniff(bytes: &[u8]) -> bool { + bytes.starts_with(b"PK") && [MIMETYPE, LEGACY_MIMETYPE].iter().any(|m| bytes.windows(m.len()).take(200).any(|w| w == m.as_bytes())) +} + +/// A binary member of a package being written. +#[derive(Clone, Copy, Debug)] +pub struct Member<'a> { + /// Its name, from [`media_entry`] or [`chart_part_entry`]. + pub name: &'a str, + /// Its content type, which decides whether it is stored or deflated. + pub content_type: &'a str, + pub bytes: &'a [u8], +} + +/// The package: `mimetype` (stored), the manifest naming `generator` around `presentation` +/// (deflated, with non-finite numbers written as 0), then `members` in order. +pub fn write(presentation: &T, generator: &str, members: &[Member<'_>]) -> Result> { + use craft_zip::Compression::{Deflated, Stored}; + let w = |e: craft_zip::Error| FormatError::Write(e.to_string()); + let mut z = craft_zip::Writer::new(); + z.add(MIMETYPE_ENTRY, MIMETYPE.as_bytes(), Stored).map_err(w)?; + let m = Manifest { format: FORMAT.to_string(), version: VERSION, generator: generator.to_string(), presentation }; + let json = serde_json::to_vec(&Finite(&m)).map_err(|e| FormatError::Write(e.to_string()))?; + z.add(MANIFEST_ENTRY, &json, Deflated).map_err(w)?; + for member in members { + let compression = if is_compressed(member.content_type) { Stored } else { Deflated }; + z.add(member.name, member.bytes, compression).map_err(w)?; + } + z.finish().map_err(w) +} + +/// A package open for reading. Nothing is inflated until a member is read. +pub struct Package<'a> { + zip: zip::ZipArchive>, +} + +impl<'a> Package<'a> { + /// Index `bytes` as a ZIP. + pub fn open(bytes: &'a [u8]) -> Result { + let zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| FormatError::NotOurs(e.to_string()))?; + Ok(Package { zip }) + } + + /// Open `bytes` and read its manifest, inflating at most `max_manifest` bytes of it. Missing + /// `presentation.json` or a different `format` is [`FormatError::NotOurs`]. + pub fn open_manifest(bytes: &'a [u8], max_manifest: u64) -> Result<(Manifest, Self)> { + let mut package = Package::open(bytes)?; + if !package.contains(MANIFEST_ENTRY) { + return Err(FormatError::NotOurs(format!("no {MANIFEST_ENTRY}"))); + } + let json = package.read_max(MANIFEST_ENTRY, max_manifest)?; + let m: Manifest = parse_manifest(&json)?; + if m.format != FORMAT { + return Err(FormatError::NotOurs(m.format)); + } + Ok((m, package)) + } + + /// Whether the package has a member named `name`. + pub fn contains(&self, name: &str) -> bool { + self.zip.index_for_name(name).is_some() + } + + /// The size `name` declares, inflated; `None` when there is no such readable member. + pub fn declared_size(&mut self, name: &str) -> Option { + self.zip.by_name(name).ok().map(|f| f.size()) + } + + /// Read one member within [`MAX_ENTRY`]. + pub fn read(&mut self, name: &str) -> Result> { + self.read_max(name, MAX_ENTRY) + } + + /// Read one member, refusing it before inflating if it declares more than `max` bytes, and + /// stopping at `max` if it inflates further than it declared. + pub fn read_max(&mut self, name: &str, max: u64) -> Result> { + self.read_counted(name, max, &mut 0) + } + + /// [`Package::read_max`] within `left` (and [`MAX_ENTRY`]), charging `left` for every byte + /// inflated, including those inflated before a decode or CRC error, so a member that fails + /// late still spends the shared budget it used. + pub fn read_charged(&mut self, name: &str, left: &mut u64) -> Result> { + let mut spent = 0; + let out = self.read_counted(name, (*left).min(MAX_ENTRY), &mut spent); + *left = left.saturating_sub(spent); + out + } + + /// [`Package::read_max`], adding the bytes inflated to `spent` whether or not the read succeeds. + fn read_counted(&mut self, name: &str, max: u64, spent: &mut u64) -> Result> { + let f = self.zip.by_name(name).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?; + if f.size() > max { + return Err(FormatError::Damaged(format!("{name} is too large"))); + } + let mut out = Vec::with_capacity(usize::try_from(f.size().min(64 << 20)).unwrap_or(0)); + let mut f = f.take(max.saturating_add(1)); + let read = f.read_to_end(&mut out); + *spent = spent.saturating_add(out.len() as u64); + read.map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?; + if out.len() as u64 > max { + return Err(FormatError::Damaged(format!("{name} is too large"))); + } + Ok(out) + } +} diff --git a/crates/deckcraft-format/src/manifest.rs b/crates/deckcraft-format/src/manifest.rs new file mode 100644 index 0000000000..03f017ace1 --- /dev/null +++ b/crates/deckcraft-format/src/manifest.rs @@ -0,0 +1,99 @@ +//! Reading `presentation.json`, including files written with NaN or infinity saved as `null`. + +use serde::de::DeserializeOwned; + +use crate::{FormatError, Manifest, Result}; + +/// Most `null`s standing in for numbers that [`parse_manifest`] patches in one file, and the +/// candidates it tries for each. +const MAX_NULL_FIXES: usize = 256; +const MAX_TRIES_PER_FIX: usize = 32; +/// Bytes [`parse_manifest`] may re-parse in all while patching, so a hostile file full of `null`s +/// can't keep it busy: past this the file is reported damaged. +const MAX_REPARSE_BYTES: usize = 256 * 1024 * 1024; + +/// Where a parse failed, comparable: later is progress. +fn failure(src: &[u8]) -> std::result::Result, (String, (usize, usize))> { + serde_json::from_slice::>(src).map_err(|e| (e.to_string(), (e.line(), e.column()))) +} + +/// Parse `presentation.json`. serde_json writes a NaN or infinite number as `null`, which then +/// fails to read back as a number ("invalid type: null, expected f64"), so DeckCraft could save +/// a file it couldn't open. Each such `null` is read as 0 instead (the app then brings the +/// value into range); anything else that doesn't parse is damage. +/// +/// serde reports the failing `null` exactly, except inside tagged enums (buffered), where it +/// reports the end of the enclosing object: there the `null`s before that point are tried +/// nearest first, and a patch is kept only if the parse then gets further. (Files saved since +/// [`crate::Finite`] never contain such `null`s; this reads older ones.) +pub fn parse_manifest(json: &[u8]) -> Result> { + // Parse the inflated text as it is: only a file that fails on a `null` number is copied for + // patching (the copy is bounded by `MAX_MANIFEST`). + let mut last = match failure(json) { + Ok(m) => return Ok(m), + Err(f) => f, + }; + if !is_null_number(&last.0) { + return Err(FormatError::Damaged(last.0)); + } + let mut src = json.to_vec(); + let mut budget = MAX_REPARSE_BYTES; + 'fixes: for _ in 0..MAX_NULL_FIXES { + let (msg, pos) = &last; + if !is_null_number(msg) { + break; + } + let end = offset(&src, pos.0, pos.1).unwrap_or(src.len()); + let mut progressed = false; + let candidates: Vec = value_nulls_before(&src, end + 4).take(MAX_TRIES_PER_FIX).collect(); + for at in candidates { + let (Some(head), Some(tail)) = (src.get(..at), src.get(at.saturating_add(4)..)) else { continue }; + let Some(left) = budget.checked_sub(src.len()) else { break 'fixes }; + budget = left; + let mut next = Vec::with_capacity(src.len()); + next.extend_from_slice(head); + next.push(b'0'); + next.extend_from_slice(tail); + match failure(&next) { + Ok(m) => return Ok(m), + // The patch shortened the text by 3 bytes before the error: compare positions + // allowing for that. + Err(f) if f.1 > (pos.0, pos.1.saturating_sub(3)) => { + src = next; + last = f; + progressed = true; + break; + } + Err(_) => {} + } + } + if !progressed { + break; + } + } + Err(FormatError::Damaged(last.0)) +} + +/// Is this parse error a `null` where a number belongs (a NaN or infinity serde_json wrote)? +fn is_null_number(msg: &str) -> bool { + msg.starts_with("invalid type: null, expected f") || msg.starts_with("invalid type: null, expected a number") +} + +/// Byte offset of a 1-based `line`:`column`. +fn offset(src: &[u8], line: usize, column: usize) -> Option { + let mut start = 0; + for _ in 1..line { + start += src.get(start..)?.iter().position(|b| *b == b'\n')? + 1; + } + Some((start + column).min(src.len())) +} + +/// Starts of `null` tokens in value position (after `:`, `[` or `,`) before `end`, nearest first. +fn value_nulls_before(src: &[u8], end: usize) -> impl Iterator + '_ { + let end = end.min(src.len()); + (0..end.saturating_sub(3)).rev().filter(move |&i| { + src.get(i..i + 4) == Some(b"null") + && src[..i].iter().rev().find(|b| !b.is_ascii_whitespace()).is_some_and(|b| matches!(b, b':' | b'[' | b',')) + && src.get(i + 4).is_none_or(|b| !b.is_ascii_alphanumeric()) + }) +} diff --git a/crates/deckcraft-format/src/tests.rs b/crates/deckcraft-format/src/tests.rs new file mode 100644 index 0000000000..8090d709ae --- /dev/null +++ b/crates/deckcraft-format/src/tests.rs @@ -0,0 +1,235 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde::{Deserialize, Serialize}; + +use super::*; + +/// A stand-in for an app's presentation: plain numbers, an optional number and a tagged enum +/// (whose `null`s serde reports only at the end of the enclosing object). +#[derive(Debug, Default, PartialEq, Serialize, Deserialize)] +struct Deck { + #[serde(default)] + width: f64, + #[serde(default)] + zoom: Option, + #[serde(default)] + shapes: Vec, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind")] +enum Shape { + Box { x: f64, y: f64 }, + Line { len: f64 }, +} + +fn package(members: &[Member<'_>]) -> Vec { + write(&Deck { width: 960.0, ..Default::default() }, "Test 1", members).unwrap() +} + +#[test] +fn a_package_holds_mimetype_then_manifest_then_members_in_order() { + let png = [0x89, b'P', b'N', b'G']; + let svg = b"".repeat(20); + let bytes = package(&[ + Member { name: &media_entry(7), content_type: "image/png", bytes: &png }, + Member { name: &media_entry(8), content_type: "image/svg+xml", bytes: &svg }, + Member { name: &chart_part_entry(0), content_type: "application/zip", bytes: b"PK" }, + ]); + assert!(sniff(&bytes)); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap(); + assert_eq!(z.len(), 5); + let methods: Vec<_> = (0..z.len()) + .map(|i| { + let f = z.by_index(i).unwrap(); + (f.name().unwrap().into_owned(), f.compression()) + }) + .collect(); + use zip::CompressionMethod::{Deflated, Stored}; + assert_eq!( + methods, + [("mimetype", Stored), ("presentation.json", Deflated), ("media/7", Stored), ("media/8", Deflated), ("chart-parts/0", Stored)] + .map(|(n, m)| (n.to_string(), m)) + ); + // The mimetype is the first, stored member, readable in place. + assert_eq!(craft_zip::stored_mimetype(&bytes), Some(MIMETYPE.as_bytes())); + let (m, mut p) = Package::open_manifest::(&bytes, MAX_MANIFEST).unwrap(); + assert_eq!((m.format.as_str(), m.version, m.generator.as_str(), m.presentation.width), (FORMAT, VERSION, "Test 1", 960.0)); + assert_eq!(p.read(&media_entry(8)).unwrap(), svg); + assert_eq!(p.declared_size(&media_entry(7)), Some(4)); + assert_eq!(p.declared_size("media/99"), None); +} + +#[test] +fn the_manifest_is_compact_json_with_its_fields_in_order() { + let bytes = package(&[]); + let mut p = Package::open(&bytes).unwrap(); + let json = String::from_utf8(p.read(MANIFEST_ENTRY).unwrap()).unwrap(); + assert_eq!(json, r#"{"format":"deckcraft","version":1,"generator":"Test 1","presentation":{"width":960.0,"zoom":null,"shapes":[]}}"#); +} + +#[test] +fn non_finite_numbers_are_written_as_zero_and_read_back() { + let deck = Deck { width: f64::NAN, zoom: Some(f64::INFINITY), shapes: vec![Shape::Box { x: f64::NEG_INFINITY, y: 2.0 }] }; + let bytes = write(&deck, "t", &[]).unwrap(); + let (m, _) = Package::open_manifest::(&bytes, MAX_MANIFEST).unwrap(); + assert_eq!(m.presentation, Deck { width: 0.0, zoom: Some(0.0), shapes: vec![Shape::Box { x: 0.0, y: 2.0 }] }); +} + +/// Files written before [`Finite`] (plain serde_json: NaN as `null`) open too, including a +/// `null` inside a tagged enum, where serde reports only the enclosing object. +#[test] +fn older_manifests_with_null_numbers_parse() { + let cases: [(&str, Deck); 3] = [ + (r#"{"format":"deckcraft","version":1,"generator":"old","presentation":{"width":null}}"#, Deck::default()), + ( + r#"{"format":"deckcraft","version":1,"generator":"old","presentation":{"width":3,"shapes":[{"kind":"Box","x":null,"y":4}]}}"#, + Deck { width: 3.0, shapes: vec![Shape::Box { x: 0.0, y: 4.0 }], ..Default::default() }, + ), + ( + "{\n \"format\": \"deckcraft\",\n \"version\": 1,\n \"generator\": \"t\",\n \"presentation\": {\"shapes\": [{\"kind\": \"Line\", \"len\": null}]}\n}", + Deck { shapes: vec![Shape::Line { len: 0.0 }], ..Default::default() }, + ), + ]; + for (json, want) in cases { + let m = parse_manifest::(json.as_bytes()).unwrap_or_else(|e| panic!("{json}: {e}")); + assert_eq!(m.presentation, want, "{json}"); + } +} + +/// Only `null`s where numbers belong are patched: other damage still fails. +#[test] +fn other_manifest_damage_is_still_reported() { + let ok = br#"{"format": "deckcraft", "version": 1, "generator": "t", "presentation": {}}"#; + assert!(parse_manifest::(ok).is_ok()); + let bad = br#"{"format": null, "version": 1, "generator": "t", "presentation": {}}"#; + assert!(matches!(parse_manifest::(bad), Err(FormatError::Damaged(_)))); + assert!(parse_manifest::(&ok[..ok.len() - 3]).is_err()); +} + +#[test] +fn a_manifest_full_of_nulls_is_refused_within_bounds() { + let shapes = (0..2000).map(|_| r#"{"kind":"Box","x":1,"y":"not a number"}"#).collect::>().join(","); + let json = format!(r#"{{"format":"deckcraft","version":1,"generator":"t","presentation":{{"width":null,"shapes":[{shapes}]}}}}"#); + assert!(matches!(parse_manifest::(json.as_bytes()), Err(FormatError::Damaged(_)))); +} + +#[test] +fn what_is_not_a_package_is_not_ours() { + for bytes in [&b""[..], b"PK\x03\x04garbage", &[0u8; 1000]] { + assert!(matches!(Package::open_manifest::(bytes, MAX_MANIFEST), Err(FormatError::NotOurs(_)))); + } + // A ZIP without the manifest, and one from another app. + let mut z = craft_zip::Writer::new(); + z.add("mimetype", b"application/zip", craft_zip::Compression::Stored).unwrap(); + let no_manifest = z.finish().unwrap(); + let err = Package::open_manifest::(&no_manifest, MAX_MANIFEST).err().unwrap(); + assert_eq!(err.to_string(), "not a DeckCraft file: no presentation.json"); + let mut z = craft_zip::Writer::new(); + z.add(MANIFEST_ENTRY, br#"{"format":"other","version":1,"generator":"x","presentation":{}}"#, craft_zip::Compression::Deflated).unwrap(); + let other = z.finish().unwrap(); + let err = Package::open_manifest::(&other, MAX_MANIFEST).err().unwrap(); + assert_eq!(err.to_string(), "not a DeckCraft file: other"); + // A truncated package is an error, not a panic. + let mut b = package(&[]); + b.truncate(b.len() / 2); + assert!(Package::open_manifest::(&b, MAX_MANIFEST).is_err()); +} + +#[test] +fn legacy_slidecraft_packages_are_recognised() { + let mut z = craft_zip::Writer::new(); + z.add(MIMETYPE_ENTRY, LEGACY_MIMETYPE.as_bytes(), craft_zip::Compression::Stored).unwrap(); + assert!(sniff(&z.finish().unwrap())); + assert!(!sniff(b"PK\x03\x04 application/zip")); + assert!(!sniff(MIMETYPE.as_bytes())); +} + +#[test] +fn an_oversized_manifest_is_refused_before_inflating() { + let bytes = package(&[]); + let size = Package::open(&bytes).unwrap().declared_size(MANIFEST_ENTRY).unwrap(); + assert!(Package::open_manifest::(&bytes, size).is_ok()); + let err = Package::open_manifest::(&bytes, size - 1).err().unwrap(); + assert_eq!(err.to_string(), "damaged file: presentation.json is too large"); +} + +#[test] +fn a_member_that_inflates_past_its_declared_size_stops_at_the_limit() { + // Declared sizes are the file's word: a stored member whose header lies is still capped. + let data = vec![7u8; 100]; + let bytes = package(&[Member { name: &media_entry(1), content_type: "image/png", bytes: &data }]); + let mut p = Package::open(&bytes).unwrap(); + assert_eq!(p.read_max(&media_entry(1), 100).unwrap().len(), 100); + assert!(p.read_max(&media_entry(1), 99).is_err()); + let err = p.read("media/2").unwrap_err(); + assert!(matches!(err, FormatError::Damaged(ref m) if m.starts_with("media/2: ")), "{err}"); +} + +#[test] +fn corrupt_members_are_charged_for_what_they_inflated() { + let a = b"PICTURE-AAAAAAAAAAAA"; + let b = b"PICTURE-BBBBBBBBBBBB"; + let mut bytes = package(&[ + Member { name: &media_entry(1), content_type: "image/png", bytes: a }, + Member { name: &media_entry(2), content_type: "image/png", bytes: b }, + ]); + // Corrupt both stored members, so each fails its CRC only after inflating all its bytes. + for tag in [b"PICTURE-AAAA", b"PICTURE-BBBB"] { + let at = bytes.windows(tag.len()).position(|w| w == tag).unwrap(); + bytes[at] ^= 0xff; + } + let mut p = Package::open(&bytes).unwrap(); + let mut left = 30; + assert!(p.read_charged(&media_entry(1), &mut left).is_err()); + assert_eq!(left, 10, "a failed read still spends what it inflated"); + // The second fits a fresh budget on its own, but not what is left: refused before inflating. + let err = p.read_charged(&media_entry(2), &mut left).unwrap_err(); + assert_eq!(err.to_string(), "damaged file: media/2 is too large"); + assert_eq!(left, 10); +} + +#[test] +fn chart_part_names_are_exact() { + assert_eq!(chart_part_entry(3), "chart-parts/3"); + assert!(is_chart_part_entry("chart-parts/0")); + assert!(is_chart_part_entry("chart-parts/12")); + for not in ["media/1", "chart-parts/../0", "chart-parts/00", "chart-parts/-1", "chart-parts/", "chart-parts/+1", "chart-parts/1 "] { + assert!(!is_chart_part_entry(not), "{not}"); + } +} + +#[test] +fn compressed_content_types_are_stored() { + for stored in [ + "image/jpeg", + "image/png", + "video/mp4", + "audio/mpeg", + "audio/mp4", + "application/zip", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet+zip", + ] { + assert!(is_compressed(stored), "{stored}"); + } + for deflated in ["image/svg+xml", "image/gif", "audio/wav", "application/octet-stream", "text/plain"] { + assert!(!is_compressed(deflated), "{deflated}"); + } +} + +#[test] +fn duplicate_members_are_a_write_error() { + let err = write( + &Deck::default(), + "t", + &[Member { name: "media/1", content_type: "x", bytes: b"a" }, Member { name: "media/1", content_type: "x", bytes: b"b" }], + ) + .unwrap_err(); + assert!(matches!(err, FormatError::Write(_)), "{err}"); +} + +#[test] +fn the_default_budget_is_the_formats_limits() { + assert_eq!(Budget::default(), Budget { total: 4 << 30, items: 100_000, manifest: 256 << 20 }); + assert_eq!(Budget::media(10, 2), Budget { total: 10, items: 2, manifest: MAX_MANIFEST }); +} diff --git a/crates/doc-binary/README.md b/crates/doc-binary/README.md index 359a7bce3f..0245cada81 100644 --- a/crates/doc-binary/README.md +++ b/crates/doc-binary/README.md @@ -1,22 +1,33 @@ # craft-doc-binary -Reader for the Word 97-2003 binary file format (`.doc`, [MS-DOC]) into the `craft-wordmodel` -document model. It is WordCraft's reader, on `craft-cfb` for the compound file and -`craft-codepage` for 8-bit text. +Reader and writer for the Word 97-2003 binary file format (`.doc`, [MS-DOC]) and the +`craft-wordmodel` document model. It is WordCraft's reader and writer, on `craft-cfb` for the +compound file and `craft-codepage` for 8-bit text. ```rust // Not a compound file: an error, never a panic. assert!(craft_doc_binary::read(b"not a .doc").is_err()); assert!(!craft_doc_binary::is_encrypted(b"not a .doc")); + +// A document written as a .doc reads back. +let bytes = craft_doc_binary::write(&craft_wordmodel::Document::from_text("Hello")).unwrap(); +let doc = craft_doc_binary::read(&bytes).unwrap(); +assert_eq!(doc.body[0].as_para().map(|p| p.text.as_str()), Some("Hello")); ``` -- `read(bytes)`, `read_with_password(bytes, Option<&str>)`, `is_encrypted(bytes)`. +- `read(bytes)`, `read_with_password(bytes, Option<&str>)`, `is_encrypted(bytes)`, `write(&document)`. - Text in pieces (8-bit and UTF-16), paragraph and character formatting, styles, lists, tables, sections, headers and footers, notes, comments, fields, bookmarks, pictures and OfficeArt shapes, document properties. - XOR obfuscation, RC4 and RC4 CryptoAPI password protection. +- Tracked insertions and deletions, with their author and time. -There is no writer. +`write` produces a Word 97-2003 file (nFib 0x00C1, a version 3 compound file): text, character +and paragraph formatting, styles, fonts, lists, tables, sections with headers and footers, +footnotes and endnotes, fields and hyperlinks, bookmarks, inline pictures, tracked insertions +and deletions, and the document properties. Floating pictures are written in line, nested tables +become paragraphs of their cell, and shapes, charts, text boxes and comments are left out, each +kind logged once per save. It never writes a password-protected file. ## Limits diff --git a/crates/doc-binary/src/fmt.rs b/crates/doc-binary/src/fmt.rs index 1b8be23334..8c5a0db958 100644 --- a/crates/doc-binary/src/fmt.rs +++ b/crates/doc-binary/src/fmt.rs @@ -110,8 +110,8 @@ pub(crate) fn ico(i: u8) -> Option { } /// The model border style a `brcType` stands for ([MS-DOC] §2.9.22 BrcType; 0x02, thick, is in -/// the BRC of Microsoft's Word 97-2007 specification). Types the model doesn't carry (the gap -/// variants, 3-D, inset/outset) draw as single lines, as the DOCX reader maps them. +/// the BRC of Microsoft's Word 97-2007 specification); 0x0B-0x13 are the thin/thick compound +/// lines. Types the model doesn't carry (3-D, inset/outset, art borders) draw as single lines. fn brc_style(t: u8) -> BorderStyle { match t { 0x00 => BorderStyle::None, @@ -121,6 +121,15 @@ fn brc_style(t: u8) -> BorderStyle { 0x07 | 0x16 => BorderStyle::Dashed, 0x08 | 0x09 => BorderStyle::DotDash, 0x0A => BorderStyle::Triple, + 0x0B => BorderStyle::ThinThickSmallGap, + 0x0C => BorderStyle::ThickThinSmallGap, + 0x0D => BorderStyle::ThinThickThinSmallGap, + 0x0E => BorderStyle::ThinThickMediumGap, + 0x0F => BorderStyle::ThickThinMediumGap, + 0x10 => BorderStyle::ThinThickThinMediumGap, + 0x11 => BorderStyle::ThinThickLargeGap, + 0x12 => BorderStyle::ThickThinLargeGap, + 0x13 => BorderStyle::ThinThickThinLargeGap, 0x14 | 0x15 => BorderStyle::Wave, _ => BorderStyle::Single, } diff --git a/crates/doc-binary/src/lib.rs b/crates/doc-binary/src/lib.rs index b2d7f3729a..b8c1c5c468 100644 --- a/crates/doc-binary/src/lib.rs +++ b/crates/doc-binary/src/lib.rs @@ -1,11 +1,12 @@ -//! Reader for the Word 97-2003 binary file format (`.doc`, [MS-DOC]), WordCraft's. +//! Reader and writer for the Word 97-2003 binary file format (`.doc`, [MS-DOC]), WordCraft's. //! -//! [`read`] turns the bytes of a `.doc` file into a [`craft_wordmodel::Document`]. There is no -//! writer: saving always goes through the other formats. The reader is written from the public -//! specification ([MS-DOC], Word (.doc) Binary File Format, Microsoft Open Specifications) and, -//! like the other Craft parsers, is lenient by design (unknown structures are skipped, bad numbers -//! fall back to defaults) and bounded (stream sizes, piece counts and property counts are -//! capped), so hostile input yields an error or a best-effort document, never a panic. +//! [`read`] turns the bytes of a `.doc` file into a [`craft_wordmodel::Document`], and [`write`] +//! turns a document into a Word 97-2003 `.doc` file (the `write` module lists what it keeps). +//! Both follow the public specification ([MS-DOC], Word (.doc) Binary File Format, Microsoft Open +//! Specifications). The reader, like the other Craft parsers, is lenient by design (unknown +//! structures are skipped, bad numbers fall back to defaults) and bounded (stream sizes, piece +//! counts and property counts are capped), so hostile input yields an error or a best-effort +//! document, never a panic. //! //! Word 6.0/95 files, which that specification does not cover, are read by `word6` from their //! observed layout: their text, formatting and tables so far. @@ -28,11 +29,15 @@ mod metadata; mod notes; mod officeart; mod piece; +mod rmark; mod sections; mod sprm; mod stsh; mod table; mod word6; +mod write; + +pub use write::write; use std::sync::Arc; @@ -303,6 +308,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> // tight against aliasing — and never past the absolute ceiling. let budget = std::cell::Cell::new((word.len() as u64).saturating_mul(2).min(MAX_TOTAL_CHARS)); let work = Work::new(MAX_WORK); + let revs = rmark::Revisions::new(&table, &fib); let paragraphs = ParaBudget { left: std::cell::Cell::new(max_paragraphs), exceeded: std::cell::Cell::new(false) }; let ctx = WalkCtx { @@ -321,6 +327,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> budget: &budget, paragraphs: ¶graphs, work: &work, + revs: &revs, }; // Drawings: text box stories become parts first, then the floating shapes and pictures @@ -432,6 +439,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> return Err(paragraph_limit(max_paragraphs)); } doc.media.extend(pics.media); + doc.revisions = revs.take(); doc.body = table::assemble(paras); doc.ensure_nonempty(); work.log(); @@ -460,6 +468,7 @@ fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: u let work = Work::new(MAX_WORK); let paragraphs = ParaBudget { left: std::cell::Cell::new(max_paragraphs), exceeded: std::cell::Cell::new(false) }; let mut pics = media::Pictures::for_input(word.len()); + let revs = rmark::Revisions::none(); let ctx = WalkCtx { word, data: &[], @@ -476,6 +485,7 @@ fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: u budget: &budget, paragraphs: ¶graphs, work: &work, + revs: &revs, }; let paras = walk(&ctx, 0, fib.ccp_text, &mut pics); if paragraphs.exceeded.get() { @@ -574,6 +584,8 @@ struct WalkCtx<'a> { paragraphs: &'a ParaBudget, /// Repeated-work bytes left ([`MAX_WORK`]), and what they left out. work: &'a Work, + /// Tracked insertions and deletions met so far. + revs: &'a rmark::Revisions, } /// The paragraph and cell marks still allowed in this document, and whether a walk ran into @@ -748,7 +760,10 @@ fn walk<'a>(ctx: &WalkCtx<'a>, cp_start: u32, cp_end: u32, pics: &mut media::Pic pb.props.numbering = Some(NumRef { num, level: ilvl }); } let fc = ctx.pieces.fc_of_cp(cp).unwrap_or(0); - pb.mark = char_props(ctx.chpx_bins.chpx(ctx.word, fc), ctx.fonts, &CharProps::default()); + let chpx = ctx.chpx_bins.chpx(ctx.word, fc); + pb.mark = char_props(chpx, ctx.fonts, &CharProps::default()); + // A tracked paragraph mark: an inserted or deleted paragraph break. + ctx.revs.mark(&mut pb.mark, chpx, ctx.pieces.piece_prm(cp)); let done = std::mem::take(&mut pb); out.push(ParaOut { para: Paragraph { @@ -769,7 +784,7 @@ fn walk<'a>(ctx: &WalkCtx<'a>, cp_start: u32, cp_end: u32, pics: &mut media::Pic Some(f) => { f.depth = f.depth.saturating_add(1); } - None => field = Some(FieldBuild { depth: 1, instr: String::new(), sep: None }), + None => field = Some(FieldBuild { depth: 1, instr: String::new(), sep: None, anchor: anchor_props(ctx, cp) }), } cp = cp.saturating_add(1); continue; @@ -799,13 +814,16 @@ fn walk<'a>(ctx: &WalkCtx<'a>, cp_start: u32, cp_end: u32, pics: &mut media::Pic '\u{1}' => { // Inline picture: the CHPX of the anchor carries sprmCPicLocation. let fc = ctx.pieces.fc_of_cp(cp).unwrap_or(0); - let fc_pic = pic_location(ctx.chpx_bins.chpx(ctx.word, fc)); + let chpx = ctx.chpx_bins.chpx(ctx.word, fc); + let fc_pic = pic_location(chpx); match fc_pic.and_then(|at| pics.get(ctx.data, at)) { Some(p) => { // Every anchor of a picture gets its own copy of the alt text; the // copies are charged to the work budget (#3709). let alt = if ctx.work.charge(p.alt.len() as u64, Cost::AltText) { p.alt.clone() } else { String::new() }; - pb.push('\u{FFFC}', CharProps::default()); + let mut props = CharProps::default(); + ctx.revs.mark(&mut props, chpx, ctx.pieces.piece_prm(cp)); + pb.push('\u{FFFC}', props); pb.objects.push(InlineObject::Image { media: p.key.clone(), w: p.w, @@ -829,7 +847,7 @@ fn walk<'a>(ctx: &WalkCtx<'a>, cp_start: u32, cp_end: u32, pics: &mut media::Pic if !ctx.work.charge(object_cost(obj), Cost::FloatingObject) { continue; } - pb.push('\u{FFFC}', CharProps::default()); + pb.push('\u{FFFC}', anchor_props(ctx, cp)); pb.objects.push(obj.clone()); } } @@ -837,7 +855,7 @@ fn walk<'a>(ctx: &WalkCtx<'a>, cp_start: u32, cp_end: u32, pics: &mut media::Pic // Footnote or endnote reference; custom symbols share the same character. let at = ctx.notes.partition_point(|(c, _, _)| *c < cp); if let Some((_, kind, id)) = ctx.notes.get(at).filter(|(c, _, _)| *c == cp) { - pb.push('\u{FFFC}', CharProps::default()); + pb.push('\u{FFFC}', anchor_props(ctx, cp)); pb.objects.push(InlineObject::NoteRef { kind: *kind, id: *id, custom: String::new() }); } } @@ -871,6 +889,8 @@ struct FieldBuild { depth: u32, instr: String, sep: Option, + /// The begin character's revision marks, for the field object's anchor. + anchor: CharProps, } /// A field's cached result: its text and, as runs, the formatting of that text. A run is added @@ -905,6 +925,15 @@ fn object_cost(obj: &InlineObject) -> u64 { } } +/// The properties of an object anchor at `cp`: only its revision marks, so a tracked +/// insertion or deletion of a picture, note reference or field survives. +fn anchor_props(ctx: &WalkCtx<'_>, cp: u32) -> CharProps { + let fc = ctx.pieces.fc_of_cp(cp).unwrap_or(0); + let mut props = CharProps::default(); + ctx.revs.mark(&mut props, ctx.chpx_bins.chpx(ctx.word, fc), ctx.pieces.piece_prm(cp)); + props +} + /// Emit a finished field: HYPERLINK keeps its result text as a linked run; every other /// field becomes one inline object with its cached result. /// @@ -934,7 +963,7 @@ fn finish_field(pb: &mut ParaBuild, f: FieldBuild, work: &Work) { } return; } - pb.push('\u{FFFC}', CharProps::default()); + pb.push('\u{FFFC}', f.anchor); pb.objects.push(InlineObject::Field { instr, result: result.text, locked: false, dirty: false, code: false, form: String::new() }); } @@ -1012,7 +1041,9 @@ fn push_formatted<'a>(pb: &mut ParaBuild, cp: u32, c: char, ctx: &WalkCtx<'a>, f } }; let mut props = char_props(grpprl, ctx.fonts, base); - apply_prm(&mut props, ctx.pieces.piece_prm(cp), ctx.fonts, base, ctx.work); + let piece_prm = ctx.pieces.piece_prm(cp); + apply_prm(&mut props, piece_prm, ctx.fonts, base, ctx.work); + ctx.revs.mark(&mut props, grpprl, piece_prm); st.memo = Some(FmtMemo { chpx: grpprl, prm, style: style.map(str::to_owned), props }); st.generation += 1; } @@ -1083,7 +1114,7 @@ fn prm_paragraph_sprms(prm: PrmRef<'_>, work: &Work) -> Vec { out.push(val); } } - PrmRef::Grpprl(Some(g)) => { + PrmRef::Grpprl { grpprl: Some(g), .. } => { if !work.charge(g.len() as u64, Cost::Formatting) { return out; } @@ -1092,7 +1123,7 @@ fn prm_paragraph_sprms(prm: PrmRef<'_>, work: &Work) -> Vec { out.extend_from_slice(prl.operand); } } - PrmRef::None | PrmRef::Grpprl(None) => {} + PrmRef::None | PrmRef::Grpprl { grpprl: None, .. } => {} } out } @@ -1111,7 +1142,7 @@ fn apply_prm(props: &mut CharProps, prm: PrmRef<'_>, fonts: &[String], base: &Ch } } } - PrmRef::Grpprl(Some(g)) => { + PrmRef::Grpprl { grpprl: Some(g), .. } => { if !work.charge(g.len() as u64, Cost::Formatting) { return; } @@ -1121,7 +1152,7 @@ fn apply_prm(props: &mut CharProps, prm: PrmRef<'_>, fonts: &[String], base: &Ch } } } - PrmRef::Grpprl(None) => {} + PrmRef::Grpprl { grpprl: None, .. } => {} } } diff --git a/crates/doc-binary/src/list.rs b/crates/doc-binary/src/list.rs index 8737928125..5eacf4b0c4 100644 --- a/crates/doc-binary/src/list.rs +++ b/crates/doc-binary/src/list.rs @@ -35,15 +35,19 @@ struct RawLvl { xst: Vec, } -/// A bullet level's character, with the 0xF000 flag bits stripped and the common -/// Symbol/Wingdings glyphs mapped to their Unicode equivalents so every font renders them. +/// A bullet level's character: a symbol-font character (0xF000 to 0xF0FF, the font's own code +/// in the low byte) with the common Symbol/Wingdings glyphs mapped to their Unicode equivalents +/// so every font renders them; any other character is itself. fn bullet_char(c: u16) -> char { - match c & 0x0FFF { + if !(0xF000..=0xF0FF).contains(&c) { + return char::from_u32(u32::from(c)).unwrap_or('\u{2022}'); + } + match c & 0x00FF { 0xB7 => '\u{2022}', // Symbol bullet 0xA7 => '\u{25AA}', // Wingdings small square 0x6F => '\u{25CB}', // Symbol open circle 0x77 | 0x78 => '\u{25CF}', // Wingdings filled circles - other => char::from_u32(other as u32).unwrap_or('\u{2022}'), + other => char::from_u32(u32::from(other)).unwrap_or('\u{2022}'), } } @@ -51,7 +55,7 @@ fn bullet_char(c: u16) -> char { /// 0x00 to 0x27 run in the order of ST_NumberFormat (decimal, upperRoman … 0x16 decimalZero, 0x17 /// bullet … 0x25 chineseCounting, 0x26 chineseLegalSimplified, 0x27 chineseCountingThousand); /// later codes are drawn as decimal. -fn num_format(nfc: u8) -> NumFormat { +pub(crate) fn num_format(nfc: u8) -> NumFormat { match nfc { 0xFF => NumFormat::None, 0x00..=0x27 => NumFormat::ALL.get(nfc as usize).copied().unwrap_or(NumFormat::Decimal), diff --git a/crates/doc-binary/src/metadata.rs b/crates/doc-binary/src/metadata.rs index e45520394b..05d0345a6e 100644 --- a/crates/doc-binary/src/metadata.rs +++ b/crates/doc-binary/src/metadata.rs @@ -15,6 +15,12 @@ fn u32_at(bytes: &[u8], offset: usize) -> Option { Some(u32::from_le_bytes(bytes.get(offset..offset.checked_add(4)?)?.try_into().ok()?)) } +/// [`parse`], for the writer's tests. +#[cfg(test)] +pub(crate) fn parse_for_tests(bytes: &[u8]) -> Option { + parse(bytes) +} + fn parse(bytes: &[u8]) -> Option { if bytes.get(..2)? != [0xfe, 0xff] || bytes.get(28..44)? != SUMMARY_FMTID || u32_at(bytes, 24)? < 1 { return None; diff --git a/crates/doc-binary/src/notes.rs b/crates/doc-binary/src/notes.rs index 51e3c4b846..2a398d6589 100644 --- a/crates/doc-binary/src/notes.rs +++ b/crates/doc-binary/src/notes.rs @@ -93,6 +93,11 @@ pub(crate) fn parse_bookmarks(table: &[u8], fib: &crate::fib::Fib) -> Vec<(u32, /// (1-byte length and Windows-1252 chars). `cbExtra` bytes after each string are skipped. /// Names are kept to 40 characters, but the reader always advances by the stored length. fn sttb_strings(table: &[u8], fc: u32, lcb: u32) -> Option> { + sttb_strings_max(table, fc, lcb, 40) +} + +/// [`sttb_strings`] keeping up to `max` characters of each string. +pub(crate) fn sttb_strings_max(table: &[u8], fc: u32, lcb: u32, max: usize) -> Option> { let b = table.get(fc as usize..(fc as usize).saturating_add(lcb as usize))?; let extended = b.get(0..2)? == [0xFF, 0xFF]; let head = if extended { 2 } else { 0 }; @@ -125,9 +130,10 @@ fn sttb_strings(table: &[u8], fc: u32, lcb: u32) -> Option> { } at += cb_extra; let s: String = if extended { - chars.as_chunks::<2>().0.iter().take(40).map(|c| char::from_u32(u16::from_le_bytes(*c) as u32).unwrap_or('\u{FFFD}')).collect() + // UTF-16: a surrogate pair is one character; a lone surrogate becomes U+FFFD. + char::decode_utf16(chars.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c))).take(max).map(|c| c.unwrap_or('\u{FFFD}')).collect() } else { - chars.iter().take(40).map(|&c| craft_codepage::cp1252(c)).collect() + chars.iter().take(max).map(|&c| craft_codepage::cp1252(c)).collect() }; out.push(s); } @@ -153,6 +159,20 @@ mod tests { b } + /// A character outside the BMP (a surrogate pair) stays one character; a lone surrogate + /// is U+FFFD. The limit counts characters, not UTF-16 units. + #[test] + fn extended_strings_decode_surrogate_pairs() { + let mut b = ext_sttb(&["Ada \u{1F600}"], &[]); + let lone = [0x00u8, 0xD8]; + b[2] = 2; + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&lone); + b.extend_from_slice(&u16::from(b'x').to_le_bytes()); + let got = super::sttb_strings_max(&b, 0, b.len() as u32, 5).unwrap(); + assert_eq!(got, vec!["Ada \u{1F600}".to_string(), "\u{FFFD}x".to_string()]); + } + #[test] fn long_bookmark_name_does_not_desync_table() { let long = "A".repeat(50); diff --git a/crates/doc-binary/src/piece.rs b/crates/doc-binary/src/piece.rs index 701a4bc67c..07ad13a636 100644 --- a/crates/doc-binary/src/piece.rs +++ b/crates/doc-binary/src/piece.rs @@ -228,7 +228,8 @@ impl PieceTable { } PrmRef::Sprm0 { isprm, val: (p.prm >> 8) as u8 } } else { - PrmRef::Grpprl(self.prc_grpprls.get((p.prm >> 1) as usize).map(Vec::as_slice)) + let index = p.prm >> 1; + PrmRef::Grpprl { index, grpprl: self.prc_grpprls.get(usize::from(index)).map(Vec::as_slice) } } } @@ -342,6 +343,7 @@ impl PieceSpan<'_> { } /// What a piece's `Prm` refers to. +#[derive(Clone, Copy)] pub(crate) enum PrmRef<'a> { None, /// Prm0: a short sprm index into the isprm table, with a 1-byte operand. @@ -349,8 +351,11 @@ pub(crate) enum PrmRef<'a> { isprm: u8, val: u8, }, - /// Prm1: a grpprl from a Prc (absent if out of range). - Grpprl(Option<&'a [u8]>), + /// Prm1: the Prc at `index` and its grpprl (absent if out of range). + Grpprl { + index: u16, + grpprl: Option<&'a [u8]>, + }, } /// Windows' code page number for symbol fonts (CP_SYMBOL). diff --git a/crates/doc-binary/src/rmark.rs b/crates/doc-binary/src/rmark.rs new file mode 100644 index 0000000000..f5b3a3f7e4 --- /dev/null +++ b/crates/doc-binary/src/rmark.rs @@ -0,0 +1,232 @@ +//! Tracked insertions and deletions: the revision-mark sprms of a run's CHPX (`sprmCFRMarkIns` +//! and `sprmCFRMarkDel`, each with its author index into `SttbfRMark` and its `DTTM`) +//! ([MS-DOC] §2.6.1, §2.9.290), as model revisions. + +use std::cell::RefCell; +use std::collections::HashMap; + +use craft_wordmodel::props::CharProps; +use craft_wordmodel::{Revision, RevisionKind}; + +use crate::fib::Fib; +use crate::piece::PrmRef; +use crate::sprm; + +const C_RMARK_DEL: u16 = 0x0800; +const C_RMARK_INS: u16 = 0x0801; +const C_IBST_RMARK: u16 = 0x4804; +const C_DTTM_RMARK: u16 = 0x6805; +const C_IBST_RMARK_DEL: u16 = 0x4863; +const C_DTTM_RMARK_DEL: u16 = 0x6864; +/// `fcSttbfRMark`: the revision authors. +const STTBF_RMARK: usize = 51; +/// Most distinct revisions (author, time and kind) one document gets. +const MAX_REVISIONS: usize = 100_000; +/// Longest author name kept. +const MAX_AUTHOR: usize = 255; + +/// The document's revisions, made as the walk meets their marks: runs with the same author, +/// time and kind share one. +pub(crate) struct Revisions { + authors: Vec, + list: RefCell>, + index: RefCell>, + /// The marks of each Prc a piece's Prm1 names, by its index (at most 32,768 of them): a Prc + /// grpprl of up to 64 KB is scanned once, not at every run, paragraph mark and object anchor + /// of its pieces. + prcs: RefCell>, +} + +impl Revisions { + /// No revision authors: a file whose revision marks are not read (Word 6.0/95, whose + /// revision sprms differ). Marks are still never set, as none of its sprms are Word 97's. + pub(crate) fn none() -> Self { + Self { authors: Vec::new(), list: RefCell::default(), index: RefCell::default(), prcs: RefCell::default() } + } + + pub(crate) fn new(table: &[u8], fib: &Fib) -> Self { + let authors = fib + .pair(STTBF_RMARK) + .filter(|(_, lcb)| *lcb > 0) + .and_then(|(fc, lcb)| crate::notes::sttb_strings_max(table, fc, lcb, MAX_AUTHOR)) + .unwrap_or_default(); + Revisions { authors, list: RefCell::new(Vec::new()), index: RefCell::new(HashMap::new()), prcs: RefCell::new(HashMap::new()) } + } + + /// Set `props.ins` / `props.del` from the revision marks of a run: those in its CHPX + /// `grpprl`, then those of its piece's `prm`, which apply after the CHPX's. + pub(crate) fn mark(&self, props: &mut CharProps, grpprl: &[u8], prm: PrmRef<'_>) { + let mut m = Marks::of(grpprl); + match prm { + PrmRef::Sprm0 { isprm, val } => { + if let Some(op) = sprm::from_prm0(isprm) { + m.apply(op, &[val]); + } + } + PrmRef::Grpprl { index, grpprl: Some(g) } => { + let prc = *self.prcs.borrow_mut().entry(index).or_insert_with(|| Marks::of(g)); + m = m.then(prc); + } + PrmRef::Grpprl { grpprl: None, .. } | PrmRef::None => {} + } + if m.ins == Some(true) { + props.ins = self.id(true, m.ibst_ins.unwrap_or(0), m.dttm_ins.unwrap_or(0)); + } + if m.del == Some(true) { + props.del = self.id(false, m.ibst_del.unwrap_or(0), m.dttm_del.unwrap_or(0)); + } + } + + /// The index of the revision of this kind, author and time, made on first use. + fn id(&self, insert: bool, ibst: u16, dttm: u32) -> Option { + let key = (insert, ibst, dttm); + if let Some(&i) = self.index.borrow().get(&key) { + return Some(i); + } + let mut list = self.list.borrow_mut(); + if list.len() >= MAX_REVISIONS { + return None; + } + let author = self.authors.get(usize::from(ibst)).cloned().unwrap_or_else(|| "Unknown".to_string()); + let kind = if insert { RevisionKind::Insert } else { RevisionKind::Delete }; + list.push(Revision::new(kind, author, dttm_iso(dttm))); + let i = u32::try_from(list.len() - 1).ok()?; + self.index.borrow_mut().insert(key, i); + Some(i) + } + + pub(crate) fn take(self) -> Vec { + self.list.into_inner() + } +} + +/// The revision-mark sprms seen so far for one run, a later one replacing an earlier one; each +/// is `None` until one is seen. +#[derive(Clone, Copy, Default)] +struct Marks { + ins: Option, + del: Option, + ibst_ins: Option, + dttm_ins: Option, + ibst_del: Option, + dttm_del: Option, +} + +impl Marks { + /// The marks of one grpprl. + fn of(grpprl: &[u8]) -> Self { + let mut m = Marks::default(); + for prl in sprm::iter(grpprl) { + m.apply(prl.op, prl.operand); + } + m + } + + /// These marks with `later`'s applied after them, as if its sprms came next. + fn then(self, later: Marks) -> Self { + Marks { + ins: later.ins.or(self.ins), + del: later.del.or(self.del), + ibst_ins: later.ibst_ins.or(self.ibst_ins), + dttm_ins: later.dttm_ins.or(self.dttm_ins), + ibst_del: later.ibst_del.or(self.ibst_del), + dttm_del: later.dttm_del.or(self.dttm_del), + } + } + + fn apply(&mut self, op: u16, operand: &[u8]) { + let u16v = || operand.get(..2).map_or(0, |b| u16::from_le_bytes([b[0], b[1]])); + let u32v = || operand.get(..4).map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + match op { + C_RMARK_INS => self.ins = Some(operand.first().is_some_and(|&v| v == 1 || v == 0x81)), + C_RMARK_DEL => self.del = Some(operand.first().is_some_and(|&v| v == 1 || v == 0x81)), + C_IBST_RMARK => self.ibst_ins = Some(u16v()), + C_DTTM_RMARK => self.dttm_ins = Some(u32v()), + C_IBST_RMARK_DEL => self.ibst_del = Some(u16v()), + C_DTTM_RMARK_DEL => self.dttm_del = Some(u32v()), + _ => {} + } + } +} + +/// A `DTTM` ([MS-DOC] §2.9.75) as an ISO 8601 UTC time; empty for 0 or an impossible date. +pub(crate) fn dttm_iso(d: u32) -> String { + if d == 0 { + return String::new(); + } + let minute = d & 0x3F; + let hour = (d >> 6) & 0x1F; + let day = (d >> 11) & 0x1F; + let month = (d >> 16) & 0xF; + let year = 1900 + ((d >> 20) & 0x1FF) as i32; + match chrono::NaiveDate::from_ymd_opt(year, month, day).and_then(|date| date.and_hms_opt(hour, minute, 0)) { + Some(t) => t.format("%Y-%m-%dT%H:%M:%SZ").to_string(), + None => String::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn revisions() -> Revisions { + Revisions { + authors: vec!["Ada".into(), "Grace".into()], + list: RefCell::new(Vec::new()), + index: RefCell::new(HashMap::new()), + prcs: RefCell::new(HashMap::new()), + } + } + + fn marked(chpx: &[u8], prm: PrmRef<'_>) -> (CharProps, Vec) { + let r = revisions(); + let mut props = CharProps::default(); + r.mark(&mut props, chpx, prm); + (props, r.take()) + } + + const INS: [u8; 3] = [0x01, 0x08, 1]; + const NOT_INS: [u8; 3] = [0x01, 0x08, 0]; + /// sprmCFRMarkDel on, by the author at index 1. + const DEL_BY_GRACE: [u8; 7] = [0x00, 0x08, 1, 0x63, 0x48, 1, 0]; + + #[test] + fn a_piece_prm_marks_a_run() { + // Prm1: a grpprl from the piece table's Prc. + let (p, revs) = marked(&[], PrmRef::Grpprl { index: 0, grpprl: Some(&DEL_BY_GRACE) }); + assert_eq!(p.del, Some(0)); + assert_eq!((revs[0].kind, revs[0].author.as_str()), (RevisionKind::Delete, "Grace")); + // Prm0: sprmCFRMarkIns by its isprm. + let (p, revs) = marked(&[], PrmRef::Sprm0 { isprm: 0x42, val: 1 }); + assert_eq!(p.ins, Some(0)); + assert_eq!((revs[0].kind, revs[0].author.as_str()), (RevisionKind::Insert, "Ada")); + } + + #[test] + fn the_piece_prm_applies_after_the_chpx() { + let (p, _) = marked(&INS, PrmRef::Grpprl { index: 0, grpprl: Some(&NOT_INS) }); + assert_eq!(p.ins, None, "the Prm turns the CHPX's insertion off"); + let (p, _) = marked(&NOT_INS, PrmRef::Sprm0 { isprm: 0x42, val: 1 }); + assert_eq!(p.ins, Some(0)); + let (p, _) = marked(&INS, PrmRef::None); + assert_eq!(p.ins, Some(0)); + } + + #[test] + fn a_prcs_marks_apply_after_the_chpx_one_by_one_and_are_scanned_once() { + let r = revisions(); + // The CHPX inserts, by Grace; the Prc only sets the time, so the author stays Grace's. + let chpx = [INS.as_slice(), &[0x04, 0x48, 1, 0]].concat(); + let prc = [0x05u8, 0x68, 0x21, 0x2B, 0xC3, 0x07]; + let mut p = CharProps::default(); + r.mark(&mut p, &chpx, PrmRef::Grpprl { index: 3, grpprl: Some(&prc) }); + assert_eq!(p.ins, Some(0)); + // The marks of Prc 3 are kept: the same index finds them without its grpprl's bytes. + let mut again = CharProps::default(); + r.mark(&mut again, &INS, PrmRef::Grpprl { index: 3, grpprl: Some(&[]) }); + assert_eq!(again.ins, Some(1), "Ada's insertion at the Prc's time"); + let revs = r.take(); + assert_eq!((revs[0].author.as_str(), revs[0].date.as_str()), ("Grace", "2024-03-05T12:33:00Z")); + assert_eq!((revs[1].author.as_str(), revs[1].date.as_str()), ("Ada", "2024-03-05T12:33:00Z")); + } +} diff --git a/crates/doc-binary/src/sprm.rs b/crates/doc-binary/src/sprm.rs index 7db632caff..73792d4038 100644 --- a/crates/doc-binary/src/sprm.rs +++ b/crates/doc-binary/src/sprm.rs @@ -86,6 +86,8 @@ pub(crate) fn from_prm0(isprm: u8) -> Option { 0x09 => 0x2407, // sprmPFPageBreakBefore 0x33 => 0x2435, // sprmPWidowControl (low byte of the operand is the value) 0x78 => 0x2640, // sprmPOutLvl + 0x41 => 0x0800, // sprmCFRMarkDel + 0x42 => 0x0801, // sprmCFRMarkIns 0x4D => 0x2A0C, // sprmCHighlight 0x55 => 0x0835, // sprmCFBold 0x56 => 0x0836, // sprmCFItalic diff --git a/crates/doc-binary/src/tests.rs b/crates/doc-binary/src/tests.rs index ec56506954..8c1025eb27 100644 --- a/crates/doc-binary/src/tests.rs +++ b/crates/doc-binary/src/tests.rs @@ -2822,7 +2822,12 @@ fn a_long_hyperlink_over_a_long_result_is_one_linked_run() { // what the copies charge to the work budget, which a busy machine can't skew. let mut result = super::FieldResult::default(); (0..n).for_each(|_| result.push('y', craft_wordmodel::props::CharProps::default())); - let f = super::FieldBuild { depth: 1, instr: format!("HYPERLINK \"http://{target}\""), sep: Some(result) }; + let f = super::FieldBuild { + depth: 1, + instr: format!("HYPERLINK \"http://{target}\""), + sep: Some(result), + anchor: craft_wordmodel::props::CharProps::default(), + }; let work = super::Work::new(u64::MAX); super::finish_field(&mut super::ParaBuild::default(), f, &work); assert_eq!(u64::MAX - work.left.get(), ("http://".len() + n) as u64, "one copy of the target"); @@ -2836,7 +2841,12 @@ fn hyperlink_target_copies_are_charged_to_the_work_budget() { let bold = CharProps { bold: Some(true), ..Default::default() }; let mut result = super::FieldResult::default(); (0..1000).for_each(|i| result.push('a', if i % 2 == 0 { bold.clone() } else { CharProps::default() })); - let f = super::FieldBuild { depth: 1, instr: format!("HYPERLINK \"{}\"", "u".repeat(100)), sep: Some(result) }; + let f = super::FieldBuild { + depth: 1, + instr: format!("HYPERLINK \"{}\"", "u".repeat(100)), + sep: Some(result), + anchor: craft_wordmodel::props::CharProps::default(), + }; let mut pb = super::ParaBuild::default(); let budget = super::Work::new(10_000); super::finish_field(&mut pb, f, &budget); @@ -2901,15 +2911,46 @@ fn prm_grpprls_past_the_work_budget_are_skipped() { let work = super::Work::new(g.len() as u64 + 1); let base = CharProps::default(); let mut first = CharProps::default(); - super::apply_prm(&mut first, crate::piece::PrmRef::Grpprl(Some(&g)), &[], &base, &work); + super::apply_prm(&mut first, crate::piece::PrmRef::Grpprl { index: 0, grpprl: Some(&g) }, &[], &base, &work); assert_eq!(first.bold, Some(true)); let mut second = CharProps::default(); - super::apply_prm(&mut second, crate::piece::PrmRef::Grpprl(Some(&g)), &[], &base, &work); + super::apply_prm(&mut second, crate::piece::PrmRef::Grpprl { index: 0, grpprl: Some(&g) }, &[], &base, &work); assert_eq!(second.bold, None); assert_eq!(work.left.get(), 1); assert_eq!(work.dropped(), [super::Cost::Formatting]); } +/// A piece's Prm grpprl (a Prc of up to 64 KB) was scanned for revision marks again at every +/// paragraph mark and object anchor, which the per-formatting-change memo (#3692) doesn't +/// cover. Each Prc's marks are now found once. +#[test] +fn a_large_prc_is_scanned_for_revision_marks_once() { + // 21,844 bold sprms, then sprmCFRMarkIns: the Prc's marks are only known at its end. + let mut prls = vec![(0x0835u16, &[0x01u8][..]); 21_844]; + prls.push((0x0801, &[0x01])); + let prc = grpprl(&prls); + // A field and a paragraph mark per paragraph, all in the piece with that Prc. + let text: &'static str = Box::leak("\u{13}\u{15}\r".repeat(100_000).into_boxed_str()); + let spec = RichSpec { + text, + styles: vec![(1, 0x0FFF, "Normal", Vec::new(), Vec::new())], + fonts: vec!["Times New Roman"], + chpx_runs: vec![(0, Vec::new())], + papx_entries: vec![(0, 0, Vec::new())], + }; + let bytes = rich_doc_with(&spec, &RichExtra { prcs: vec![prc], prm: 0x0001, ..Default::default() }); + let t = std::time::Instant::now(); + let doc = read(&bytes).expect("opens"); + // Well under a second; scanning the Prc at every mark and anchor took 17 s. + assert!(t.elapsed().as_secs() < 10, "opened in {:?}", t.elapsed()); + assert_eq!(doc.body.len(), 100_000); + assert_eq!(doc.revisions.len(), 1); + for p in doc.body.iter().filter_map(|b| b.as_para()) { + assert_eq!(p.mark.ins, Some(0), "the paragraph mark is a tracked insertion"); + assert_eq!(p.runs.first().and_then(|r| r.props.ins), Some(0), "so is the field"); + } +} + /// A field's cached result keeps one `CharProps` per formatting run, not one per character /// (365 bytes each: 4 million result characters took 1.4 GB). #[test] @@ -2941,7 +2982,7 @@ fn field_results_keep_their_text_and_runs() { { result.push(c, p); } - let f = super::FieldBuild { depth: 1, instr: "HYPERLINK \"http://x\"".into(), sep: Some(result) }; + let f = super::FieldBuild { depth: 1, instr: "HYPERLINK \"http://x\"".into(), sep: Some(result), anchor: CharProps::default() }; let mut pb = super::ParaBuild::default(); super::finish_field(&mut pb, f, &super::Work::new(u64::MAX)); assert_eq!(pb.text, "a\u{e9}\u{20ac}bc"); diff --git a/crates/doc-binary/src/write/fkp.rs b/crates/doc-binary/src/write/fkp.rs new file mode 100644 index 0000000000..1d7853f66d --- /dev/null +++ b/crates/doc-binary/src/write/fkp.rs @@ -0,0 +1,280 @@ +//! Formatted disk pages ([MS-DOC] §2.9.43 ChpxFkp, §2.9.177 PapxFkp) and the bin tables that +//! index them (`PlcBteChpx`, `PlcBtePapx`), plus the PLC and STTB containers the Table stream +//! is made of. + +/// Bytes in a formatted disk page. +const PAGE: usize = 512; +/// Most runs a `ChpxFkp` holds ([MS-DOC]: crun MUST be at most 0x65). +const MAX_CHPX_RUNS: usize = 0x65; +/// Most paragraphs a `PapxFkp` holds ([MS-DOC]: crun MUST be at most 0x1D). +const MAX_PAPX_RUNS: usize = 0x1D; +/// Size of a `BxPap`: a word offset and a 12-byte `PHE` (left zero: Word recomputes heights). +const BX: usize = 13; + +/// One run of text sharing its character formatting: `[fc_start, fc_end)` in the WordDocument +/// stream, with the CHPX grpprl (empty = no direct formatting). +pub(crate) struct ChpxRun<'a> { + pub(crate) fc_start: u32, + pub(crate) fc_end: u32, + pub(crate) grpprl: &'a [u8], +} + +/// One paragraph: `[fc_start, fc_end)` (its mark included), its style and PAPX grpprl. +pub(crate) struct PapxRun<'a> { + pub(crate) fc_start: u32, + pub(crate) fc_end: u32, + pub(crate) istd: u16, + pub(crate) grpprl: &'a [u8], +} + +/// Pages ready for the WordDocument stream and the bin table (`aFc` + `aPn`) that indexes them. +pub(crate) struct Paged { + pub(crate) pages: Vec<[u8; PAGE]>, + /// `aFc`: the first FC of each page, then the last page's end. + fcs: Vec, +} + +impl Paged { + /// The `PlcBte*` for these pages once they sit from page number `first_pn` on. + pub(crate) fn plc_bte(&self, first_pn: u32) -> Vec { + let mut v = Vec::with_capacity(self.fcs.len() * 4 + self.pages.len() * 4); + for fc in &self.fcs { + v.extend_from_slice(&fc.to_le_bytes()); + } + for i in 0..self.pages.len() { + v.extend_from_slice(&first_pn.saturating_add(i as u32).to_le_bytes()); + } + v + } +} + +/// A page being filled: the `rgfc` entries so far and the property bytes, which grow down from +/// the end of the page (the last byte is `crun`). +struct Page { + buf: [u8; PAGE], + fcs: Vec, + /// Word offset (÷2) of each entry's properties (0 = none). + offs: Vec, + /// Lowest byte used by property data. + low: usize, + /// Property bytes already on the page and where they are, so equal ones are stored once. + stored: Vec<(Vec, u8)>, +} + +impl Page { + fn new() -> Page { + Page { buf: [0; PAGE], fcs: Vec::new(), offs: Vec::new(), low: PAGE - 1, stored: Vec::new() } + } + + /// Bytes the header takes with `crun` entries of `entry` bytes each. + fn header(crun: usize, entry: usize) -> usize { + (crun + 1) * 4 + crun * entry + } + + /// Place `data` (already in its on-page form), returning its word offset, if it fits beside + /// a header for `crun` entries. + fn place(&mut self, data: &[u8], crun: usize, entry: usize) -> Option { + if data.is_empty() { + return (Page::header(crun, entry) <= self.low).then_some(0); + } + if let Some((_, off)) = self.stored.iter().find(|(d, _)| d == data) { + return (Page::header(crun, entry) <= self.low).then_some(*off); + } + let at = self.low.checked_sub(data.len())? & !1; + if at < Page::header(crun, entry) || at / 2 > u8::MAX as usize { + return None; + } + self.buf.get_mut(at..at + data.len())?.copy_from_slice(data); + self.low = at; + let off = (at / 2) as u8; + self.stored.push((data.to_vec(), off)); + Some(off) + } + + /// Write the header and `crun`; `entry` is the size of each `rgb`/`rgbx` element. + fn finish(mut self, end_fc: u32, entry: usize) -> ([u8; PAGE], u32) { + let crun = self.offs.len(); + let first = self.fcs.first().copied().unwrap_or(end_fc); + self.fcs.push(end_fc); + for (i, fc) in self.fcs.iter().enumerate() { + if let Some(b) = self.buf.get_mut(i * 4..i * 4 + 4) { + b.copy_from_slice(&fc.to_le_bytes()); + } + } + let rgb_at = (crun + 1) * 4; + for (i, off) in self.offs.iter().enumerate() { + if let Some(b) = self.buf.get_mut(rgb_at + i * entry) { + *b = *off; + } + } + self.buf[PAGE - 1] = crun as u8; + (self.buf, first) + } +} + +/// Page the character runs into `ChpxFkp`s: each run's `Chpx` is `cb` then the grpprl (at most +/// 255 bytes; the caller truncates). +pub(crate) fn chpx_pages(runs: &[ChpxRun<'_>]) -> Paged { + let mut out = Paged { pages: Vec::new(), fcs: Vec::new() }; + let mut page = Page::new(); + for r in runs { + let mut data = Vec::new(); + if !r.grpprl.is_empty() { + data.push(r.grpprl.len().min(255) as u8); + data.extend_from_slice(r.grpprl.get(..255).unwrap_or(r.grpprl)); + } + let off = if page.offs.len() < MAX_CHPX_RUNS { page.place(&data, page.offs.len() + 1, 1) } else { None }; + let off = match off { + Some(o) => o, + None => { + let (buf, first) = std::mem::replace(&mut page, Page::new()).finish(r.fc_start, 1); + out.pages.push(buf); + out.fcs.push(first); + // A fresh page always has room for one Chpx of at most 256 bytes. + page.place(&data, 1, 1).unwrap_or(0) + } + }; + page.fcs.push(r.fc_start); + page.offs.push(off); + } + let end = runs.last().map_or(0, |r| r.fc_end); + if !page.offs.is_empty() { + let (buf, first) = page.finish(end, 1); + out.pages.push(buf); + out.fcs.push(first); + } + out.fcs.push(end); + out +} + +/// A `PapxInFkp` ([MS-DOC] §2.9.175): the istd and grpprl with the size byte(s) in front: `cb` +/// (2×cb−1 bytes follow) for an odd size, else 0 and `cb'` (2×cb' bytes follow). +fn papx_in_fkp(istd: u16, grpprl: &[u8]) -> Vec { + let mut body = istd.to_le_bytes().to_vec(); + body.extend_from_slice(grpprl); + let mut v = Vec::with_capacity(body.len() + 2); + if body.len() % 2 == 1 { + v.push(body.len().div_ceil(2) as u8); + } else { + v.push(0); + v.push((body.len() / 2) as u8); + } + v.extend_from_slice(&body); + v +} + +/// Largest PAPX grpprl a page takes: one paragraph alone on a page must still fit. +pub(crate) const MAX_PAPX_GRPPRL: usize = 480; + +/// Page the paragraphs into `PapxFkp`s. +pub(crate) fn papx_pages(paras: &[PapxRun<'_>]) -> Paged { + let mut out = Paged { pages: Vec::new(), fcs: Vec::new() }; + let mut page = Page::new(); + for p in paras { + let data = papx_in_fkp(p.istd, p.grpprl.get(..MAX_PAPX_GRPPRL).unwrap_or(p.grpprl)); + // Even an unformatted paragraph names its style, so every BX points at a PAPX. + let off = if page.offs.len() < MAX_PAPX_RUNS { page.place(&data, page.offs.len() + 1, BX) } else { None }; + let off = match off { + Some(o) => o, + None => { + let (buf, first) = std::mem::replace(&mut page, Page::new()).finish(p.fc_start, BX); + out.pages.push(buf); + out.fcs.push(first); + page.place(&data, 1, BX).unwrap_or(0) + } + }; + page.fcs.push(p.fc_start); + page.offs.push(off); + } + let end = paras.last().map_or(0, |p| p.fc_end); + if !page.offs.is_empty() { + let (buf, first) = page.finish(end, BX); + out.pages.push(buf); + out.fcs.push(first); + } + out.fcs.push(end); + out +} + +/// A PLC ([MS-DOC] §2.2.2): `cps` (one more than the data elements), then the elements. +pub(crate) fn plc(cps: &[u32], data: &[&[u8]]) -> Vec { + let mut v = Vec::with_capacity(cps.len() * 4 + data.iter().map(|d| d.len()).sum::()); + for cp in cps { + v.extend_from_slice(&cp.to_le_bytes()); + } + for d in data { + v.extend_from_slice(d); + } + v +} + +/// An extended STTB ([MS-DOC] §2.2.4): `fExtend`, `cData`, `cbExtra`, then each string as a +/// count of UTF-16 units and the units, followed by its `extra` bytes. +pub(crate) fn sttb_ext(strings: &[(String, Vec)], cb_extra: u16) -> Vec { + let mut v = vec![0xFF, 0xFF]; + v.extend_from_slice(&(strings.len().min(u16::MAX as usize) as u16).to_le_bytes()); + v.extend_from_slice(&cb_extra.to_le_bytes()); + for (s, extra) in strings.iter().take(u16::MAX as usize) { + let units: Vec = s.encode_utf16().take(u16::MAX as usize).collect(); + v.extend_from_slice(&(units.len() as u16).to_le_bytes()); + for u in units { + v.extend_from_slice(&u.to_le_bytes()); + } + let mut e = extra.clone(); + e.resize(cb_extra as usize, 0); + v.extend_from_slice(&e); + } + v +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fkp::Bins; + + #[test] + fn chpx_pages_read_back() { + let bold = [0x35u8, 0x08, 1]; + let runs: Vec = + (0..300u32).map(|i| ChpxRun { fc_start: 0x400 + i * 2, fc_end: 0x402 + i * 2, grpprl: if i % 2 == 0 { &bold } else { &[] } }).collect(); + let paged = chpx_pages(&runs); + assert!(paged.pages.len() >= 3, "300 runs need several pages"); + let mut word = vec![0u8; 0x1000]; + for p in &paged.pages { + word.extend_from_slice(p); + } + let bte = paged.plc_bte(8); + let bins = Bins::parse(&bte, 0, bte.len() as u32).unwrap(); + for i in 0..300u32 { + let g = bins.chpx(&word, 0x400 + i * 2); + assert_eq!(g, if i % 2 == 0 { &bold[..] } else { &[][..] }, "run {i}"); + } + } + + #[test] + fn papx_pages_read_back_odd_and_even_sizes() { + let odd = [0x03u8, 0x24, 1]; // 2 + 3 = 5 bytes with the istd + let even = [0x03u8, 0x24, 1, 0]; // padded to 6 by the istd + let paras: Vec = (0..70u32) + .map(|i| PapxRun { + fc_start: 0x400 + i * 10, + fc_end: 0x40A + i * 10, + istd: i as u16 % 3, + grpprl: if i % 2 == 0 { &odd } else { &even[..3] }, + }) + .collect(); + let paged = papx_pages(¶s); + assert!(paged.pages.len() >= 3); + let mut word = vec![0u8; 0x1000]; + for p in &paged.pages { + word.extend_from_slice(p); + } + let bte = paged.plc_bte(8); + let bins = Bins::parse(&bte, 0, bte.len() as u32).unwrap(); + for i in 0..70u32 { + let (istd, g) = bins.papx(&word, 0x400 + i * 10 + 9); + assert_eq!(istd, i as u16 % 3); + assert_eq!(g, &odd[..]); + } + } +} diff --git a/crates/doc-binary/src/write/grpprl.rs b/crates/doc-binary/src/write/grpprl.rs new file mode 100644 index 0000000000..39b19d2ff6 --- /dev/null +++ b/crates/doc-binary/src/write/grpprl.rs @@ -0,0 +1,753 @@ +//! Model properties → grpprls of sprms ([MS-DOC] §2.6): character (CHPX), paragraph (PAPX) and +//! section (SEPX) formatting. The opcodes are the ones the reader decodes (`fmt.rs`, +//! `sections.rs`, `table.rs`), so a saved file reads back with the same properties. + +use craft_wordmodel::Rgb; +use craft_wordmodel::props::{ + Align, Border, BorderStyle, Borders, CharProps, Highlight, LineSpacing, ParaProps, TabAlign, TabLeader, TextColor, Underline, VertAlign, +}; +use craft_wordmodel::section::{NumFormat, PageVAlign, SectionProps, SectionStart}; + +/// A grpprl being built: Prls appended one by one. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub(crate) struct Grpprl(pub(crate) Vec); + +impl Grpprl { + pub(crate) fn len(&self) -> usize { + self.0.len() + } + + fn op(&mut self, op: u16) { + self.0.extend_from_slice(&op.to_le_bytes()); + } + + pub(crate) fn u8(&mut self, op: u16, v: u8) { + self.op(op); + self.0.push(v); + } + + pub(crate) fn u16(&mut self, op: u16, v: u16) { + self.op(op); + self.0.extend_from_slice(&v.to_le_bytes()); + } + + pub(crate) fn i16(&mut self, op: u16, v: i16) { + self.u16(op, v as u16); + } + + pub(crate) fn u32(&mut self, op: u16, v: u32) { + self.op(op); + self.0.extend_from_slice(&v.to_le_bytes()); + } + + /// A Prl whose operand is written as given (its size implied by the opcode's spra, or a + /// leading size byte the caller includes). + pub(crate) fn raw(&mut self, op: u16, operand: &[u8]) { + self.op(op); + self.0.extend_from_slice(operand); + } + + /// A variable-length Prl (spra 6): a size byte, then the operand. + pub(crate) fn var(&mut self, op: u16, operand: &[u8]) { + self.op(op); + self.0.push(u8::try_from(operand.len()).unwrap_or(u8::MAX)); + self.0.extend_from_slice(operand.get(..255).unwrap_or(operand)); + } + + pub(crate) fn extend(&mut self, other: &Grpprl) { + self.0.extend_from_slice(&other.0); + } + + /// Keep whole Prls up to `max` bytes: a grpprl that doesn't fit where it is stored (a CHPX + /// holds 255 bytes) loses its last properties rather than the file its shape. + pub(crate) fn truncate_to(&mut self, max: usize) { + if self.0.len() <= max { + return; + } + let mut keep = 0usize; + for prl in crate::sprm::iter(&self.0) { + let next = keep + 2 + prl.operand.len(); + if next > max { + break; + } + keep = next; + } + self.0.truncate(keep); + } +} + +// Character sprms ([MS-DOC] §2.6.1). +pub(crate) const C_RMARK_DEL: u16 = 0x0800; +pub(crate) const C_RMARK_INS: u16 = 0x0801; +pub(crate) const C_IBST_RMARK: u16 = 0x4804; +pub(crate) const C_DTTM_RMARK: u16 = 0x6805; +pub(crate) const C_IBST_RMARK_DEL: u16 = 0x4863; +pub(crate) const C_DTTM_RMARK_DEL: u16 = 0x6864; +pub(crate) const C_ISTD: u16 = 0x4A30; +const C_BOLD: u16 = 0x0835; +const C_ITALIC: u16 = 0x0836; +const C_STRIKE: u16 = 0x0837; +const C_OUTLINE: u16 = 0x0838; +const C_SHADOW: u16 = 0x0839; +const C_SMALL_CAPS: u16 = 0x083A; +const C_CAPS: u16 = 0x083B; +const C_VANISH: u16 = 0x083C; +const C_IMPRINT: u16 = 0x0854; +pub(crate) const C_SPEC: u16 = 0x0855; +const C_EMBOSS: u16 = 0x0858; +const C_RTL: u16 = 0x085A; +const C_BOLD_BI: u16 = 0x085C; +const C_ITALIC_BI: u16 = 0x085D; +const C_NO_PROOF: u16 = 0x0875; +const C_COMPLEX: u16 = 0x0882; +const C_HIGHLIGHT: u16 = 0x2A0C; +const C_KUL: u16 = 0x2A3E; +const C_ICO: u16 = 0x2A42; +const C_ISS: u16 = 0x2A48; +const C_DSTRIKE: u16 = 0x2A53; +const C_HPS: u16 = 0x4A43; +const C_HPS_POS: u16 = 0x4845; +const C_HPS_KERN: u16 = 0x484B; +const C_CHAR_SCALE: u16 = 0x4852; +const C_LID_BI: u16 = 0x485F; +const C_LID0_80: u16 = 0x486D; +const C_LID1_80: u16 = 0x486E; +const C_LID0: u16 = 0x4873; +const C_LID1: u16 = 0x4874; +const C_FTC0: u16 = 0x4A4F; +const C_FTC1: u16 = 0x4A50; +const C_FTC2: u16 = 0x4A51; +const C_FTC_BI: u16 = 0x4A5E; +const C_HPS_BI: u16 = 0x4A61; +pub(crate) const C_PIC_LOCATION: u16 = 0x6A03; +const C_CV: u16 = 0x6870; +const C_CV_UL: u16 = 0x6877; +const C_DXA_SPACE: u16 = 0x8840; +const C_SHD: u16 = 0xCA71; + +/// What [`chpx`] needs besides the properties: the font table, the style table, and the +/// tracked-change authors. +pub(crate) trait CharCtx { + /// Index of `name` in the font table (added on first use). + fn font(&mut self, name: &str) -> u16; + /// The istd of a character style id; `None` when the stylesheet doesn't have it. + fn char_style(&self, id: &str) -> Option; + /// The author index and `DTTM` of revision `rev` (`Document::revisions`). + fn revision(&mut self, rev: u32) -> Option<(u16, u32)>; +} + +/// The CHPX grpprl for `p`: only the properties it sets, in the order Word applies them (the +/// style first, then toggles, then values). Inherited (`None`) properties are left out. +pub(crate) fn chpx(p: &CharProps, ctx: &mut dyn CharCtx) -> Grpprl { + let mut g = Grpprl::default(); + if let Some(istd) = p.style.as_deref().and_then(|s| ctx.char_style(s)) { + g.u16(C_ISTD, istd); + } + // Tracked changes: the mark, the author and the time ([MS-DOC] sprmCFRMarkIns and friends). + if let Some((ibst, dttm)) = p.ins.and_then(|r| ctx.revision(r)) { + g.u8(C_RMARK_INS, 1); + g.u16(C_IBST_RMARK, ibst); + g.u32(C_DTTM_RMARK, dttm); + } + if let Some((ibst, dttm)) = p.del.and_then(|r| ctx.revision(r)) { + g.u8(C_RMARK_DEL, 1); + g.u16(C_IBST_RMARK_DEL, ibst); + g.u32(C_DTTM_RMARK_DEL, dttm); + } + for (op, v) in [ + (C_BOLD, p.bold), + (C_ITALIC, p.italic), + (C_STRIKE, p.strike), + (C_OUTLINE, p.outline), + (C_SHADOW, p.shadow), + (C_SMALL_CAPS, p.small_caps), + (C_CAPS, p.caps), + (C_VANISH, p.hidden), + (C_IMPRINT, p.engrave), + (C_EMBOSS, p.emboss), + (C_RTL, p.rtl), + (C_BOLD_BI, p.bold_cs), + (C_ITALIC_BI, p.italic_cs), + (C_NO_PROOF, p.no_proof), + (C_COMPLEX, p.cs), + ] { + if let Some(on) = v { + g.u8(op, u8::from(on)); + } + } + if let Some(d) = p.double_strike { + g.u8(C_DSTRIKE, u8::from(d)); + } + if let Some(u) = p.underline { + g.u8(C_KUL, kul(u)); + } + if let Some(c) = p.underline_color { + g.u32(C_CV_UL, colorref(c)); + } + match p.color { + Some(TextColor::Auto) => g.u8(C_ICO, 0), + Some(TextColor::Rgb(c)) => { + // The palette colour for Word 97, then the exact colour for every later version. + g.u8(C_ICO, nearest_ico(c)); + g.u32(C_CV, colorref(c)); + } + None => {} + } + if let Some(h) = p.highlight { + g.u8(C_HIGHLIGHT, highlight_ico(h)); + } + if let Some(s) = p.size { + g.u16(C_HPS, half_points(s)); + } + if let Some(s) = p.size_cs { + g.u16(C_HPS_BI, half_points(s)); + } + if let Some(v) = p.vert_align { + g.u8( + C_ISS, + match v { + VertAlign::Baseline => 0, + VertAlign::Superscript => 1, + VertAlign::Subscript => 2, + }, + ); + } + if let Some(pos) = p.position { + g.i16(C_HPS_POS, (pos * 2.0).round().clamp(-3168.0, 3168.0) as i16); + } + if let Some(sp) = p.spacing { + g.i16(C_DXA_SPACE, twips(sp)); + } + if let Some(sc) = p.scale { + g.u16(C_CHAR_SCALE, sc.round().clamp(1.0, 600.0) as u16); + } + if let Some(k) = p.kern { + g.u16(C_HPS_KERN, half_points(k.max(0.0))); + } + if let Some(f) = p.font.as_deref() { + let i = ctx.font(f); + g.u16(C_FTC0, i); + // Text outside ASCII but not East Asian takes the third font; Word sets both together. + g.u16(C_FTC2, i); + } + if let Some(f) = p.font_ea.as_deref() { + let i = ctx.font(f); + g.u16(C_FTC1, i); + } + if let Some(f) = p.font_cs.as_deref() { + let i = ctx.font(f); + g.u16(C_FTC_BI, i); + } + if let Some(lid) = p.lang.as_deref().and_then(lcid) { + g.u16(C_LID0_80, lid); + g.u16(C_LID0, lid); + } + if let Some(lid) = p.lang_ea.as_deref().and_then(lcid) { + g.u16(C_LID1_80, lid); + g.u16(C_LID1, lid); + } + if let Some(lid) = p.lang_bidi.as_deref().and_then(lcid) { + g.u16(C_LID_BI, lid); + } + if let Some(c) = p.shading { + g.var(C_SHD, &shd(Some(c))); + } + g +} + +/// Points → half-points, as the size sprms store them. +fn half_points(pt: f32) -> u16 { + (pt * 2.0).round().clamp(2.0, 3276.0) as u16 +} + +/// Points → twips, clamped to what an `XAS`/`YAS` holds. +pub(crate) fn twips(pt: f32) -> i16 { + if !pt.is_finite() { + return 0; + } + (pt * 20.0).round().clamp(-31_680.0, 31_680.0) as i16 +} + +/// A `COLORREF` (0x00BBGGRR, stored R, G, B, 0). +pub(crate) fn colorref(c: Rgb) -> u32 { + u32::from_le_bytes([c.0, c.1, c.2, 0]) +} + +/// The automatic colour (`fAuto` in the high byte). +pub(crate) const CV_AUTO: u32 = 0xFF00_0000; + +/// A 10-byte `Shd` ([MS-DOC] §2.9.248): automatic foreground, `fill` as background, clear +/// pattern; no fill is an all-automatic one. +pub(crate) fn shd(fill: Option) -> [u8; 10] { + let mut b = [0u8; 10]; + b[0..4].copy_from_slice(&CV_AUTO.to_le_bytes()); + let back = fill.map_or(CV_AUTO, colorref); + b[4..8].copy_from_slice(&back.to_le_bytes()); + b +} + +/// Word's 16-colour palette ([MS-DOC] §2.9.135 Ico), index 1..=16. +const ICO: [Rgb; 16] = [ + Rgb(0, 0, 0), + Rgb(0, 0, 255), + Rgb(0, 255, 255), + Rgb(0, 255, 0), + Rgb(255, 0, 255), + Rgb(255, 0, 0), + Rgb(255, 255, 0), + Rgb(255, 255, 255), + Rgb(0, 0, 128), + Rgb(0, 128, 128), + Rgb(0, 128, 0), + Rgb(128, 0, 128), + Rgb(128, 0, 0), + Rgb(128, 128, 0), + Rgb(128, 128, 128), + Rgb(192, 192, 192), +]; + +/// The palette entry nearest `c` (by squared distance), 1-based. +pub(crate) fn nearest_ico(c: Rgb) -> u8 { + let d = |p: &Rgb| { + let dr = i32::from(p.0) - i32::from(c.0); + let dg = i32::from(p.1) - i32::from(c.1); + let db = i32::from(p.2) - i32::from(c.2); + dr * dr + dg * dg + db * db + }; + ICO.iter().enumerate().min_by_key(|(_, p)| d(p)).map_or(1, |(i, _)| i as u8 + 1) +} + +/// A highlight colour as the `Ico` `sprmCHighlight` takes. +fn highlight_ico(h: Highlight) -> u8 { + match h { + Highlight::None => 0, + Highlight::Black => 1, + Highlight::Blue => 2, + Highlight::Turquoise => 3, + Highlight::BrightGreen => 4, + Highlight::Pink => 5, + Highlight::Red => 6, + Highlight::Yellow => 7, + Highlight::White => 8, + Highlight::DarkBlue => 9, + Highlight::Teal => 10, + Highlight::Green => 11, + Highlight::Violet => 12, + Highlight::DarkRed => 13, + Highlight::DarkYellow => 14, + Highlight::Gray50 => 15, + Highlight::Gray25 => 16, + } +} + +/// An underline as a `Kul` ([MS-DOC] §2.9.133). +fn kul(u: Underline) -> u8 { + match u { + Underline::None => 0x00, + Underline::Single => 0x01, + Underline::Words => 0x02, + Underline::Double => 0x03, + Underline::Dotted => 0x04, + Underline::Thick => 0x06, + Underline::Dash => 0x07, + Underline::DotDash => 0x09, + Underline::DotDotDash => 0x0A, + Underline::Wave => 0x0B, + Underline::DoubleWave => 0x2B, + } +} + +/// The Windows language id (LCID) of a BCP 47 tag, for the common languages; `None` for a tag +/// not in the table (the text keeps the style's language). +pub(crate) fn lcid(tag: &str) -> Option { + let t = tag.trim().to_ascii_lowercase().replace('_', "-"); + Some(match t.as_str() { + "ar-sa" | "ar" => 0x0401, + "bg-bg" | "bg" => 0x0402, + "ca-es" | "ca" => 0x0403, + "zh-tw" => 0x0404, + "cs-cz" | "cs" => 0x0405, + "da-dk" | "da" => 0x0406, + "de-de" | "de" => 0x0407, + "el-gr" | "el" => 0x0408, + "en-us" | "en" => 0x0409, + "es-es" | "es" => 0x0C0A, + "fi-fi" | "fi" => 0x040B, + "fr-fr" | "fr" => 0x040C, + "he-il" | "he" => 0x040D, + "hu-hu" | "hu" => 0x040E, + "is-is" | "is" => 0x040F, + "it-it" | "it" => 0x0410, + "ja-jp" | "ja" => 0x0411, + "ko-kr" | "ko" => 0x0412, + "nl-nl" | "nl" => 0x0413, + "nb-no" | "nb" | "no" => 0x0414, + "pl-pl" | "pl" => 0x0415, + "pt-br" => 0x0416, + "ro-ro" | "ro" => 0x0418, + "ru-ru" | "ru" => 0x0419, + "hr-hr" | "hr" => 0x041A, + "sk-sk" | "sk" => 0x041B, + "sv-se" | "sv" => 0x041D, + "th-th" | "th" => 0x041E, + "tr-tr" | "tr" => 0x041F, + "id-id" | "id" => 0x0421, + "uk-ua" | "uk" => 0x0422, + "sl-si" | "sl" => 0x0424, + "et-ee" | "et" => 0x0425, + "lv-lv" | "lv" => 0x0426, + "lt-lt" | "lt" => 0x0427, + "fa-ir" | "fa" => 0x0429, + "vi-vn" | "vi" => 0x042A, + "hi-in" | "hi" => 0x0439, + "ne-np" | "ne" => 0x0461, + "zh-cn" | "zh" => 0x0804, + "de-ch" => 0x0807, + "en-gb" => 0x0809, + "es-mx" => 0x080A, + "pt-pt" | "pt" => 0x0816, + "sr-latn-rs" => 0x241A, + "sr-cyrl-rs" | "sr" => 0x281A, + "en-au" => 0x0C09, + "en-ca" => 0x1009, + "fr-ca" => 0x0C0C, + "es-uy" => 0x380A, + "es-419" => 0x580A, + _ => return None, + }) +} + +// Paragraph sprms ([MS-DOC] §2.6.2). +const P_JC80: u16 = 0x2403; +const P_JC: u16 = 0x2461; +const P_KEEP: u16 = 0x2405; +const P_KEEP_FOLLOW: u16 = 0x2406; +const P_PAGE_BREAK_BEFORE: u16 = 0x2407; +const P_NO_LINE_NUMB: u16 = 0x240C; +const P_IN_TABLE: u16 = 0x2416; +const P_TTP: u16 = 0x2417; +const P_NO_AUTO_HYPH: u16 = 0x242A; +const P_WIDOW: u16 = 0x2431; +const P_BIDI: u16 = 0x2441; +const P_OUTLVL: u16 = 0x2640; +const P_CONTEXTUAL: u16 = 0x246D; +const P_ILVL: u16 = 0x260A; +const P_ILFO: u16 = 0x460B; +const P_DXC_RIGHT: u16 = 0x4455; +const P_DXC_LEFT: u16 = 0x4456; +const P_DXC_FIRST: u16 = 0x4457; +const P_DYA_LINE: u16 = 0x6412; +const P_ITAP: u16 = 0x6649; +const P_DXA_RIGHT80: u16 = 0x840E; +const P_DXA_LEFT80: u16 = 0x840F; +const P_DXA_FIRST80: u16 = 0x8411; +const P_DXA_RIGHT: u16 = 0x845D; +const P_DXA_LEFT: u16 = 0x845E; +const P_DXA_FIRST: u16 = 0x8460; +const P_DYA_BEFORE: u16 = 0xA413; +const P_DYA_AFTER: u16 = 0xA414; +const P_CHG_TABS_PAPX: u16 = 0xC60D; +const P_SHD: u16 = 0xC64D; +const P_BRC: [u16; 5] = [0xC64E, 0xC64F, 0xC650, 0xC651, 0xC652]; +const P_BRC80: [u16; 5] = [0x6424, 0x6425, 0x6426, 0x6427, 0x6428]; + +/// What [`papx`] needs besides the properties: the list (LFO) a model num id became. +pub(crate) trait ParaCtx { + /// The 1-based LFO index of model num `id` (0 = no list). + fn lfo(&self, num: u32) -> u16; +} + +/// The PAPX grpprl for `p` (its style is the PAPX's istd, not a sprm). +pub(crate) fn papx(p: &ParaProps, ctx: &dyn ParaCtx) -> Grpprl { + let mut g = Grpprl::default(); + if let Some(a) = p.align { + let jc = match a { + Align::Left => 0, + Align::Center => 1, + Align::Right => 2, + Align::Justify => 3, + Align::Distribute => 4, + }; + g.u8(P_JC80, jc); + g.u8(P_JC, jc); + } + for (v, op80, op) in + [(p.indent_left, P_DXA_LEFT80, P_DXA_LEFT), (p.indent_right, P_DXA_RIGHT80, P_DXA_RIGHT), (p.indent_first, P_DXA_FIRST80, P_DXA_FIRST)] + { + if let Some(v) = v { + g.i16(op80, twips(v)); + g.i16(op, twips(v)); + } + } + for (v, op) in [(p.indent_left_chars, P_DXC_LEFT), (p.indent_right_chars, P_DXC_RIGHT), (p.indent_first_chars, P_DXC_FIRST)] { + if let Some(v) = v.filter(|v| v.is_finite()) { + g.i16(op, (v * 100.0).round().clamp(-31_680.0, 31_680.0) as i16); + } + } + if let Some(v) = p.space_before { + g.u16(P_DYA_BEFORE, twips(v.max(0.0)) as u16); + } + if let Some(v) = p.space_after { + g.u16(P_DYA_AFTER, twips(v.max(0.0)) as u16); + } + if let Some(ls) = p.line_spacing { + // LSPD: dyaLine, then fMultLinespace. + let (line, mult): (i16, i16) = match ls { + LineSpacing::Multiple(m) => ((m * 240.0).round().clamp(1.0, 31_680.0) as i16, 1), + LineSpacing::AtLeast(pt) => (twips(pt.max(0.0)), 0), + LineSpacing::Exactly(pt) => (twips(pt.max(0.05)).saturating_neg(), 0), + }; + let mut op = line.to_le_bytes().to_vec(); + op.extend_from_slice(&mult.to_le_bytes()); + g.raw(P_DYA_LINE, &op); + } + for (op, v) in [ + (P_KEEP, p.keep_lines), + (P_KEEP_FOLLOW, p.keep_next), + (P_PAGE_BREAK_BEFORE, p.page_break_before), + (P_WIDOW, p.widow_control), + (P_CONTEXTUAL, p.contextual_spacing), + (P_NO_AUTO_HYPH, p.suppress_hyphens), + (P_NO_LINE_NUMB, p.suppress_line_numbers), + (P_BIDI, p.bidi), + ] { + if let Some(on) = v { + g.u8(op, u8::from(on)); + } + } + if let Some(l) = p.outline_level { + g.u8(P_OUTLVL, l.min(9)); + } + if let Some(n) = p.numbering { + g.u8(P_ILVL, n.level.min(8)); + g.u16(P_ILFO, if n.num == 0 { 0 } else { ctx.lfo(n.num) }); + } + if let Some(c) = p.shading { + g.var(P_SHD, &shd(Some(c))); + } + if let Some(b) = &p.borders { + para_borders(&mut g, b); + } + if let Some(tabs) = &p.tabs { + tab_stops(&mut g, tabs); + } + g +} + +/// The paragraph's borders: the Word 97 form (palette colour) and the exact one, side by side. +fn para_borders(g: &mut Grpprl, b: &Borders) { + for (i, side) in [b.top, b.left, b.bottom, b.right, b.between].iter().enumerate() { + let Some(side) = side else { continue }; + if let (Some(&op80), Some(&op)) = (P_BRC80.get(i), P_BRC.get(i)) { + g.raw(op80, &brc80(side)); + g.var(op, &brc(side)); + } + } +} + +/// A border's `brcType` ([MS-DOC] §2.9.22). +fn brc_type(s: BorderStyle) -> u8 { + match s { + BorderStyle::None => 0x00, + BorderStyle::Single => 0x01, + BorderStyle::Thick => 0x02, + BorderStyle::Double => 0x03, + BorderStyle::Dotted => 0x06, + BorderStyle::Dashed => 0x07, + BorderStyle::DotDash => 0x08, + BorderStyle::Triple => 0x0A, + BorderStyle::Wave => 0x14, + BorderStyle::ThinThickSmallGap => 0x0B, + BorderStyle::ThickThinSmallGap => 0x0C, + BorderStyle::ThinThickThinSmallGap => 0x0D, + BorderStyle::ThinThickMediumGap => 0x0E, + BorderStyle::ThickThinMediumGap => 0x0F, + BorderStyle::ThinThickThinMediumGap => 0x10, + BorderStyle::ThinThickLargeGap => 0x11, + BorderStyle::ThickThinLargeGap => 0x12, + BorderStyle::ThinThickThinLargeGap => 0x13, + } +} + +/// A `Brc80` ([MS-DOC] §2.9.18): width in eighths of a point, type, palette colour, space. +pub(crate) fn brc80(b: &Border) -> [u8; 4] { + if b.style == BorderStyle::None { + return [0; 4]; + } + let dpt = (b.width * 8.0).round().clamp(2.0, 255.0) as u8; + let ico = b.color.map_or(0, nearest_ico); + let space = b.space.round().clamp(0.0, 31.0) as u8; + [dpt, brc_type(b.style), ico, space] +} + +/// A `Brc` ([MS-DOC] §2.9.16): `COLORREF`, width in eighths of a point, type, space and flags. +pub(crate) fn brc(b: &Border) -> [u8; 8] { + if b.style == BorderStyle::None { + return [0; 8]; + } + let cv = b.color.map_or(0, colorref); + let [c0, c1, c2, c3] = cv.to_le_bytes(); + let dpt = (b.width * 8.0).round().clamp(2.0, 255.0) as u8; + let space = b.space.round().clamp(0.0, 31.0) as u8; + [c0, c1, c2, c3, dpt, brc_type(b.style), space, 0] +} + +/// The paragraph's own tab stops as a `PChgTabsPapxOperand`: the cleared stops in `rgdxaDel`, +/// the others (with their alignment and leader) in `rgdxaAdd`, each list ascending. +fn tab_stops(g: &mut Grpprl, tabs: &[craft_wordmodel::props::TabStop]) { + let mut del: Vec = tabs.iter().filter(|t| t.align == TabAlign::Clear).map(|t| twips(t.pos)).collect(); + let mut add: Vec<(i16, u8)> = tabs + .iter() + .filter(|t| t.align != TabAlign::Clear) + .map(|t| { + let jc = match t.align { + TabAlign::Center => 1, + TabAlign::Right => 2, + TabAlign::Decimal => 3, + TabAlign::Bar => 4, + _ => 0, + }; + let tlc = match t.leader { + TabLeader::None => 0, + TabLeader::Dot => 1, + TabLeader::Hyphen => 2, + TabLeader::Underscore => 3, + TabLeader::MiddleDot => 5, + }; + (twips(t.pos), jc | (tlc << 3)) + }) + .collect(); + del.sort_unstable(); + del.dedup(); + add.sort_by_key(|t| t.0); + add.dedup_by_key(|t| t.0); + // The operand's size byte holds 255: 64 stops each way is Word's own limit and fits. + del.truncate(64); + add.truncate(64); + if del.is_empty() && add.is_empty() { + return; + } + let mut op = vec![del.len() as u8]; + for d in &del { + op.extend_from_slice(&d.to_le_bytes()); + } + op.push(add.len() as u8); + for (x, _) in &add { + op.extend_from_slice(&x.to_le_bytes()); + } + op.extend(add.iter().map(|(_, tbd)| *tbd)); + g.var(P_CHG_TABS_PAPX, &op); +} + +/// The table membership of a paragraph inside a table cell (`sprmPFInTable`, `sprmPItap`); the +/// row-end mark adds `sprmPFTtp`. +pub(crate) fn in_table(g: &mut Grpprl, row_end: bool) { + g.u8(P_IN_TABLE, 1); + if row_end { + g.u8(P_TTP, 1); + } + g.u32(P_ITAP, 1); +} + +// Section sprms ([MS-DOC] §2.6.4). +const S_BKC: u16 = 0x3009; +const S_TITLE_PAGE: u16 = 0x300A; +const S_CCOLUMNS: u16 = 0x500B; +const S_DXA_COLUMNS: u16 = 0x900C; +const S_NFC_PGN: u16 = 0x300E; +const S_PGN_RESTART: u16 = 0x3011; +const S_LNC: u16 = 0x3013; +const S_NLNN_MOD: u16 = 0x5015; +const S_DXA_LNN: u16 = 0x9016; +const S_HDR_TOP: u16 = 0xB017; +const S_HDR_BOTTOM: u16 = 0xB018; +const S_VJC: u16 = 0x301A; +const S_LNN_MIN: u16 = 0x501B; +const S_PGN_START: u16 = 0x501C; +const S_ORIENTATION: u16 = 0x301D; +const S_XA_PAGE: u16 = 0xB01F; +const S_YA_PAGE: u16 = 0xB020; +const S_DXA_LEFT: u16 = 0xB021; +const S_DXA_RIGHT: u16 = 0xB022; +const S_DYA_TOP: u16 = 0x9023; +const S_DYA_BOTTOM: u16 = 0x9024; +const S_DZA_GUTTER: u16 = 0xB025; +const S_EVENLY_SPACED: u16 = 0x3005; +const S_BIDI: u16 = 0x3228; + +/// The SEPX grpprl of a section: every page property, so the section reads the same whatever +/// the reader's defaults. +pub(crate) fn sepx(s: &SectionProps) -> Grpprl { + let mut g = Grpprl::default(); + g.u8( + S_BKC, + match s.start { + SectionStart::Continuous => 0, + SectionStart::NextColumn => 1, + SectionStart::NextPage => 2, + SectionStart::EvenPage => 3, + SectionStart::OddPage => 4, + }, + ); + if s.title_page { + g.u8(S_TITLE_PAGE, 1); + } + let cols = s.columns.count.clamp(1, 44); + if cols > 1 { + g.u16(S_CCOLUMNS, (cols - 1) as u16); + g.u16(S_DXA_COLUMNS, twips(s.columns.space.max(0.0)) as u16); + g.u8(S_EVENLY_SPACED, 1); + } + if let Some(start) = s.page_num_start { + g.u8(S_PGN_RESTART, 1); + g.u16(S_PGN_START, start.min(0x7FFF) as u16); + } + if s.page_num_format != NumFormat::Decimal { + g.u8(S_NFC_PGN, nfc(s.page_num_format)); + } + if let Some(ln) = &s.line_numbers { + g.u8( + S_LNC, + match ln.restart { + craft_wordmodel::section::LineNumberRestart::Page => 0, + craft_wordmodel::section::LineNumberRestart::Section => 1, + craft_wordmodel::section::LineNumberRestart::Continuous => 2, + }, + ); + g.u16(S_NLNN_MOD, ln.count_by.clamp(1, 100) as u16); + g.i16(S_DXA_LNN, twips(ln.distance.max(0.0))); + g.u16(S_LNN_MIN, ln.start.saturating_sub(1).min(0x7FFF) as u16); + } + g.u8(S_ORIENTATION, if s.landscape { 2 } else { 1 }); + g.u16(S_XA_PAGE, twips(s.page_w.max(7.2)) as u16); + g.u16(S_YA_PAGE, twips(s.page_h.max(7.2)) as u16); + g.u16(S_DXA_LEFT, twips(s.margin_left.max(0.0)) as u16); + g.u16(S_DXA_RIGHT, twips(s.margin_right.max(0.0)) as u16); + g.i16(S_DYA_TOP, twips(s.margin_top)); + g.i16(S_DYA_BOTTOM, twips(s.margin_bottom)); + g.u16(S_DZA_GUTTER, twips(s.gutter.max(0.0)) as u16); + g.u16(S_HDR_TOP, twips(s.header.max(0.0)) as u16); + g.u16(S_HDR_BOTTOM, twips(s.footer.max(0.0)) as u16); + let vjc = match s.valign { + PageVAlign::Top => 0, + PageVAlign::Center => 1, + PageVAlign::Justify => 2, + PageVAlign::Bottom => 3, + }; + if vjc != 0 { + g.u8(S_VJC, vjc); + } + if s.rtl { + g.u8(S_BIDI, 1); + } + g +} + +/// A number format as an `MSONFC` ([MS-OSHARED] §2.2.1.3): its place in the ST_NumberFormat +/// order up to 0x27, decimal past it (the formats Word 97 never had), 0xFF for none. +pub(crate) fn nfc(f: NumFormat) -> u8 { + match f { + NumFormat::None => 0xFF, + f => NumFormat::ALL.iter().position(|x| *x == f).filter(|&i| i <= 0x27).map_or(0, |i| i as u8), + } +} diff --git a/crates/doc-binary/src/write/lists.rs b/crates/doc-binary/src/write/lists.rs new file mode 100644 index 0000000000..37c5b4e5bf --- /dev/null +++ b/crates/doc-binary/src/write/lists.rs @@ -0,0 +1,184 @@ +//! Lists: `PlfLst` (one LSTF per abstract list, its nine LVLs after the array) and `PlfLfo` +//! (one LFO per model num, with LFOLVL start and level overrides) ([MS-DOC] §2.9.147, §2.9.150). + +use std::collections::HashMap; + +use craft_wordmodel::numbering::{Level, LevelSuffix, Numbering}; +use craft_wordmodel::props::{Align, ParaProps}; +use craft_wordmodel::section::NumFormat; + +use super::grpprl::{self, CharCtx, ParaCtx}; + +/// Levels of a multi-level list. +const LEVELS: usize = 9; +/// Most lists written (the format counts LFOs from 1 to 0x07FE). +const MAX_LISTS: usize = 0x07FE; + +/// The written lists: `PlfLst` (with its LVLs appended) and how much of it `lcbPlfLst` covers, +/// `PlfLfo`, and each model num id's LFO index. +pub(crate) struct Lists { + pub(crate) plf_lst: Vec, + pub(crate) lcb_plf_lst: u32, + pub(crate) plf_lfo: Vec, +} + +/// Each model num's 1-based LFO index, in `Numbering::nums` order. +pub(crate) fn lfo_indexes(n: &Numbering) -> HashMap { + n.nums.iter().take(MAX_LISTS).enumerate().map(|(i, num)| (num.id, (i + 1) as u16)).collect() +} + +/// The list id (`lsid`) of abstract list `i`: any unique value other than 0 and -1. +fn lsid(i: usize) -> i32 { + 0x1000_0000 + i as i32 +} + +pub(crate) fn write(n: &Numbering, ctx: &mut (impl CharCtx + ParaCtx)) -> Option { + let abstracts: Vec<_> = n.abstracts.iter().take(MAX_LISTS).collect(); + if abstracts.is_empty() || n.nums.is_empty() { + return None; + } + let mut lst = Vec::new(); + lst.extend_from_slice(&(abstracts.len() as i16).to_le_bytes()); + for (i, _) in abstracts.iter().enumerate() { + // LSTF: lsid, tplc, rgistdPara[9] (none), flags (multi-level), grfhic. + lst.extend_from_slice(&lsid(i).to_le_bytes()); + lst.extend_from_slice(&0u32.to_le_bytes()); + for _ in 0..LEVELS { + lst.extend_from_slice(&0x0FFFu16.to_le_bytes()); + } + lst.push(0); + lst.push(0); + } + let lcb_plf_lst = lst.len() as u32; + for a in &abstracts { + for l in 0..LEVELS { + let level = a.levels.get(l).cloned().unwrap_or_else(|| default_level(l)); + lst.extend_from_slice(&lvl(&level, ctx)); + } + } + + let nums: Vec<_> = n.nums.iter().take(MAX_LISTS).collect(); + let mut lfo = Vec::new(); + lfo.extend_from_slice(&(nums.len() as i32).to_le_bytes()); + let mut data = Vec::new(); + for num in &nums { + let ai = abstracts.iter().position(|a| a.id == num.abstract_id).unwrap_or(0); + // The overrides per level: a start value, a whole level, or both. + let mut over: Vec<(u8, Option, Option<&Level>)> = Vec::new(); + for &(l, start) in &num.start_overrides { + if usize::from(l) < LEVELS { + over.push((l, Some(start), None)); + } + } + for (l, level) in &num.level_overrides { + if usize::from(*l) >= LEVELS { + continue; + } + match over.iter_mut().find(|o| o.0 == *l) { + Some(o) => o.2 = Some(level), + None => over.push((*l, None, Some(level))), + } + } + over.sort_by_key(|o| o.0); + // LFO: lsid, unused1, unused2, clfolvl, ibstFltAutoNum, grfhic, unused3. + lfo.extend_from_slice(&lsid(ai).to_le_bytes()); + lfo.extend_from_slice(&[0u8; 8]); + lfo.push(over.len() as u8); + lfo.extend_from_slice(&[0u8; 3]); + // LFOData: cp (unused, 0xFFFFFFFF), then the LFOLVLs. + data.extend_from_slice(&u32::MAX.to_le_bytes()); + for (l, start, level) in over { + let start_at = start.or(level.map(|lv| lv.start)).unwrap_or(1).min(0x7FFF); + data.extend_from_slice(&(start_at as i32).to_le_bytes()); + let mut flags = l & 0x0F; + if start.is_some() { + flags |= 0x10; // fStartAt + } + if level.is_some() { + flags |= 0x20; // fFormatting + } + data.push(flags); + data.extend_from_slice(&[0u8; 3]); + if let Some(level) = level { + data.extend_from_slice(&lvl(level, ctx)); + } + } + } + lfo.extend_from_slice(&data); + Some(Lists { plf_lst: lst, lcb_plf_lst, plf_lfo: lfo }) +} + +/// A level the model's list doesn't have: decimal, `%n.`, indented a quarter inch a level. +fn default_level(l: usize) -> Level { + Level { start: 1, format: NumFormat::Decimal, text: format!("%{}.", l + 1), indent: 18.0 * (l as f32 + 1.0), hanging: 18.0, ..Level::default() } +} + +/// One LVL: LVLF, grpprlPapx (the indents), grpprlChpx (the number's formatting), number text. +fn lvl(level: &Level, ctx: &mut (impl CharCtx + ParaCtx)) -> Vec { + // Number text: `%n` placeholders become the level index (n − 1), their 1-based positions + // go in rgbxchNums. + let mut xst: Vec = Vec::new(); + let mut nums: Vec = Vec::new(); + let mut chars = level.text.chars().peekable(); + while let Some(c) = chars.next() { + if c == '%' + && let Some(d) = chars.peek().and_then(|d| d.to_digit(10)).filter(|d| (1..=9).contains(d)) + { + chars.next(); + xst.push((d - 1) as u16); + if nums.len() < 9 { + nums.push(xst.len() as u8); + } + continue; + } + let mut buf = [0u16; 2]; + xst.extend_from_slice(c.encode_utf16(&mut buf)); + } + xst.truncate(64); + nums.retain(|&p| usize::from(p) <= xst.len()); + + let mut papx = grpprl::papx(&ParaProps { indent_left: Some(level.indent), indent_first: Some(-level.hanging), ..Default::default() }, ctx); + papx.truncate_to(255); + let mut chpx = grpprl::chpx(&level.chr, ctx); + chpx.truncate_to(255); + + let mut v = Vec::with_capacity(28 + papx.len() + chpx.len() + 2 + xst.len() * 2); + v.extend_from_slice(&(level.start.min(0x7FFF) as i32).to_le_bytes()); + v.push(grpprl::nfc(level.format)); + let jc: u8 = match level.align { + Align::Center => 1, + Align::Right => 2, + _ => 0, + }; + let mut flags = jc; + if level.legal { + flags |= 0x04; + } + if !level.restart { + flags |= 0x08; + } + v.push(flags); + let mut rgbxch = [0u8; 9]; + for (slot, p) in rgbxch.iter_mut().zip(&nums) { + *slot = *p; + } + v.extend_from_slice(&rgbxch); + v.push(match level.suffix { + LevelSuffix::Tab => 0, + LevelSuffix::Space => 1, + LevelSuffix::Nothing => 2, + }); + v.extend_from_slice(&0i32.to_le_bytes()); // dxaIndentSav + v.extend_from_slice(&0u32.to_le_bytes()); // unused2 + v.push(chpx.len() as u8); + v.push(papx.len() as u8); + v.push(level.restart_after.map_or(0, |r| r.saturating_add(1)).min(LEVELS as u8)); + v.push(0); // grfhic + v.extend_from_slice(&papx.0); + v.extend_from_slice(&chpx.0); + v.extend_from_slice(&(xst.len() as u16).to_le_bytes()); + for u in &xst { + v.extend_from_slice(&u.to_le_bytes()); + } + v +} diff --git a/crates/doc-binary/src/write/mod.rs b/crates/doc-binary/src/write/mod.rs new file mode 100644 index 0000000000..08cb43d53d --- /dev/null +++ b/crates/doc-binary/src/write/mod.rs @@ -0,0 +1,463 @@ +//! The `.doc` writer: a [`Document`] as a Word 97-2003 binary file ([MS-DOC]). +//! +//! The file is what Word 97 itself writes, minus the parts the model has nothing for: a compound file +//! with the WordDocument stream (the FIB, the text as one Unicode piece, the formatting pages and +//! the section properties), the 1Table stream (stylesheet, fonts, piece table, document +//! properties, the PLCs locating sections, headers, notes, fields and bookmarks, the lists), a +//! Data stream with the pictures, and the summary information. +//! +//! Kept: text, character and paragraph formatting, styles, lists, tables (one level; nested +//! tables become paragraphs of their cell), sections with headers and footers, footnotes and +//! endnotes, fields and hyperlinks, bookmarks, inline pictures, tracked insertions and deletions, +//! and the document properties. Floating pictures are written in line; shapes, charts, text +//! boxes and comments are left out, each kind logged once per save. + +mod fkp; +mod grpprl; +mod lists; +mod picture; +mod story; +mod styles; +mod summary; +mod tables; + +use std::collections::HashMap; + +use craft_wordmodel::Document; +use craft_wordmodel::para::{NoteKind, Paragraph}; +use craft_wordmodel::section::SectionProps; + +use crate::DocbinError; +use crate::fib::pair; +use grpprl::{CharCtx, Grpprl}; +use story::{Lookup, PARA, Text}; + +/// Where the text starts in the WordDocument stream: right after the FIB (900 bytes). +const TEXT_FC: u32 = 0x400; +/// Bytes in the FIB this writer produces: FibBase, csw + FibRgW97, cslw + FibRgLw97, +/// cbRgFcLcb + FibRgFcLcb97 (0x5D pairs), cswNew. +const FIB_LEN: usize = 0x9A + 0x5D * 8 + 2; +/// Most characters written: the WordDocument stream's FCs are 32-bit and each character takes +/// two bytes; stay far inside. +const MAX_CP: usize = 256 << 20; +/// Size of a Dop97. +const DOP97_LEN: usize = 500; + +/// Write `doc` as a Word 97-2003 document. +pub fn write(doc: &Document) -> Result, DocbinError> { + let plan = styles::plan(&doc.styles); + let normal = plan.istd.get("Normal").copied().unwrap_or(0); + let lfos = lists::lfo_indexes(&doc.numbering); + let mut look = Lookup::new(doc, plan.istd.clone(), normal, lfos); + // Font 0 is the document's default font, as in every Word file; the stylesheet header names + // it as the standard font. + let default_font = doc.styles.default_chr.font.clone().unwrap_or_else(|| "Times New Roman".to_string()); + let f_ascii = look.font(&default_font); + let f_ea = doc.styles.default_chr.font_ea.as_deref().map_or(f_ascii, |f| look.font(f)); + let f_cs = doc.styles.default_chr.font_cs.as_deref().map_or(f_ascii, |f| look.font(f)); + let stsh = styles::stsh(&doc.styles, &plan, &mut look, [f_ascii, f_ea, f_cs]); + let lists = lists::write(&doc.numbering, &mut look); + + let mut t = Text::new(look); + // The main document; it ends with a plain paragraph (a table or a section break can't end it). + t.blocks(&doc.body, true); + t.close_fields(); + let ends_plain = doc.body.last().and_then(|b| b.as_para()).is_some_and(|p| p.section.is_none()); + if !ends_plain || t.paras.last().is_none_or(|p| p.end_cp != t.cp()) { + t.mark(&Paragraph::new(), PARA, &Grpprl::default()); + } + let ccp_text = t.cp(); + let mut sections: Vec<(u32, SectionProps)> = std::mem::take(&mut t.sections); + sections.push((ccp_text, doc.last_section.clone())); + + // Footnotes, then the header document, then endnotes, each a subdocument. + let (ccp_ftn, ftn_txt) = notes(&mut t, doc, NoteKind::Footnote); + let hdd_start = t.cp(); + let hdd_stories = headers(&mut t, doc, §ions); + let ccp_hdd = t.cp() - hdd_start; + let (ccp_edn, edn_txt) = notes(&mut t, doc, NoteKind::Endnote); + if ccp_ftn + ccp_hdd + ccp_edn > 0 { + // One more paragraph mark after the last subdocument ([MS-DOC] §2.8.35). + t.mark(&Paragraph::new(), PARA, &Grpprl::default()); + } + let ccp_all = t.cp(); + if t.units.len() > MAX_CP { + return Err(DocbinError::Limit(format!("the document has {} characters, more than a .doc holds", t.units.len()))); + } + log_dropped(&t.dropped); + + // ---- WordDocument stream: FIB, text, formatting pages, section properties. + let mut word = vec![0u8; TEXT_FC as usize]; + for u in &t.units { + word.extend_from_slice(&u.to_le_bytes()); + } + let fc = |cp: u32| TEXT_FC + cp * 2; + pad_to(&mut word, 512); + let runs = t.char_runs(); + let chpx_runs: Vec = runs.iter().map(|&(a, b, g)| fkp::ChpxRun { fc_start: fc(a), fc_end: fc(b), grpprl: g }).collect(); + let chpx = fkp::chpx_pages(&chpx_runs); + let chpx_pn = (word.len() / 512) as u32; + for p in &chpx.pages { + word.extend_from_slice(p); + } + let mut start = 0u32; + let papx_runs: Vec = t + .paras + .iter() + .map(|p| { + let r = fkp::PapxRun { fc_start: fc(start), fc_end: fc(p.end_cp), istd: p.istd, grpprl: p.grpprl.as_slice() }; + start = p.end_cp; + r + }) + .collect(); + let papx = fkp::papx_pages(&papx_runs); + let papx_pn = (word.len() / 512) as u32; + for p in &papx.pages { + word.extend_from_slice(p); + } + let mut sepx_at = Vec::with_capacity(sections.len()); + for (_, s) in §ions { + pad_to(&mut word, 2); + sepx_at.push(word.len() as u32); + let g = grpprl::sepx(s); + word.extend_from_slice(&(g.len() as u16).to_le_bytes()); + word.extend_from_slice(&g.0); + } + let cb_mac = word.len() as u32; + + // ---- Table stream. + let mut tbl = TableStream::default(); + tbl.put(pair::STSHF, &stsh); + if let Some(&v) = tbl.pairs.get(&pair::STSHF) { + tbl.pairs.insert(0, v); // fcStshfOrig: the same stylesheet + } + // Notes: references in the main text and the stories in their subdocuments. + for (kind, ref_pair, txt_pair, ccp, txt) in [ + (NoteKind::Footnote, pair::PLCF_FND_REF, pair::PLCF_FND_TXT, ccp_ftn, &ftn_txt), + (NoteKind::Endnote, pair::PLCF_END_REF, pair::PLCF_END_TXT, ccp_edn, &edn_txt), + ] { + if ccp == 0 { + continue; + } + let refs: Vec<&story::NoteRefAt> = t.notes.iter().filter(|n| n.kind == kind).collect(); + let mut cps: Vec = refs.iter().map(|n| n.cp).collect(); + cps.push(ccp_text); + let idx: Vec<[u8; 2]> = refs.iter().enumerate().map(|(i, n)| if n.auto { (i as u16 + 1).to_le_bytes() } else { [0, 0] }).collect(); + tbl.put(ref_pair, &fkp::plc(&cps, &idx.iter().map(|x| &x[..]).collect::>())); + let mut tcps = txt.clone(); + tcps.push(ccp - 1); + tcps.push(ccp); + tbl.put(txt_pair, &fkp::plc(&tcps, &[])); + } + // Sections. + let mut sed_cps = vec![0u32]; + sed_cps.extend(sections.iter().map(|(end, _)| *end)); + let seds: Vec<[u8; 12]> = sepx_at + .iter() + .map(|at| { + let mut s = [0u8; 12]; + s[2..6].copy_from_slice(&at.to_le_bytes()); + s[8..12].copy_from_slice(&u32::MAX.to_le_bytes()); + s + }) + .collect(); + tbl.put(pair::PLCF_SED, &fkp::plc(&sed_cps, &seds.iter().map(|x| &x[..]).collect::>())); + if ccp_hdd > 0 { + let mut cps = hdd_stories; + cps.push(ccp_hdd - 1); + cps.push(ccp_hdd); + tbl.put(pair::PLCF_HDD, &fkp::plc(&cps, &[])); + } + tbl.put(pair::PLCF_BTE_CHPX, &chpx.plc_bte(chpx_pn)); + tbl.put(pair::PLCF_BTE_PAPX, &papx.plc_bte(papx_pn)); + // Fields, one PLC per subdocument with CPs relative to it. + let ftn_start = ccp_text; + let edn_start = hdd_start + ccp_hdd; + for (i, a, len) in [(16usize, 0, ccp_text), (18, ftn_start, ccp_ftn), (17, hdd_start, ccp_hdd), (48, edn_start, ccp_edn)] { + let f: Vec<&story::FieldChar> = t.fields.iter().filter(|f| f.cp >= a && f.cp < a + len).collect(); + if f.is_empty() { + continue; + } + let mut cps: Vec = f.iter().map(|f| f.cp - a).collect(); + cps.push(len); + tbl.put(i, &fkp::plc(&cps, &f.iter().map(|f| &f.fld[..]).collect::>())); + } + // Bookmarks in the main text (with an end): names, starts with the index of their end, ends. + let mut marks: Vec<(String, u32, u32)> = + t.bookmarks.iter().filter_map(|(n, a, b)| b.filter(|&b| b <= ccp_text && *a <= b).map(|b| (n.clone(), *a, b))).take(0x3FFF).collect(); + marks.sort_by_key(|m| m.1); + if !marks.is_empty() { + let mut ends: Vec<(u32, usize)> = marks.iter().enumerate().map(|(i, m)| (m.2, i)).collect(); + ends.sort(); + let mut ibkl = vec![0u16; marks.len()]; + for (pos, (_, i)) in ends.iter().enumerate() { + if let Some(slot) = ibkl.get_mut(*i) { + *slot = pos as u16; + } + } + let names: Vec<(String, Vec)> = marks.iter().map(|m| (m.0.chars().take(40).collect(), Vec::new())).collect(); + tbl.put(pair::STTBF_BKMK, &fkp::sttb_ext(&names, 0)); + let mut cps: Vec = marks.iter().map(|m| m.1).collect(); + cps.push(ccp_text + 1); + let fbkf: Vec<[u8; 4]> = ibkl + .iter() + .map(|i| { + let mut b = [0u8; 4]; + b[0..2].copy_from_slice(&i.to_le_bytes()); + b + }) + .collect(); + tbl.put(pair::PLCF_BKF, &fkp::plc(&cps, &fbkf.iter().map(|x| &x[..]).collect::>())); + let mut cps: Vec = ends.iter().map(|e| e.0).collect(); + cps.push(ccp_text + 1); + tbl.put(pair::PLCF_BKL, &fkp::plc(&cps, &[])); + } + tbl.put(31, &dop(doc)); + // SttbfAssoc MUST be there: 18 strings (template, title, author…), all empty here. + tbl.put(32, &fkp::sttb_ext(&vec![(String::new(), Vec::new()); 18], 0)); + // The piece table: one Unicode piece holding every character. + let mut plc = fkp::plc(&[0, ccp_all], &[]); + plc.extend_from_slice(&0u16.to_le_bytes()); + plc.extend_from_slice(&TEXT_FC.to_le_bytes()); + plc.extend_from_slice(&0u16.to_le_bytes()); + let mut clx = vec![0x02]; + clx.extend_from_slice(&(plc.len() as u32).to_le_bytes()); + clx.extend_from_slice(&plc); + tbl.put(pair::CLX, &clx); + if t.look.authors.len() > 1 { + let authors: Vec<(String, Vec)> = t.look.authors.iter().map(|a| (a.clone(), Vec::new())).collect(); + tbl.put(51, &fkp::sttb_ext(&authors, 0)); + } + if let Some(l) = &lists { + pad_to(&mut tbl.bytes, 2); + tbl.pairs.insert(pair::PLF_LST, (tbl.bytes.len() as u32, l.lcb_plf_lst)); + tbl.bytes.extend_from_slice(&l.plf_lst); + tbl.put(pair::PLF_LFO, &l.plf_lfo); + } + // The font table last: every font the text and styles name is in it now. + tbl.put(pair::STTBF_FFN, &styles::font_table(&t.look.fonts)); + + // ---- FIB. + let has_pic = !t.pictures.data.is_empty(); + let fib = fib(cb_mac, [ccp_text, ccp_ftn, ccp_hdd, ccp_edn], &tbl.pairs, has_pic); + if let Some(head) = word.get_mut(..FIB_LEN) { + head.copy_from_slice(&fib); + } + + // ---- The compound file. + let mut streams: Vec<(&str, Vec)> = vec![("WordDocument", word), ("1Table", tbl.bytes)]; + if has_pic { + streams.push(("Data", std::mem::take(&mut t.pictures.data))); + } + streams.push(("\u{5}SummaryInformation", summary::stream(&doc.core))); + compound(&streams) +} + +/// The Table stream being built, and the FIB pair (fc, lcb) of each structure in it. +#[derive(Default)] +struct TableStream { + bytes: Vec, + pairs: HashMap, +} + +impl TableStream { + /// Append a structure (word-aligned) and record it as FIB pair `i`; nothing for an empty one. + fn put(&mut self, i: usize, bytes: &[u8]) { + if bytes.is_empty() { + return; + } + pad_to(&mut self.bytes, 2); + self.pairs.insert(i, (self.bytes.len() as u32, bytes.len() as u32)); + self.bytes.extend_from_slice(bytes); + } +} + +/// Write the stories of the notes of `kind` the main text referred to, in reference order: +/// the subdocument's length and each story's start CP (relative to it). +fn notes(t: &mut Text<'_>, doc: &Document, kind: NoteKind) -> (u32, Vec) { + let start = t.cp(); + let parts: Vec = t.notes.iter().filter(|n| n.kind == kind).map(|n| n.part).collect(); + if parts.is_empty() { + return (0, Vec::new()); + } + let mut starts = Vec::with_capacity(parts.len()); + for id in parts { + starts.push(t.cp() - start); + let blocks = doc.parts.get(&id).map(|p| p.blocks.as_slice()).unwrap_or_default(); + t.note_story(kind, id, blocks); + t.close_fields(); + } + // The guard paragraph mark after the last story. + t.mark(&Paragraph::new(), PARA, &Grpprl::default()); + (t.cp() - start, starts) +} + +/// Write the header document: the six (empty) note separator stories, then six stories per +/// section (even header, header, even footer, footer, first-page header, first-page footer), +/// each ended by a guard paragraph mark. The story start CPs (relative); nothing is written +/// when no section has a header or footer. +fn headers(t: &mut Text<'_>, doc: &Document, sections: &[(u32, SectionProps)]) -> Vec { + let any = sections.iter().any(|(_, s)| { + [s.headers.default, s.headers.first, s.headers.even, s.footers.default, s.footers.first, s.footers.even].iter().any(Option::is_some) + }); + if !any { + return Vec::new(); + } + let start = t.cp(); + let mut cps = vec![0u32; 6]; + for (_, s) in sections { + for id in [s.headers.even, s.headers.default, s.footers.even, s.footers.default, s.headers.first, s.footers.first] { + cps.push(t.cp() - start); + let Some(part) = id.and_then(|id| doc.parts.get(&id)) else { continue }; + if part.blocks.is_empty() { + t.mark(&Paragraph::new(), PARA, &Grpprl::default()); + } else { + t.blocks(&part.blocks, false); + } + t.close_fields(); + t.mark(&Paragraph::new(), PARA, &Grpprl::default()); + } + } + // The final mark the last CP of Plcfhdd ends at ([MS-DOC] §2.8.22). + t.mark(&Paragraph::new(), PARA, &Grpprl::default()); + cps +} + +/// Log, once per save, each kind of content the file leaves out. +fn log_dropped(d: &story::Dropped) { + for (n, what) in [ + (d.shapes, "shapes, charts and text boxes are left out"), + (d.comments, "comments are left out"), + (d.nested_tables, "tables inside table cells become paragraphs of their cell"), + (d.floating_pictures, "floating pictures are placed in line with the text"), + (d.pictures, "pictures in formats a .doc can't hold are left out"), + (d.equations, "equations are written as their linear text"), + ] { + if n > 0 { + log::warn!(".doc save: {n} × {what}"); + } + } +} + +fn pad_to(v: &mut Vec, align: usize) { + while !v.len().is_multiple_of(align) { + v.push(0); + } +} + +/// The FIB for nFib 0x00C1 ([MS-DOC] §2.5): `ccp` is text, footnotes, headers, endnotes. +fn fib(cb_mac: u32, ccp: [u32; 4], pairs: &HashMap, has_pic: bool) -> Vec { + let mut v = vec![0u8; FIB_LEN]; + let put16 = |v: &mut Vec, at: usize, x: u16| { + if let Some(b) = v.get_mut(at..at + 2) { + b.copy_from_slice(&x.to_le_bytes()); + } + }; + put16(&mut v, 0x00, 0xA5EC); // wIdent + put16(&mut v, 0x02, 0x00C1); // nFib + put16(&mut v, 0x06, 0x0409); // lid + // fHasPic, fWhichTblStm (1Table), fExtChar. + put16(&mut v, 0x0A, 0x0200 | 0x1000 | if has_pic { 0x0008 } else { 0 }); + put16(&mut v, 0x0C, 0x00BF); // nFibBack + put16(&mut v, 0x20, 0x000E); // csw + put16(&mut v, 0x22 + 13 * 2, 0x0409); // FibRgW97.lidFE + put16(&mut v, 0x3E, 0x0016); // cslw + let put32 = |v: &mut Vec, at: usize, x: u32| { + if let Some(b) = v.get_mut(at..at + 4) { + b.copy_from_slice(&x.to_le_bytes()); + } + }; + put32(&mut v, 0x40, cb_mac); + put32(&mut v, 0x40 + 3 * 4, ccp[0]); + put32(&mut v, 0x40 + 4 * 4, ccp[1]); + put32(&mut v, 0x40 + 5 * 4, ccp[2]); + put32(&mut v, 0x40 + 8 * 4, ccp[3]); + put16(&mut v, 0x98, 0x005D); // cbRgFcLcb + for (&i, &(fc, lcb)) in pairs { + if i < 0x5D { + put32(&mut v, 0x9A + i * 8, fc); + put32(&mut v, 0x9A + i * 8 + 4, lcb); + } + } + // cswNew = 0: the last two bytes stay zero. + v +} + +/// A Dop97 ([MS-DOC] §2.7.4): footnotes at the bottom of the page, endnotes at the end of the +/// document, both numbered from 1; the default tab stop, hyphenation zone and the settings the +/// document carries; 100 % zoom. +fn dop(doc: &Document) -> Vec { + let s = &doc.settings; + let mut v = vec![0u8; DOP97_LEN]; + // fFacingPages (different odd and even headers), fpc = 1 (bottom of page). + v[0] = u8::from(s.even_odd_headers) | (1 << 5); + v[2..4].copy_from_slice(&(1u16 << 2).to_le_bytes()); // rncFtn 0, nFtn 1 + let mut flags: u32 = 0; + if s.auto_hyphenation { + flags |= 1 << 12; // fAutoHyphen + } + if s.hyphenate_caps { + flags |= 1 << 11; // fHyphCapitals + } + if s.track_changes { + flags |= 1 << 15; // fRevMarking + } + if s.mirror_margins { + flags |= 1 << 21; // fMirrorMargins + } + v[4..8].copy_from_slice(&flags.to_le_bytes()); + let tab = if s.default_tab > 0.0 { grpprl::twips(s.default_tab) } else { 720 }; + v[10..12].copy_from_slice(&tab.to_le_bytes()); // dxaTab + let hot = if s.hyphenation_zone > 0.0 { grpprl::twips(s.hyphenation_zone) } else { 360 }; + v[14..16].copy_from_slice(&hot.to_le_bytes()); // dxaHotZ + v[20..24].copy_from_slice(&dttm(&doc.core.created).to_le_bytes()); + v[24..28].copy_from_slice(&dttm(&doc.core.modified).to_le_bytes()); + v[32..34].copy_from_slice(&(doc.core.revision.clamp(1, u16::MAX as u32) as u16).to_le_bytes()); + v[52..54].copy_from_slice(&(1u16 << 2).to_le_bytes()); // rncEdn 0, nEdn 1 + v[54..56].copy_from_slice(&3u16.to_le_bytes()); // epc: end of document + v[82..84].copy_from_slice(&((100u16 << 3) | (1 << 12)).to_le_bytes()); // pctWwdSaved, zkSaved + v +} + +/// A `DTTM` ([MS-DOC] §2.9.75) from an ISO 8601 date; 0 when there is none. +pub(crate) fn dttm(iso: &str) -> u32 { + use chrono::{Datelike, Timelike}; + let Some(t) = parse_time(iso) else { return 0 }; + let year = t.year(); + if !(1900..=2411).contains(&year) { + return 0; + } + (t.minute() & 0x3F) + | ((t.hour() & 0x1F) << 6) + | ((t.day() & 0x1F) << 11) + | ((t.month() & 0xF) << 16) + | ((((year - 1900) as u32) & 0x1FF) << 20) + | ((t.weekday().num_days_from_sunday() & 7) << 29) +} + +/// An ISO 8601 date or date-time (UTC when it doesn't say). +pub(crate) fn parse_time(iso: &str) -> Option { + let s = iso.trim(); + if s.is_empty() { + return None; + } + if let Ok(t) = chrono::DateTime::parse_from_rfc3339(s) { + return Some(t.naive_utc()); + } + for f in ["%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%d %H:%M:%S"] { + if let Ok(t) = chrono::NaiveDateTime::parse_from_str(s.trim_end_matches('Z'), f) { + return Some(t); + } + } + chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").ok().and_then(|d| d.and_hms_opt(0, 0, 0)) +} + +/// The compound file holding `streams` at its root. Version 3 (512-byte sectors), the version +/// Word 97-2003 writes; readers of that era expect it. +fn compound(streams: &[(&str, Vec)]) -> Result, DocbinError> { + let refs: Vec<(&str, &[u8])> = streams.iter().map(|(name, data)| (*name, data.as_slice())).collect(); + craft_cfb::write_streams(craft_cfb::Version::V3, &refs).map_err(|e| DocbinError::Container(e.to_string())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/doc-binary/src/write/picture.rs b/crates/doc-binary/src/write/picture.rs new file mode 100644 index 0000000000..07eb19fa4e --- /dev/null +++ b/crates/doc-binary/src/write/picture.rs @@ -0,0 +1,211 @@ +//! Inline pictures in the Data stream: a `PICF` header ([MS-DOC] §2.9.193) followed by an +//! `OfficeArtInlineSpContainer` ([MS-ODRAW]): the picture-frame shape, its properties (the +//! picture's place in the BLIP store, crop, alt text) and the `OfficeArtFBSE` with the BLIP +//! embedded in it. The character 0x01 in the text points here through `sprmCPicLocation`. + +use sha1::Digest; + +/// `PICF.cbHeader`. +const CB_HEADER: u16 = 0x44; +/// `MM_SHAPE`: the picture is the OfficeArt shape that follows the header. +const MM_SHAPE: u16 = 0x0064; +/// Largest picture written (bytes of its BLIP): Word's own limit for one picture is far above +/// what the Data stream's 32-bit offsets allow many of. +const MAX_PICTURE: usize = 64 << 20; +/// All pictures together: `sprmCPicLocation` offsets are 32-bit, keep well inside them. +const MAX_DATA: usize = 1 << 30; + +/// OfficeArt record types and BLIP instances ([MS-ODRAW] §2.2). +const SP_CONTAINER: u16 = 0xF004; +const FSP: u16 = 0xF00A; +const FOPT: u16 = 0xF00B; +const FBSE: u16 = 0xF007; +const BLIP_EMF: (u16, u16) = (0xF01A, 0x3D4); +const BLIP_WMF: (u16, u16) = (0xF01B, 0x216); +const BLIP_JPEG: (u16, u16) = (0xF01D, 0x46A); +const BLIP_PNG: (u16, u16) = (0xF01E, 0x6E0); +/// `msosptPictureFrame`. +const SPT_PICTURE_FRAME: u16 = 75; + +/// The Data stream being built. +#[derive(Default)] +pub(crate) struct Pictures { + pub(crate) data: Vec, +} + +/// A picture in a form the BLIP store holds, with its `btWin32` type. +enum Blip { + Png(Vec), + Jpeg(Vec), + /// EMF (true) or WMF metafile bytes. + Metafile(Vec, bool), +} + +impl Blip { + /// Sniff `bytes`: PNG and JPEG go in as they are, metafiles compressed, other raster + /// formats (GIF, BMP, TIFF, WebP) re-encoded as PNG. + fn of(bytes: &[u8]) -> Option { + if bytes.starts_with(b"\x89PNG") { + return Some(Blip::Png(bytes.to_vec())); + } + if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + return Some(Blip::Jpeg(bytes.to_vec())); + } + // EMF: an EMR_HEADER record (type 1) with " EMF" at offset 40. + if bytes.get(0..4) == Some(&[1, 0, 0, 0]) && bytes.get(40..44) == Some(b" EMF") { + return Some(Blip::Metafile(bytes.to_vec(), true)); + } + // WMF: the placeable header's key, or a plain header (type 1 or 2, header size 9). + if bytes.starts_with(&[0xD7, 0xCD, 0xC6, 0x9A]) || (matches!(bytes.get(0..4), Some([1 | 2, 0, 9, 0]))) { + // The BLIP holds the metafile without the placeable header. + let body = if bytes.starts_with(&[0xD7, 0xCD, 0xC6, 0x9A]) { bytes.get(22..)? } else { bytes }; + return Some(Blip::Metafile(body.to_vec(), false)); + } + let img = image::load_from_memory(bytes).ok()?; + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + Some(Blip::Png(png)) + } + + /// `btWin32` ([MS-ODRAW] §2.4.1 MSOBLIPTYPE). + fn bt(&self) -> u8 { + match self { + Blip::Png(_) => 6, + Blip::Jpeg(_) => 5, + Blip::Metafile(_, true) => 2, + Blip::Metafile(_, false) => 3, + } + } + + /// The `OfficeArtBlip*` record. + fn record(&self, w_emu: i32, h_emu: i32) -> Vec { + let (raw, (typ, inst)) = match self { + Blip::Png(b) => (b, BLIP_PNG), + Blip::Jpeg(b) => (b, BLIP_JPEG), + Blip::Metafile(b, emf) => (b, if *emf { BLIP_EMF } else { BLIP_WMF }), + }; + let mut body = uid(raw).to_vec(); + match self { + Blip::Png(b) | Blip::Jpeg(b) => { + body.push(0xFF); // tag + body.extend_from_slice(b); + } + Blip::Metafile(b, _) => { + let packed = miniz_oxide::deflate::compress_to_vec_zlib(b, 6); + // OfficeArtMetafileHeader: cbSize, rcBounds, ptSize (EMUs), cbSave, compression + // (0 = deflate), filter (0xFE = none). + body.extend_from_slice(&(b.len() as u32).to_le_bytes()); + for v in [0i32, 0, w_emu / 12_700, h_emu / 12_700] { + body.extend_from_slice(&v.to_le_bytes()); + } + body.extend_from_slice(&w_emu.to_le_bytes()); + body.extend_from_slice(&h_emu.to_le_bytes()); + body.extend_from_slice(&(packed.len() as u32).to_le_bytes()); + body.push(0); + body.push(0xFE); + body.extend_from_slice(&packed); + } + } + rec(0, inst, typ, &body) + } +} + +/// A 16-byte id for a BLIP (the format wants an MD4; any digest identifies it). +fn uid(bytes: &[u8]) -> [u8; 16] { + let d = sha1::Sha1::digest(bytes); + let mut u = [0u8; 16]; + u.copy_from_slice(d.get(..16).unwrap_or(&[0; 16])); + u +} + +/// An OfficeArt record: header (version, instance, type, length) then the body. +fn rec(ver: u16, inst: u16, typ: u16, body: &[u8]) -> Vec { + let mut v = Vec::with_capacity(8 + body.len()); + v.extend_from_slice(&((ver & 0xF) | (inst << 4)).to_le_bytes()); + v.extend_from_slice(&typ.to_le_bytes()); + v.extend_from_slice(&(body.len() as u32).to_le_bytes()); + v.extend_from_slice(body); + v +} + +/// A 16.16 fixed-point fraction. +fn fixed(f: f32) -> u32 { + ((f.clamp(0.0, 0.99) * 65_536.0).round() as i32) as u32 +} + +impl Pictures { + /// Add a picture shown `w` × `h` points with `crop` (left, top, right, bottom fractions): + /// the offset of its `PICF` in the Data stream, `None` when the picture can't be stored. + pub(crate) fn add(&mut self, bytes: &[u8], w: f32, h: f32, crop: [f32; 4], alt: &str) -> Option { + if bytes.len() > MAX_PICTURE { + return None; + } + let blip = Blip::of(bytes)?; + let [cl, ct, cr, cb] = crop.map(|c| if c.is_finite() { c.clamp(0.0, 0.99) } else { 0.0 }); + // The goal size is the uncropped picture's: the crop takes its share off it. + let gw = (w.max(1.0) / (1.0 - cl - cr).max(0.01)).min(1584.0); + let gh = (h.max(1.0) / (1.0 - ct - cb).max(0.01)).min(1584.0); + let emu = |pt: f32| (pt * 12_700.0).round() as i32; + + let blip_rec = blip.record(emu(gw), emu(gh)); + let mut fbse = vec![blip.bt(), blip.bt()]; + fbse.extend_from_slice(&uid(bytes)); + fbse.extend_from_slice(&0x00FFu16.to_le_bytes()); // tag + fbse.extend_from_slice(&(blip_rec.len() as u32).to_le_bytes()); + fbse.extend_from_slice(&1u32.to_le_bytes()); // cRef + fbse.extend_from_slice(&0u32.to_le_bytes()); // foDelay: embedded + fbse.extend_from_slice(&[0, 0, 0, 0]); // unused1, cbName, unused2, unused3 + fbse.extend_from_slice(&blip_rec); + let fbse = rec(2, u16::from(blip.bt()), FBSE, &fbse); + + // The shape: an FSP (spid, fHaveAnchor | fHaveSpt) and its properties. + let mut fsp = 1025u32.to_le_bytes().to_vec(); + fsp.extend_from_slice(&0x0A00u32.to_le_bytes()); + let fsp = rec(2, SPT_PICTURE_FRAME, FSP, &fsp); + let mut props: Vec<(u16, u32)> = Vec::new(); + for (pid, f) in [(0x0100u16, ct), (0x0101, cb), (0x0102, cl), (0x0103, cr)] { + if f > 0.0 { + props.push((pid, fixed(f))); + } + } + props.push((0x4104, 1)); // pib, fBid: the first (only) store entry + let alt_units: Vec = alt.encode_utf16().take(4095).chain(std::iter::once(0)).collect(); + let has_alt = alt_units.len() > 1; + if has_alt { + props.push((0x8381, (alt_units.len() * 2) as u32)); // wzDescription, complex + } + let mut fopt = Vec::new(); + for (pid, v) in &props { + fopt.extend_from_slice(&pid.to_le_bytes()); + fopt.extend_from_slice(&v.to_le_bytes()); + } + if has_alt { + for u in &alt_units { + fopt.extend_from_slice(&u.to_le_bytes()); + } + } + let fopt = rec(3, props.len() as u16, FOPT, &fopt); + let mut sp = fsp; + sp.extend_from_slice(&fopt); + let sp = rec(0xF, 0, SP_CONTAINER, &sp); + + let lcb = usize::from(CB_HEADER) + sp.len() + fbse.len(); + let at = self.data.len(); + if at.checked_add(lcb)? > MAX_DATA { + return None; + } + let mut picf = vec![0u8; usize::from(CB_HEADER)]; + picf[0..4].copy_from_slice(&(lcb as u32).to_le_bytes()); + picf[4..6].copy_from_slice(&CB_HEADER.to_le_bytes()); + picf[6..8].copy_from_slice(&MM_SHAPE.to_le_bytes()); + // PICMID: dxaGoal, dyaGoal, mx, my (1000 = 100 %). + picf[28..30].copy_from_slice(&super::grpprl::twips(gw).to_le_bytes()); + picf[30..32].copy_from_slice(&super::grpprl::twips(gh).to_le_bytes()); + picf[32..34].copy_from_slice(&1000u16.to_le_bytes()); + picf[34..36].copy_from_slice(&1000u16.to_le_bytes()); + self.data.extend_from_slice(&picf); + self.data.extend_from_slice(&sp); + self.data.extend_from_slice(&fbse); + u32::try_from(at).ok() + } +} diff --git a/crates/doc-binary/src/write/story.rs b/crates/doc-binary/src/write/story.rs new file mode 100644 index 0000000000..b74720c763 --- /dev/null +++ b/crates/doc-binary/src/write/story.rs @@ -0,0 +1,735 @@ +//! The text of every story, as Word's character stream: paragraphs and table cells end with +//! their marks, fields become begin/separator/end characters, pictures and note references +//! special characters, each character carrying its CHPX and each paragraph its PAPX +//! ([MS-DOC] §2.4.1 Retrieving Text, §2.4.3 Table Text). + +use std::collections::HashMap; +use std::sync::Arc; + +use craft_wordmodel::para::{InlineObject, NoteKind, Paragraph}; +use craft_wordmodel::props::{CharProps, ParaProps}; +use craft_wordmodel::section::SectionProps; +use craft_wordmodel::table::Table; +use craft_wordmodel::{Block, Document}; + +use super::grpprl::{self, CharCtx, Grpprl, ParaCtx}; +use super::picture::Pictures; +use super::tables; + +/// Paragraph mark, cell or row end, section mark and the other characters Word gives meaning. +pub(crate) const PARA: u16 = 0x0D; +pub(crate) const CELL: u16 = 0x07; +pub(crate) const SECTION: u16 = 0x0C; +const FIELD_BEGIN: u16 = 0x13; +const FIELD_SEP: u16 = 0x14; +const FIELD_END: u16 = 0x15; +const NOTE_REF: u16 = 0x02; +const PICTURE: u16 = 0x01; + +/// Deepest field nesting written; deeper fields keep their result text only. +const MAX_FIELD_DEPTH: usize = 20; + +/// One paragraph's mark: the CP after it, the paragraph's style and PAPX grpprl. +pub(crate) struct ParaEnd { + pub(crate) end_cp: u32, + pub(crate) istd: u16, + pub(crate) grpprl: Arc>, +} + +/// One field character ([MS-DOC] §2.9.84 Fld): its CP (absolute) and its two bytes. +pub(crate) struct FieldChar { + pub(crate) cp: u32, + pub(crate) fld: [u8; 2], +} + +/// A note reference in the main text: its CP, kind, story (part id) and whether it is numbered +/// automatically. +pub(crate) struct NoteRefAt { + pub(crate) cp: u32, + pub(crate) kind: NoteKind, + pub(crate) part: u32, + pub(crate) auto: bool, +} + +/// What the writer needs to look up while building the text. +pub(crate) struct Lookup<'d> { + pub(crate) doc: &'d Document, + /// Style id → istd. + pub(crate) styles: HashMap, + /// The istd of `Normal`. + pub(crate) normal: u16, + /// Model num id → 1-based LFO index. + pub(crate) lfos: HashMap, + /// Font names in table order and their indexes. + pub(crate) fonts: Vec, + font_index: HashMap, + /// Revision authors (`SttbfRMark`, index 0 = "Unknown") and their indexes. + pub(crate) authors: Vec, +} + +impl<'d> Lookup<'d> { + pub(crate) fn new(doc: &'d Document, styles: HashMap, normal: u16, lfos: HashMap) -> Self { + Lookup { doc, styles, normal, lfos, fonts: Vec::new(), font_index: HashMap::new(), authors: vec!["Unknown".to_string()] } + } +} + +impl CharCtx for Lookup<'_> { + fn font(&mut self, name: &str) -> u16 { + let name = name.trim(); + if let Some(&i) = self.font_index.get(name) { + return i; + } + // The font table keeps names Word can store (it counts them in 16-bit units). + let i = u16::try_from(self.fonts.len()).unwrap_or(0).min(0x7FFF); + if self.fonts.len() < 0x7FFF { + self.fonts.push(name.chars().take(31).collect()); + self.font_index.insert(name.to_string(), i); + } + i + } + + fn char_style(&self, id: &str) -> Option { + let st = self.doc.styles.get(id)?; + (st.kind == craft_wordmodel::styles::StyleKind::Character).then(|| self.styles.get(id).copied()).flatten() + } + + fn revision(&mut self, rev: u32) -> Option<(u16, u32)> { + let r = self.doc.revisions.get(rev as usize)?; + let author = if r.author.trim().is_empty() { "Unknown" } else { r.author.trim() }; + let ibst = match self.authors.iter().position(|a| a == author) { + Some(i) => i, + None => { + self.authors.push(author.to_string()); + self.authors.len() - 1 + } + }; + Some((u16::try_from(ibst).unwrap_or(0), super::dttm(&r.date))) + } +} + +impl ParaCtx for Lookup<'_> { + fn lfo(&self, num: u32) -> u16 { + self.lfos.get(&num).copied().unwrap_or(0) + } +} + +/// Grpprls are shared: a run or paragraph names one by its index. +#[derive(Default)] +struct Interned { + all: Vec>>, + index: HashMap>, usize>, +} + +impl Interned { + fn get(&mut self, g: Vec) -> usize { + if let Some(&i) = self.index.get(&g) { + return i; + } + let g = Arc::new(g); + self.all.push(g.clone()); + self.index.insert(g, self.all.len() - 1); + self.all.len() - 1 + } +} + +/// Counts of content the binary format (as written here) leaves out, logged once per save. +#[derive(Default, Debug)] +pub(crate) struct Dropped { + pub(crate) shapes: usize, + pub(crate) comments: usize, + pub(crate) nested_tables: usize, + pub(crate) floating_pictures: usize, + pub(crate) pictures: usize, + pub(crate) equations: usize, +} + +/// The character stream of every story, with what each character and paragraph carries. +pub(crate) struct Text<'d> { + pub(crate) look: Lookup<'d>, + pub(crate) units: Vec, + /// Run starts: (CP, interned CHPX), each run up to the next start. + runs: Vec<(u32, usize)>, + chpx: Interned, + /// CHPX → the same with `sprmCFSpec`, for field characters. + spec: HashMap, + pub(crate) paras: Vec, + /// Field characters of the subdocument being written, then of each finished one. + pub(crate) fields: Vec, + /// Bookmarks: name, start CP, end CP (absolute), in the order they start. + pub(crate) bookmarks: Vec<(String, u32, Option)>, + pub(crate) notes: Vec, + /// Section ends in the main text: the CP after each section mark, and its properties. + pub(crate) sections: Vec<(u32, SectionProps)>, + pub(crate) pictures: Pictures, + pub(crate) dropped: Dropped, + /// Fields begun with a `FieldStart` and not yet ended (their nesting depth counts here). + open_fields: usize, + /// The note story being written: its own reference mark is its leading 0x02. + note: Option<(NoteKind, u32)>, + /// Inside a table cell: section marks can't end a cell's paragraph. + in_cell: bool, +} + +impl<'d> Text<'d> { + pub(crate) fn new(look: Lookup<'d>) -> Self { + Text { + look, + units: Vec::new(), + runs: Vec::new(), + chpx: Interned::default(), + spec: HashMap::new(), + paras: Vec::new(), + fields: Vec::new(), + bookmarks: Vec::new(), + notes: Vec::new(), + sections: Vec::new(), + pictures: Pictures::default(), + dropped: Dropped::default(), + open_fields: 0, + note: None, + in_cell: false, + } + } + + /// The CP the next character gets. + pub(crate) fn cp(&self) -> u32 { + u32::try_from(self.units.len()).unwrap_or(u32::MAX) + } + + /// The character runs: (start CP, end CP, CHPX grpprl). + pub(crate) fn char_runs(&self) -> Vec<(u32, u32, &[u8])> { + let end = self.cp(); + self.runs + .iter() + .enumerate() + .map(|(i, &(cp, g))| { + let next = self.runs.get(i + 1).map_or(end, |r| r.0); + (cp, next, self.chpx.all.get(g).map_or(&[][..], |v| v.as_slice())) + }) + .collect() + } + + fn emit(&mut self, unit: u16, chpx: usize) { + let cp = self.cp(); + if self.runs.last().is_none_or(|&(_, g)| g != chpx) { + self.runs.push((cp, chpx)); + } + self.units.push(unit); + } + + /// The interned CHPX of `props`, plus `extra` sprms. + fn chpx_of(&mut self, props: &CharProps, extra: Option<&Grpprl>) -> usize { + let mut g = grpprl::chpx(props, &mut self.look); + if let Some(e) = extra { + g.extend(e); + } + g.truncate_to(255); + self.chpx.get(g.0) + } + + fn text(&mut self, s: &str, chpx: usize) { + for c in s.chars() { + self.char(c, chpx); + } + } + + /// One character of text, mapped to what Word stores for it. + fn char(&mut self, c: char, chpx: usize) { + let unit = match c { + '\n' => 0x0B, + '\t' => 0x09, + '\u{C}' => 0x0C, + '\u{E}' => 0x0E, + '\u{2011}' => 0x1E, + '\u{AD}' => 0x1F, + '\r' | '\u{FFFC}' => return, + c if (c as u32) < 0x20 => return, + c => { + let mut buf = [0u16; 2]; + for u in c.encode_utf16(&mut buf).iter() { + self.emit(*u, chpx); + } + return; + } + }; + self.emit(unit, chpx); + } + + /// A field character: the text's formatting with `sprmCFSpec` on, as every field character + /// MUST have ([MS-DOC] §2.8.25). + fn field_char(&mut self, ch: u16, second: u8, chpx: usize) { + let spec = match self.spec.get(&chpx) { + Some(&s) => s, + None => { + let mut g = Grpprl(self.chpx.all.get(chpx).map_or_else(Vec::new, |g| g.as_ref().clone())); + g.truncate_to(252); + g.u8(grpprl::C_SPEC, 1); + let s = self.chpx.get(g.0); + self.spec.insert(chpx, s); + s + } + }; + self.fields.push(FieldChar { cp: self.cp(), fld: [ch as u8, second] }); + self.emit(ch, spec); + } + + /// A whole field: begin, its code, separator and result, end. + fn field(&mut self, instr: &str, result: Option<&str>, locked: bool, dirty: bool, chpx: usize) { + if self.open_fields >= MAX_FIELD_DEPTH { + if let Some(r) = result { + self.text(r, chpx); + } + return; + } + self.field_char(FIELD_BEGIN, flt(instr), chpx); + self.text(&format!(" {} ", instr.trim()), chpx); + if let Some(r) = result { + self.field_char(FIELD_SEP, 0, chpx); + self.text(r, chpx); + } + self.field_char(FIELD_END, end_flags(result.is_some(), locked, dirty, self.open_fields > 0), chpx); + } + + /// Write `blocks` as a story's paragraphs and tables. + pub(crate) fn blocks(&mut self, blocks: &[Arc], top: bool) { + for b in blocks { + match &**b { + Block::Para(p) => self.paragraph(p, top, None), + Block::Table(t) => self.table(t), + } + } + } + + /// Write a note's story, its reference mark first. + pub(crate) fn note_story(&mut self, kind: NoteKind, part: u32, blocks: &[Arc]) { + let own_mark = blocks + .first() + .and_then(|b| b.as_para()) + .is_some_and(|p| p.objects.iter().any(|o| matches!(o, InlineObject::NoteRef { kind: k, id, .. } if *k == kind && *id == part))); + self.note = Some((kind, part)); + if !own_mark { + let style = self.note_ref_style(kind); + let chpx = self.special(&style); + self.emit(NOTE_REF, chpx); + } + if blocks.is_empty() { + self.mark(&Paragraph::new(), PARA, &Grpprl::default()); + } + self.blocks(blocks, false); + self.note = None; + } + + /// A character style for note references ("footnote reference"), when the document has it. + fn note_ref_style(&self, kind: NoteKind) -> CharProps { + let id = match kind { + NoteKind::Footnote => "FootnoteReference", + NoteKind::Endnote => "EndnoteReference", + }; + let style = self.look.styles.contains_key(id).then(|| id.to_string()); + CharProps { style, ..Default::default() } + } + + /// The CHPX of a special character (a note reference, a picture): `sprmCFSpec` on. + fn special(&mut self, props: &CharProps) -> usize { + let mut extra = Grpprl::default(); + extra.u8(grpprl::C_SPEC, 1); + self.chpx_of(props, Some(&extra)) + } + + /// One paragraph: its text, then its mark (`mark` overrides the paragraph mark, for cells; + /// a paragraph ending a main-text section takes a section mark). + pub(crate) fn paragraph(&mut self, p: &Paragraph, top: bool, cell: Option<(u16, &Grpprl)>) { + let mut objects = p.objects.iter(); + let mut link: Option<(String, usize)> = None; + let mut at = 0usize; + for run in &p.runs { + let end = at.saturating_add(run.len).min(p.text.len()); + let Some(s) = p.text.get(at..end) else { break }; + at = end; + if s.is_empty() { + continue; + } + // A run's link becomes a HYPERLINK field around the runs that share it. + let mut props = run.props.clone(); + let target = props.link.take(); + if link.as_ref().map(|l| &l.0) != target.as_ref() { + if let Some((_, chpx)) = link.take() { + self.field_char(FIELD_END, end_flags(true, false, false, self.open_fields > 0), chpx); + } + if let Some(t) = &target { + let chpx = self.chpx_of(&props, None); + self.field_char(FIELD_BEGIN, FLT_HYPERLINK, chpx); + self.text(&format!(" {} ", hyperlink_instr(t)), chpx); + self.field_char(FIELD_SEP, 0, chpx); + link = Some((t.clone(), chpx)); + } + } + let chpx = self.chpx_of(&props, None); + for c in s.chars() { + if c == '\u{FFFC}' { + if let Some(o) = objects.next() { + self.object(o, &props, chpx); + } + } else { + self.char(c, chpx); + } + } + } + if let Some((_, chpx)) = link.take() { + self.field_char(FIELD_END, end_flags(true, false, false, self.open_fields > 0), chpx); + } + match cell { + Some((mark, extra)) => self.mark(p, mark, extra), + None => { + let section = top && !self.in_cell && p.section.is_some(); + self.mark(p, if section { SECTION } else { PARA }, &Grpprl::default()); + if section && let Some(s) = &p.section { + self.sections.push((self.cp(), (**s).clone())); + } + } + } + } + + /// The paragraph mark: its character formatting is the paragraph's mark formatting; the + /// PAPX carries the style and paragraph properties (plus `extra`, for table cells). + pub(crate) fn mark(&mut self, p: &Paragraph, mark: u16, extra: &Grpprl) { + let chpx = self.chpx_of(&p.mark, None); + self.emit(mark, chpx); + let (istd, g) = self.papx_of(&p.props, extra); + self.paras.push(ParaEnd { end_cp: self.cp(), istd, grpprl: g }); + } + + pub(crate) fn papx_of(&mut self, props: &ParaProps, extra: &Grpprl) -> (u16, Arc>) { + let istd = props.style.as_deref().and_then(|s| self.look.styles.get(s).copied()).unwrap_or(self.look.normal); + let mut g = grpprl::papx(props, &self.look); + g.extend(extra); + g.truncate_to(super::fkp::MAX_PAPX_GRPPRL); + (istd, Arc::new(g.0)) + } + + fn object(&mut self, o: &InlineObject, props: &CharProps, chpx: usize) { + match o { + InlineObject::Field { instr, result, locked, dirty, .. } => self.field(instr, Some(result), *locked, *dirty, chpx), + InlineObject::FieldStart { instr, locked, dirty } => { + if self.open_fields >= MAX_FIELD_DEPTH { + self.open_fields += 1; + return; + } + self.field_char(FIELD_BEGIN, flt(instr), chpx); + self.text(&format!(" {} ", instr.trim()), chpx); + self.field_char(FIELD_SEP, 0, chpx); + // The end's flags are decided now: they don't depend on the result. + self.open_fields += 1; + let _ = (locked, dirty); + } + InlineObject::FieldEnd => { + if self.open_fields == 0 { + return; + } + self.open_fields -= 1; + if self.open_fields < MAX_FIELD_DEPTH { + self.field_char(FIELD_END, end_flags(true, false, false, self.open_fields > 0), chpx); + } + } + InlineObject::NoteRef { kind, id, custom } => { + if self.note == Some((*kind, *id)) { + let c = self.special(props); + self.emit(NOTE_REF, c); + } else if self.note.is_none() { + let cp = self.cp(); + let c = self.special(props); + self.emit(NOTE_REF, c); + self.notes.push(NoteRefAt { cp, kind: *kind, part: *id, auto: custom.is_empty() }); + } + } + InlineObject::BookmarkStart { name } => { + if !name.is_empty() && self.bookmarks.iter().all(|(n, _, _)| n != name) { + self.bookmarks.push((name.clone(), self.cp(), None)); + } + } + InlineObject::BookmarkEnd { name } => { + let cp = self.cp(); + if let Some(b) = self.bookmarks.iter_mut().find(|(n, _, e)| n == name && e.is_none()) { + b.2 = Some(cp); + } + } + InlineObject::Image { media, w, h, crop, float, alt, .. } => { + if float.wrap != craft_wordmodel::para::Wrap::Inline { + self.dropped.floating_pictures += 1; + } + let Some(bytes) = self.look.doc.media.get(media).cloned() else { + self.dropped.pictures += 1; + return; + }; + match self.pictures.add(&bytes, *w, *h, *crop, alt) { + Some(fc) => { + let mut extra = Grpprl::default(); + extra.u8(grpprl::C_SPEC, 1); + extra.u32(grpprl::C_PIC_LOCATION, fc); + let c = self.chpx_of(props, Some(&extra)); + self.emit(PICTURE, c); + } + None => self.dropped.pictures += 1, + } + } + InlineObject::Equation { linear, .. } => { + self.dropped.equations += 1; + self.text(linear, chpx); + } + InlineObject::Ruby { base, .. } => self.text(base, chpx), + InlineObject::PositionalTab { .. } => self.emit(0x09, chpx), + InlineObject::Opaque { text, .. } => self.text(text, chpx), + InlineObject::CommentStart { .. } => self.dropped.comments += 1, + InlineObject::Shape { .. } | InlineObject::Group { .. } | InlineObject::Graphic { .. } => self.dropped.shapes += 1, + InlineObject::CommentEnd { .. } + | InlineObject::ControlStart { .. } + | InlineObject::ControlEnd + | InlineObject::PermStart { .. } + | InlineObject::PermEnd { .. } => {} + } + } + + /// End fields left open at the end of a story, so every begin has its end; the ends get a + /// paragraph of their own, as the story must end with a mark. + pub(crate) fn close_fields(&mut self) { + let mut wrote = false; + while self.open_fields > 0 { + self.open_fields -= 1; + if self.open_fields < MAX_FIELD_DEPTH { + let chpx = self.chpx.get(Vec::new()); + self.field_char(FIELD_END, end_flags(true, false, false, self.open_fields > 0), chpx); + wrote = true; + } + } + if wrote { + self.mark(&Paragraph::new(), PARA, &Grpprl::default()); + } + } + + /// A table: each cell's paragraphs end with a cell mark, each row with a row-end mark that + /// carries the row's table properties ([MS-DOC] §2.4.3). + fn table(&mut self, t: &Table) { + let was = self.in_cell; + self.in_cell = true; + let rows = t.rows.len(); + let style_borders = t.props.style.as_deref().and_then(|s| self.look.doc.styles.get(s)).and_then(|s| s.table.as_ref()).and_then(|p| p.borders); + for (ri, row) in t.rows.iter().enumerate() { + // A row has at most 63 cells: the text of any past them goes in the last one. + let last = row.cells.len().min(tables::MAX_CELLS).saturating_sub(1); + let mut in_table = Grpprl::default(); + grpprl::in_table(&mut in_table, false); + for (ci, cell) in row.cells.iter().enumerate() { + let mut paras: Vec<&Paragraph> = Vec::new(); + let mut owned: Vec = Vec::new(); + flatten(&cell.blocks, &mut paras, &mut owned, &mut self.dropped.nested_tables); + let all: Vec<&Paragraph> = if owned.is_empty() { paras } else { owned.iter().collect() }; + // Whether this cell's last paragraph ends the (possibly merged) cell. + let ends_cell = ci < last || ci + 1 == row.cells.len(); + if all.is_empty() { + let mark = if ends_cell { CELL } else { PARA }; + self.paragraph(&Paragraph::new(), false, Some((mark, &in_table))); + continue; + } + for (i, p) in all.iter().enumerate() { + let mark = if ends_cell && i + 1 == all.len() { CELL } else { PARA }; + self.paragraph(p, false, Some((mark, &in_table))); + } + } + let tapx = tables::row_end(t, ri, rows, style_borders); + let mut extra = Grpprl::default(); + grpprl::in_table(&mut extra, true); + extra.extend(&tapx); + self.mark(&Paragraph::new(), CELL, &extra); + } + self.in_cell = was; + } +} + +/// A cell's paragraphs, nested tables flattened into their own paragraphs (the writer keeps one +/// level of tables). When there is nothing to flatten `paras` borrows; else `owned` holds all. +fn flatten<'a>(blocks: &'a [Arc], paras: &mut Vec<&'a Paragraph>, owned: &mut Vec, nested: &mut usize) { + if blocks.iter().all(|b| b.as_para().is_some()) { + paras.extend(blocks.iter().filter_map(|b| b.as_para())); + return; + } + *nested += 1; + fn walk(blocks: &[Arc], out: &mut Vec, depth: usize) { + for b in blocks { + match &**b { + Block::Para(p) => out.push(p.clone()), + Block::Table(t) if depth < 16 => { + for row in &t.rows { + for c in &row.cells { + walk(&c.blocks, out, depth + 1); + } + } + } + Block::Table(_) => {} + } + } + } + walk(blocks, owned, 0); +} + +/// `flt` of a HYPERLINK field. +const FLT_HYPERLINK: u8 = 88; + +/// The field type (`flt`, [MS-DOC] §2.9.87) of a field code, from its first word; 0x01 (an +/// unknown keyword) for anything not in the table, which Word reparses from the code anyway. +fn flt(instr: &str) -> u8 { + let word = instr.split_whitespace().next().unwrap_or("").trim_start_matches('=').to_ascii_uppercase(); + if instr.trim_start().starts_with('=') { + return 34; + } + match word.as_str() { + "REF" => 3, + "FTNREF" => 5, + "SET" => 6, + "IF" => 7, + "INDEX" => 8, + "TC" => 9, + "STYLEREF" => 10, + "SEQ" => 12, + "TOC" => 13, + "INFO" => 14, + "TITLE" => 15, + "SUBJECT" => 16, + "AUTHOR" => 17, + "KEYWORDS" => 18, + "COMMENTS" => 19, + "LASTSAVEDBY" => 20, + "CREATEDATE" => 21, + "SAVEDATE" => 22, + "PRINTDATE" => 23, + "REVNUM" => 24, + "EDITTIME" => 25, + "NUMPAGES" => 26, + "NUMWORDS" => 27, + "NUMCHARS" => 28, + "FILENAME" => 29, + "TEMPLATE" => 30, + "DATE" => 31, + "TIME" => 32, + "PAGE" => 33, + "QUOTE" => 35, + "INCLUDE" => 36, + "PAGEREF" => 37, + "ASK" => 38, + "FILLIN" => 39, + "DATA" => 40, + "NEXT" => 41, + "NEXTIF" => 42, + "SKIPIF" => 43, + "MERGEREC" => 44, + "DDE" => 45, + "DDEAUTO" => 46, + "GLOSSARY" => 47, + "PRINT" => 48, + "EQ" => 49, + "GOTOBUTTON" => 50, + "MACROBUTTON" => 51, + "AUTONUMOUT" => 52, + "AUTONUMLGL" => 53, + "AUTONUM" => 54, + "IMPORT" => 55, + "LINK" => 56, + "SYMBOL" => 57, + "EMBED" => 58, + "MERGEFIELD" => 59, + "USERNAME" => 60, + "USERINITIALS" => 61, + "USERADDRESS" => 62, + "BARCODE" => 63, + "DOCVARIABLE" => 64, + "SECTION" => 65, + "SECTIONPAGES" => 66, + "INCLUDEPICTURE" => 67, + "INCLUDETEXT" => 68, + "FILESIZE" => 69, + "FORMTEXT" => 70, + "FORMCHECKBOX" => 71, + "NOTEREF" => 72, + "TOA" => 73, + "TA" => 74, + "MERGESEQ" => 75, + "AUTOTEXT" => 79, + "COMPARE" => 80, + "ADDIN" => 81, + "FORMDROPDOWN" => 83, + "ADVANCE" => 84, + "DOCPROPERTY" => 85, + "CONTROL" => 87, + "HYPERLINK" => 88, + "AUTOTEXTLIST" => 89, + "LISTNUM" => 90, + "HTMLCONTROL" => 91, + "BIDIOUTLINE" => 92, + "ADDRESSBLOCK" => 93, + "GREETINGLINE" => 94, + "SHAPE" => 95, + "CITATION" => 96, + "BIBLIOGRAPHY" => 97, + _ => 1, + } +} + +/// The second byte of a field end ([MS-DOC] §2.9.84 grffldEnd): `fHasSep` when there is a +/// result, `fLocked`, `fResultsDirty` and `fNested`. +fn end_flags(has_sep: bool, locked: bool, dirty: bool, nested: bool) -> u8 { + let mut f = 0u8; + if dirty { + f |= 0x04; + } + if locked { + f |= 0x10; + } + if nested { + f |= 0x40; + } + if has_sep { + f |= 0x80; + } + f +} + +/// The field code of a link: `HYPERLINK "url"`, `HYPERLINK \l "bookmark"` for an internal +/// one, or both for a link into another document's bookmark. A quote or backslash in an +/// argument is escaped with a backslash, as field codes do. +fn hyperlink_instr(target: &str) -> String { + let q = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\""); + match target.split_once('#') { + Some(("", frag)) => format!("HYPERLINK \\l \"{}\"", q(frag)), + Some((url, frag)) if !frag.is_empty() && !url.contains("://") => format!("HYPERLINK \"{}\" \\l \"{}\"", q(url), q(frag)), + _ => format!("HYPERLINK \"{}\"", q(target)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn field_types() { + assert_eq!(flt("PAGE"), 33); + assert_eq!(flt(" hyperlink \"x\""), 88); + assert_eq!(flt("= 2 + 2"), 34); + assert_eq!(flt("NOSUCHFIELD"), 1); + } + + #[test] + fn hyperlink_codes() { + assert_eq!(hyperlink_instr("https://example.org/a#b"), "HYPERLINK \"https://example.org/a#b\""); + assert_eq!(hyperlink_instr("#Intro"), "HYPERLINK \\l \"Intro\""); + assert_eq!(hyperlink_instr("other.doc#Part"), "HYPERLINK \"other.doc\" \\l \"Part\""); + assert_eq!(craft_wordmodel::link::hyperlink_target(&hyperlink_instr("#Intro")).as_deref(), Some("#Intro")); + assert_eq!( + craft_wordmodel::link::hyperlink_target(&hyperlink_instr("https://example.org/?q=\"x\"")).as_deref(), + Some("https://example.org/?q=\"x\"") + ); + assert_eq!( + craft_wordmodel::link::hyperlink_target(&hyperlink_instr(r"file:///C:\docs\report.doc")).as_deref(), + Some(r"file:///C:\docs\report.doc") + ); + assert_eq!(craft_wordmodel::link::hyperlink_target(&hyperlink_instr("#a\"b")).as_deref(), Some("#a\"b")); + } +} diff --git a/crates/doc-binary/src/write/styles.rs b/crates/doc-binary/src/write/styles.rs new file mode 100644 index 0000000000..d1d6a6649a --- /dev/null +++ b/crates/doc-binary/src/write/styles.rs @@ -0,0 +1,400 @@ +//! The stylesheet (`STSH`, [MS-DOC] §2.9.271) and the font table (`SttbfFfn`, §2.9.286). +//! +//! Istds 0–14 are fixed: 0 Normal, 1–9 heading 1–9, 10 Default Paragraph Font, 11 Normal +//! Table, 12 No List, 13–14 unused. Every other style follows from istd 15 in stylesheet +//! order. A style Word has built in keeps its `sti` and the name Word gives it, so Word treats +//! it as its own; the rest are user styles. + +use std::collections::HashMap; + +use craft_wordmodel::props::CharProps; +use craft_wordmodel::styles::{Style, StyleKind, StyleSheet}; + +use super::grpprl::{self, CharCtx, Grpprl, ParaCtx}; + +/// Istds reserved for built-in styles. +const FIXED: u16 = 15; +/// `sti` of a user-defined style. +const STI_USER: u16 = 0x0FFE; +/// `istdBase` / `istdNext` meaning "none". +const ISTD_NIL: u16 = 0x0FFF; +/// Most styles written (the format allows 0x0FFE). +const MAX_STYLES: usize = 4000; + +/// Built-in styles: the name Word stores (lower-case where Word's is), and the `sti`. +const BUILTIN: &[(&str, u16)] = &[ + ("Normal", 0), + ("heading 1", 1), + ("heading 2", 2), + ("heading 3", 3), + ("heading 4", 4), + ("heading 5", 5), + ("heading 6", 6), + ("heading 7", 7), + ("heading 8", 8), + ("heading 9", 9), + ("toc 1", 19), + ("toc 2", 20), + ("toc 3", 21), + ("toc 4", 22), + ("toc 5", 23), + ("toc 6", 24), + ("toc 7", 25), + ("toc 8", 26), + ("toc 9", 27), + ("Normal Indent", 28), + ("footnote text", 29), + ("annotation text", 30), + ("header", 31), + ("footer", 32), + ("index heading", 33), + ("caption", 34), + ("table of figures", 35), + ("footnote reference", 38), + ("annotation reference", 39), + ("line number", 40), + ("page number", 41), + ("endnote reference", 42), + ("endnote text", 43), + ("List", 47), + ("List Bullet", 48), + ("List Number", 49), + ("Title", 62), + ("Signature", 64), + ("Default Paragraph Font", 65), + ("Body Text", 66), + ("Body Text Indent", 67), + ("List Continue", 68), + ("Subtitle", 74), + ("Salutation", 75), + ("Date", 76), + ("Hyperlink", 85), + ("FollowedHyperlink", 86), + ("Strong", 87), + ("Emphasis", 88), + ("Plain Text", 91), + ("Normal (Web)", 94), + ("Normal Table", 105), + ("No List", 107), + ("Balloon Text", 153), + ("Table Grid", 154), + ("Placeholder Text", 156), + ("No Spacing", 157), + ("List Paragraph", 179), + ("Quote", 180), + ("Intense Quote", 181), + ("Subtle Emphasis", 260), + ("Intense Emphasis", 261), + ("Subtle Reference", 262), + ("Intense Reference", 263), + ("Book Title", 264), + ("Bibliography", 265), + ("TOC Heading", 266), +]; + +/// The built-in style a model style is, by its name or id (`Heading 1`, `Heading1` and +/// `heading 1` are the same), with the name Word stores. +fn builtin(st: &Style) -> Option<(&'static str, u16)> { + let norm = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); + let (name, id) = (norm(&st.name), norm(&st.id)); + // The docx reader's ids for a few styles differ from their names. + let alias = |s: &str| match s { + "tablenormal" => "normaltable".to_string(), + "commenttext" => "annotationtext".to_string(), + "commentreference" => "annotationreference".to_string(), + other => other.to_string(), + }; + BUILTIN + .iter() + .find(|(n, _)| { + let n = norm(n); + n == alias(&name) || n == alias(&id) + }) + .copied() +} + +/// The stylesheet as written: each model style's istd. +pub(crate) struct Plan { + /// Model style id → istd. + pub(crate) istd: HashMap, + /// Istd → model style (index into the stylesheet), `None` for an empty slot. + slots: Vec>, + /// Istd → the name and sti it is written with. + names: Vec<(String, u16)>, +} + +/// Assign istds: the fixed built-ins to their slots, everything else after them. +pub(crate) fn plan(sheet: &StyleSheet) -> Plan { + let mut slots: Vec> = vec![None; FIXED as usize]; + let mut names: Vec<(String, u16)> = vec![(String::new(), 0); FIXED as usize]; + let mut istd = HashMap::new(); + let mut taken = std::collections::HashSet::new(); + for (i, st) in sheet.styles.iter().enumerate().take(MAX_STYLES) { + if st.id.is_empty() || istd.contains_key(&st.id) { + continue; + } + let bi = builtin(st); + // The fixed slot a built-in style takes, when its kind is the one Word gives it. + let fixed = bi.and_then(|(_, sti)| match (sti, st.kind) { + (0..=9, StyleKind::Paragraph) => Some(sti), + (65, StyleKind::Character) => Some(10), + (105, StyleKind::Table) => Some(11), + (107, StyleKind::Numbering) => Some(12), + _ => None, + }); + let slot = match fixed { + Some(s) if !taken.contains(&s) => s, + _ => { + slots.push(None); + names.push((String::new(), 0)); + (slots.len() - 1) as u16 + } + }; + taken.insert(slot); + if let Some(s) = slots.get_mut(slot as usize) { + *s = Some(i); + } + // A built-in name is Word's own spelling; its sti only where the kind matches. + let (name, sti) = match bi { + Some((n, sti)) if builtin_kind(sti) == st.kind => (n.to_string(), sti), + _ => (st.name.clone(), STI_USER), + }; + if let Some(n) = names.get_mut(slot as usize) { + *n = (name, sti); + } + istd.insert(st.id.clone(), slot); + } + // Normal and Default Paragraph Font are always there. + if slots.first().is_some_and(Option::is_none) + && let Some(n) = names.get_mut(0) + { + *n = ("Normal".into(), 0); + } + for (i, name, sti) in [(10usize, "Default Paragraph Font", 65u16), (11, "Normal Table", 105), (12, "No List", 107)] { + if slots.get(i).is_some_and(Option::is_none) + && let Some(n) = names.get_mut(i) + { + *n = (name.into(), sti); + } + } + Plan { istd, slots, names } +} + +/// The kind of style Word's built-in `sti` is. +fn builtin_kind(sti: u16) -> StyleKind { + match sti { + 38 | 39 | 40 | 41 | 42 | 65 | 85 | 86 | 87 | 88 | 156 | 260..=264 => StyleKind::Character, + 105 | 154 => StyleKind::Table, + 107 => StyleKind::Numbering, + _ => StyleKind::Paragraph, + } +} + +/// The STSH bytes. `default_font` is the font-table index of the document's default font +/// (the standard font of the stylesheet header). +pub(crate) fn stsh(sheet: &StyleSheet, plan: &Plan, ctx: &mut (impl CharCtx + ParaCtx), default_fonts: [u16; 3]) -> Vec { + // LPStshi: cbStshi, then Stshi: Stshif (18 bytes), ftcBi, and the latent style data (an + // empty LSD for every sti below stiMaxWhenSaved). + let cstd = plan.slots.len().min(0x0FFE) as u16; + let sti_max = plan.names.iter().map(|(_, sti)| *sti).filter(|&s| s != STI_USER).max().map_or(0x5B, |m| (m + 1).max(0x5B)); + let cb_stshi = 18 + 2 + 2 + 4 * usize::from(sti_max); + let mut v = Vec::new(); + v.extend_from_slice(&(cb_stshi as u16).to_le_bytes()); + v.extend_from_slice(&cstd.to_le_bytes()); + v.extend_from_slice(&0x000Au16.to_le_bytes()); // cbSTDBaseInFile + v.extend_from_slice(&1u16.to_le_bytes()); // fStdStylenamesWritten + v.extend_from_slice(&sti_max.to_le_bytes()); // stiMaxWhenSaved + v.extend_from_slice(&FIXED.to_le_bytes()); // istdMaxFixedWhenSaved + v.extend_from_slice(&0u16.to_le_bytes()); // nVerBuiltInNamesWhenSaved + for f in default_fonts { + v.extend_from_slice(&f.to_le_bytes()); // rgftcStandardChpStsh + } + v.extend_from_slice(&default_fonts[2].to_le_bytes()); // ftcBi + v.extend_from_slice(&4u16.to_le_bytes()); // StshiLsd.cbLSD + v.extend(std::iter::repeat_n(0u8, 4 * usize::from(sti_max))); + for (istd, slot) in plan.slots.iter().enumerate().take(cstd as usize) { + let (name, sti) = plan.names.get(istd).cloned().unwrap_or_default(); + let std = match slot.and_then(|i| sheet.styles.get(i)) { + Some(st) => std_bytes(st, &name, sti, sheet, plan, ctx, istd == 0), + None if !name.is_empty() => empty_builtin(&name, sti, istd as u16), + None => Vec::new(), + }; + v.extend_from_slice(&(std.len() as u16).to_le_bytes()); + v.extend_from_slice(&std); + } + v +} + +/// A built-in style the document doesn't define (Normal, Default Paragraph Font). +fn empty_builtin(name: &str, sti: u16, istd: u16) -> Vec { + let own = istd.to_le_bytes().to_vec(); + let (stk, upx): (u16, Vec>) = match sti { + 65 => (2, vec![Vec::new()]), + 105 => (3, vec![Vec::new(), own, Vec::new()]), + 107 => (4, vec![own]), + _ => (1, vec![own, Vec::new()]), + }; + let next = if stk == 1 { istd } else { ISTD_NIL }; + assemble(sti, stk, ISTD_NIL, next, upx.len() as u16, 0, name, &upx) +} + +/// One STD: `StdfBase`, the name, then the UPXs for its kind. +#[allow(clippy::too_many_arguments)] +fn std_bytes(st: &Style, name: &str, sti: u16, sheet: &StyleSheet, plan: &Plan, ctx: &mut (impl CharCtx + ParaCtx), normal: bool) -> Vec { + let base = st.based_on.as_deref().and_then(|b| plan.istd.get(b).copied()).unwrap_or(ISTD_NIL); + let istd_self = plan.istd.get(&st.id).copied().unwrap_or(0); + let next = st.next.as_deref().and_then(|b| plan.istd.get(b).copied()).unwrap_or(istd_self); + // Document defaults have nowhere else to go in this format: Normal (and any other root + // paragraph or character style) starts from them. + let root = base == ISTD_NIL; + let mut chr = st.chr.clone(); + let mut para = st.para.clone(); + if root && matches!(st.kind, StyleKind::Paragraph) { + chr = overlay(&sheet.default_chr, &chr); + para = craft_wordmodel::props::ParaProps { style: None, ..overlay_para(&sheet.default_para, ¶) }; + } + if normal { + chr.style = None; + } + para.style = None; + para.numbering = para.numbering.filter(|n| n.num != 0); + chr.style = None; + let mut grfstd: u16 = 0; + if st.hidden { + grfstd |= 0x0002 | 0x0100; // fHidden, fSemiHidden + } + if st.locked { + grfstd |= 0x0200; + } + if st.quick { + grfstd |= 0x1000; // fQFormat + } + let (stk, cupx, upx): (u16, u16, Vec>) = match st.kind { + StyleKind::Paragraph => { + let mut papx = istd_self.to_le_bytes().to_vec(); + let mut g = grpprl::papx(¶, ctx); + g.truncate_to(super::fkp::MAX_PAPX_GRPPRL); + papx.extend_from_slice(&g.0); + let mut c = grpprl::chpx(&chr, ctx); + c.truncate_to(255); + (1, 2, vec![papx, c.0]) + } + StyleKind::Character => { + let mut c = grpprl::chpx(&chr, ctx); + c.truncate_to(255); + (2, 1, vec![c.0]) + } + // Table styles: their paragraph and character formatting; the conditional formats stay + // with the model (tables carry their own borders and shading when written). + StyleKind::Table => { + let mut papx = istd_self.to_le_bytes().to_vec(); + papx.extend_from_slice(&grpprl::papx(¶, ctx).0); + (3, 3, vec![Vec::new(), papx, grpprl::chpx(&chr, ctx).0]) + } + StyleKind::Numbering => { + let mut papx = istd_self.to_le_bytes().to_vec(); + papx.extend_from_slice(&Grpprl::default().0); + (4, 1, vec![papx]) + } + }; + assemble(sti, stk, base, next, cupx, grfstd, name, &upx) +} + +/// `StdfBase` + `xstzName` + `GrLPUpxSw` (each UPX padded to an even size). +#[allow(clippy::too_many_arguments)] +fn assemble(sti: u16, stk: u16, base: u16, next: u16, cupx: u16, grfstd: u16, name: &str, upx: &[Vec]) -> Vec { + let mut v = Vec::new(); + v.extend_from_slice(&(sti & 0x0FFF).to_le_bytes()); + v.extend_from_slice(&((stk & 0xF) | ((base & 0x0FFF) << 4)).to_le_bytes()); + v.extend_from_slice(&((cupx & 0xF) | ((next & 0x0FFF) << 4)).to_le_bytes()); + let bch_at = v.len(); + v.extend_from_slice(&0u16.to_le_bytes()); // bchUpe, filled below + v.extend_from_slice(&grfstd.to_le_bytes()); + let units: Vec = name.encode_utf16().take(253).collect(); + v.extend_from_slice(&(units.len() as u16).to_le_bytes()); + for u in &units { + v.extend_from_slice(&u.to_le_bytes()); + } + v.extend_from_slice(&0u16.to_le_bytes()); + for u in upx { + v.extend_from_slice(&(u.len() as u16).to_le_bytes()); + v.extend_from_slice(u); + if u.len() % 2 == 1 { + v.push(0); + } + } + let len = v.len() as u16; + if let Some(b) = v.get_mut(bch_at..bch_at + 2) { + b.copy_from_slice(&len.to_le_bytes()); + } + v +} + +/// `over`'s character properties over `under`'s. +fn overlay(under: &CharProps, over: &CharProps) -> CharProps { + let mut out = under.clone(); + out.overlay(over); + out +} + +fn overlay_para(under: &craft_wordmodel::props::ParaProps, over: &craft_wordmodel::props::ParaProps) -> craft_wordmodel::props::ParaProps { + let mut out = under.clone(); + out.overlay(over); + out +} + +/// The `SttbfFfn`: a non-extended STTB whose entries are `FFN`s (a byte count, then the FFN). +pub(crate) fn font_table(names: &[String]) -> Vec { + let mut v = Vec::new(); + v.extend_from_slice(&(names.len().min(0x7FFF) as u16).to_le_bytes()); + v.extend_from_slice(&0u16.to_le_bytes()); // cbExtra + for name in names.iter().take(0x7FFF) { + let ffn = ffn(name); + v.push(ffn.len() as u8); + v.extend_from_slice(&ffn); + } + v +} + +/// One `FFN` ([MS-DOC] §2.9.82): pitch/TrueType/family bits, `wWeight`, `chs`, +/// `ixchSzAlt`, `panose`, `fs`, then the name, NUL-terminated UTF-16. +fn ffn(name: &str) -> Vec { + let units: Vec = name.encode_utf16().take(31).collect(); + let mut v = Vec::with_capacity(40 + units.len() * 2 + 2); + let symbol = matches!(name.to_ascii_lowercase().as_str(), "symbol" | "wingdings" | "wingdings 2" | "wingdings 3" | "webdings"); + let family: u8 = if symbol { + 5 // FF_DECORATIVE + } else if name.to_ascii_lowercase().contains("mono") || name.eq_ignore_ascii_case("courier new") { + 3 // FF_MODERN + } else if name.to_ascii_lowercase().contains("sans") + || ["arial", "calibri", "aptos", "verdana", "tahoma", "segoe ui"].contains(&name.to_ascii_lowercase().as_str()) + { + 2 // FF_SWISS + } else { + 1 // FF_ROMAN + }; + // prq (2 = variable pitch), fTrueType, ff. + v.push(2 | 0x04 | (family << 4)); + v.extend_from_slice(&400u16.to_le_bytes()); // wWeight + v.push(if symbol { 2 } else { 0 }); // chs: SYMBOL_CHARSET or ANSI_CHARSET + v.push(0); // ixchSzAlt: no alternate name + v.extend_from_slice(&[0u8; 10]); // panose + v.extend_from_slice(&[0u8; 24]); // fs + for u in &units { + v.extend_from_slice(&u.to_le_bytes()); + } + v.extend_from_slice(&0u16.to_le_bytes()); + v +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn font_table_reads_back() { + let names = vec!["Times New Roman".to_string(), "Symbol".to_string(), "Noto Sans Ünï".to_string()]; + let t = font_table(&names); + assert_eq!(crate::stsh::fonts(&t, 0, t.len() as u32), names); + } +} diff --git a/crates/doc-binary/src/write/summary.rs b/crates/doc-binary/src/write/summary.rs new file mode 100644 index 0000000000..f67dc8cc18 --- /dev/null +++ b/crates/doc-binary/src/write/summary.rs @@ -0,0 +1,112 @@ +//! The `\u{5}SummaryInformation` stream ([MS-OLEPS] §2.21): title, subject, author, keywords, +//! comments, last author, revision and the creation and save times. + +use craft_wordmodel::CoreProps; + +/// `FMTID_SummaryInformation` as stored (little-endian GUID fields). +const SUMMARY_FMTID: [u8; 16] = [0xe0, 0x85, 0x9f, 0xf2, 0xf9, 0x4f, 0x68, 0x10, 0xab, 0x91, 0x08, 0x00, 0x2b, 0x27, 0xb3, 0xd9]; +const VT_I2: u32 = 2; +const VT_LPSTR: u32 = 30; +const VT_FILETIME: u32 = 64; +/// Longest string property written (characters). +const MAX_CHARS: usize = 32 << 10; + +/// The text of `s` in code page 1252, when every character has a byte there. +fn cp1252(s: &str) -> Option> { + s.chars().map(|c| (0u8..=255).find(|&b| craft_codepage::cp1252(b) == c && (b >= 0x20 || c == '\t' || c == '\n' || c == '\r'))).collect() +} + +/// The stream's bytes. Strings are Windows-1252 when they all fit it, else UTF-16 (code page +/// 1200). +pub(crate) fn stream(core: &CoreProps) -> Vec { + let strings: Vec<(u32, String)> = + [(2u32, &core.title), (3, &core.subject), (4, &core.creator), (5, &core.keywords), (6, &core.description), (8, &core.last_modified_by)] + .into_iter() + .filter(|(_, s)| !s.is_empty()) + .map(|(id, s)| (id, s.chars().take(MAX_CHARS).collect())) + .chain((core.revision > 0).then(|| (9u32, core.revision.to_string()))) + .collect(); + let ansi = strings.iter().all(|(_, s)| cp1252(s).is_some()); + let codepage: u16 = if ansi { 1252 } else { 1200 }; + + let mut props: Vec<(u32, Vec)> = Vec::new(); + let mut cp = VT_I2.to_le_bytes().to_vec(); + cp.extend_from_slice(&codepage.to_le_bytes()); + cp.extend_from_slice(&[0, 0]); + props.push((1, cp)); + for (id, s) in &strings { + let mut bytes = if ansi { cp1252(s).unwrap_or_default() } else { s.encode_utf16().flat_map(u16::to_le_bytes).collect() }; + bytes.extend_from_slice(if ansi { &[0][..] } else { &[0, 0][..] }); + let mut v = VT_LPSTR.to_le_bytes().to_vec(); + v.extend_from_slice(&(bytes.len() as u32).to_le_bytes()); + v.extend_from_slice(&bytes); + while !v.len().is_multiple_of(4) { + v.push(0); + } + props.push((*id, v)); + } + for (id, iso) in [(12u32, &core.created), (13, &core.modified)] { + if let Some(ft) = filetime(iso) { + let mut v = VT_FILETIME.to_le_bytes().to_vec(); + v.extend_from_slice(&(ft as u32).to_le_bytes()); + v.extend_from_slice(&((ft >> 32) as u32).to_le_bytes()); + props.push((id, v)); + } + } + + // PropertySet: size, count, (id, offset) pairs, then the values. + let table = 8 + props.len() * 8; + let mut set = Vec::new(); + let mut values = Vec::new(); + let mut index = Vec::new(); + for (id, v) in &props { + index.extend_from_slice(&id.to_le_bytes()); + index.extend_from_slice(&((table + values.len()) as u32).to_le_bytes()); + values.extend_from_slice(v); + } + set.extend_from_slice(&((table + values.len()) as u32).to_le_bytes()); + set.extend_from_slice(&(props.len() as u32).to_le_bytes()); + set.extend_from_slice(&index); + set.extend_from_slice(&values); + + // PropertySetStream header: byte order, version, system id, CLSID, one set, its FMTID and + // offset. + let mut out = vec![0xFE, 0xFF, 0, 0]; + out.extend_from_slice(&0x0002_0006u32.to_le_bytes()); + out.extend_from_slice(&[0u8; 16]); + out.extend_from_slice(&1u32.to_le_bytes()); + out.extend_from_slice(&SUMMARY_FMTID); + out.extend_from_slice(&48u32.to_le_bytes()); + out.extend_from_slice(&set); + out +} + +/// A FILETIME (100 ns since 1601) from an ISO 8601 date. +fn filetime(iso: &str) -> Option { + let t = super::parse_time(iso)?.and_utc().timestamp(); + let ft = (t.checked_add(11_644_473_600)?).checked_mul(10_000_000)?; + u64::try_from(ft).ok() +} + +#[cfg(test)] +mod tests { + #[test] + fn summary_reads_back() { + let core = craft_wordmodel::CoreProps { + title: "Annual Report".into(), + creator: "Zoë Writer".into(), + keywords: "a, b".into(), + revision: 3, + created: "2024-05-06T07:08:09Z".into(), + ..Default::default() + }; + let read = crate::metadata::parse_for_tests(&super::stream(&core)).unwrap(); + assert_eq!(read.title, "Annual Report"); + assert_eq!(read.creator, "Zoë Writer"); + assert_eq!(read.keywords, "a, b"); + assert_eq!(read.revision, 3); + assert_eq!(read.created, "2024-05-06T07:08:09Z"); + let unicode = craft_wordmodel::CoreProps { title: "Отчёт 报告".into(), ..Default::default() }; + assert_eq!(crate::metadata::parse_for_tests(&super::stream(&unicode)).unwrap().title, "Отчёт 报告"); + } +} diff --git a/crates/doc-binary/src/write/tables.rs b/crates/doc-binary/src/write/tables.rs new file mode 100644 index 0000000000..43476b17a2 --- /dev/null +++ b/crates/doc-binary/src/write/tables.rs @@ -0,0 +1,224 @@ +//! A table row's properties, carried by its row-end mark ([MS-DOC] §2.4.3, §2.6.3): the cell +//! edges and per-cell borders (`sprmTDefTable`), the table's borders, alignment and indent, row +//! height and flags, and the cells' shading, widths, vertical merges and alignment. + +use craft_wordmodel::props::{Align, Border, Borders, HeightRule, VAlign, VMerge}; +use craft_wordmodel::table::Table; + +use super::grpprl::{Grpprl, brc, brc80, shd, twips}; + +const T_JC90: u16 = 0x5400; +const T_JC: u16 = 0x548A; +const T_DXA_LEFT: u16 = 0x9601; +const T_DXA_GAP_HALF: u16 = 0x9602; +const T_CANT_SPLIT90: u16 = 0x3403; +const T_TABLE_HEADER: u16 = 0x3404; +const T_CANT_SPLIT: u16 = 0x3466; +const T_TABLE_BORDERS80: u16 = 0xD605; +const T_ROW_HEIGHT: u16 = 0x9407; +const T_DEF_TABLE: u16 = 0xD608; +const T_DEF_TABLE_SHD: [u16; 3] = [0xD612, 0xD616, 0xD60C]; +const T_TABLE_BORDERS: u16 = 0xD613; +const T_TABLE_WIDTH: u16 = 0xF614; +const T_VERT_MERGE: u16 = 0xD62B; +const T_VERT_ALIGN: u16 = 0xD62C; +const T_CELL_PADDING_DEFAULT: u16 = 0xD634; +const T_CELL_WIDTH: u16 = 0xD635; + +/// Most cells a row holds (`itcMac` MUST be at most 63). +pub(crate) const MAX_CELLS: usize = 63; +/// Word's default space left of a cell's text (5.4 pt), when the table doesn't say. +const DEFAULT_GAP: f32 = 5.4; + +/// The TAPX sprms of row `ri` of `t` (of `rows`), for its row-end mark; `style_borders` are +/// the borders of the table's style, for a table without its own. +pub(crate) fn row_end(t: &Table, ri: usize, rows: usize, style_borders: Option) -> Grpprl { + let mut g = Grpprl::default(); + let Some(row) = t.rows.get(ri) else { return g }; + let cells = &row.cells.get(..row.cells.len().min(MAX_CELLS)).unwrap_or(&[]); + let n = cells.len(); + let tp = &t.props; + + // Alignment, indent and the cell gap. + let jc: u16 = match tp.align { + Some(Align::Center) => 1, + Some(Align::Right) => 2, + _ => 0, + }; + if jc != 0 { + g.u16(T_JC90, jc); + g.u16(T_JC, jc); + } + let gap = tp.cell_margins.map_or(DEFAULT_GAP, |m| m[1]).clamp(0.0, 100.0); + g.i16(T_DXA_GAP_HALF, twips(gap)); + let indent = tp.indent.unwrap_or(0.0); + g.i16(T_DXA_LEFT, twips(indent + gap)); + if let Some(m) = tp.cell_margins { + // CSSAOperand: itcFirst, itcLim, grfbrc (top 1, left 2, bottom 4, right 8), ftsWidth + // (3 = twips), wWidth. + for (side, v) in [(1u8, m[0]), (2, m[1]), (4, m[2]), (8, m[3])] { + let w = twips(v.max(0.0)) as u16; + let mut op = vec![0, n.max(1) as u8, side, 3]; + op.extend_from_slice(&w.to_le_bytes()); + g.var(T_CELL_PADDING_DEFAULT, &op); + } + } + if let Some(pct) = tp.width_pct { + // ftsWidth 2: fiftieths of a percent. + let mut op = vec![2u8]; + op.extend_from_slice(&((pct.clamp(0.0, 600.0) * 50.0).round() as u16).to_le_bytes()); + g.raw(T_TABLE_WIDTH, &op); + } else if let Some(w) = tp.width { + let mut op = vec![3u8]; + op.extend_from_slice(&(twips(w.max(0.0)) as u16).to_le_bytes()); + g.raw(T_TABLE_WIDTH, &op); + } + + // Row height and flags. + if let Some(h) = row.props.height { + let tw = twips(h.max(0.0)); + g.i16(T_ROW_HEIGHT, if row.props.height_rule == HeightRule::Exact { tw.saturating_neg() } else { tw }); + } + if row.props.header { + g.u8(T_TABLE_HEADER, 1); + } + if row.props.cant_split { + g.u8(T_CANT_SPLIT90, 1); + g.u8(T_CANT_SPLIT, 1); + } + + // The table's borders: its own, else its style's. + let borders = tp.borders.or(style_borders).unwrap_or_default(); + let six = [borders.top, borders.left, borders.bottom, borders.right, borders.between, borders.inside_v]; + let mut b80 = Vec::with_capacity(24); + let mut b = Vec::with_capacity(48); + for side in &six { + b80.extend_from_slice(&side.as_ref().map_or([0; 4], brc80)); + b.extend_from_slice(&side.as_ref().map_or([0; 8], brc)); + } + g.var(T_TABLE_BORDERS80, &b80); + g.var(T_TABLE_BORDERS, &b); + + // Cell edges: each cell spans its grid columns (from the row's `grid_before`), else its own + // preferred width; the edges start at the table's indent. + let widths = cell_widths(t, ri); + let mut edges: Vec = Vec::with_capacity(n + 1); + let mut x = twips(indent); + edges.push(x); + for w in &widths { + x = x.saturating_add(twips(*w).max(1)); + edges.push(x); + } + // TDefTableOperand: cb, itcMac, rgdxaCenter, rgTc80. + let mut body = vec![n as u8]; + for e in &edges { + body.extend_from_slice(&e.to_le_bytes()); + } + for (ci, cell) in cells.iter().enumerate() { + let mut grf: u16 = 0; + match cell.props.vmerge { + VMerge::Restart => grf |= 0x20 | 0x40, + VMerge::Continue => grf |= 0x20, + VMerge::None => {} + } + grf |= valign_bits(cell.props.valign) << 7; + grf |= 3 << 9; // ftsWidth: twips + if cell.props.no_wrap { + grf |= 1 << 13; + } + body.extend_from_slice(&grf.to_le_bytes()); + body.extend_from_slice(&(twips(widths.get(ci).copied().unwrap_or(0.0)) as u16).to_le_bytes()); + let cb = cell_borders(&borders, cell.props.borders.as_ref(), ri, rows, ci, n); + for side in [cb.top, cb.left, cb.bottom, cb.right] { + body.extend_from_slice(&side.as_ref().map_or([0; 4], brc80)); + } + } + let cb = u16::try_from(body.len() + 1).unwrap_or(u16::MAX); + let mut op = cb.to_le_bytes().to_vec(); + op.extend_from_slice(&body); + g.raw(T_DEF_TABLE, &op); + + // Cell shading, in three arrays of up to 22 cells each. + if cells.iter().any(|c| c.props.shading.is_some()) || tp.shading.is_some() { + for (k, op) in T_DEF_TABLE_SHD.iter().enumerate() { + let chunk = cells.get(k * 22..((k + 1) * 22).min(n)).unwrap_or(&[]); + if chunk.is_empty() { + break; + } + let mut v = Vec::with_capacity(chunk.len() * 10); + for c in chunk { + v.extend_from_slice(&shd(c.props.shading.or(tp.shading))); + } + g.var(*op, &v); + } + } + // Per-cell preferred widths, vertical merges and alignment, for the readers that take them + // from sprms rather than from the TC80s. + for (ci, cell) in cells.iter().enumerate() { + let i = ci as u8; + let mut op = vec![i, i + 1]; + if let Some(pct) = cell.props.width_pct { + op.push(2); + op.extend_from_slice(&((pct.clamp(0.0, 100.0) * 50.0).round() as u16).to_le_bytes()); + } else { + op.push(3); + op.extend_from_slice(&(twips(widths.get(ci).copied().unwrap_or(0.0)) as u16).to_le_bytes()); + } + g.var(T_CELL_WIDTH, &op); + match cell.props.vmerge { + VMerge::Restart => g.var(T_VERT_MERGE, &[i, 3]), + VMerge::Continue => g.var(T_VERT_MERGE, &[i, 1]), + VMerge::None => {} + } + if let Some(v) = cell.props.valign + && v != VAlign::Top + { + g.var(T_VERT_ALIGN, &[i, i + 1, valign_bits(Some(v)) as u8]); + } + } + g +} + +fn valign_bits(v: Option) -> u16 { + match v { + Some(VAlign::Center) => 1, + Some(VAlign::Bottom) => 2, + _ => 0, + } +} + +/// Each cell's width in points: the grid columns it spans, else its preferred width, else an +/// equal share of a 6-inch row. +fn cell_widths(t: &Table, ri: usize) -> Vec { + let Some(row) = t.rows.get(ri) else { return Vec::new() }; + let n = row.cells.len().min(MAX_CELLS); + let mut col = row.props.grid_before as usize; + let mut out = Vec::with_capacity(n); + for cell in row.cells.iter().take(n) { + let span = (cell.props.span.max(1) as usize).min(MAX_CELLS); + let from_grid: f32 = t.grid.get(col..col.saturating_add(span).min(t.grid.len())).map_or(0.0, |g| g.iter().sum()); + col = col.saturating_add(span); + let w = if from_grid > 0.0 && from_grid.is_finite() { + from_grid + } else { + cell.props.width.filter(|w| *w > 0.0 && w.is_finite()).unwrap_or(432.0 / n.max(1) as f32) + }; + out.push(w.clamp(1.0, 1584.0)); + } + out +} + +/// The borders cell `ci` of `n` in row `ri` of `rows` shows: the table's outer borders on the +/// table's edges, its inside ones between cells, the cell's own over both. +fn cell_borders(table: &Borders, own: Option<&Borders>, ri: usize, rows: usize, ci: usize, n: usize) -> Borders { + let pick = |own: Option, edge: bool, outer: Option, inner: Option| own.or(if edge { outer } else { inner }); + let own = own.copied().unwrap_or_default(); + Borders { + top: pick(own.top, ri == 0, table.top, table.between), + bottom: pick(own.bottom, ri + 1 == rows, table.bottom, table.between), + left: pick(own.left, ci == 0, table.left, table.inside_v), + right: pick(own.right, ci + 1 == n, table.right, table.inside_v), + between: None, + inside_v: None, + } +} diff --git a/crates/doc-binary/src/write/tests.rs b/crates/doc-binary/src/write/tests.rs new file mode 100644 index 0000000000..b649a4c9f7 --- /dev/null +++ b/crates/doc-binary/src/write/tests.rs @@ -0,0 +1,707 @@ +//! Round trips: documents written as `.doc` and read back with the reader, which follows the +//! same specification independently of the writer. + +use std::sync::Arc; + +use craft_wordmodel::para::{InlineObject, NoteKind, Paragraph}; +use craft_wordmodel::props::*; +use craft_wordmodel::section::{Columns, SectionProps, SectionStart}; +use craft_wordmodel::table::{Cell, Row, Table}; +use craft_wordmodel::{Block, Document, PartKind, para_block}; + +use crate::{read, write}; + +fn doc_of(paras: Vec) -> Document { + let mut d = Document::new(); + d.body = paras.into_iter().map(para_block).collect(); + d +} + +fn round(d: &Document) -> Document { + let bytes = write(d).expect("write"); + read(&bytes).expect("read back") +} + +fn texts(d: &Document) -> Vec { + d.body.iter().filter_map(|b| b.as_para().map(|p| p.plain_text())).collect() +} + +fn para(text: &str) -> Paragraph { + Paragraph::with_text(text, CharProps::default()) +} + +#[test] +fn plain_text_round_trips() { + let d = doc_of(vec![ + para("Hello, world."), + para(""), + para("Ünïcødé — “quotesâ€� 😀 ð�„ž 中文"), + para("tab\there, line\nbreak, nb\u{2011}hyphen, soft\u{AD}hyphen"), + ]); + let r = round(&d); + assert_eq!(texts(&r), texts(&d)); +} + +#[test] +fn an_empty_document_is_one_paragraph() { + let r = round(&Document::new()); + assert_eq!(texts(&r), vec![String::new()]); +} + +#[test] +fn character_formatting_round_trips() { + let mut p = para("bold italic under red big font high sup"); + let fmt = |p: &mut Paragraph, a: usize, b: usize, f: &dyn Fn(&mut CharProps)| p.format(a, b, f).unwrap(); + fmt(&mut p, 0, 4, &|c| c.bold = Some(true)); + fmt(&mut p, 5, 11, &|c| c.italic = Some(true)); + fmt(&mut p, 12, 17, &|c| c.underline = Some(Underline::Double)); + fmt(&mut p, 18, 21, &|c| c.color = Some(TextColor::Rgb(craft_wordmodel::Rgb(0xC0, 0x10, 0x20)))); + fmt(&mut p, 22, 25, &|c| c.size = Some(18.5)); + fmt(&mut p, 26, 30, &|c| c.font = Some("Georgia".into())); + fmt(&mut p, 31, 35, &|c| c.highlight = Some(Highlight::Yellow)); + fmt(&mut p, 36, 39, &|c| { + c.strike = Some(true); + c.small_caps = Some(true); + }); + let r = round(&doc_of(vec![p.clone()])); + let q = r.body[0].as_para().unwrap(); + assert_eq!(q.plain_text(), p.plain_text()); + let at = |i: usize| q.props_at(i + 1).clone(); + assert_eq!(at(0).bold, Some(true)); + assert_eq!(at(5).italic, Some(true)); + assert_eq!(at(12).underline, Some(Underline::Double)); + assert_eq!(at(18).color, Some(TextColor::Rgb(craft_wordmodel::Rgb(0xC0, 0x10, 0x20)))); + assert_eq!(at(22).size, Some(18.5)); + assert_eq!(at(26).font.as_deref(), Some("Georgia")); + assert_eq!(at(36).strike, Some(true)); + assert_eq!(at(36).small_caps, Some(true)); + assert_ne!(at(5).bold, Some(true)); +} + +#[test] +fn paragraph_formatting_round_trips() { + let mut p = para("Centred and indented"); + p.props.align = Some(Align::Center); + p.props.indent_left = Some(36.0); + p.props.indent_right = Some(18.0); + p.props.indent_first = Some(-9.0); + p.props.space_before = Some(12.0); + p.props.space_after = Some(6.0); + p.props.line_spacing = Some(LineSpacing::Multiple(1.5)); + p.props.keep_next = Some(true); + p.props.page_break_before = Some(true); + p.props.tabs = Some(vec![TabStop { pos: 72.0, align: TabAlign::Right, leader: TabLeader::Dot }]); + p.props.borders = Some(Borders { + bottom: Some(Border { style: BorderStyle::Double, width: 1.5, color: Some(craft_wordmodel::Rgb(0, 0, 255)), space: 1.0 }), + ..Default::default() + }); + let mut exact = para("Exactly 14 pt"); + exact.props.line_spacing = Some(LineSpacing::Exactly(14.0)); + let r = round(&doc_of(vec![p.clone(), exact])); + let q = &r.body[0].as_para().unwrap().props; + assert_eq!(q.align, Some(Align::Center)); + assert_eq!(q.indent_left, Some(36.0)); + assert_eq!(q.indent_right, Some(18.0)); + assert_eq!(q.indent_first, Some(-9.0)); + assert_eq!(q.space_before, Some(12.0)); + assert_eq!(q.space_after, Some(6.0)); + assert_eq!(q.line_spacing, Some(LineSpacing::Multiple(1.5))); + assert_eq!(q.keep_next, Some(true)); + assert_eq!(q.page_break_before, Some(true)); + assert_eq!(q.tabs, p.props.tabs); + assert_eq!(q.borders.and_then(|b| b.bottom), p.props.borders.and_then(|b| b.bottom)); + assert_eq!(r.body[1].as_para().unwrap().props.line_spacing, Some(LineSpacing::Exactly(14.0))); +} + +#[test] +fn styles_round_trip() { + let mut d = Document::new(); + let h1 = d.styles.styles.iter().find(|s| s.name == "Heading 1").map(|s| s.id.clone()).expect("a Heading 1 style"); + Arc::make_mut(&mut d.styles).styles.push(craft_wordmodel::styles::Style { + id: "MyQuote".into(), + name: "My Quote".into(), + kind: craft_wordmodel::styles::StyleKind::Paragraph, + based_on: Some("Normal".into()), + chr: CharProps { italic: Some(true), ..Default::default() }, + para: ParaProps { indent_left: Some(24.0), ..Default::default() }, + ..Default::default() + }); + d.body = vec![para_block(para("Title text").styled(&h1)), para_block(para("Quoted").styled("MyQuote")), para_block(para("Body"))]; + let r = round(&d); + assert_eq!(texts(&r), vec!["Title text", "Quoted", "Body"]); + let style_of = |i: usize| r.body[i].as_para().unwrap().props.style.clone().and_then(|id| r.styles.get(&id).map(|s| s.name.clone())); + assert_eq!(style_of(0).as_deref(), Some("Heading 1")); + assert_eq!(style_of(1).as_deref(), Some("My Quote")); + let q = r.styles.styles.iter().find(|s| s.name == "My Quote").unwrap(); + assert_eq!(q.chr.italic, Some(true)); + assert_eq!(q.para.indent_left, Some(24.0)); + // The heading keeps its outline level, the stylesheet its default font. + let h = r.styles.styles.iter().find(|s| s.name == "Heading 1").unwrap(); + assert_eq!(h.para.outline_level, Some(0)); +} + +#[test] +fn many_paragraphs_page_their_formatting() { + let paras: Vec = (0..2000) + .map(|i| { + let mut p = para(&format!("Paragraph {i} with some text")); + if i % 3 == 0 { + p.format(0, 9, &|c| c.bold = Some(true)).unwrap(); + } + if i % 5 == 0 { + p.props.indent_left = Some(i as f32 % 100.0); + } + p + }) + .collect(); + let d = doc_of(paras); + let r = round(&d); + assert_eq!(texts(&r), texts(&d)); + for i in [0usize, 3, 999, 1998] { + let q = r.body[i].as_para().unwrap(); + assert_eq!(q.props_at(1).bold, if i % 3 == 0 { Some(true) } else { q.props_at(1).bold.filter(|_| false) }, "paragraph {i}"); + if i % 5 == 0 { + assert_eq!(q.props.indent_left, Some(i as f32 % 100.0)); + } + } +} + +fn cell(text: &str) -> Cell { + Cell { props: CellProps { span: 1, ..Default::default() }, blocks: vec![para_block(para(text))], controls: Default::default() } +} + +#[test] +fn tables_round_trip() { + let mut a = cell("A1"); + a.props.shading = Some(craft_wordmodel::Rgb(0xEE, 0xDD, 0x00)); + a.props.vmerge = VMerge::Restart; + let mut b = cell(""); + b.props.vmerge = VMerge::Continue; + let mut multi = cell("B1 first"); + multi.blocks.push(para_block(para("B1 second"))); + let t = Table { + props: TableProps { + borders: Some(Borders { top: Some(Border::single(0.5)), bottom: Some(Border::single(0.5)), ..Default::default() }), + ..Default::default() + }, + grid: vec![100.0, 150.0, 80.0], + rows: vec![ + Row { props: RowProps { header: true, ..Default::default() }, cells: vec![a, multi, cell("C1")], controls: Default::default() }, + Row { + props: RowProps { height: Some(30.0), height_rule: HeightRule::Exact, ..Default::default() }, + cells: vec![b, cell("B2"), cell("C2")], + controls: Default::default(), + }, + ], + controls: Default::default(), + }; + let mut d = Document::new(); + d.body = vec![para_block(para("Before")), Arc::new(Block::Table(t)), para_block(para("After"))]; + let r = round(&d); + assert_eq!(r.body.len(), 3, "{:?}", r.body.iter().map(|b| b.as_para().map(|p| p.plain_text())).collect::>()); + let t = r.body[1].as_table().expect("a table"); + assert_eq!(t.rows.len(), 2); + assert_eq!(t.grid, vec![100.0, 150.0, 80.0]); + let cell_text = |r: usize, c: usize| t.rows[r].cells[c].blocks.iter().filter_map(|b| b.as_para().map(|p| p.plain_text())).collect::>(); + assert_eq!(cell_text(0, 0), vec!["A1"]); + assert_eq!(cell_text(0, 1), vec!["B1 first", "B1 second"]); + assert_eq!(cell_text(1, 2), vec!["C2"]); + assert_eq!(t.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(0xEE, 0xDD, 0x00))); + assert_eq!(t.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(t.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert!(t.rows[0].props.header); + assert_eq!(t.rows[1].props.height, Some(30.0)); + assert_eq!(t.rows[1].props.height_rule, HeightRule::Exact); + assert_eq!(texts(&r), vec!["Before", "After"]); +} + +#[test] +fn sections_headers_and_footers_round_trip() { + let mut d = Document::new(); + let h1 = d.add_part(PartKind::Header, vec![para_block(para("First header"))]); + let f1 = d.add_part(PartKind::Footer, vec![para_block(para("First footer"))]); + let h2 = d.add_part(PartKind::Header, vec![para_block(para("Landscape header"))]); + let mut first = para("Portrait section"); + let mut s1 = SectionProps::default(); + s1.headers.default = Some(h1); + s1.footers.default = Some(f1); + s1.margin_left = 54.0; + first.section = Some(Box::new(s1)); + let mut last = + SectionProps { landscape: true, start: SectionStart::NextPage, columns: Columns { count: 2, ..Default::default() }, ..Default::default() }; + (last.page_w, last.page_h) = (792.0, 612.0); + last.headers.default = Some(h2); + d.body = vec![para_block(first), para_block(para("Landscape section"))]; + d.last_section = last; + let r = round(&d); + assert_eq!(texts(&r), vec!["Portrait section", "Landscape section"]); + let s = r.body[0].as_para().unwrap().section.as_ref().expect("the first section ends here"); + assert_eq!(s.margin_left, 54.0); + assert!(!s.landscape); + let part_text = + |id: Option| id.and_then(|i| r.parts.get(&i)).and_then(|p| p.blocks.first()).and_then(|b| b.as_para()).map(|p| p.plain_text()); + assert_eq!(part_text(s.headers.default).as_deref(), Some("First header")); + assert_eq!(part_text(s.footers.default).as_deref(), Some("First footer")); + assert!(r.last_section.landscape); + assert_eq!((r.last_section.page_w, r.last_section.page_h), (792.0, 612.0)); + assert_eq!(r.last_section.columns.count, 2); + assert_eq!(part_text(r.last_section.headers.default).as_deref(), Some("Landscape header")); +} + +#[test] +fn notes_round_trip() { + let mut d = Document::new(); + let f = d.add_part(PartKind::Footnote, vec![para_block(para("The footnote."))]); + let e = d.add_part(PartKind::Endnote, vec![para_block(para("The endnote."))]); + let mut p = para("Text."); + p.insert_object(5, InlineObject::NoteRef { kind: NoteKind::Footnote, id: f, custom: String::new() }, &CharProps::default()).unwrap(); + let end = p.text.len(); + p.insert_object(end, InlineObject::NoteRef { kind: NoteKind::Endnote, id: e, custom: String::new() }, &CharProps::default()).unwrap(); + d.body = vec![para_block(p), para_block(para("After."))]; + let r = round(&d); + assert_eq!(texts(&r)[1], "After."); + let q = r.body[0].as_para().unwrap(); + let notes: Vec<(NoteKind, String)> = q + .objects + .iter() + .filter_map(|o| match o { + InlineObject::NoteRef { kind, id, .. } => { + Some((*kind, r.parts.get(id).and_then(|p| p.blocks.first()).and_then(|b| b.as_para()).map(|p| p.plain_text()).unwrap_or_default())) + } + _ => None, + }) + .collect(); + assert_eq!(notes, vec![(NoteKind::Footnote, "The footnote.".to_string()), (NoteKind::Endnote, "The endnote.".to_string())]); +} + +#[test] +fn fields_links_and_bookmarks_round_trip() { + let mut p = para("Page , see Example and here."); + p.insert_object( + 5, + InlineObject::Field { instr: "PAGE".into(), result: "7".into(), locked: false, dirty: false, code: false, form: String::new() }, + &CharProps::default(), + ) + .unwrap(); + let at = p.text.find("Example").unwrap(); + p.format(at, at + 7, &|c| c.link = Some("https://example.org/a?b=1".into())).unwrap(); + let here = p.text.find("here").unwrap(); + p.insert_object(here + 4, InlineObject::BookmarkEnd { name: "Spot".into() }, &CharProps::default()).unwrap(); + p.insert_object(here, InlineObject::BookmarkStart { name: "Spot".into() }, &CharProps::default()).unwrap(); + let r = round(&doc_of(vec![p])); + let q = r.body[0].as_para().unwrap(); + assert!(q.objects.iter().any(|o| matches!(o, InlineObject::Field { instr, result, .. } if instr == "PAGE" && result == "7")), "{:?}", q.objects); + let link_at = q.text.find("Example").unwrap(); + assert_eq!(q.props_at(link_at + 1).link.as_deref(), Some("https://example.org/a?b=1")); + assert!(q.objects.iter().any(|o| matches!(o, InlineObject::BookmarkStart { name } if name == "Spot"))); + assert!(q.objects.iter().any(|o| matches!(o, InlineObject::BookmarkEnd { name } if name == "Spot"))); +} + +/// A 2×1 PNG. +fn png() -> Vec { + let img = image::RgbaImage::from_pixel(2, 1, image::Rgba([10, 200, 30, 255])); + let mut out = Vec::new(); + image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +#[test] +fn inline_pictures_round_trip() { + let mut d = Document::new(); + let bytes = png(); + d.media.insert("pic.png".into(), Arc::new(bytes.clone())); + let mut p = para("Picture: ."); + p.insert_object( + 9, + InlineObject::Image { + media: "pic.png".into(), + w: 144.0, + h: 72.0, + alt: "A green bar".into(), + float: Default::default(), + crop: [0.0; 4], + ole: None, + fx: Default::default(), + }, + &CharProps::default(), + ) + .unwrap(); + d.body = vec![para_block(p)]; + let r = round(&d); + let q = r.body[0].as_para().unwrap(); + let Some(InlineObject::Image { media, w, h, alt, .. }) = q.objects.first() else { panic!("no picture: {:?}", q.objects) }; + assert!((w - 144.0).abs() < 0.1 && (h - 72.0).abs() < 0.1, "{w}×{h}"); + assert_eq!(alt, "A green bar"); + assert_eq!(r.media.get(media).map(|m| m.as_slice()), Some(bytes.as_slice())); +} + +#[test] +fn document_properties_round_trip() { + let mut d = Document::new(); + d.core.title = "Quarterly".into(); + d.core.creator = "A. Writer".into(); + let r = round(&d); + assert_eq!(r.core.title, "Quarterly"); + assert_eq!(r.core.creator, "A. Writer"); +} + +#[test] +fn lists_round_trip() { + use craft_wordmodel::numbering::{AbstractNum, Level, Num}; + use craft_wordmodel::section::NumFormat; + let mut d = Document::new(); + let levels = vec![ + Level { start: 1, format: NumFormat::Decimal, text: "%1.".into(), indent: 36.0, hanging: 18.0, ..Level::default() }, + Level { start: 1, format: NumFormat::LowerLetter, text: "%1.%2)".into(), indent: 72.0, hanging: 18.0, ..Level::default() }, + Level { start: 1, format: NumFormat::Bullet, text: "\u{2022}".into(), indent: 108.0, hanging: 18.0, ..Level::default() }, + ]; + let numbering = Arc::make_mut(&mut d.numbering); + numbering.abstracts = vec![AbstractNum { id: 7, levels, ..Default::default() }]; + numbering.nums = vec![Num { id: 3, abstract_id: 7, start_overrides: vec![(0, 4)], ..Default::default() }]; + let item = |text: &str, level: u8| { + let mut p = para(text); + p.props.numbering = Some(NumRef { num: 3, level }); + para_block(p) + }; + d.body = vec![item("One", 0), item("One a", 1), item("Dot", 2)]; + let r = round(&d); + let num = |i: usize| r.body[i].as_para().unwrap().props.numbering.expect("numbered"); + assert_eq!((num(0).level, num(1).level, num(2).level), (0, 1, 2)); + let n = r.numbering.nums.iter().find(|n| n.id == num(0).num).expect("the list"); + assert_eq!(n.start_overrides, vec![(0, 4)]); + let a = r.numbering.abstracts.iter().find(|a| a.id == n.abstract_id).expect("its levels"); + assert_eq!(a.levels[0].text, "%1."); + assert_eq!(a.levels[1].text, "%1.%2)"); + assert_eq!(a.levels[1].format, NumFormat::LowerLetter); + assert_eq!(a.levels[2].text, "\u{2022}"); + assert_eq!(a.levels[2].format, NumFormat::Bullet); + assert_eq!((a.levels[1].indent, a.levels[1].hanging), (72.0, 18.0)); +} + +#[test] +fn tracked_changes_round_trip() { + use craft_wordmodel::{Revision, RevisionKind}; + let mut d = Document::new(); + d.revisions = vec![ + Revision::new(RevisionKind::Insert, "Ada", "2025-03-04T05:06:00Z"), + Revision::new(RevisionKind::Delete, "Grace", "2025-03-05T10:20:00Z"), + ]; + let mut p = para("kept added removed"); + p.format(5, 10, &|c| c.ins = Some(0)).unwrap(); + p.format(11, 18, &|c| c.del = Some(1)).unwrap(); + d.body = vec![para_block(p)]; + let r = round(&d); + let q = r.body[0].as_para().unwrap(); + assert_eq!(q.plain_text(), "kept added removed"); + let ins = q.props_at(6).ins.and_then(|i| r.revisions.get(i as usize)).expect("an insertion"); + assert_eq!((ins.kind, ins.author.as_str(), ins.date.as_str()), (RevisionKind::Insert, "Ada", "2025-03-04T05:06:00Z")); + let del = q.props_at(12).del.and_then(|i| r.revisions.get(i as usize)).expect("a deletion"); + assert_eq!((del.kind, del.author.as_str(), del.date.as_str()), (RevisionKind::Delete, "Grace", "2025-03-05T10:20:00Z")); + assert_eq!(q.props_at(1).ins, None); + assert_eq!(q.mark.ins, None); +} + +/// An inserted or deleted paragraph break (the paragraph mark's revision) round-trips too. +#[test] +fn tracked_paragraph_marks_round_trip() { + use craft_wordmodel::{Revision, RevisionKind}; + let mut d = Document::new(); + d.revisions = vec![ + Revision::new(RevisionKind::Insert, "Ada", "2025-03-04T05:06:00Z"), + Revision::new(RevisionKind::Delete, "Grace", "2025-03-05T10:20:00Z"), + ]; + let (mut inserted, mut deleted) = (para("inserted break"), para("deleted break")); + inserted.mark.ins = Some(0); + deleted.mark.del = Some(1); + d.body = vec![para_block(inserted), para_block(deleted), para_block(para("last"))]; + let r = round(&d); + let mark = |i: usize| r.body[i].as_para().unwrap().mark.clone(); + let ins = mark(0).ins.and_then(|i| r.revisions.get(i as usize)).expect("an inserted mark"); + assert_eq!((ins.kind, ins.author.as_str()), (RevisionKind::Insert, "Ada")); + let del = mark(1).del.and_then(|i| r.revisions.get(i as usize)).expect("a deleted mark"); + assert_eq!((del.kind, del.author.as_str()), (RevisionKind::Delete, "Grace")); + assert_eq!((mark(2).ins, mark(2).del), (None, None)); + assert_eq!(r.body[0].as_para().unwrap().props_at(1).ins, None, "the text itself isn't marked"); +} + +/// A tracked insertion or deletion of a picture, a note reference or a field round-trips: the +/// reader takes each anchor's revision marks from its CHPX. +#[test] +fn tracked_object_anchors_round_trip() { + use craft_wordmodel::{Revision, RevisionKind}; + let mut d = Document::new(); + d.revisions = vec![ + Revision::new(RevisionKind::Insert, "Ada", "2025-03-04T05:06:00Z"), + Revision::new(RevisionKind::Delete, "Grace", "2025-03-05T10:20:00Z"), + ]; + d.media.insert("pic.png".into(), Arc::new(png())); + let f = d.add_part(PartKind::Footnote, vec![para_block(para("The footnote."))]); + let inserted = CharProps { ins: Some(0), ..Default::default() }; + let deleted = CharProps { del: Some(1), ..Default::default() }; + let mut p = para("a b c d"); + let picture = InlineObject::Image { + media: "pic.png".into(), + w: 20.0, + h: 10.0, + alt: String::new(), + float: Default::default(), + crop: [0.0; 4], + ole: None, + fx: Default::default(), + }; + let page = InlineObject::Field { instr: "PAGE".into(), result: "1".into(), locked: false, dirty: false, code: false, form: String::new() }; + let note = InlineObject::NoteRef { kind: NoteKind::Footnote, id: f, custom: String::new() }; + // Inserted back to front so the offsets stay put: picture after "a", note after "b", + // field after "c" and an untracked field after "d". + p.insert_object(7, page.clone(), &CharProps::default()).unwrap(); + p.insert_object(5, page, &inserted).unwrap(); + p.insert_object(3, note, &deleted).unwrap(); + p.insert_object(1, picture, &inserted).unwrap(); + d.body = vec![para_block(p)]; + let r = round(&d); + let q = r.body[0].as_para().unwrap(); + let anchors: Vec<(&str, Option, Option)> = q + .text + .match_indices('\u{FFFC}') + .zip(&q.objects) + .map(|((at, _), o)| { + let props = q.props_of_char(at); + let kind = |rev: Option| rev.and_then(|i| r.revisions.get(i as usize)).map(|rev| rev.kind); + let name = match o { + InlineObject::Image { .. } => "picture", + InlineObject::NoteRef { .. } => "note", + InlineObject::Field { .. } => "field", + _ => "other", + }; + (name, kind(props.ins), kind(props.del)) + }) + .collect(); + assert_eq!( + anchors, + vec![ + ("picture", Some(RevisionKind::Insert), None), + ("note", None, Some(RevisionKind::Delete)), + ("field", Some(RevisionKind::Insert), None), + ("field", None, None), + ] + ); +} + +#[test] +#[ignore = "the reader pairs bookmark ends through FBKF.ibkl once craft-libs#1817 is in"] +fn overlapping_bookmarks_keep_their_ends() { + // Outer starts first and ends last; inner ends before it: the ends sort apart from the starts. + let mut p = para("abcdef"); + p.insert_object(6, InlineObject::BookmarkEnd { name: "Outer".into() }, &CharProps::default()).unwrap(); + p.insert_object(4, InlineObject::BookmarkEnd { name: "Inner".into() }, &CharProps::default()).unwrap(); + p.insert_object(2, InlineObject::BookmarkStart { name: "Inner".into() }, &CharProps::default()).unwrap(); + p.insert_object(0, InlineObject::BookmarkStart { name: "Outer".into() }, &CharProps::default()).unwrap(); + let r = round(&doc_of(vec![p.clone()])); + let q = r.body[0].as_para().unwrap(); + let marks = |p: &Paragraph| -> Vec { + p.objects + .iter() + .filter_map(|o| match o { + InlineObject::BookmarkStart { name } => Some(format!("+{name}")), + InlineObject::BookmarkEnd { name } => Some(format!("-{name}")), + _ => None, + }) + .collect() + }; + assert_eq!(marks(q), marks(&p)); + assert_eq!(q.text, p.text); +} + +/// What the writer writes for a character's vertical position: superscript and subscript as +/// `sprmCIss`, a raised or lowered position as `sprmCHpsPos`, character spacing as +/// `sprmCDxaSpace`. The reader reads them once craft-libs#1799 is in. +#[test] +#[ignore = "the reader reads sprmCIss, sprmCHpsPos and sprmCDxaSpace once craft-libs#1799 is in"] +fn position_and_spacing_round_trip() { + let mut p = para("sup sub up sp"); + p.format(0, 3, &|c| c.vert_align = Some(VertAlign::Superscript)).unwrap(); + p.format(4, 7, &|c| c.vert_align = Some(VertAlign::Subscript)).unwrap(); + p.format(8, 10, &|c| c.position = Some(3.0)).unwrap(); + p.format(11, 13, &|c| c.spacing = Some(1.5)).unwrap(); + let r = round(&doc_of(vec![p])); + let q = r.body[0].as_para().unwrap(); + assert_eq!(q.props_at(1).vert_align, Some(VertAlign::Superscript)); + assert_eq!(q.props_at(5).vert_align, Some(VertAlign::Subscript)); + assert_eq!(q.props_at(9).position, Some(3.0)); + assert_ne!(q.props_at(9).vert_align, Some(VertAlign::Superscript)); + assert_eq!(q.props_at(12).spacing, Some(1.5)); +} + +/// Double strikethrough, emboss and the double-wave underline. The reader reads them once +/// craft-libs#1969 is fixed. +#[test] +#[ignore = "the reader reads sprmCFDStrike, sprmCFEmboss and Kul 0x2B once craft-libs#1969 is fixed"] +fn character_effects_round_trip() { + let mut p = para("dbl emb"); + p.format(0, 3, &|c| c.double_strike = Some(true)).unwrap(); + p.format(4, 7, &|c| { + c.emboss = Some(true); + c.underline = Some(Underline::DoubleWave); + }) + .unwrap(); + let r = round(&doc_of(vec![p])); + let q = r.body[0].as_para().unwrap(); + assert_eq!(q.props_at(1).double_strike, Some(true)); + assert_eq!(q.props_at(5).emboss, Some(true)); + assert_eq!(q.props_at(5).underline, Some(Underline::DoubleWave)); +} + +#[test] +#[ignore = "the reader reads sprmCHighlight as an Ico once craft-libs#1854 is in"] +fn every_highlight_colour_round_trips() { + for h in Highlight::ALL { + let mut p = para("x"); + p.format(0, 1, &|c| c.highlight = Some(h)).unwrap(); + let r = round(&doc_of(vec![p])); + assert_eq!(r.body[0].as_para().unwrap().props_at(0).highlight, Some(h), "{h:?}"); + } +} + +/// A section's column count survives a save. +#[test] +fn section_columns_round_trip() { + let mut d = Document::new(); + d.last_section.columns = Columns { count: 3, space: 18.0, ..Default::default() }; + d.body = vec![para_block(para("Three columns"))]; + let r = round(&d); + assert_eq!(r.last_section.columns.count, 3); +} + +/// The page-number start and format, the column spacing, and the paragraph's shading, widow +/// control and contextual spacing, as the writer writes them. Each needs a reader change that is +/// still open: page numbers craft-libs#1354, column spacing and widow control craft-libs#1799, +/// shading craft-libs#1808, contextual spacing craft-libs#1969. +#[test] +#[ignore = "needs the reader changes in craft-libs#1354, #1799 and #1808, and craft-libs#1969"] +fn page_numbering_and_paragraph_shading_round_trip() { + let mut d = Document::new(); + d.last_section.page_num_start = Some(5); + d.last_section.page_num_format = craft_wordmodel::section::NumFormat::LowerRoman; + d.last_section.columns = Columns { count: 3, space: 18.0, ..Default::default() }; + let mut p = para("Shaded"); + p.props.shading = Some(craft_wordmodel::Rgb(0xDD, 0xEE, 0xFF)); + p.props.widow_control = Some(false); + p.props.contextual_spacing = Some(true); + d.body = vec![para_block(p)]; + let r = round(&d); + assert_eq!(r.last_section.page_num_start, Some(5)); + assert_eq!(r.last_section.page_num_format, craft_wordmodel::section::NumFormat::LowerRoman); + assert_eq!((r.last_section.columns.count, r.last_section.columns.space), (3, 18.0)); + let q = &r.body[0].as_para().unwrap().props; + assert_eq!(q.shading, Some(craft_wordmodel::Rgb(0xDD, 0xEE, 0xFF))); + assert_eq!(q.widow_control, Some(false)); + assert_eq!(q.contextual_spacing, Some(true)); +} + +fn table_of(grid: Vec, rows: Vec>) -> Table { + Table { + props: TableProps::default(), + grid, + rows: rows.into_iter().map(|cells| Row { props: RowProps::default(), cells, controls: Default::default() }).collect(), + controls: Default::default(), + } +} + +#[test] +fn nested_tables_become_paragraphs_of_their_cell() { + let inner = table_of(vec![50.0, 50.0], vec![vec![cell("i1"), cell("i2")]]); + let mut outer_cell = cell("before"); + outer_cell.blocks.push(Arc::new(Block::Table(inner))); + let mut d = Document::new(); + d.body = vec![Arc::new(Block::Table(table_of(vec![200.0], vec![vec![outer_cell]]))), para_block(para("end"))]; + let r = round(&d); + let t = r.body[0].as_table().expect("the outer table"); + let texts: Vec = t.rows[0].cells[0].blocks.iter().filter_map(|b| b.as_para().map(|p| p.plain_text())).collect(); + assert_eq!(texts, vec!["before", "i1", "i2"]); +} + +#[test] +fn a_table_ending_the_document_gets_a_paragraph_after_it() { + let mut d = Document::new(); + d.body = vec![Arc::new(Block::Table(table_of(vec![100.0], vec![vec![cell("only")]])))]; + let r = round(&d); + assert!(r.body[0].as_table().is_some()); + assert_eq!(texts(&r), vec![String::new()]); +} + +#[test] +fn rows_wider_than_the_format_keep_their_first_cells() { + let cells: Vec = (0..80).map(|i| cell(&format!("c{i}"))).collect(); + let mut d = Document::new(); + d.body = vec![Arc::new(Block::Table(table_of(vec![10.0; 80], vec![cells]))), para_block(para("after"))]; + // Never a panic; the first 63 cells (the format's most) keep their text. + let r = round(&d); + let all: Vec = r + .body + .iter() + .flat_map(|b| match &**b { + Block::Para(p) => vec![p.plain_text()], + Block::Table(t) => { + t.rows.iter().flat_map(|r| r.cells.iter()).flat_map(|c| c.blocks.iter()).filter_map(|b| b.as_para().map(|p| p.plain_text())).collect() + } + }) + .collect(); + for i in [0, 30, 62, 79] { + assert!(all.iter().any(|t| t == &format!("c{i}")), "c{i} missing: {all:?}"); + } + assert_eq!(texts(&r).last().map(String::as_str), Some("after")); +} + +proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(64))] + /// Any text, with any run boundaries and formatting, writes without panicking and reads back + /// as the same text. + #[test] + fn any_text_round_trips(lines in proptest::collection::vec("\\PC{0,40}", 1..8), bold in proptest::collection::vec(proptest::prelude::any::(), 8)) { + let paras: Vec = lines + .iter() + .enumerate() + .map(|(i, l)| { + let clean: String = l.chars().filter(|c| !c.is_control() && *c != '\u{FFFC}').collect(); + let mut p = para(&clean); + if bold.get(i).copied().unwrap_or(false) && !clean.is_empty() { + let end = clean.char_indices().nth(clean.chars().count() / 2).map_or(clean.len(), |(i, _)| i); + p.format(0, end, &|c| c.bold = Some(true)).unwrap(); + } + p + }) + .collect(); + let d = doc_of(paras); + let r = round(&d); + proptest::prop_assert_eq!(texts(&r), texts(&d)); + } +} + +/// The thin/thick compound border lines (`brcType` 0x0B-0x13) keep their style through a save, +/// rather than coming back as single lines. +#[test] +fn compound_border_lines_round_trip() { + let styles = [ + BorderStyle::ThinThickSmallGap, + BorderStyle::ThickThinSmallGap, + BorderStyle::ThinThickThinSmallGap, + BorderStyle::ThinThickMediumGap, + BorderStyle::ThickThinMediumGap, + BorderStyle::ThinThickThinMediumGap, + BorderStyle::ThinThickLargeGap, + BorderStyle::ThickThinLargeGap, + BorderStyle::ThinThickThinLargeGap, + ]; + let mut d = Document::new(); + d.body = styles + .iter() + .map(|&style| { + let mut p = para("Bordered"); + p.props.borders = Some(Borders { bottom: Some(Border { style, width: 3.0, color: None, space: 1.0 }), ..Default::default() }); + para_block(p) + }) + .collect(); + let r = round(&d); + let got: Vec<_> = r.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.borders.as_ref()?.bottom.map(|b| b.style)).collect(); + assert_eq!(got, styles); +} diff --git a/crates/docx/src/chart_spec.rs b/crates/docx/src/chart_spec.rs index e313639036..a090c5c96f 100644 --- a/crates/docx/src/chart_spec.rs +++ b/crates/docx/src/chart_spec.rs @@ -6,7 +6,7 @@ //! [`spec_of`] turns a chart part back into the model only when writing that model again gives //! the same markup, so a chart with anything the model leaves out stays as it was read. -use craft_wordmodel::chart::{ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES}; +use craft_wordmodel::chart::{ChartAxis, ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES}; use craft_wordmodel::graphic::GraphicItem; use craft_wordmodel::props::Rgb; @@ -102,11 +102,24 @@ fn bounded(spec: &ChartSpec) -> ChartSpec { .series .iter() .take(MAX_SERIES) - .map(|s| ChartSeries { name: s.name.clone(), values: s.values.iter().take(MAX_POINTS).copied().collect() }) + .map(|s| ChartSeries { + name: s.name.clone(), + values: s.values.iter().take(MAX_POINTS).copied().collect(), + fill: s.fill, + no_fill: s.no_fill, + line_w: s.line_w, + no_line: s.no_line, + markers: s.markers, + smooth: s.smooth, + labels: s.labels, + fmt: s.fmt.clone(), + }) .collect(), title: spec.title.clone(), legend: spec.legend, data_labels: spec.data_labels, + cat_axis: spec.cat_axis.clone(), + val_axis: spec.val_axis.clone(), } .sanitized() } @@ -185,17 +198,19 @@ fn plot(w: &mut W, spec: &ChartSpec) { match k { ChartType::Pie | ChartType::Doughnut => {} ChartType::Scatter => { - value_axis(w, CAT_AX, VAL_AX, "b", false, "midCat"); - value_axis(w, VAL_AX, CAT_AX, "l", true, "midCat"); + value_axis(w, CAT_AX, VAL_AX, "b", "midCat", &spec.cat_axis); + value_axis(w, VAL_AX, CAT_AX, "l", "midCat", &spec.val_axis); } _ => { - category_axis(w, if horizontal { "l" } else { "b" }); - value_axis(w, VAL_AX, CAT_AX, if horizontal { "b" } else { "l" }, true, "between"); + category_axis(w, if horizontal { "l" } else { "b" }, &spec.cat_axis); + value_axis(w, VAL_AX, CAT_AX, if horizontal { "b" } else { "l" }, "between", &spec.val_axis); } } } -/// One `c:ser` (ECMA-376 element order: idx, order, tx, spPr, marker, cat/xVal, val/yVal, smooth). +/// One `c:ser` (ECMA-376 element order: idx, order, tx, spPr, marker, invertIfNegative, dLbls, +/// cat/xVal, val/yVal, smooth): the series' formatting (fill, line, markers, its own labels) sits +/// in `c:spPr`, `c:marker` and `c:dLbls`; the values carry their number format. fn series(w: &mut W, spec: &ChartSpec, i: usize, s: &ChartSeries) { let k = spec.kind; let i = i.to_string(); @@ -207,25 +222,26 @@ fn series(w: &mut W, spec: &ChartSpec, i: usize, s: &ChartSeries) { w.leaf("c:v", &[], &s.name); w.close("c:tx"); } - match k { - // Markers only: the series has no line. - ChartType::Scatter => { - w.open("c:spPr", &[]); - w.open("a:ln", &[("w", "19050")]); - w.empty("a:noFill", &[]); - w.close("a:ln"); - w.close("c:spPr"); - } - ChartType::Column | ChartType::ColumnStacked | ChartType::Bar | ChartType::BarStacked => { - w.empty("c:invertIfNegative", &[("val", "0")]); - } - ChartType::Line => { - w.open("c:marker", &[]); - w.empty("c:symbol", &[("val", "none")]); - w.close("c:marker"); - } - _ => {} + series_props(w, s); + series_marker(w, k, s); + if matches!(k, ChartType::Column | ChartType::ColumnStacked | ChartType::Bar | ChartType::BarStacked) { + w.empty("c:invertIfNegative", &[("val", "0")]); } + if let Some(on) = s.labels { + w.open("c:dLbls", &[]); + for (name, show) in [ + ("c:showLegendKey", false), + ("c:showVal", on), + ("c:showCatName", false), + ("c:showSerName", false), + ("c:showPercent", false), + ("c:showBubbleSize", false), + ] { + w.empty(name, &[("val", if show { "1" } else { "0" })]); + } + w.close("c:dLbls"); + } + let code = s.fmt.as_deref().unwrap_or("General"); if k == ChartType::Scatter { let xs: Option>> = spec .categories @@ -234,27 +250,85 @@ fn series(w: &mut W, spec: &ChartSpec, i: usize, s: &ChartSeries) { .collect(); w.open("c:xVal", &[]); match xs { - Some(xs) => num_lit(w, &xs), + Some(xs) => num_lit(w, &xs, "General"), None => str_lit(w, &spec.categories), } w.close("c:xVal"); w.open("c:yVal", &[]); - num_lit(w, &s.values); + num_lit(w, &s.values, code); w.close("c:yVal"); } else { w.open("c:cat", &[]); str_lit(w, &spec.categories); w.close("c:cat"); w.open("c:val", &[]); - num_lit(w, &s.values); + num_lit(w, &s.values, code); w.close("c:val"); } if matches!(k, ChartType::Line | ChartType::Scatter) { - w.empty("c:smooth", &[("val", "0")]); + w.empty("c:smooth", &[("val", if s.smooth { "1" } else { "0" })]); } w.close("c:ser"); } +/// `c:spPr`: the series' fill (`a:solidFill` / `a:noFill`) and line (`a:ln`), written when the +/// model sets them. `a:ln` without `w` is the default width, `w` a fixed one, and `a:noFill` +/// inside it "no line" (a scatter series keeps its markers with no line). +fn series_props(w: &mut W, s: &ChartSeries) { + let fill_set = s.no_fill || s.fill.is_some(); + let ln_set = s.no_line || s.line_w.is_some(); + if !(fill_set || ln_set) { + return; + } + w.open("c:spPr", &[]); + if fill_set { + // "No fill" wins over a stored colour, so the pair reads back as it was written. + match &s.fill { + Some(c) if !s.no_fill => { + w.open("a:solidFill", &[]); + w.empty("a:srgbClr", &[("val", &c.hex())]); + w.close("a:solidFill"); + } + _ => w.empty("a:noFill", &[]), + } + } + if ln_set { + let w_attr = s.line_w.map(emu).unwrap_or_default(); + let attrs = [("w", w_attr.as_str())]; + w.open("a:ln", if w_attr.is_empty() { &[] } else { &attrs }); + if s.no_line { + w.empty("a:noFill", &[]); + } + w.close("a:ln"); + } + w.close("c:spPr"); +} + +/// `c:marker`: line and scatter series say which symbol each point gets; other types have none. +fn series_marker(w: &mut W, k: ChartType, s: &ChartSeries) { + match k { + ChartType::Line => { + w.open("c:marker", &[]); + w.empty("c:symbol", &[("val", if s.markers == Some(true) { "circle" } else { "none" })]); + w.close("c:marker"); + } + // Unset: no `c:marker`, so Word picks its automatic symbol for each series. + ChartType::Scatter => { + if let Some(on) = s.markers { + w.open("c:marker", &[]); + w.empty("c:symbol", &[("val", if on { "circle" } else { "none" })]); + w.close("c:marker"); + } + } + _ => {} + } +} + +/// A line width in points as the `w` attribute DrawingML wants (EMU). +fn emu(pt: f32) -> String { + ((pt * 12700.0).round().max(0.0) as i64).to_string() +} + fn str_lit(w: &mut W, items: &[String]) { w.open("c:strLit", &[]); w.empty("c:ptCount", &[("val", &items.len().to_string())]); @@ -266,9 +340,9 @@ fn str_lit(w: &mut W, items: &[String]) { w.close("c:strLit"); } -fn num_lit(w: &mut W, values: &[Option]) { +fn num_lit(w: &mut W, values: &[Option], code: &str) { w.open("c:numLit", &[]); - w.leaf("c:formatCode", &[], "General"); + w.leaf("c:formatCode", &[], code); w.empty("c:ptCount", &[("val", &values.len().to_string())]); for (i, v) in values.iter().enumerate() { if let Some(v) = v.filter(|v| v.is_finite()) { @@ -285,17 +359,21 @@ fn num(v: f64) -> String { if v == 0.0 { "0".to_string() } else { format!("{v}") } } -fn category_axis(w: &mut W, pos: &str) { +fn category_axis(w: &mut W, pos: &str, ax: &ChartAxis) { w.open("c:catAx", &[]); w.empty("c:axId", &[("val", CAT_AX)]); - w.open("c:scaling", &[]); - w.empty("c:orientation", &[("val", "minMax")]); - w.close("c:scaling"); + scaling(w, ax); w.empty("c:delete", &[("val", "0")]); w.empty("c:axPos", &[("val", pos)]); + if ax.gridlines { + w.empty("c:majorGridlines", &[]); + } + axis_title(w, ax); + num_fmt(w, ax); w.empty("c:majorTickMark", &[("val", "none")]); w.empty("c:minorTickMark", &[("val", "none")]); - w.empty("c:tickLblPos", &[("val", "nextTo")]); + w.empty("c:tickLblPos", &[("val", if ax.labels { "nextTo" } else { "none" })]); + axis_line(w, ax); w.empty("c:crossAx", &[("val", VAL_AX)]); w.empty("c:crosses", &[("val", "autoZero")]); w.empty("c:auto", &[("val", "1")]); @@ -305,34 +383,81 @@ fn category_axis(w: &mut W, pos: &str) { w.close("c:catAx"); } -/// A value axis: with gridlines and no axis line (`grid`), else with its line and no gridlines. -fn value_axis(w: &mut W, id: &str, cross: &str, pos: &str, grid: bool, between: &str) { +/// A value axis (scatter x axes included): its scale, gridlines, title, labels and line, as the +/// model sets them. +fn value_axis(w: &mut W, id: &str, cross: &str, pos: &str, between: &str, ax: &ChartAxis) { w.open("c:valAx", &[]); w.empty("c:axId", &[("val", id)]); - w.open("c:scaling", &[]); - w.empty("c:orientation", &[("val", "minMax")]); - w.close("c:scaling"); + scaling(w, ax); w.empty("c:delete", &[("val", "0")]); w.empty("c:axPos", &[("val", pos)]); - if grid { + if ax.gridlines { w.empty("c:majorGridlines", &[]); } + axis_title(w, ax); + num_fmt(w, ax); w.empty("c:majorTickMark", &[("val", "none")]); w.empty("c:minorTickMark", &[("val", "none")]); - w.empty("c:tickLblPos", &[("val", "nextTo")]); - if grid { - w.open("c:spPr", &[]); - w.open("a:ln", &[]); - w.empty("a:noFill", &[]); - w.close("a:ln"); - w.close("c:spPr"); - } + w.empty("c:tickLblPos", &[("val", if ax.labels { "nextTo" } else { "none" })]); + axis_line(w, ax); w.empty("c:crossAx", &[("val", cross)]); w.empty("c:crosses", &[("val", "autoZero")]); w.empty("c:crossBetween", &[("val", between)]); w.close("c:valAx"); } +/// `c:scaling`: the orientation, then the fixed bounds when the model sets them. +fn scaling(w: &mut W, ax: &ChartAxis) { + w.open("c:scaling", &[]); + w.empty("c:orientation", &[("val", "minMax")]); + for (name, v) in [("c:max", ax.max), ("c:min", ax.min)] { + if let Some(v) = v.filter(|v| v.is_finite()) { + w.empty(name, &[("val", &num(v))]); + } + } + w.close("c:scaling"); +} + +/// The axis title, in the same rich-text shape the chart title uses. +fn axis_title(w: &mut W, ax: &ChartAxis) { + let Some(t) = &ax.title else { return }; + w.open("c:title", &[]); + w.open("c:tx", &[]); + w.open("c:rich", &[]); + w.empty("a:bodyPr", &[]); + w.empty("a:lstStyle", &[]); + w.open("a:p", &[]); + w.open("a:r", &[]); + w.leaf("a:t", &[], t); + w.close("a:r"); + w.close("a:p"); + w.close("c:rich"); + w.close("c:tx"); + w.empty("c:overlay", &[("val", "0")]); + w.close("c:title"); +} + +/// Tick-label number format: the model's code, unlinked from the source, else the default. +fn num_fmt(w: &mut W, ax: &ChartAxis) { + match &ax.fmt { + Some(code) => w.empty("c:numFmt", &[("formatCode", code), ("sourceLinked", "0")]), + None => w.empty("c:numFmt", &[("formatCode", "General"), ("sourceLinked", "1")]), + } +} + +/// `c:spPr`: an axis line only when the model keeps it (the default writes nothing, which reads +/// as a line); `a:noFill` when the axis line is off. +fn axis_line(w: &mut W, ax: &ChartAxis) { + if ax.line { + return; + } + w.open("c:spPr", &[]); + w.open("a:ln", &[]); + w.empty("a:noFill", &[]); + w.close("a:ln"); + w.close("c:spPr"); +} + /// The chart a chart part holds, when the part is exactly what [`chart_xml`] writes for it (so /// editing and saving it loses nothing). `None` for any other chart. pub(crate) fn spec_of(space: &El) -> Option { @@ -365,15 +490,40 @@ pub(crate) fn spec_of(space: &El) -> Option { let categories = sers.first().and_then(|s| s.child(if scatter { "c:xVal" } else { "c:cat" })).map(literal).unwrap_or_default(); let series = sers .iter() - .map(|s| ChartSeries { - name: s.child("c:tx").and_then(|t| t.child("c:v")).map(|v| v.text()).unwrap_or_default(), - values: s - .child(if scatter { "c:yVal" } else { "c:val" }) - .map(literal) - .unwrap_or_default() - .iter() - .map(|v| v.parse::().ok().filter(|v| v.is_finite())) - .collect(), + .map(|s| { + let ln = s.child("c:spPr").and_then(|p| p.child("a:ln")); + let symbol = s.child("c:marker").and_then(|m| m.child("c:symbol")).and_then(|m| m.attr("val")); + ChartSeries { + name: s.child("c:tx").and_then(|t| t.child("c:v")).map(|v| v.text()).unwrap_or_default(), + values: s + .child(if scatter { "c:yVal" } else { "c:val" }) + .map(literal) + .unwrap_or_default() + .iter() + .map(|v| v.parse::().ok().filter(|v| v.is_finite())) + .collect(), + fill: s + .child("c:spPr") + .and_then(|p| p.child("a:solidFill")) + .and_then(|f| f.child("a:srgbClr")) + .and_then(|c| c.attr("val")) + .and_then(Rgb::parse), + no_fill: s.child("c:spPr").and_then(|p| p.child("a:noFill")).is_some(), + line_w: ln.and_then(|l| l.attr("w")).and_then(|w| w.parse::().ok()).filter(|w| w.is_finite()).map(|w| (w / 12700.0) as f32), + no_line: ln.and_then(|l| l.child("a:noFill")).is_some(), + // Line series show no markers by default: only a setting that differs from that + // belongs in the model. A scatter series keeps what the file says, so a missing + // `c:marker` (Word's automatic symbols) stays unset and is not written back. + markers: symbol.map(|v| v != "none").filter(|m| scatter || *m), + smooth: s.child("c:smooth").and_then(|v| v.attr("val")).is_some_and(|v| v == "1"), + labels: s.child("c:dLbls").and_then(|d| d.child("c:showVal")).and_then(|v| v.attr("val")).map(|v| v == "1"), + fmt: s + .child(if scatter { "c:yVal" } else { "c:val" }) + .and_then(|v| v.els().find(|e| e.name == "c:numLit")) + .and_then(|l| l.child("c:formatCode")) + .map(|f| f.text()) + .filter(|f| *f != "General"), + } }) .collect(); let title = chart.child("c:title").and_then(|t| t.find("a:t")).map(|t| t.text()); @@ -384,12 +534,48 @@ pub(crate) fn spec_of(space: &El) -> Option { _ => LegendPos::Right, }); let data_labels = ty.child("c:dLbls").and_then(|d| d.child("c:showVal")).and_then(|v| v.attr("val")) == Some("1"); - let spec = ChartSpec { kind, categories, series, title, legend, data_labels }.sanitized(); - // Editable only when nothing would be lost: writing the model again gives the same part. - let again = xml::parse(chart_xml(&spec).as_bytes()).ok()?; + let (cat_a, val_a) = crate::read::chart::chart_axes(plot, scatter); + let axis = |a: crate::read::chart::Axis| ChartAxis { + title: a.title, + min: a.min, + max: a.max, + fmt: a.fmt, + gridlines: a.grid, + labels: a.labels, + line: a.line, + }; + let spec = ChartSpec { kind, categories, series, title, legend, data_labels, cat_axis: axis(cat_a), val_axis: axis(val_a) }.sanitized(); + // Editable only when nothing would be lost: writing the model again gives the same part, as + // this writer or the earlier one wrote it. + let mut again = xml::parse(chart_xml(&spec).as_bytes()).ok()?; + if same(space, &again, 0) { + return Some(spec); + } + as_previous_writer(&mut again); same(space, &again, 0).then_some(spec) } +/// `part` (what [`chart_xml`] writes) as the earlier WordCraft writer wrote the same model: it +/// had no axis `c:numFmt`. Only that element goes, and only with the value its absence reads as +/// (General, linked to the source), so a part that matches still holds nothing the model leaves out. +fn as_previous_writer(part: &mut El) { + fn els_mut(e: &mut El) -> impl Iterator { + e.kids.iter_mut().filter_map(|n| match n { + Node::El(e) => Some(e), + Node::Text(_) => None, + }) + } + fn drop_els(e: &mut El, drop: impl Fn(&El) -> bool) { + e.kids.retain(|n| !matches!(n, Node::El(c) if drop(c))); + } + let Some(plot) = els_mut(part).find(|e| e.name == "c:chart").and_then(|c| els_mut(c).find(|e| e.name == "c:plotArea")) else { return }; + for e in els_mut(plot) { + if matches!(e.name.as_str(), "c:catAx" | "c:valAx") { + drop_els(e, |c| c.name == "c:numFmt" && c.attr("sourceLinked") == Some("1")); + } + } +} + /// The points of a `c:strLit` / `c:numLit` (or a cache) as texts by index, `ptCount` long. fn literal(e: &El) -> Vec { let Some(lit) = e.els().find(|c| matches!(c.name.as_str(), "c:strLit" | "c:numLit")) else { return Vec::new() }; @@ -461,10 +647,11 @@ mod tests { let spec = ChartSpec { kind: ChartType::Column, categories: (0..4500).map(|i| i.to_string()).collect(), - series: (0..300).map(|i| ChartSeries { name: format!("S{i}"), values: vec![Some(1.0); 4500] }).collect(), + series: (0..300).map(|i| ChartSeries { name: format!("S{i}"), values: vec![Some(1.0); 4500], ..Default::default() }).collect(), title: None, legend: None, data_labels: false, + ..Default::default() }; let x = chart_xml(&spec); let series = x.matches("").count(); @@ -491,6 +678,33 @@ mod tests { assert_eq!(spec_of(&parse(&plain)), Some(plain)); } + #[test] + fn no_fill_wins_over_a_stored_colour() { + let mut spec = ChartSpec::sample(ChartType::Column); + spec.series[0].fill = Some(Rgb(255, 0, 0)); + spec.series[0].no_fill = true; + let x = chart_xml(&spec); + assert!(!x.contains("FF0000"), "colour written next to no_fill"); + let back = spec_of(&parse(&spec)).expect("stays editable"); + assert!(back.series[0].no_fill); + assert_eq!(back.series[0].fill, None); + } + + #[test] + fn an_axis_format_is_limited_in_characters_not_bytes() { + use craft_wordmodel::chart::MAX_FMT; + let cjk = format!("0\"{}\"", "\u{5143}".repeat(90)); + let ascii = format!("0\"{}\"", "x".repeat(90)); + for fmt in [cjk, ascii] { + assert!(fmt.chars().count() <= MAX_FMT); + let mut spec = ChartSpec::sample(ChartType::Column); + spec.val_axis.fmt = Some(fmt.clone()); + let spec = spec.sanitized(); + assert_eq!(spec.val_axis.fmt.as_deref(), Some(fmt.as_str())); + assert_eq!(spec_of(&parse(&spec)).as_ref(), Some(&spec), "{} chars", fmt.chars().count()); + } + } + #[test] fn a_chart_with_more_than_the_model_stays_read_only() { let spec = ChartSpec::sample(ChartType::Column); @@ -500,6 +714,61 @@ mod tests { assert_eq!(spec_of(&xml::parse(x.as_bytes()).unwrap()), None); } + /// Chart parts as the previous WordCraft chart writer saved them (its output for + /// `ChartSpec::sample`): no axis `c:numFmt`, and scatter series with no `c:marker`. + const PREVIOUS_COLUMN: &str = r#"Series 1Q1Q2Q3Q4General3.24.13.65Series 2Q1Q2Q3Q4General22.73.93.3Series 3Q1Q2Q3Q4General1.52.22.43.8"#; + const PREVIOUS_SCATTER: &str = r#"Series 1General1234General2.13.434.6Series 2General1234General1.21.92.83.1"#; + + #[test] + fn charts_saved_by_the_previous_writer_stay_editable() { + for (x, kind) in [(PREVIOUS_COLUMN, ChartType::Column), (PREVIOUS_SCATTER, ChartType::Scatter)] { + let spec = spec_of(&xml::parse(x.as_bytes()).unwrap()).unwrap_or_else(|| panic!("{kind:?}: the earlier part is read-only")); + assert_eq!((spec.kind, spec.series.len()), (kind, if kind == ChartType::Scatter { 2 } else { 3 })); + assert_eq!((spec.cat_axis.fmt.as_deref(), spec.val_axis.fmt.as_deref()), (None, None), "{kind:?}"); + assert!(spec.series.iter().all(|s| s.markers.is_none()), "{kind:?}: markers unset"); + // Saved again, it is in the current shape and still reads back as the same model. + assert_eq!(spec_of(&parse(&spec)).as_ref(), Some(&spec), "{kind:?}"); + } + // What neither writer writes still keeps such a part read-only: an axis format linked to + // the source that isn't General, a scatter marker other than the default, a marker size. + let edited = |x: &str, from: &str, to: &str| { + assert!(x.contains(from), "{from}"); + spec_of(&xml::parse(x.replacen(from, to, 1).as_bytes()).unwrap()) + }; + let ax = r#""#; + assert_eq!(edited(PREVIOUS_COLUMN, ax, &format!(r#"{ax}"#)), None); + let ln = r#""#; + assert_eq!(edited(PREVIOUS_SCATTER, ln, &format!(r#"{ln}"#)), None); + assert_eq!(edited(PREVIOUS_SCATTER, ln, &format!(r#"{ln}"#)), None); + assert_eq!(edited(PREVIOUS_COLUMN, "", ""), None); + } + + /// A scatter series with no `c:marker` (Word's automatic symbols) stays without one after an + /// unrelated edit and a save; an explicit circle or "none" stays explicit. + #[test] + fn scatter_series_without_a_marker_stay_without_after_a_save() { + let marker_of = |x: &El| -> Vec> { + let sc = x.child("c:chart").unwrap().child("c:plotArea").unwrap().child("c:scatterChart").unwrap(); + sc.children("c:ser").map(|s| s.child("c:marker").map(|m| m.child("c:symbol").unwrap().attr("val").unwrap().to_string())).collect() + }; + let mut spec = spec_of(&xml::parse(PREVIOUS_SCATTER.as_bytes()).unwrap()).unwrap(); + assert_eq!(marker_of(&xml::parse(PREVIOUS_SCATTER.as_bytes()).unwrap()), [None, None]); + spec.title = Some("Edited".into()); + spec.series[0].name = "Renamed".into(); + let saved = parse(&spec); + assert_eq!(marker_of(&saved), [None, None]); + let again = spec_of(&saved).unwrap(); + assert_eq!(again, spec); + assert!(again.series.iter().all(|s| s.markers.is_none())); + // Explicit choices are kept as written. + spec.series[0].markers = Some(true); + spec.series[1].markers = Some(false); + let saved = parse(&spec); + assert_eq!(marker_of(&saved), [Some("circle".to_string()), Some("none".to_string())]); + let again = spec_of(&saved).unwrap(); + assert_eq!((again.series[0].markers, again.series[1].markers), (Some(true), Some(false))); + } + #[test] fn elements_come_in_schema_order() { let mut spec = ChartSpec::sample(ChartType::ColumnStacked); @@ -517,6 +786,11 @@ mod tests { ["c:barDir", "c:grouping", "c:varyColors", "c:ser", "c:ser", "c:ser", "c:dLbls", "c:gapWidth", "c:overlap", "c:axId", "c:axId"] ); assert_eq!(names(bar.child("c:ser").unwrap()), ["c:idx", "c:order", "c:tx", "c:invertIfNegative", "c:cat", "c:val"]); + // A series with its own labels keeps `c:invertIfNegative` ahead of `c:dLbls` (CT_BarSer). + spec.series[0].labels = Some(true); + let labelled = parse(&spec); + let ser = labelled.child("c:chart").unwrap().child("c:plotArea").unwrap().child("c:barChart").unwrap().child("c:ser").unwrap(); + assert_eq!(names(ser), ["c:idx", "c:order", "c:tx", "c:invertIfNegative", "c:dLbls", "c:cat", "c:val"]); let val_ax = plot.child("c:valAx").unwrap(); assert_eq!( names(val_ax), @@ -526,6 +800,7 @@ mod tests { "c:delete", "c:axPos", "c:majorGridlines", + "c:numFmt", "c:majorTickMark", "c:minorTickMark", "c:tickLblPos", @@ -535,13 +810,35 @@ mod tests { "c:crossBetween" ] ); + let cat_ax = plot.child("c:catAx").unwrap(); + assert_eq!( + names(cat_ax), + [ + "c:axId", + "c:scaling", + "c:delete", + "c:axPos", + "c:numFmt", + "c:majorTickMark", + "c:minorTickMark", + "c:tickLblPos", + "c:crossAx", + "c:crosses", + "c:auto", + "c:lblAlgn", + "c:lblOffset", + "c:noMultiLvlLbl" + ] + ); let line = parse(&ChartSpec { data_labels: true, ..ChartSpec::sample(ChartType::Line) }); let lc = line.child("c:chart").unwrap().child("c:plotArea").unwrap().child("c:lineChart").unwrap(); assert_eq!(names(lc), ["c:grouping", "c:varyColors", "c:ser", "c:ser", "c:ser", "c:dLbls", "c:marker", "c:axId", "c:axId"]); assert_eq!(names(lc.child("c:ser").unwrap()), ["c:idx", "c:order", "c:tx", "c:marker", "c:cat", "c:val", "c:smooth"]); - let sc = parse(&ChartSpec::sample(ChartType::Scatter)); + let mut scatter = ChartSpec::sample(ChartType::Scatter); + scatter.series.iter_mut().for_each(|s| s.markers = Some(true)); + let sc = parse(&scatter); let sc = sc.child("c:chart").unwrap().child("c:plotArea").unwrap().child("c:scatterChart").unwrap(); - assert_eq!(names(sc.child("c:ser").unwrap()), ["c:idx", "c:order", "c:tx", "c:spPr", "c:xVal", "c:yVal", "c:smooth"]); + assert_eq!(names(sc.child("c:ser").unwrap()), ["c:idx", "c:order", "c:tx", "c:spPr", "c:marker", "c:xVal", "c:yVal", "c:smooth"]); let dn = parse(&ChartSpec::sample(ChartType::Doughnut)); let dn = dn.child("c:chart").unwrap().child("c:plotArea").unwrap(); assert_eq!(names(dn), ["c:layout", "c:doughnutChart"]); diff --git a/crates/docx/src/lib.rs b/crates/docx/src/lib.rs index 7f47d948b3..c3c3e8df3d 100644 --- a/crates/docx/src/lib.rs +++ b/crates/docx/src/lib.rs @@ -20,6 +20,19 @@ mod custom; mod flat; mod fonts; mod package; + +static APPLICATION_NAME: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Names the application written to `docProps/app.xml` (``), for an app that +/// embeds this writer under its own name; "WordCraft" until set. Only the first call counts. +pub fn set_application_name(name: &str) { + let _ = APPLICATION_NAME.set(name.to_owned()); +} + +/// The application `docProps/app.xml` names (see [`set_application_name`]). +pub fn application_name() -> &'static str { + APPLICATION_NAME.get().map_or("WordCraft", String::as_str) +} mod read; mod smart_art; #[cfg(test)] diff --git a/crates/docx/src/read/chart.rs b/crates/docx/src/read/chart.rs index a0087a3bba..4b7696eee4 100644 --- a/crates/docx/src/read/chart.rs +++ b/crates/docx/src/read/chart.rs @@ -29,13 +29,15 @@ pub(super) use canvas::text_w; use canvas::{Rect, clip_text, legend, text}; #[cfg(test)] use format::{civil, excel_stamp, format_value}; -use model::{Axis, Grouping, Kind, Pos, Series}; +pub(crate) use model::Axis; +use model::{Grouping, Kind, Pos, Series}; +pub(crate) use parse::chart_axes; #[cfg(test)] use parse::{axis, category_text, labels, numbers}; use parse::{read_series, text_size, title_of}; #[cfg(test)] use plot::{Scale, narrow, nice_scale}; -use plot::{backdrop, cartesian}; +use plot::{backdrop, cartesian, label}; use polar::{pie, radar}; /// Most series read from one chart. @@ -139,6 +141,51 @@ fn placeholder(out: &mut Vec, space: &El, theme: &[Rgb], w: f32, h: text(out, line, &clip_text(&msg, area.w, size), size, TextAlign::Center, false); } +/// Items for an Office 2016 chart (`cx:chartSpace`: waterfall, funnel, treemap…), sized `w` x `h` +/// points: none of these types is drawn yet, so this is the same placeholder an unsupported +/// classic chart gets (frame, title, the type it is), at the size the chart takes in Word. +/// `space` is `None` when the part can't be read: the frame and "Chart" are still drawn. +pub(crate) fn chartex_items(space: Option<&El>, w: f32, h: f32) -> Vec { + let mut out = Vec::new(); + if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + return out; + } + out.push(GraphicItem::Shape { rect: [0.0, 0.0, w, h], kind: ShapeKind::Rectangle, fill: None, stroke: Some(AXIS), stroke_width: 0.75 }); + let mut area = Rect { x: PAD, y: PAD, w: (w - 2.0 * PAD).max(1.0), h: (h - 2.0 * PAD).max(1.0) }; + let chart = space.and_then(|s| s.child("cx:chart")); + let title = chart.and_then(|c| c.child("cx:title")).and_then(|t| { + // Rich text keeps its runs together ("Sales " + "funnel"); a text-data title is one value. + let s = t.find("cx:rich").or_else(|| t.find("cx:v")).map(|e| e.deep_text()).unwrap_or_default(); + let s = label(s.trim()); + (!s.is_empty()).then_some(s) + }); + if let Some(t) = title { + area = title_block(&mut out, &t, area); + } + let kind = chart.and_then(|c| c.find("cx:series")).and_then(|s| s.attr("layoutId")).unwrap_or(""); + let size = FONT; + let lh = size * LINE; + let msg = format!("{} (not supported yet)", chartex_name(kind)); + let line = Rect { x: area.x, y: area.y + ((area.h - lh) / 2.0).max(0.0), w: area.w, h: lh }; + text(&mut out, line, &clip_text(&msg, area.w, size), size, TextAlign::Center, false); + out +} + +/// What a placeholder calls an Office 2016 chart type (`cx:series` `layoutId`). +fn chartex_name(layout: &str) -> &'static str { + match layout { + "waterfall" => "Waterfall chart", + "funnel" => "Funnel chart", + "treemap" => "Treemap chart", + "sunburst" => "Sunburst chart", + "boxWhisker" => "Box and whisker chart", + "clusteredColumn" => "Histogram chart", + "paretoLine" => "Pareto chart", + "regionMap" => "Map chart", + _ => "Chart", + } +} + /// What a placeholder calls a chart type element WordCraft doesn't draw. fn unsupported_name(name: &str) -> &'static str { match name { diff --git a/crates/docx/src/read/chart/canvas.rs b/crates/docx/src/read/chart/canvas.rs index a8280e4ba7..ab3fbf4109 100644 --- a/crates/docx/src/read/chart/canvas.rs +++ b/crates/docx/src/read/chart/canvas.rs @@ -41,8 +41,13 @@ pub(super) fn widest(items: &[String], size: f32) -> f32 { items.iter().map(|s| text_w(s, size)).fold(0.0, f32::max) } +/// Text in `rect`; `angle` degrees clockwise turns it about the rect's centre (axis titles). pub(super) fn text(out: &mut Vec, rect: Rect, s: &str, size: f32, align: TextAlign, bold: bool) { - out.push(GraphicItem::Text { rect: rect.arr(), text: s.to_string(), size, color: TEXT, bold, align, font: None }); + text_angle(out, rect, s, size, align, bold, 0.0); +} + +pub(super) fn text_angle(out: &mut Vec, rect: Rect, s: &str, size: f32, align: TextAlign, bold: bool, angle: f32) { + out.push(GraphicItem::Text { rect: rect.arr(), text: s.to_string(), size, color: TEXT, bold, align, font: None, angle }); } /// Text centred on `cx` with its top at `y`. diff --git a/crates/docx/src/read/chart/model.rs b/crates/docx/src/read/chart/model.rs index 71ee7040f6..13da1d6546 100644 --- a/crates/docx/src/read/chart/model.rs +++ b/crates/docx/src/read/chart/model.rs @@ -7,6 +7,33 @@ pub(super) struct DataLabel { pub(super) y: f32, pub(super) text: String, pub(super) inside: bool, + /// Where a label that is not `inside` sits relative to (`x`, `y`). + pub(super) pos: LabelPos, + /// Distance from (`x`, `y`) to the label for `pos` other than `Center`, points (half the marker). + pub(super) off: f32, +} + +/// Where a data label sits beside its point (`c:dLblPos`: `t`, `b`, `l`, `r`, `ctr`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum LabelPos { + Above, + Below, + Left, + Right, + Center, +} + +impl LabelPos { + pub(super) fn parse(v: &str) -> Option { + Some(match v.trim() { + "t" => LabelPos::Above, + "b" => LabelPos::Below, + "l" => LabelPos::Left, + "r" => LabelPos::Right, + "ctr" => LabelPos::Center, + _ => return None, + }) + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -52,16 +79,56 @@ pub(super) enum Pos { /// One value axis (or category axis) as the file states it. #[derive(Default)] -pub(super) struct Axis { - pub(super) deleted: bool, - pub(super) grid: bool, - pub(super) line: bool, +pub(crate) struct Axis { + pub(crate) deleted: bool, + pub(crate) grid: bool, + pub(crate) line: bool, /// `c:crossBetween val="midCat"`: categories sit on the tick marks, not between them. pub(super) mid: bool, - pub(super) min: Option, - pub(super) max: Option, + pub(crate) min: Option, + pub(crate) max: Option, /// Number format of the tick labels, when not linked to the source data. - pub(super) fmt: Option, + pub(crate) fmt: Option, + /// The axis title, when the file gives it one. + pub(crate) title: Option, + /// The title's `a:bodyPr/@rot` in degrees clockwise (`-5400000` is 90° counter-clockwise), + /// when the file gives one. + pub(crate) title_rot: Option, + /// Tick labels, as `c:tickLblPos` says (`none` hides them; a file that says nothing shows + /// them, as Word does). + pub(crate) labels: bool, +} + +/// The shape of a series' point markers (`ST_MarkerStyle`, ECMA-376 §21.2.3.28). +#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] +pub(super) enum Symbol { + #[default] + Circle, + Square, + Diamond, + Triangle, + X, + Plus, + Star, + Dash, + Dot, +} + +impl Symbol { + /// The symbol a `c:symbol` value names; anything unknown (`auto`, `picture`) is a circle. + pub(super) fn parse(name: &str) -> Symbol { + match name { + "square" => Symbol::Square, + "diamond" => Symbol::Diamond, + "triangle" => Symbol::Triangle, + "x" => Symbol::X, + "plus" => Symbol::Plus, + "star" => Symbol::Star, + "dash" => Symbol::Dash, + "dot" => Symbol::Dot, + _ => Symbol::Circle, + } + } } pub(super) struct Series { @@ -70,9 +137,21 @@ pub(super) struct Series { /// when missing or not a valid number. pub(super) idx: Option, pub(super) color: Option, - pub(super) line_w: f32, + /// Fixed line width in points, `None`: the chart's default. + pub(super) line_w: Option, /// Whether the series is drawn as a line (scatter series without one get markers). pub(super) line: bool, + /// The series' own fill: `Some` colour, `None` colour with `no_fill` set, else the chart's + /// accent for the series. + pub(super) no_fill: bool, + /// Markers on the series' points, when the file says. + pub(super) markers: Option, + /// The marker shape (`c:marker/c:symbol`; a circle when missing or unknown) and its size in + /// points (`c:marker/c:size`), when the file gives one. + pub(super) symbol: Symbol, + pub(super) marker_size: Option, + /// Draw the series' line as a smooth curve (`c:smooth`). + pub(super) smooth: bool, pub(super) values: Vec>, /// Scatter x values (index + 1 when the file has none). pub(super) xs: Vec>, @@ -83,6 +162,13 @@ pub(super) struct Series { pub(super) x_fmt: Option, /// Data labels on or off for this series (`c:dLbls` of its own), when it says. pub(super) labels: Option, + /// The labels' number format (`c:dLbls/c:numFmt`): `None` when not given (the chart type's + /// applies), `Some(None)` when linked to the source, else `Some(Some(code))`. + pub(super) label_fmt: Option>, + /// The data labels' `c:dLblPos`, when the file gives a known one. + pub(super) label_pos: Option, + /// The marker's own fill (`c:marker/c:spPr`); without it markers take the automatic colour. + pub(super) marker_color: Option, /// The values as the file has them, for data labels (`values` become shares in a 100% /// stacked chart); empty when the series shows no labels. pub(super) raw: Vec>, diff --git a/crates/docx/src/read/chart/parse.rs b/crates/docx/src/read/chart/parse.rs index 3c09fcfe9d..522d50b3b2 100644 --- a/crates/docx/src/read/chart/parse.rs +++ b/crates/docx/src/read/chart/parse.rs @@ -1,7 +1,7 @@ use super::format::{date_text, excel_stamp, format_value, is_date_code}; -use super::model::{Axis, Grouping, Kind, Pos, Series}; +use super::model::{Axis, Grouping, Kind, LabelPos, Pos, Series, Symbol}; use super::plot::label; -use super::{Chart, El, FONT, LINE_W, MAX_CELLS, MAX_POINTS, MAX_RADAR_SERIES, MAX_SERIES, MAX_SPOKES, Rgb, fill_colour, int, measure, slot}; +use super::{Chart, El, FONT, MAX_CELLS, MAX_POINTS, MAX_RADAR_SERIES, MAX_SERIES, MAX_SPOKES, Rgb, fill_colour, int, measure, slot}; impl Chart { pub(super) fn parse(space: &El, theme: &[Rgb]) -> Option { @@ -39,10 +39,15 @@ impl Chart { cats.resize(n, String::new()); let radar_style = ty.child("c:radarStyle").and_then(|r| r.attr("val")); let type_labels = show_values(ty.child("c:dLbls")); + let type_fmt = label_format(ty.child("c:dLbls")); for s in &mut series { s.values.resize(n, None); s.xs.resize(n, None); s.labels = Some(s.labels.or(type_labels).unwrap_or(false)); + // Absent (`None`) inherits the chart type's; explicitly source-linked (`Some(None)`) does not. + if s.label_fmt.is_none() { + s.label_fmt.clone_from(&type_fmt); + } if s.labels == Some(true) { s.raw = s.values.clone(); } @@ -98,6 +103,13 @@ impl Chart { s.and_then(|s| s.color).unwrap_or_else(|| self.accent(s.and_then(|s| s.idx).unwrap_or(j))) } + /// Colour of series `j`'s markers: the marker's own fill, else the automatic colour of the + /// series index (not the series' explicit line colour, as Word draws them). + pub(super) fn marker_colour(&self, j: usize) -> Rgb { + let s = self.series.get(j); + s.and_then(|s| s.marker_color).unwrap_or_else(|| self.accent(s.and_then(|s| s.idx).unwrap_or(j))) + } + /// Colour of point `i` of series `j`: its `c:dPt` override, else the varied accent (pie) or /// the series colour. pub(super) fn point_colour(&self, j: usize, i: usize) -> Rgb { @@ -149,7 +161,7 @@ fn to_percent(series: &mut [Series], n: usize) { } /// The category axis (scatter: the horizontal value axis) and the value axis of a plot area. -fn chart_axes(plot: &El, scatter: bool) -> (Axis, Axis) { +pub(crate) fn chart_axes(plot: &El, scatter: bool) -> (Axis, Axis) { let vals_ax: Vec<&El> = plot.children("c:valAx").collect(); let horiz_pos = |a: &&El| matches!(a.child("c:axPos").and_then(|p| p.attr("val")), Some("b" | "t")); let (val_el, x_el) = if scatter { @@ -180,6 +192,17 @@ fn show_values(d: Option<&El>) -> Option { d.child("c:showVal").map(|v| v.attr("val").is_none_or(truthy)) } +/// The number format of data labels (`c:dLbls/c:numFmt`): `None` when the labels say nothing, +/// `Some(None)` when they are linked to the source (so a chart-level format does not apply), +/// `Some(Some(code))` for their own format code. +fn label_format(d: Option<&El>) -> Option> { + let f = d?.child("c:numFmt")?; + if f.attr("sourceLinked").is_some_and(truthy) { + return Some(None); + } + f.attr("formatCode").filter(|f| f.chars().count() <= craft_wordmodel::chart::MAX_FMT).map(|f| Some(f.to_string())) +} + fn legend_pos(chart: &El) -> Option { chart.child("c:legend").map(|l| match l.child("c:legendPos").and_then(|p| p.attr("val")).unwrap_or("r") { "l" => Pos::Left, @@ -206,9 +229,24 @@ impl Series { let sp = ser.child("c:spPr"); let ln = sp.and_then(|p| p.child("a:ln")); let marker = ser.child("c:marker").and_then(|m| m.child("c:spPr")).and_then(|p| fill_colour(p, theme)); + let marker_color = marker; let color = sp.and_then(|p| fill_colour(p, theme)).or_else(|| ln.and_then(|l| fill_colour(l, theme))).or(marker); - let line_w = ln.and_then(|l| l.attr("w")).and_then(|v| measure(v, 12_700.0)).map_or(LINE_W, |w| w.clamp(0.0, 20.0)); + let no_fill = sp.and_then(|p| p.child("a:noFill")).is_some(); + let line_w = ln.and_then(|l| l.attr("w")).and_then(|v| measure(v, 12_700.0)).map(|w| w.clamp(0.0, 20.0)); let line = ln.is_none_or(|l| l.child("a:noFill").is_none()); + // `c:marker/c:symbol`: which symbol each point gets (`none` for no markers). Scatter + // series show markers unless the file says not; line series only when it says so. + let symbol = ser.child("c:marker").and_then(|m| m.child("c:symbol")).and_then(|s| s.attr("val")).map(str::to_string); + let markers = symbol.as_deref().map(|s| s != "none").or_else(|| scatter.then_some(true)); + let symbol = symbol.as_deref().map_or(Symbol::Circle, Symbol::parse); + let marker_size = ser + .child("c:marker") + .and_then(|m| m.child("c:size")) + .and_then(|s| s.attr("val")) + .and_then(|v| v.trim().parse::().ok()) + .filter(|v| v.is_finite()) + .map(|v| v.clamp(2.0, 72.0)); + let smooth = ser.child("c:smooth").and_then(|s| s.attr("val")).is_some_and(truthy); let (values, fmt) = numbers(ser.child(if scatter { "c:yVal" } else { "c:val" }), cap); let (mut xs, x_fmt) = if scatter { numbers(ser.child("c:xVal"), cap) } else { (Vec::new(), None) }; if scatter && xs.is_empty() { @@ -223,7 +261,30 @@ impl Series { } } let labels = show_values(ser.child("c:dLbls")); - Series { name, idx, color, line_w, line, values, xs, points, fmt, x_fmt, labels, raw: Vec::new() } + let label_fmt = label_format(ser.child("c:dLbls")); + let label_pos = ser.child("c:dLbls").and_then(|d| d.child("c:dLblPos")).and_then(|p| p.attr("val")).and_then(LabelPos::parse); + Series { + name, + idx, + color, + line_w, + line, + no_fill, + markers, + symbol, + marker_size, + smooth, + values, + xs, + points, + fmt, + x_fmt, + labels, + label_fmt, + label_pos, + marker_color, + raw: Vec::new(), + } } } @@ -290,7 +351,7 @@ fn pts(cache: &El, cap: usize) -> Vec> { } pub(super) fn axis(a: Option<&El>) -> Axis { - let Some(a) = a else { return Axis { deleted: true, ..Default::default() } }; + let Some(a) = a else { return Axis { deleted: true, labels: true, line: true, ..Default::default() } }; let scaling = a.child("c:scaling"); let num = |n: &str| scaling.and_then(|s| s.child(n)).and_then(|e| e.attr("val")).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()); @@ -305,8 +366,16 @@ pub(super) fn axis(a: Option<&El>) -> Axis { .child("c:numFmt") .filter(|f| f.attr("sourceLinked") != Some("1")) .and_then(|f| f.attr("formatCode")) - .filter(|f| f.len() <= MAX_FORMAT_CODE) + .filter(|f| f.chars().count() <= craft_wordmodel::chart::MAX_FMT) .map(str::to_string), + title: a.child("c:title").and_then(title_text), + title_rot: a + .child("c:title") + .and_then(|t| t.find("a:bodyPr")) + .and_then(|b| b.attr("rot")) + .and_then(|v| v.trim().parse::().ok()) + .map(|v| (v as f64 / 60_000.0).clamp(-360.0, 360.0) as f32), + labels: a.child("c:tickLblPos").and_then(|p| p.attr("val")) != Some("none"), } } diff --git a/crates/docx/src/read/chart/plot.rs b/crates/docx/src/read/chart/plot.rs index 652ee79a8b..22d05b5547 100644 --- a/crates/docx/src/read/chart/plot.rs +++ b/crates/docx/src/read/chart/plot.rs @@ -1,9 +1,12 @@ -use super::canvas::{Rect, fill, rect_segs, runs, seg, stroke, text, text_at, text_w, widest, wrap}; +use super::canvas::{Rect, clip_text, fill, rect_segs, runs, seg, stroke, text, text_angle, text_at, text_w, widest, wrap}; use super::format::format_value; -use super::model::{DataLabel, Grouping, Kind, Series}; +use super::model::{DataLabel, Grouping, Kind, LabelPos, Series, Symbol}; use super::parse::category_text; use super::polar::{draw_data_labels, label_of}; -use super::{AXIS, Chart, El, GAP, GRID, GraphicItem, LINE, MAX_LABEL, MAX_TICKS, PathSeg, Rgb, ShapeKind, TextAlign, fill_colour, measure}; +use super::{AXIS, Chart, El, GAP, GRID, GraphicItem, LINE, LINE_W, MAX_LABEL, MAX_TICKS, PathSeg, Rgb, ShapeKind, TextAlign, fill_colour, measure}; + +/// Line width of the stroked marker symbols (x, plus, star), points. +const MARKER_STROKE: f32 = 1.5; pub(super) fn label(s: &str) -> String { s.chars().take(MAX_LABEL).collect() @@ -142,6 +145,8 @@ impl Axes { /// The room around the plot for axis labels, and the category labels as they'll be drawn. struct Margins { left: f32, + /// Part of `left` taken by the rotated category-axis title (bars): the labels start after it. + title: f32, top: f32, bottom: f32, /// Category labels in lines (none for scatter charts or a deleted category axis). @@ -151,22 +156,25 @@ struct Margins { } /// The margins the axis labels need around the plot in `area`. Category labels under a column -/// chart wrap to the band; labels that still don't fit show every k-th category. +/// chart wrap to the band; labels that still don't fit show every k-th category. Hidden tick +/// labels take no room; an axis title adds one line on its side. fn axis_margins(c: &Chart, ax: &Axes, area: Rect) -> Margins { let fs = c.text_size; let lh = fs * LINE; let scatter = c.kind == Kind::Scatter; let (cat_on, val_on) = (!c.cat.deleted, !c.val.deleted); + let (cat_labels, val_labels) = (cat_on && c.cat.labels, val_on && c.val.labels); + let title = title_left(c, cat_on, val_on, area.w); let left = if c.horizontal { - if cat_on { widest(&c.cats, fs).min(area.w * 0.4) + GAP } else { 0.0 } - } else if val_on { + if cat_labels { widest(&c.cats, fs).min(area.w * 0.4) + GAP } else { 0.0 } + } else if val_labels { ax.vticks.iter().map(|(_, s)| text_w(s, fs)).fold(0.0, f32::max) + GAP } else { 0.0 - }; + } + title; let band_w = (area.w - left).max(1.0) / c.n as f32; - let wrapped: Vec> = if cat_on && !scatter { - let width = if c.horizontal { left - GAP } else { band_w }; + let wrapped: Vec> = if cat_labels && !scatter { + let width = if c.horizontal { left - title - GAP } else { band_w }; c.cats.iter().map(|s| wrap(s, width, fs)).collect() } else { Vec::new() @@ -174,15 +182,48 @@ fn axis_margins(c: &Chart, ax: &Axes, area: Rect) -> Margins { let widest_line = wrapped.iter().flatten().map(|s| text_w(s, fs)).fold(0.0, f32::max); let skip = ((widest_line / band_w).ceil() as usize).max(1); let label_lines = wrapped.iter().map(Vec::len).max().unwrap_or(1) as f32; - let bottom = if cat_on && !c.horizontal { + let bottom = (if cat_labels && !c.horizontal { if scatter { lh + GAP } else { label_lines * lh + GAP } - } else if c.horizontal && val_on { + } else if c.horizontal && val_labels { lh + GAP } else { 0.0 - }; - let top = if !c.horizontal && val_on { lh / 2.0 } else { 0.0 }; - Margins { left, top, bottom, wrapped, skip } + }) + title_bottom(c, cat_on, val_on, lh); + let top = if !c.horizontal && val_labels { lh / 2.0 } else { 0.0 }; + Margins { left, title, top, bottom, wrapped, skip } +} + +/// Room for the vertical axis title on the plot's left: one line when the axis that sits there +/// (the value axis for columns, the category axis for bars) has a title. +/// A horizontal title (`rot="0"`) gets a strip as wide as its wrapped lines, at most a quarter of +/// `area_w`, so the plot keeps its room. +fn title_left(c: &Chart, cat_on: bool, val_on: bool, area_w: f32) -> f32 { + let side = if c.horizontal { cat_on && c.cat.title.is_some() } else { val_on && c.val.title.is_some() }; + if !side { + return 0.0; + } + match flat_title_lines(c, area_w) { + Some(lines) => widest(&lines, c.text_size).min((area_w * 0.25).max(0.0)) + GAP, + None => c.text_size * LINE, + } +} + +/// The wrapped lines of the left axis's title when the file keeps it horizontal (`rot="0"`). +fn flat_title_lines(c: &Chart, area_w: f32) -> Option> { + let left = if c.horizontal { &c.cat } else { &c.val }; + let r = left.title_rot?.rem_euclid(360.0); + if !(r < 1.0 || r > 359.0) { + return None; + } + let width = if area_w.is_finite() { (area_w * 0.18).max(1.0) } else { 1.0 }; + left.title.as_ref().map(|t| wrap(t, width, c.text_size)) +} + +/// Room for the horizontal axis title under the plot: one line when the axis that sits there +/// (the category axis for columns, the value axis for bars) has a title. +fn title_bottom(c: &Chart, cat_on: bool, val_on: bool, lh: f32) -> f32 { + let side = if c.horizontal { val_on && c.val.title.is_some() } else { cat_on && c.cat.title.is_some() }; + if side { lh } else { 0.0 } } /// A bar, column, line, area or scatter chart in `area`: gridlines, series, axes, then labels. @@ -200,6 +241,9 @@ pub(super) fn cartesian(out: &mut Vec, c: &Chart, area: Rect) { if c.val.grid { draw_grid(out, &g, &ax.vticks); } + if c.cat.grid { + draw_cat_grid(out, &g, &ax.xticks, c.kind); + } let mut labels = Vec::new(); match c.kind { Kind::Bar => bars(out, c, &g, &mut labels), @@ -210,12 +254,49 @@ pub(super) fn cartesian(out: &mut Vec, c: &Chart, area: Rect) { } draw_axes(out, c, &g); draw_data_labels(out, &labels, c.text_size, g.horiz && c.kind == Kind::Bar); - if !c.val.deleted { - draw_value_labels(out, c, &g, &ax.vticks, Rect { w: m.left, ..area }); + if !c.val.deleted && c.val.labels { + let room = title_left(c, !c.cat.deleted, true, area.w); + draw_value_labels(out, c, &g, &ax.vticks, Rect { x: area.x + room, w: m.left - room, ..area }); } - if !c.cat.deleted { + if !c.cat.deleted && c.cat.labels { draw_category_labels(out, c, &g, &ax.xticks, &m, area); } + draw_axis_titles(out, c, &g, area); +} + +/// The axis titles, one line: the title of the vertical axis (the value axis for columns, the +/// category axis for bars) is turned 90° on the plot's left; the horizontal axis's title sits +/// under the plot. +fn draw_axis_titles(out: &mut Vec, c: &Chart, g: &Frame, area: Rect) { + let lh = c.text_size * LINE; + // The axis drawn along the plot's left (the value axis for columns, the category axis for + // bars) gets its title rotated there; the other axis's title sits under the plot. + let (left, bottom) = if c.horizontal { (&c.cat, &c.val) } else { (&c.val, &c.cat) }; + // Word turns the vertical axis's title counter-clockwise (reading upwards) unless the file + // turns it the other way or keeps it horizontal (`rot="0"`, wrapped in its own strip); any + // other rotation would not fit the strip and is read as counter-clockwise. + let up = if left.title_rot.is_some_and(|r| (r.rem_euclid(360.0) - 90.0).abs() < 1.0) { 90.0 } else { -90.0 }; + if !left.deleted + && let Some(lines) = flat_title_lines(c, area.w) + { + let strip = (g.plot.x - area.x - GAP).max(1.0); + let top = g.plot.y + g.plot.h / 2.0 - lines.len() as f32 * lh / 2.0; + for (k, l) in lines.iter().enumerate() { + let l = clip_text(l, strip, c.text_size); + text_angle(out, Rect { x: area.x, y: top + k as f32 * lh, w: strip, h: lh }, &l, c.text_size, TextAlign::Center, false, 0.0); + } + } else if !left.deleted + && let Some(t) = &left.title + { + let t = clip_text(t, g.plot.h, c.text_size); + text_angle(out, Rect { x: area.x, y: g.plot.y, w: lh, h: g.plot.h }, &t, c.text_size, TextAlign::Center, false, up); + } + if !bottom.deleted + && let Some(t) = &bottom.title + { + let t = clip_text(t, g.plot.w, c.text_size); + text_angle(out, Rect { x: g.plot.x, y: area.bottom() - lh, w: g.plot.w, h: lh }, &t, c.text_size, TextAlign::Center, false, 0.0); + } } /// Major gridlines at the value ticks. @@ -228,6 +309,31 @@ fn draw_grid(out: &mut Vec, g: &Frame, ticks: &[(f64, String)]) { } } +/// Gridlines along the category axis: across the plot at each category's centre (where line and +/// area points sit, on the tick marks when the axis crosses "midCat"), at the x ticks of a +/// scatter chart. +fn draw_cat_grid(out: &mut Vec, g: &Frame, xticks: &[(f64, String)], kind: Kind) { + let plot = g.plot; + if kind == Kind::Scatter { + for (t, _) in xticks { + let p = g.scat_x(*t); + stroke(out, seg(p, plot.y, p, plot.bottom()), GRID, 0.75); + } + return; + } + for i in 0..g.n { + let segs = if g.horiz { + let p = g.band_start(i) + g.band() / 2.0; + seg(plot.x, p, plot.right(), p) + } else { + // Bars stay in their bands; only line and area points move onto the ticks. + let p = if matches!(kind, Kind::Line | Kind::Area) { g.cat_x(i) } else { g.band_start(i) + g.band() / 2.0 }; + seg(p, plot.y, p, plot.bottom()) + }; + stroke(out, segs, GRID, 0.75); + } +} + /// The category axis line, the plot area's outline and the value axis line, as the file shows them. fn draw_axes(out: &mut Vec, c: &Chart, g: &Frame) { let plot = g.plot; @@ -271,7 +377,7 @@ fn draw_category_labels(out: &mut Vec, c: &Chart, g: &Frame, xticks for (i, lines) in m.wrapped.iter().enumerate() { let top = g.band_start(i) + g.band() / 2.0 - lines.len() as f32 * lh / 2.0; for (k, s) in lines.iter().enumerate() { - text(out, Rect { x: area.x, y: top + k as f32 * lh, w: m.left - GAP, h: lh }, s, fs, TextAlign::Right, false); + text(out, Rect { x: area.x + m.title, y: top + k as f32 * lh, w: m.left - m.title - GAP, h: lh }, s, fs, TextAlign::Right, false); } } } else { @@ -361,7 +467,13 @@ fn bars(out: &mut Vec, c: &Chart, g: &Frame, labels: &mut Vec, c: &Chart, g: &Frame, labels: &mut Vec (if v >= 0.0 { p1 } else { p0 }, mid), (false, false) => (mid, if v >= 0.0 { p0 } else { p1 }), }; - labels.push(DataLabel { x, y, text, inside: stacked }); + labels.push(DataLabel { x, y, text, inside: stacked, pos: LabelPos::Above, off: 0.0 }); } } } @@ -401,13 +513,109 @@ fn lines(out: &mut Vec, c: &Chart, g: &Frame, labels: &mut Vec f32 { + if drawn { s.marker_size.filter(|v| v.is_finite()).unwrap_or(6.0).clamp(2.0, 72.0) / 2.0 } else { 0.0 } +} + +fn markers(out: &mut Vec, pts: impl Iterator, colour: Rgb, s: &Series) { + const MARKER: f32 = 6.0; + let size = s.marker_size.filter(|v| v.is_finite()).unwrap_or(MARKER).clamp(2.0, 72.0); + let h = size / 2.0; + let shape = |out: &mut Vec, rect: [f32; 4], kind: ShapeKind| { + out.push(GraphicItem::Shape { rect, kind, fill: Some(colour), stroke: None, stroke_width: 0.0 }); + }; + let mut strokes = Vec::new(); + for (x, y) in pts { + match s.symbol { + Symbol::Circle => shape(out, [x - h, y - h, size, size], ShapeKind::Ellipse), + Symbol::Square => shape(out, [x - h, y - h, size, size], ShapeKind::Rectangle), + Symbol::Dot => shape(out, [x - h / 2.0, y - h / 2.0, h, h], ShapeKind::Ellipse), + Symbol::Dash => shape(out, [x - h, y - size / 6.0, size, size / 3.0], ShapeKind::Rectangle), + Symbol::Diamond => fill( + out, + vec![PathSeg::Move(x, y - h), PathSeg::Line(x + h, y), PathSeg::Line(x, y + h), PathSeg::Line(x - h, y), PathSeg::Close], + colour, + ), + Symbol::Triangle => { + fill(out, vec![PathSeg::Move(x, y - h), PathSeg::Line(x + h, y + h), PathSeg::Line(x - h, y + h), PathSeg::Close], colour) + } + Symbol::X | Symbol::Plus | Symbol::Star => { + if s.symbol != Symbol::Plus { + strokes.extend(seg(x - h, y - h, x + h, y + h)); + strokes.extend(seg(x - h, y + h, x + h, y - h)); + } + if s.symbol != Symbol::X { + strokes.extend(seg(x - h, y, x + h, y)); + strokes.extend(seg(x, y - h, x, y + h)); + } + } + } + } + stroke(out, strokes, colour, MARKER_STROKE); +} + +/// A polyline through `pts`, a smooth curve (Catmull-Rom pieces) when `smooth` and there are at +/// least three points in a row; gaps (`None`) end a run. +fn curve(pts: impl Iterator>, smooth: bool) -> Vec { + if !smooth { + return runs(pts); + } + let pts: Vec> = pts.collect(); + let mut segs = Vec::new(); + let mut i = 0; + while i < pts.len() { + let Some(first) = pts[i] else { + i += 1; + continue; + }; + // Collect one run of points. + let mut run = vec![first]; + while let Some(p) = pts.get(i + 1).copied().flatten() { + run.push(p); + i += 1; + } + i += 1; + if run.len() < 3 { + segs.extend(runs(run.into_iter().map(Some))); + continue; + } + segs.push(PathSeg::Move(run[0].0, run[0].1)); + for k in 0..run.len() - 1 { + // Catmull-Rom: tangent at p1 from p0 to p2 (ends mirror their own tangent). + let p0 = run[k.max(1) - 1]; + let p1 = run[k]; + let p2 = run[k + 1]; + let p3 = run.get(k + 2).copied().unwrap_or(p2); + let c1 = (p1.0 + (p2.0 - p0.0) / 6.0, p1.1 + (p2.1 - p0.1) / 6.0); + let c2 = (p2.0 - (p3.0 - p1.0) / 6.0, p2.1 - (p3.1 - p1.1) / 6.0); + segs.push(PathSeg::Cubic(c1.0, c1.1, c2.0, c2.1, p2.0, p2.1)); + } + } + segs +} + fn areas(out: &mut Vec, c: &Chart, g: &Frame, labels: &mut Vec) { let mut base = vec![0.0f64; g.n]; for (j, s) in c.series.iter().enumerate().filter(|(_, s)| has_values(s)) { @@ -422,10 +630,12 @@ fn areas(out: &mut Vec, c: &Chart, g: &Frame, labels: &mut Vec, c: &Chart, g: &Frame, labels: &mut Vec, c: &Chart, g: &Frame, labels: &mut Vec) { - const MARKER: f32 = 6.0; for (j, s) in c.series.iter().enumerate() { let pts: Vec> = s.xs.iter() @@ -448,16 +657,21 @@ fn draw_scatter(out: &mut Vec, c: &Chart, g: &Frame, labels: &mut V .collect(); for (i, p) in pts.iter().enumerate() { if let (Some((x, y)), Some(text)) = (p, label_of(s, i)) { - labels.push(DataLabel { x: *x, y: *y - MARKER / 2.0, text, inside: false }); + labels.push(DataLabel { + x: *x, + y: *y, + text, + inside: false, + pos: s.label_pos.unwrap_or(LabelPos::Right), + off: marker_half(s, s.markers != Some(false)) + 2.0, + }); } } if s.line { - stroke(out, runs(pts.iter().copied()), c.series_colour(j), s.line_w); - continue; + stroke(out, curve(pts.iter().copied(), s.smooth), c.series_colour(j), s.line_w.unwrap_or(LINE_W)); } - for (x, y) in pts.iter().flatten() { - let rect = [x - MARKER / 2.0, y - MARKER / 2.0, MARKER, MARKER]; - out.push(GraphicItem::Shape { rect, kind: ShapeKind::Ellipse, fill: Some(c.series_colour(j)), stroke: None, stroke_width: 0.0 }); + if s.markers != Some(false) { + markers(out, pts.iter().flatten().copied(), c.marker_colour(j), s); } } } diff --git a/crates/docx/src/read/chart/polar.rs b/crates/docx/src/read/chart/polar.rs index 57ad10472b..cf5e7452e6 100644 --- a/crates/docx/src/read/chart/polar.rs +++ b/crates/docx/src/read/chart/polar.rs @@ -1,8 +1,8 @@ use super::canvas::{Rect, clip_text, fill, stroke, text, text_w, widest}; use super::format::format_value; -use super::model::{DataLabel, Kind, Series}; +use super::model::{DataLabel, Kind, LabelPos, Series}; use super::plot::{Axes, has_values}; -use super::{Chart, FRAC_PI_2, GAP, GRID, GraphicItem, LINE, PathSeg, Rgb, ShapeKind, TAU, TEXT, TextAlign}; +use super::{Chart, FRAC_PI_2, GAP, GRID, GraphicItem, LINE, LINE_W, PathSeg, Rgb, ShapeKind, TAU, TEXT, TextAlign}; pub(super) fn pie(out: &mut Vec, c: &Chart, area: Rect) { let Some(s) = c.series.first() else { return }; @@ -38,7 +38,7 @@ pub(super) fn pie(out: &mut Vec, c: &Chart, area: Rect) { // Halfway across the ring (pie: two thirds out from the centre). let at = if inner > 0.0 { (r + inner) / 2.0 } else { r * 0.65 }; let (x, y) = polar(cx, cy, at, (a + b) / 2.0); - labels.push(DataLabel { x: x as f32, y: y as f32, text, inside: true }); + labels.push(DataLabel { x: x as f32, y: y as f32, text, inside: true, pos: LabelPos::Above, off: 0.0 }); } a = b; } @@ -92,14 +92,14 @@ pub(super) fn radar(out: &mut Vec, c: &Chart, area: Rect) { if c.radar_fill { fill(out, segs.clone(), col); } - stroke(out, segs, col, s.line_w); + stroke(out, segs, col, s.line_w.unwrap_or(LINE_W)); for (i, p) in ring.iter().enumerate() { if c.radar_marks && s.values.get(i).copied().flatten().is_some() { let rect = [p.0 as f32 - MARKER / 2.0, p.1 as f32 - MARKER / 2.0, MARKER, MARKER]; out.push(GraphicItem::Shape { rect, kind: ShapeKind::Ellipse, fill: Some(col), stroke: None, stroke_width: 0.0 }); } if let Some(text) = label_of(s, i) { - labels.push(DataLabel { x: p.0 as f32, y: p.1 as f32, text, inside: false }); + labels.push(DataLabel { x: p.0 as f32, y: p.1 as f32, text, inside: false, pos: LabelPos::Above, off: 0.0 }); } } } @@ -134,13 +134,13 @@ pub(super) fn radar(out: &mut Vec, c: &Chart, area: Rect) { } /// The data label of point `i` of series `s`, when it shows one: the value as the file has it, -/// in the series' number format. +/// in the labels' own number format, else the series' one. pub(super) fn label_of(s: &Series, i: usize) -> Option { if s.labels != Some(true) { return None; } let v = s.raw.get(i).copied().flatten()?; - let fmt = s.fmt.as_deref().filter(|f| !f.eq_ignore_ascii_case("General")); + let fmt = s.label_fmt.as_ref().map_or(s.fmt.as_deref(), |f| f.as_deref().or(s.fmt.as_deref())).filter(|f| !f.eq_ignore_ascii_case("General")); Some(match fmt { Some(f) => format_value(v, f, 1.0), None => general_value(v), @@ -165,13 +165,22 @@ pub(super) fn draw_data_labels(out: &mut Vec, labels: &[DataLabel], let w = text_w(&l.text, fs) + 4.0; let (rect, align) = if l.inside { (Rect { x: l.x - w / 2.0, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Center) + } else if l.off > 0.0 || l.pos != LabelPos::Above { + let o = l.off; + match l.pos { + LabelPos::Right => (Rect { x: l.x + o, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Left), + LabelPos::Left => (Rect { x: l.x - o - w, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Right), + LabelPos::Below => (Rect { x: l.x - w / 2.0, y: l.y + o, w, h: lh }, TextAlign::Center), + LabelPos::Center => (Rect { x: l.x - w / 2.0, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Center), + LabelPos::Above => (Rect { x: l.x - w / 2.0, y: l.y - o - lh, w, h: lh }, TextAlign::Center), + } } else if beside_right { (Rect { x: l.x + GAP / 2.0, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Left) } else { (Rect { x: l.x - w / 2.0, y: l.y - lh, w, h: lh }, TextAlign::Center) }; let color = if l.inside { Rgb::WHITE } else { TEXT }; - out.push(GraphicItem::Text { rect: rect.arr(), text: l.text.clone(), size: fs, color, bold: false, align, font: None }); + out.push(GraphicItem::Text { rect: rect.arr(), text: l.text.clone(), size: fs, color, bold: false, align, font: None, angle: 0.0 }); } } diff --git a/crates/docx/src/read/chart/tests.rs b/crates/docx/src/read/chart/tests.rs index 6e8bcfd828..d785d44005 100644 --- a/crates/docx/src/read/chart/tests.rs +++ b/crates/docx/src/read/chart/tests.rs @@ -386,9 +386,13 @@ fn axis_format_code_length_is_capped() { let x = format!(r#""#); axis(Some(&crate::xml::parse(x.as_bytes()).unwrap())).fmt }; - let ok = format!("{}0", "x".repeat(254)); + use craft_wordmodel::chart::MAX_FMT; + // The limit is the model's, counted in characters (a CJK character is one). + let ok = format!("{}0", "x".repeat(MAX_FMT - 1)); assert_eq!(fmt(&ok), Some(ok.clone())); - assert_eq!(fmt(&format!("{}0", "x".repeat(300))), None); + let cjk = format!("{}0", "\u{5143}".repeat(MAX_FMT - 1)); + assert_eq!(fmt(&cjk), Some(cjk.clone())); + assert_eq!(fmt(&format!("{}0", "x".repeat(MAX_FMT))), None); } #[test] @@ -590,3 +594,332 @@ fn series_without_a_usable_c_idx_take_their_place() { let big = [renumbered(&a, &format!(r#""#, u32::MAX))]; assert_eq!(column_colours(&big).0.len(), 1); } + +#[test] +fn bar_category_labels_start_after_the_axis_title() { + let long = "A category label that is much too long for its column"; + let title = r#"Region"#; + let plot = format!( + r#"{}{title}"#, + ser(0, "S", Some("FF0000"), &[long, "Short"], &["4", "8"]), + ); + let items = chart_items(&space(&plot), &theme(), 300.0, 200.0); + let rect_of = |f: &dyn Fn(&str, &TextAlign) -> bool| -> Vec<[f32; 4]> { + items + .iter() + .filter_map(|it| if let GraphicItem::Text { rect, text, align, .. } = it { f(text, align).then_some(*rect) } else { None }) + .collect() + }; + let title_rect = rect_of(&|t, _| t == "Region"); + assert_eq!(title_rect.len(), 1); + let strip_end = title_rect[0][0] + title_rect[0][2]; + let labels = rect_of(&|t, a| matches!(a, TextAlign::Right) && t != "Region" && (long.contains(t) || t == "Short")); + assert!(!labels.is_empty()); + assert!(labels.iter().all(|r| r[0] >= strip_end - 1e-3), "labels {labels:?} overlap the title strip ending at {strip_end}"); + assert!(labels.iter().all(|r| r[2] <= 0.4 * 300.0), "{labels:?}"); +} + +#[test] +fn category_gridlines_follow_the_points_when_the_axis_crosses_mid() { + let line = |cross: &str| { + let plot = format!( + r#"{}"#, + ser(0, "L", Some("FF0000"), &["Q1", "Q2", "Q3"], &["1", "5", "3"]), + ); + let items = chart_items(&space(&plot), &theme(), 300.0, 200.0); + let grid: Vec = items + .iter() + .filter_map(|it| match it { + GraphicItem::Path { segs, stroke: Some(c), .. } if *c == GRID => match segs.first() { + Some(PathSeg::Move(x, _)) => Some(*x), + _ => None, + }, + _ => None, + }) + .collect(); + let pts: Vec = items + .iter() + .filter_map(|it| match it { + GraphicItem::Path { segs, stroke: Some(c), .. } if *c == Rgb(255, 0, 0) => Some( + segs.iter().filter_map(|s| if let PathSeg::Move(x, _) | PathSeg::Line(x, _) = s { Some(*x) } else { None }).collect::>(), + ), + _ => None, + }) + .next() + .unwrap_or_default(); + (grid, pts) + }; + for cross in ["midCat", "between"] { + let (grid, pts) = line(cross); + assert_eq!(grid.len(), 3, "{cross}"); + assert_eq!(pts.len(), 3, "{cross}"); + assert!(grid.iter().zip(&pts).all(|(g, p)| (g - p).abs() < 1e-3), "{cross}: grid {grid:?} points {pts:?}"); + } +} + +/// A line chart with one series; `extra` goes into the series (`c:marker`, `c:dLbls`), `axes` +/// into the value axis. +fn line_with(extra: &str, val_axis: &str) -> Vec { + let s = ser(0, "S", Some("FF0000"), &["Q1", "Q2", "Q3"], &["3.2", "4.1", "5"]).replace("", &format!("{extra}")); + let plot = format!( + r#"{s}{val_axis}"# + ); + chart_items(&space(&plot), &theme(), 300.0, 200.0) +} + +fn marker_xml(symbol: &str, size: u32) -> String { + format!(r#""#) +} + +#[test] +fn marker_symbols_are_drawn_as_their_shape() { + let shapes = |items: &[GraphicItem], kind: ShapeKind| { + items + .iter() + .filter(|it| matches!(it, GraphicItem::Shape { kind: k, rect, .. } if *k == kind && rect[2] > 3.0 && rect[2] < 20.0 && rect[3] > 1.0)) + .count() + }; + let paths = |items: &[GraphicItem], filled: bool| { + items + .iter() + .filter(|it| matches!(it, GraphicItem::Path { fill, segs, .. } if fill.is_some() == filled && segs.len() <= 12 && segs.len() >= 3)) + .count() + }; + // One marker per point, in the series' size. + let circle = line_with(&marker_xml("circle", 9), ""); + assert_eq!(shapes(&circle, ShapeKind::Ellipse), 3); + assert!(circle.iter().any(|it| matches!(it, GraphicItem::Shape { kind: ShapeKind::Ellipse, rect, .. } if (rect[2] - 9.0).abs() < 1e-3))); + let square = line_with(&marker_xml("square", 7), ""); + assert_eq!(shapes(&square, ShapeKind::Rectangle) - shapes(&circle, ShapeKind::Rectangle), 3, "a square per point"); + assert_eq!(shapes(&square, ShapeKind::Ellipse), 0, "no circles"); + // Diamonds and triangles are filled polygons; x, plus and star are strokes. + let base = paths(&line_with("", ""), true); + assert_eq!(paths(&line_with(&marker_xml("diamond", 7), ""), true) - base, 3); + assert_eq!(paths(&line_with(&marker_xml("triangle", 7), ""), true) - base, 3); + for symbol in ["x", "plus", "star"] { + let items = line_with(&marker_xml(symbol, 7), ""); + assert!(items.iter().any(|it| matches!(it, GraphicItem::Path { fill: None, stroke: Some(_), segs, .. } if segs.len() >= 6)), "{symbol}"); + assert_eq!(shapes(&items, ShapeKind::Ellipse), 0, "{symbol} is not a circle"); + } + // Dash and dot are small shapes; `none` and unknown names never crash (unknown: a circle). + assert_eq!(shapes(&line_with(&marker_xml("dash", 7), ""), ShapeKind::Rectangle) - shapes(&circle, ShapeKind::Rectangle), 3); + assert_eq!(shapes(&line_with(&marker_xml("dot", 7), ""), ShapeKind::Ellipse), 3); + assert_eq!(shapes(&line_with(&marker_xml("none", 7), ""), ShapeKind::Ellipse), 0); + assert_eq!(shapes(&line_with(&marker_xml("wibble", 7), ""), ShapeKind::Ellipse), 3); + // Hostile sizes are clamped. + for size in ["0", "99999999999", "-4", "x"] { + let items = line_with(&format!(r#""#), ""); + assert!(items.iter().all(|it| match it { + GraphicItem::Shape { rect, .. } => rect.iter().all(|v| v.is_finite()) && rect[2] <= 300.0, + _ => true, + })); + } +} + +#[test] +fn data_labels_use_their_own_format_code() { + let dl = |num: &str| format!(r#"{num}"#); + let shown = |items: &[GraphicItem]| -> Vec { + items.iter().filter_map(|it| if let GraphicItem::Text { text, .. } = it { Some(text.clone()) } else { None }).collect() + }; + let own = shown(&line_with(&dl(r#""#), "")); + assert!(own.contains(&"3.20".to_string()) && own.contains(&"5.00".to_string()), "{own:?}"); + // Linked to the source: the series' format (General here). + let linked = shown(&line_with(&dl(r#""#), "")); + assert!(linked.contains(&"3.2".to_string()) && linked.contains(&"5".to_string()), "{linked:?}"); + // A format code beyond the cap is ignored, not applied. + let long = "0".repeat(craft_wordmodel::chart::MAX_FMT + 1); + let capped = shown(&line_with(&dl(&format!(r#""#)), "")); + assert!(capped.contains(&"3.2".to_string()), "{capped:?}"); +} + +#[test] +fn value_axis_title_turns_counter_clockwise_like_word() { + let title = |body: &str| format!(r#"{body}Revenue"#); + let angle = |items: &[GraphicItem]| { + items.iter().find_map(|it| if let GraphicItem::Text { text, angle, .. } = it { (text == "Revenue").then_some(*angle) } else { None }) + }; + // The file's rotation (`-5400000` is 90° counter-clockwise), or Word's default when it says none. + assert_eq!(angle(&line_with("", &title(r#""#))), Some(-90.0)); + assert_eq!(angle(&line_with("", &title(""))), Some(-90.0)); + assert_eq!(angle(&line_with("", &title(r#""#))), Some(90.0)); + // A horizontal title (`rot="0"`) stays horizontal: the plot makes room for it (see below). + assert_eq!(angle(&line_with("", &title(r#""#))), Some(0.0)); + // Hostile values stay finite. + let odd = angle(&line_with("", &title(r#""#))); + assert!(odd.is_some_and(f32::is_finite)); +} + +fn first_ellipse(items: &[GraphicItem]) -> Option<([f32; 4], Rgb)> { + items.iter().find_map(|it| match it { + GraphicItem::Shape { kind: ShapeKind::Ellipse, rect, fill: Some(c), .. } if rect[2] > 3.0 && rect[2] < 20.0 => Some((*rect, *c)), + _ => None, + }) +} + +#[test] +fn markers_use_the_automatic_series_colour_not_the_line_colour() { + // The series has an explicit red line/fill but no marker fill: Word draws the markers in the + // palette colour of the series index (accent 1 here). + let items = line_with(&marker_xml("circle", 9), ""); + assert_eq!(first_ellipse(&items).map(|e| e.1), Some(theme()[4])); + // A marker's own fill wins. + let own = + r#""#; + assert_eq!(first_ellipse(&line_with(own, "")).map(|e| e.1), Some(Rgb(0, 0xAA, 0))); +} + +#[test] +fn line_data_labels_default_to_the_right_and_honour_dlblpos() { + let dl = |pos: &str| format!(r#"{}{pos}"#, marker_xml("circle", 9)); + let text_rect = |items: &[GraphicItem]| { + items.iter().find_map(|it| if let GraphicItem::Text { text, rect, .. } = it { (text == "3.2").then_some(*rect) } else { None }) + }; + let at = |pos: &str| { + let items = line_with(&dl(pos), ""); + let (m, _) = first_ellipse(&items).unwrap(); + let t = text_rect(&items).unwrap(); + // Centre of the marker and of the label box. + ((t[0] + t[2] / 2.0) - (m[0] + m[2] / 2.0), (t[1] + t[3] / 2.0) - (m[1] + m[3] / 2.0), t, m) + }; + let (dx, dy, t, m) = at(""); + assert!(t[0] >= m[0] + m[2] && dy.abs() < 1.0, "default is right of the marker: {dx} {dy}"); + let (dx, dy, t, m) = at(r#""#); + assert!(t[0] >= m[0] + m[2] && dy.abs() < 1.0, "{dx} {dy}"); + let (dx, dy, _, _) = at(r#""#); + assert!(dx.abs() < 1.0 && dy < -4.0, "{dx} {dy}"); + let (dx, dy, _, _) = at(r#""#); + assert!(dx.abs() < 1.0 && dy > 4.0, "{dx} {dy}"); + let (dx, dy, t, m) = at(r#""#); + assert!(t[0] + t[2] <= m[0] && dy.abs() < 1.0, "{dx} {dy}"); + let (dx, dy, _, _) = at(r#""#); + assert!(dx.abs() < 1.0 && dy.abs() < 1.0, "{dx} {dy}"); + // Unknown positions fall back to the default. + let (_, _, t, m) = at(r#""#); + assert!(t[0] >= m[0] + m[2]); +} + +#[test] +fn horizontal_value_axis_title_gets_its_own_strip() { + let title = |rot: &str, name: &str| { + format!(r#"{name}"#) + }; + let plot_left = |items: &[GraphicItem]| { + // The first gridline's start is the plot's left edge. + items.iter().find_map(|it| match it { + GraphicItem::Path { segs, stroke: Some(_), fill: None, .. } if segs.len() == 2 => match segs.first() { + Some(PathSeg::Move(x, _)) => Some(*x), + _ => None, + }, + _ => None, + }) + }; + let rect_of = |items: &[GraphicItem], name: &str| { + items.iter().find_map(|it| if let GraphicItem::Text { text, rect, .. } = it { text.starts_with(name).then_some(*rect) } else { None }) + }; + let turned = line_with("", &title(r#" rot="-5400000" vert="horz""#, "Revenue")); + let flat = line_with("", &title(r#" rot="0" vert="horz""#, "Revenue")); + let (a, b) = (plot_left(&turned).unwrap(), plot_left(&flat).unwrap()); + assert!(b > a + 10.0, "a horizontal title takes more room than a turned one: {a} {b}"); + // The title box lies left of the plot and inside the chart. + let r = rect_of(&flat, "Revenue").unwrap(); + assert!(r[0] >= 0.0 && r[0] + r[2] <= b + 0.5, "{r:?} {b}"); + // A hostile title never takes more than a quarter of the width and stays finite. + let long = "Wibble ".repeat(500); + let items = line_with("", &title(r#" rot="0""#, &long)); + let p = plot_left(&items).unwrap(); + assert!(p.is_finite() && p <= 300.0 * 0.3, "{p}"); +} + +/// A one-series chart whose series carries `sp` as its `c:spPr`. +fn chart_with_sp(kind: &str, sp: &str) -> Vec { + let s = ser(0, "S", None, &["Q1", "Q2"], &["4", "8"]).replace("", &format!("{sp}")); + let plot = match kind { + "area" => format!( + r#"{s}"# + ), + dir => format!( + r#"{s}"# + ), + }; + chart_items(&space(&plot), &theme(), 300.0, 200.0) +} + +/// The series' closed shapes: (filled, stroked with the given width). +fn series_shapes(items: &[GraphicItem], width: f32) -> (usize, usize) { + let closed = |segs: &[PathSeg]| segs.iter().any(|s| matches!(s, PathSeg::Close)); + let fills = items.iter().filter(|it| matches!(it, GraphicItem::Path { segs, fill: Some(_), .. } if closed(segs))).count(); + let strokes = items + .iter() + .filter(|it| matches!(it, GraphicItem::Path { segs, fill: None, stroke: Some(_), stroke_width, .. } if closed(segs) && (*stroke_width - width).abs() < 0.01)) + .count(); + (fills, strokes) +} + +#[test] +fn unfilled_bars_keep_their_explicit_outline() { + let outlined = r#""#; + let no_line = r#""#; + for dir in ["col", "bar"] { + // Two points, two outlines, no fill. + assert_eq!(series_shapes(&chart_with_sp(dir, outlined), 2.0), (0, 2), "{dir}"); + // Control: no fill and no line draws nothing. + assert_eq!(series_shapes(&chart_with_sp(dir, no_line), 2.0), (0, 0), "{dir}"); + } +} + +#[test] +fn no_fill_area_series_is_not_painted() { + let filled = r#""#; + let none = r#""#; + assert_eq!(series_shapes(&chart_with_sp("area", filled), 2.0).0, 1); + assert_eq!(series_shapes(&chart_with_sp("area", none), 2.0).0, 0); +} + +#[test] +fn source_linked_series_labels_do_not_inherit_the_chart_format() { + let dl = |fmt: &str| format!(r#""#); + let shown = |items: &[GraphicItem]| -> Vec { + items.iter().filter_map(|it| if let GraphicItem::Text { text, .. } = it { Some(text.clone()) } else { None }).collect() + }; + // Chart-level 0%; the series' own labels are `linked` (or have no labels element at all). + let run = |series_dl: &str| { + let s = ser(0, "S", Some("FF0000"), &["Q1", "Q2", "Q3"], &["3.2", "4.1", "5"]).replace("", &format!("{series_dl}")); + let chart_dl = dl("0%").replace("{}", "0"); + let plot = format!( + r#"{s}{chart_dl}"# + ); + shown(&chart_items(&space(&plot), &theme(), 300.0, 200.0)) + }; + for linked in ["1", "true"] { + let own = run(&dl("General").replace("{}", linked)); + assert!(own.contains(&"3.2".to_string()) && !own.contains(&"320%".to_string()), "sourceLinked={linked}: {own:?}"); + } + // Control: a series without a label format still takes the chart's. + let inherited = run(r#""#); + assert!(inherited.contains(&"320%".to_string()), "{inherited:?}"); +} + +#[test] +fn office_2016_chart_draws_a_placeholder_of_its_size() { + let cx = |series: &str, title: &str| { + let x = format!( + r#"{title}{series}"# + ); + crate::xml::parse(x.as_bytes()).unwrap() + }; + let title = r#"Quarterly steps"#; + let rich = r#"Sales funnel"#; + let waterfall = chartex_items(Some(&cx(r#""#, title)), 432.0, 252.0); + assert_eq!(texts(&waterfall), ["Quarterly steps", "Waterfall chart (not supported yet)"]); + let framed = waterfall.iter().any(|it| matches!(it, GraphicItem::Shape { rect, stroke: Some(_), .. } if *rect == [0.0, 0.0, 432.0, 252.0])); + assert!(framed, "the frame has the chart's size: {waterfall:?}"); + let funnel = chartex_items(Some(&cx(r#""#, rich)), 300.0, 200.0); + assert_eq!(texts(&funnel), ["Sales funnel", "Funnel chart (not supported yet)"]); + let other = chartex_items(Some(&cx(r#""#, "")), 300.0, 200.0); + assert_eq!(texts(&other), ["Chart (not supported yet)"]); + // An unreadable part still reserves and frames the chart's place. + let missing = chartex_items(None, 300.0, 200.0); + assert_eq!(texts(&missing), ["Chart (not supported yet)"]); + assert!(chartex_items(None, 0.0, 200.0).is_empty() && chartex_items(None, f32::NAN, 200.0).is_empty()); +} diff --git a/crates/docx/src/read/diagram.rs b/crates/docx/src/read/diagram.rs index 7f03e8b516..7b7bbeebf6 100644 --- a/crates/docx/src/read/diagram.rs +++ b/crates/docx/src/read/diagram.rs @@ -463,7 +463,16 @@ fn text(sp: &El, xf: Xf, b: [f64; 4], theme: &[Rgb], filled: bool, fit: f32, out let mut y = y0 + (th - total) / 2.0; for l in lines { let lh = l.size * LINE; - out.push(GraphicItem::Text { rect: [x0, y, tw, lh], text: l.text, size: l.size, color: l.color, bold: l.bold, align: l.align, font: l.font }); + out.push(GraphicItem::Text { + rect: [x0, y, tw, lh], + text: l.text, + size: l.size, + color: l.color, + bold: l.bold, + align: l.align, + font: l.font, + angle: 0.0, + }); y += lh; } } diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index fa5ef62efb..3093e52b81 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -58,6 +58,7 @@ impl Reader<'_> { } "m:mathPr" => s.math = Some(math::read_math_pr(k)), "w:mirrorMargins" => s.mirror_margins = on_off(k), + "w:gutterAtTop" => s.gutter_at_top = on_off(k), "w:autoHyphenation" => s.auto_hyphenation = on_off(k), "w:doNotHyphenateCaps" => s.hyphenate_caps = !on_off(k), "w:hyphenationZone" => { diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index dc61b3a288..618ef8c10b 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use craft_wordmodel::para::cap_alt; use craft_wordmodel::props::{ - Align, Border, BorderStyle, Borders, CellProps, CharProps, CombineBrackets, EastAsianLayout, HeightRule, Highlight, LineSpacing, NumRef, + Align, Border, BorderStyle, Borders, CellProps, CharProps, CombineBrackets, EastAsianLayout, HeightRule, Highlight, Kashida, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, Rgb, RowProps, TabAlign, TabLeader, TabStop, TableFloat, TableLook, TableProps, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign, }; @@ -465,7 +465,14 @@ impl PropCtx { _ => {} } } - "w:jc" => p.align = k.attr("w:val").map(align), + "w:jc" => { + if let Some(v) = k.attr("w:val") { + p.align = Some(align(v)); + if let Some(kashida) = Kashida::from_jc(v) { + p.kashida = Some(kashida); + } + } + } "w:outlineLvl" => p.outline_level = k.attr("w:val").and_then(u32_of).map(|v| v.min(9) as u8), "w:rPr" => mark = self.rpr(k), _ => {} @@ -555,6 +562,17 @@ pub fn margins(e: &El) -> [f32; 4] { margin_sides(e).map(|side| side.unwrap_or(0.0)) } +/// Word's own cell margins (the Normal Table style): 0.08" left and right, none above or below. +pub const WORD_CELL_MARGINS: [f32; 4] = [0.0, 5.4, 0.0, 5.4]; + +/// A table's `w:tblCellMar` over the margins it would have without one (its +/// style's, else Word's). A side the element leaves out keeps the underlying margin, as in Word: +/// a form table that sets only `w:left` keeps its style's right margin, not none. +pub fn margins_over(e: &El, base: [f32; 4]) -> [f32; 4] { + let sides = margin_sides(e); + std::array::from_fn(|i| sides.get(i).copied().flatten().or_else(|| base.get(i).copied()).unwrap_or(0.0)) +} + fn margin_sides(e: &El) -> [Option; 4] { let get = |names: &[&str]| names.iter().find_map(|n| e.child(n)).and_then(|c| tw(c, "w:w")).map(|v| v.clamp(0.0, 1584.0)); [get(&["w:top"]), get(&["w:left", "w:start"]), get(&["w:bottom"]), get(&["w:right", "w:end"])] diff --git a/crates/docx/src/read/shape_style.rs b/crates/docx/src/read/shape_style.rs index 9f28ef2ff2..983218f9e1 100644 --- a/crates/docx/src/read/shape_style.rs +++ b/crates/docx/src/read/shape_style.rs @@ -47,6 +47,7 @@ pub(crate) fn preset_kind(prst: &str) -> ShapeKind { "downArrow" => ShapeKind::ArrowDown, "star4" | "star5" | "star6" | "star7" | "star8" | "star10" | "star12" | "star16" | "star24" | "star32" => ShapeKind::Star, "heart" => ShapeKind::Heart, + "frame" => ShapeKind::Frame, _ => ShapeKind::Rectangle, } } diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 770375365a..86ceb1651a 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -22,6 +22,7 @@ use craft_wordmodel::wordart::TextWarp; mod blocks; mod drawing; mod fields; +mod locked_canvas; mod runs; mod vml; diff --git a/crates/docx/src/read/story/blocks.rs b/crates/docx/src/read/story/blocks.rs index 38c35a02b9..91c54714fd 100644 --- a/crates/docx/src/read/story/blocks.rs +++ b/crates/docx/src/read/story/blocks.rs @@ -249,10 +249,11 @@ impl Reader<'_> { .unwrap_or_default(); para.props.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, ch), old); } - if para.props.numbering.is_some() - && let Some(ch) = ppr.child("w:numPr").and_then(|n| n.child("w:numberingChange")) - { - let original = ch.attr("w:original").unwrap_or("").chars().take(256).collect(); + if let Some(ch) = ppr.child("w:numPr").and_then(|n| n.child("w:numberingChange")) { + // Multi-level numbering caches (`w:original`) routinely exceed 256 chars while staying + // bounded against hostile attributes. + const MAX_CHANGE_ORIGINAL: usize = 4096; + let original = ch.attr("w:original").unwrap_or("").chars().take(MAX_CHANGE_ORIGINAL).collect(); para.props.num_change = Some(Box::new(NumChange { rev: self.revision(RevisionKind::Format, ch), original })); } if let Some(s) = ppr.child("w:sectPr") { @@ -332,12 +333,37 @@ impl Reader<'_> { } } + /// Omitted table-margin sides inherit from that property set's style. + fn table_margin_base(&self, style: Option<&str>) -> [f32; 4] { + style.and_then(|id| self.doc.styles.table_style(id)).and_then(|st| st.parts.cell_margins).unwrap_or(if self.no_default_table_style { + [0.0; 4] + } else { + crate::read::props::WORD_CELL_MARGINS + }) + } + fn read_table(&mut self, sc: &mut StoryCtx, t: &El, rels: &Rels, depth: usize) -> Option
{ let mut table = Table::default(); if let Some(p) = t.child("w:tblPr") { table.props = self.pc.tblpr(p); + // Sides `w:tblCellMar` leaves out keep the style's margins; without a style, Word's + // 0.08" left and right, or none in a file with no default table style. + if let Some(m) = p.child("w:tblCellMar") { + let base = self.table_margin_base(table.props.style.as_deref()); + table.props.cell_margins = Some(crate::read::props::margins_over(m, base)); + } if let Some(ch) = p.child("w:tblPrChange") { - let mut old = ch.child("w:tblPr").map(|o| self.pc.tblpr(o)).unwrap_or_default(); + let mut old = ch + .child("w:tblPr") + .map(|o| { + let mut props = self.pc.tblpr(o); + if let Some(m) = o.child("w:tblCellMar") { + let base = self.table_margin_base(props.style.as_deref()); + props.cell_margins = Some(crate::read::props::margins_over(m, base)); + } + props + }) + .unwrap_or_default(); // Rejecting the change brings back these properties: with the same margins. self.no_default_margins(&mut old); table.props.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, ch), old); diff --git a/crates/docx/src/read/story/drawing.rs b/crates/docx/src/read/story/drawing.rs index cb1152da89..92e4981336 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -12,23 +12,7 @@ impl Reader<'_> { /// text and drawing ids are carried into the object. Returns `None` when the frame or payload /// cannot be read. Ink written by WordCraft keeps its tool's caps rather than an outline cap. pub(super) fn read_drawing(&mut self, sc: &mut StoryCtx, d: &El, rels: &Rels) -> Option { - let (c, anchored) = match d.child("wp:inline") { - Some(c) => (c, false), - None => (d.child("wp:anchor")?, true), - }; - let ext = c.child("wp:extent"); - let dim = |n: &str| ext.and_then(|e| e.attr(n)).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT); - let (w, h) = (dim("cx"), dim("cy")); - let (alt, meta) = nv_alt(c.child("wp:docPr")); - let mut float = if anchored { anchor_float(c) } else { Float::default() }; - float.alt = meta; - float.hidden = c.child("wp:docPr").is_some_and(|p| on_off_attr(p, "hidden")); - if let Some(e) = c.child("wp:effectExtent") { - for (slot, n) in float.effect.iter_mut().zip(["l", "t", "r", "b"]) { - // Negative for a rotated object narrower than its frame; settled below. - *slot = e.attr(n).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(-1584.0, 1584.0); - } - } + let Frame { c, anchored, w, h, alt, mut float } = drawing_frame(d)?; let gd = c.child("a:graphic").and_then(|g| g.child("a:graphicData"))?; // Checked by URI before the blip search: a diagram's data can hold a blip further down. let uri = gd.attr("uri").unwrap_or(""); @@ -82,6 +66,10 @@ impl Reader<'_> { self.read_canvas(sc, c, rels, w, h, float) } else if let Some(g) = gd.child("wpg:wgp") { self.read_group(sc, g, rels, w, h, float)? + } else if let Some(lc) = gd.child("lc:lockedCanvas") { + // Word 2007's shapes, pictures and text in a drawing: read as the group they are. + let g = super::locked_canvas::as_group(lc, &self.doc.settings.theme_colors); + self.read_group(sc, &g, rels, w, h, float)? } else if direct_shape.is_none() && gd.find("a:blip").is_some() { self.read_pic(gd, rels, w, h, alt.clone(), float)? } else { @@ -188,14 +176,39 @@ impl Reader<'_> { let fallback = ac.child("mc:Fallback")?; let kept = El { name: "mc:AlternateContent".into(), attrs: Vec::new(), kids: vec![Node::El(choice.clone()), Node::El(fallback.clone())] }; let source = self.keep_embedded(&kept, rels, &[])?; - let Some(InlineObject::Image { media, w, h, alt, float, .. }) = self.read_drawing(sc, fallback.child("w:drawing")?, rels) else { - return None; + let picture = fallback.child("w:drawing").and_then(|d| self.read_drawing(sc, d, rels)); + let Some(InlineObject::Image { media, w, h, alt, float, .. }) = picture else { + return self.chartex_placeholder(choice, fallback, rels, source); }; let items = vec![GraphicItem::Image { rect: [0.0, 0.0, w, h], media }]; let graphic = Arc::new(Graphic { kind: GraphicKind::Chart, items, w, h, source: Some(source), ..Default::default() }); Some(InlineObject::Graphic { w, h, alt, float, graphic }) } + /// An Office 2016 chart whose fallback holds no picture (only text, say "Chart not + /// available"): a placeholder of the chart's own size (the `wp:extent` of its `mc:Choice`), + /// so the page breaks where they do with the chart drawn. The fallback is written back as it + /// was. `None` when the fallback has a picture or another drawing (read as before), or + /// holds runs or paragraphs, which a writer can't put inside the run that holds the object. + fn chartex_placeholder(&mut self, choice: &El, fallback: &El, rels: &Rels, source: Arc) -> Option { + const RUN_CONTENT: [&str; 6] = ["w:t", "w:tab", "w:br", "w:cr", "w:noBreakHyphen", "w:softHyphen"]; + if fallback.find("a:graphic").is_some() || !fallback.els().all(|e| RUN_CONTENT.contains(&e.name.as_str())) { + return None; + } + let Frame { c, w, h, alt, mut float, .. } = drawing_frame(choice.child("w:drawing")?)?; + let part = c + .child("a:graphic") + .and_then(|g| g.child("a:graphicData")) + .and_then(|gd| gd.child("cx:chart")) + .and_then(|cx| cx.attr("r:id")) + .and_then(|id| crate::read::part_of(rels, id, "chartEx")); + let space = part.and_then(|p| self.graphic_part(&p)); + let items = crate::read::chart::chartex_items(space.as_deref(), w, h); + float.effect = float.effect.map(|e| e.max(0.0)); + let graphic = Arc::new(Graphic { kind: GraphicKind::Chart, items, w, h, source: Some(source), ..Default::default() }); + Some(InlineObject::Graphic { w, h, alt, float, graphic }) + } + /// A group or canvas member that is native ink (`content`, a `w14:contentPart`, inside /// `alternate` when it has a picture fallback): what to write back (the whole alternate when /// it can be kept, else the ink alone) and its fallback picture (a `Document::media` key). @@ -526,12 +539,17 @@ impl Reader<'_> { outline_fill: paint.outline_fill, ..ShapeExtra::default() }; - // A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56); other presets drawn as - // rounded rectangles keep the default. - if prst == "roundRect" { + // A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56), a frame's own border + // width (`adj1`); other presets drawn as rounded rectangles keep the default. + let adj = match prst { + "roundRect" => Some("adj"), + "frame" => Some("adj1"), + _ => None, + }; + if let Some(adj) = adj { extra.corner = sppr .and_then(|s| s.child("a:prstGeom")) - .and_then(|g| preset_adj(g, "adj")) + .and_then(|g| preset_adj(g, adj)) .and_then(|v| u32::try_from(v.clamp(0, i64::from(craft_wordmodel::connector::MAX_CORNER))).ok()); } // Arrowheads: any end type but `none` (ECMA-376 §20.1.10.33) is drawn as a triangle of its @@ -598,6 +616,38 @@ impl Reader<'_> { } } +/// The frame of a `w:drawing`: its `wp:inline` or `wp:anchor` element, the size in points, +/// the alternative text, and the placement with its effect extent (rotation not yet settled). +struct Frame<'a> { + c: &'a El, + anchored: bool, + w: f32, + h: f32, + alt: String, + float: Float, +} + +fn drawing_frame(d: &El) -> Option> { + let (c, anchored) = match d.child("wp:inline") { + Some(c) => (c, false), + None => (d.child("wp:anchor")?, true), + }; + let ext = c.child("wp:extent"); + let dim = |n: &str| ext.and_then(|e| e.attr(n)).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT); + let (w, h) = (dim("cx"), dim("cy")); + let (alt, meta) = nv_alt(c.child("wp:docPr")); + let mut float = if anchored { anchor_float(c) } else { Float::default() }; + float.alt = meta; + float.hidden = c.child("wp:docPr").is_some_and(|p| on_off_attr(p, "hidden")); + if let Some(e) = c.child("wp:effectExtent") { + for (slot, n) in float.effect.iter_mut().zip(["l", "t", "r", "b"]) { + // Negative for a rotated object narrower than its frame; settled below. + *slot = e.attr(n).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(-1584.0, 1584.0); + } + } + Some(Frame { c, anchored, w, h, alt, float }) +} + /// The `mc:Choice` holding an Office 2016 chart (`cx:chart`) in an `mc:AlternateContent`. fn chartex_choice(ac: &El) -> Option<&El> { ac.children("mc:Choice").find(|c| c.child("w:drawing").and_then(|d| d.find("a:graphicData")).and_then(|g| g.attr("uri")) == Some(CHARTEX_URI)) diff --git a/crates/docx/src/read/story/locked_canvas.rs b/crates/docx/src/read/story/locked_canvas.rs new file mode 100644 index 0000000000..59a52cea2c --- /dev/null +++ b/crates/docx/src/read/story/locked_canvas.rs @@ -0,0 +1,265 @@ +//! A DrawingML locked canvas (`lc:lockedCanvas`, ECMA-376 Part 1 §20.3.2.1): the shapes, +//! pictures and text Word 2007 writes in a drawing in compatibility mode (wordcraft#5060). It is a group +//! shape in the DrawingML namespace (`a:sp`, `a:pic`, `a:grpSp`, `a:cxnSp`, text in `a:txSp`), so +//! it is read as the `wpg:wgp` group the reader already knows: each member renamed into its +//! WordprocessingML drawing form, and its DrawingML text into `w:txbxContent` paragraphs. + +use super::{El, Node, Rgb}; + +/// Groups nested deeper than this are left out, as `group_members` does. +const MAX_NEST: usize = 8; +/// DrawingML's text size when neither the run nor the list style gives one (18 pt, in +/// hundredths of a point). +const DEFAULT_SZ: i64 = 1800; + +/// The locked canvas `lc` as a `wpg:wgp` group. `theme` resolves its text colours. +pub(super) fn as_group(lc: &El, theme: &[Rgb]) -> El { + el("wpg:wgp", Vec::new(), members(lc, theme, 0)) +} + +/// The members of DrawingML group `g`, in their WordprocessingML drawing form. +fn members(g: &El, theme: &[Rgb], depth: usize) -> Vec { + g.els() + .filter_map(|e| match e.name.as_str() { + "a:grpSpPr" => Some(renamed(e, "wpg:grpSpPr")), + "a:grpSp" if depth < MAX_NEST => Some(el("wpg:grpSp", Vec::new(), members(e, theme, depth + 1))), + "a:sp" => Some(shape(e, theme)), + "a:cxnSp" => Some(connector(e)), + "a:pic" => Some(picture(e)), + "a:txSp" => Some(text_shape(e, theme)), + _ => None, + }) + .map(Node::El) + .collect() +} + +/// `a:sp` as `wps:wsp`: its name, properties and style, and its text as a text box's. +fn shape(sp: &El, theme: &[Rgb]) -> El { + let nv = sp.child("a:nvSpPr"); + let mut kids: Vec = [ + nv.and_then(|n| n.child("a:cNvPr")).map(|e| renamed(e, "wps:cNvPr")), + nv.and_then(|n| n.child("a:cNvSpPr")).map(|e| renamed(e, "wps:cNvSpPr")), + sp.child("a:spPr").map(|e| renamed(e, "wps:spPr")), + sp.child("a:style").map(|e| renamed(e, "wps:style")), + ] + .into_iter() + .flatten() + .map(Node::El) + .collect(); + // The text sits in the shape's own rectangle (`a:useSpRect`); a text rectangle of its own + // (`a:txSp/a:xfrm`) is not kept apart. + if let Some(body) = sp.child("a:txSp").and_then(|t| t.child("a:txBody")) { + kids.extend(text_box(body, theme)); + } + el("wps:wsp", Vec::new(), kids) +} + +/// A group's text shape (`a:txSp` as a member, text with no shape of its own) as a `wps:wsp` text +/// box without fill or outline at its own rectangle (`a:xfrm`). +fn text_shape(tx: &El, theme: &[Rgb]) -> El { + let none = || Node::El(el("a:noFill", Vec::new(), Vec::new())); + let geometry = el("a:prstGeom", attrs(&[("prst", "rect")]), vec![Node::El(el("a:avLst", Vec::new(), Vec::new()))]); + let mut sp_pr: Vec = tx.child("a:xfrm").map(|x| Node::El(x.clone())).into_iter().collect(); + sp_pr.extend([Node::El(geometry), none(), Node::El(el("a:ln", Vec::new(), vec![none()]))]); + let mut kids = vec![Node::El(el("wps:cNvSpPr", attrs(&[("txBox", "1")]), Vec::new())), Node::El(el("wps:spPr", Vec::new(), sp_pr))]; + if let Some(body) = tx.child("a:txBody") { + kids.extend(text_box(body, theme)); + } + el("wps:wsp", Vec::new(), kids) +} + +/// DrawingML text body `body` as a text box's content and body properties. +fn text_box(body: &El, theme: &[Rgb]) -> Vec { + let content = el("w:txbxContent", Vec::new(), paragraphs(body, theme)); + let mut kids = vec![Node::El(el("wps:txbx", Vec::new(), vec![Node::El(content)]))]; + if let Some(bp) = body.child("a:bodyPr") { + kids.push(Node::El(renamed(bp, "wps:bodyPr"))); + } + kids +} + +/// `a:cxnSp` as a `wps:wsp` line. Its glued ends name shapes by the canvas's own ids, which +/// aren't the document's, so they are left out. +fn connector(cx: &El) -> El { + let kids = [ + cx.child("a:nvCxnSpPr").and_then(|n| n.child("a:cNvPr")).map(|e| renamed(e, "wps:cNvPr")), + cx.child("a:spPr").map(|e| renamed(e, "wps:spPr")), + cx.child("a:style").map(|e| renamed(e, "wps:style")), + ]; + el("wps:wsp", Vec::new(), kids.into_iter().flatten().map(Node::El).collect()) +} + +/// `a:pic` as `pic:pic`. +fn picture(pic: &El) -> El { + let nv = pic.child("a:nvPicPr").and_then(|n| n.child("a:cNvPr")).map(|e| el("pic:nvPicPr", Vec::new(), vec![Node::El(renamed(e, "pic:cNvPr"))])); + let kids = [nv, pic.child("a:blipFill").map(|e| renamed(e, "pic:blipFill")), pic.child("a:spPr").map(|e| renamed(e, "pic:spPr"))]; + el("pic:pic", Vec::new(), kids.into_iter().flatten().map(Node::El).collect()) +} + +/// The paragraphs of DrawingML text body `body` as `w:p`s. DrawingML text has no space before +/// or after a paragraph and single lines, so each says so rather than taking the document's +/// defaults. +fn paragraphs(body: &El, theme: &[Rgb]) -> Vec { + body.children("a:p") + .map(|p| { + // A paragraph's properties default to the list style's for its level (`lvl`, 0–8), + // then to the list style's defaults (`a:defPPr`), property by property; a run's to its + // paragraph's own (`a:pPr/a:defRPr`), then to those two's. + let ppr_el = p.child("a:pPr"); + let level = ppr_el.and_then(|pp| pp.attr("lvl")).and_then(|v| v.trim().parse::().ok()).filter(|l| *l <= 8).unwrap_or(0); + let list_style = body.child("a:lstStyle"); + let paragraph_styles: Vec<&El> = + [ppr_el, list_style.and_then(|l| l.child(&format!("a:lvl{}pPr", level + 1))), list_style.and_then(|l| l.child("a:defPPr"))] + .into_iter() + .flatten() + .collect(); + let defaults: Vec<&El> = paragraph_styles.iter().filter_map(|pp| pp.child("a:defRPr")).collect(); + let defaults = defaults.as_slice(); + let mut ppr = + vec![Node::El(el("w:spacing", attrs(&[("w:before", "0"), ("w:after", "0"), ("w:line", "240"), ("w:lineRule", "auto")]), Vec::new()))]; + let jc = match paragraph_styles.iter().find_map(|pp| pp.attr("algn")) { + Some("ctr") => Some("center"), + Some("r") => Some("right"), + Some("just") => Some("both"), + Some("dist") => Some("distribute"), + Some("l") => Some("left"), + _ => None, + }; + if let Some(jc) = jc { + ppr.push(Node::El(el("w:jc", attrs(&[("w:val", jc)]), Vec::new()))); + } + // The paragraph mark's own size and font (`a:endParaRPr`), which an empty one's + // height follows. + ppr.push(Node::El(run_props(p.child("a:endParaRPr"), defaults, theme))); + let mut kids = vec![Node::El(el("w:pPr", Vec::new(), ppr))]; + for r in p.els() { + let text = match r.name.as_str() { + "a:r" | "a:fld" => Node::El(el( + "w:t", + attrs(&[("xml:space", "preserve")]), + vec![Node::Text(r.child("a:t").map(|t| t.text()).unwrap_or_default())], + )), + "a:br" => Node::El(el("w:br", Vec::new(), Vec::new())), + _ => continue, + }; + let rpr = run_props(r.child("a:rPr"), defaults, theme); + kids.push(Node::El(el("w:r", Vec::new(), vec![Node::El(rpr), text]))); + } + Node::El(el("w:p", Vec::new(), kids)) + }) + .collect() +} + +/// A DrawingML run's properties (`a:rPr`, each falling back on the first of `defaults`, the +/// `a:defRPr`s in order, that gives it) as `w:rPr`: font, size, bold, italic, underline, +/// strikethrough, caps, baseline and colour. +fn run_props(rpr: Option<&El>, defaults: &[&El], theme: &[Rgb]) -> El { + let get = |n: &str| rpr.and_then(|r| r.attr(n)).or_else(|| defaults.iter().find_map(|d| d.attr(n))); + let child = |n: &str| rpr.and_then(|r| r.child(n)).or_else(|| defaults.iter().find_map(|d| d.child(n))); + // On, off (kept, so the document's style doesn't turn it back on), or not given. + let toggle = |n: &str| match get(n) { + Some("1" | "true") => Some(true), + Some("0" | "false") => Some(false), + _ => None, + }; + let mut kids = Vec::new(); + let mut push = |name: &str, a: &[(&str, &str)]| kids.push(Node::El(el(name, attrs(a), Vec::new()))); + // Theme fonts (`+mn-lt`) are left to the document's. + let face = |n: &str| child(n).and_then(|f| f.attr("typeface")).filter(|t| !t.is_empty() && !t.starts_with('+')); + let mut fonts = Vec::new(); + if let Some(f) = face("a:latin") { + fonts.extend([("w:ascii", f), ("w:hAnsi", f)]); + } + if let Some(f) = face("a:ea") { + fonts.push(("w:eastAsia", f)); + } + if let Some(f) = face("a:cs") { + fonts.push(("w:cs", f)); + } + if !fonts.is_empty() { + push("w:rFonts", &fonts); + } + for (drawingml, word) in [("b", "w:b"), ("i", "w:i")] { + match toggle(drawingml) { + Some(true) => push(word, &[]), + Some(false) => push(word, &[("w:val", "0")]), + None => {} + } + } + match get("cap") { + Some("all") => push("w:caps", &[]), + Some("small") => push("w:smallCaps", &[]), + _ => {} + } + match get("strike") { + Some("sngStrike") => push("w:strike", &[]), + Some("dblStrike") => push("w:dstrike", &[]), + _ => {} + } + match get("u") { + None | Some("none") => {} + Some("dbl") => push("w:u", &[("w:val", "double")]), + Some(_) => push("w:u", &[("w:val", "single")]), + } + match get("baseline").and_then(|v| v.trim().parse::().ok()) { + Some(b) if b > 0 => push("w:vertAlign", &[("w:val", "superscript")]), + Some(b) if b < 0 => push("w:vertAlign", &[("w:val", "subscript")]), + _ => {} + } + if let Some(rgb) = child("a:solidFill").and_then(|f| crate::read::drawing_color::color(f, theme)) { + push("w:color", &[("w:val", &rgb.hex())]); + } + // Hundredths of a point into half-points, within Word's 1–1638 pt. + let sz = get("sz").and_then(|v| v.trim().parse::().ok()).unwrap_or(DEFAULT_SZ).clamp(100, 163_800) / 50; + let sz = sz.to_string(); + push("w:sz", &[("w:val", &sz)]); + push("w:szCs", &[("w:val", &sz)]); + // WordArt's outline, shadow, glow and reflection, as Word 2010 writes them in `w:rPr`. + kids.extend(text_effects(child("a:ln"), child("a:effectLst"), theme).into_iter().map(Node::El)); + el("w:rPr", Vec::new(), kids) +} + +/// A DrawingML run's text outline (`a:ln`) and effects (`a:effectLst`: outer shadow, glow, +/// reflection) as the `w14:` run properties ([MS-DOCX] §2.6.1) the run reader takes for WordArt. +/// Colours are resolved here, theme and modifiers included, into a `w14:srgbClr` with its +/// transparency. Lengths (EMUs), angles and percentages carry over as they are. +fn text_effects(ln: Option<&El>, fx: Option<&El>, theme: &[Rgb]) -> Vec { + let color = |e: &El| -> Option { + let (rgb, transparency) = crate::read::drawing_color::color_alpha(e, theme, None)?; + let alpha = ((transparency.clamp(0.0, 100.0) * 1000.0).round() as i64).to_string(); + let kids = if transparency > 0.0 { vec![Node::El(el("w14:alpha", attrs(&[("w14:val", &alpha)]), Vec::new()))] } else { Vec::new() }; + Some(Node::El(el("w14:srgbClr", attrs(&[("w14:val", &rgb.hex())]), kids))) + }; + // The attributes `names` of `e`, under the `w14:` prefix. + let copied = |e: &El, names: &[&str]| -> Vec<(String, String)> { + names.iter().filter_map(|n| e.attr(n).map(|v| (format!("w14:{n}"), v.to_string()))).collect() + }; + let mut out = Vec::new(); + if let Some(ln) = ln + && let Some(c) = ln.child("a:solidFill").and_then(color) + { + out.push(el("w14:textOutline", copied(ln, &["w"]), vec![Node::El(el("w14:solidFill", Vec::new(), vec![c]))])); + } + for e in fx.into_iter().flat_map(|f| f.els()) { + match e.name.as_str() { + "a:outerShdw" => out.push(el("w14:shadow", copied(e, &["blurRad", "dist", "dir"]), color(e).into_iter().collect())), + "a:glow" => out.push(el("w14:glow", copied(e, &["rad"]), color(e).into_iter().collect())), + "a:reflection" => out.push(el("w14:reflection", copied(e, &["blurRad", "stA", "endPos", "dist"]), Vec::new())), + _ => {} + } + } + out +} + +fn el(name: &str, attrs: Vec<(String, String)>, kids: Vec) -> El { + El { name: name.to_string(), attrs, kids } +} + +fn attrs(a: &[(&str, &str)]) -> Vec<(String, String)> { + a.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() +} + +/// `e` under another name, with its attributes and children. +fn renamed(e: &El, name: &str) -> El { + El { name: name.to_string(), ..e.clone() } +} diff --git a/crates/docx/src/write.rs b/crates/docx/src/write.rs index 1d9eb08184..4ba486a6cc 100644 --- a/crates/docx/src/write.rs +++ b/crates/docx/src/write.rs @@ -151,6 +151,11 @@ pub fn write_as(doc: &Document, flavor: Flavor) -> Result, DocxError> { } impl Writer<'_> { + /// The document's styles, for writers that need the resolved style chain. + pub(crate) fn styles(&self) -> &craft_wordmodel::styles::StyleSheet { + &self.doc.styles + } + fn assign_media(&mut self) { let mut used: std::collections::HashSet = std::collections::HashSet::new(); for (key, bytes) in &self.doc.media { diff --git a/crates/docx/src/write/embed.rs b/crates/docx/src/write/embed.rs index 9a8051e09f..7673a6f265 100644 --- a/crates/docx/src/write/embed.rs +++ b/crates/docx/src/write/embed.rs @@ -884,10 +884,11 @@ mod tests { let spec = ChartSpec { kind: ChartType::Column, categories: vec!["a".into(), "b".into()], - series: (0..series).map(|i| ChartSeries { name: format!("S{i}"), values: vec![Some(1.0); 2] }).collect(), + series: (0..series).map(|i| ChartSeries { name: format!("S{i}"), values: vec![Some(1.0); 2], ..Default::default() }).collect(), title: None, legend: None, data_labels: false, + ..Default::default() }; let graphic = Graphic { kind: GraphicKind::Chart, w: 100.0, h: 100.0, chart: Some(Arc::new(spec)), ..Default::default() }; InlineObject::Graphic { w: 100.0, h: 100.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) } diff --git a/crates/docx/src/write/props.rs b/crates/docx/src/write/props.rs index 0a64fc20a4..fb76da8d8f 100644 --- a/crates/docx/src/write/props.rs +++ b/crates/docx/src/write/props.rs @@ -1,8 +1,8 @@ //! Property writers, in ECMA-376 schema element order. use craft_wordmodel::props::{ - Align, Border, BorderStyle, Borders, CellProps, CharProps, EastAsianLayout, HeightRule, Highlight, LineSpacing, ParaProps, RowProps, TabAlign, - TabLeader, TableFloat, TableLook, TableProps, TextColor, VAlign, VMerge, VertAlign, + Align, Border, BorderStyle, Borders, CellProps, CharProps, EastAsianLayout, HeightRule, Highlight, Kashida, LineSpacing, ParaProps, RowProps, + TabAlign, TabLeader, TableFloat, TableLook, TableProps, TextColor, VAlign, VMerge, VertAlign, }; use crate::units::{n, twips}; @@ -201,6 +201,11 @@ pub fn align_val(a: Align) -> &'static str { } } +/// `w:jc` for a paragraph, including the kashida length of a justified one. +pub fn jc_val(a: Align, kashida: Option) -> &'static str { + if a == Align::Justify { kashida.unwrap_or(Kashida::None).jc() } else { align_val(a) } +} + /// A tab stop's or positional tab's `w:leader` value. pub fn tab_leader(l: TabLeader) -> &'static str { match l { @@ -261,10 +266,12 @@ pub fn ppr_inner(w: &mut W, p: &ParaProps, framed: bool, num_change: Option<&Cha toggle(w, "w:pageBreakBefore", p.page_break_before); write_frame(w, p, framed); toggle(w, "w:widowControl", p.widow_control); - if let Some(nr) = p.numbering { + if p.numbering.is_some() || num_change.is_some() { w.open("w:numPr", &[]); - w.val("w:ilvl", &n(nr.level.min(8) as i64)); - w.val("w:numId", &n(nr.num as i64)); + if let Some(nr) = p.numbering { + w.val("w:ilvl", &n(nr.level.min(8) as i64)); + w.val("w:numId", &n(nr.num as i64)); + } if let Some(a) = num_change { let refs: Vec<(&str, &str)> = a.iter().map(|(k, v)| (*k, v.as_str())).collect(); w.empty("w:numberingChange", &refs); @@ -285,7 +292,7 @@ pub fn ppr_inner(w: &mut W, p: &ParaProps, framed: bool, num_change: Option<&Cha toggle(w, "w:contextualSpacing", p.contextual_spacing); toggle(w, "w:mirrorIndents", p.mirror_indents); if let Some(a) = p.align { - w.val("w:jc", align_val(a)); + w.val("w:jc", jc_val(a, p.kashida)); } if let Some(direction) = p.text_direction { w.val("w:textDirection", direction.ooxml()); diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index 53fbe2be48..2a6faa7009 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -50,6 +50,10 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp if s.mirror_margins { w.empty("w:mirrorMargins", &[]); } + // CT_Settings order: after `w:mirrorMargins`, before `w:attachedTemplate`. + if s.gutter_at_top { + w.empty("w:gutterAtTop", &[]); + } // After `w:gutterAtTop` and before `w:proofState` in CT_Settings. if s.hide_spelling_errors { w.empty("w:hideSpellingErrors", &[]); @@ -356,7 +360,7 @@ pub(super) fn app_xml(doc: &Document) -> Vec { ("xmlns:vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"), ], ); - w.leaf("Application", &[], "WordCraft"); + w.leaf("Application", &[], crate::application_name()); w.leaf("Words", &[], &doc.word_count().to_string()); w.leaf("Paragraphs", &[], &doc.paragraph_count().to_string()); w.leaf("DocSecurity", &[], "0"); diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 1b9ef69980..2e064f05ac 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -18,6 +18,7 @@ const OWNED: &[&str] = &[ "w:removeDateAndTime", "w:displayBackgroundShape", "w:mirrorMargins", + "w:gutterAtTop", "w:hideSpellingErrors", "w:hideGrammaticalErrors", "w:attachedTemplate", @@ -388,4 +389,22 @@ mod tests { assert!(out.contains(""), "{out}"); assert!(out.contains(""), "{out}"); } + + #[test] + fn gutter_at_top_comes_from_the_generated_part() { + let orig = + r#""#; + assert!(has_unowned(orig.as_bytes())); + // Turned off in the model: the original element goes, the foreign one stays. + let out = String::from_utf8(merge(orig.as_bytes(), GEN.as_bytes()).unwrap()).unwrap(); + assert!(!out.contains("gutterAtTop") && out.contains("").count(), 1, "{out}"); + let at = |tag: &str| out.find(tag).unwrap_or_else(|| panic!("{tag} missing: {out}")); + assert!(at("") < at("") && at("") < at(""#)); + } } diff --git a/crates/docx/src/write/story/drawing.rs b/crates/docx/src/write/story/drawing.rs index 7c03cca6ef..3986d79643 100644 --- a/crates/docx/src/write/story/drawing.rs +++ b/crates/docx/src/write/story/drawing.rs @@ -69,9 +69,18 @@ impl Writer<'_> { } /// A shape's or text box's `wps:wsp`, at `off` in its group (or 0, 0). In a group it carries - /// its own `wps:cNvPr` with drawing id `id`. - pub(super) fn wsp(&mut self, w: &mut W, o: &InlineObject, id: Option<&str>, off: (f32, f32), rels: &mut PartRels, depth: usize) { - let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, effects, float, freeform, extra } = o else { return }; + /// its own `wps:cNvPr` with drawing id `id`. Returns where in `w` its `w:txbxContent` was + /// written, for a VML fallback to repeat. + pub(super) fn wsp( + &mut self, + w: &mut W, + o: &InlineObject, + id: Option<&str>, + off: (f32, f32), + rels: &mut PartRels, + depth: usize, + ) -> Option> { + let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, effects, float, freeform, extra } = o else { return None }; let geom = freeform.as_deref().filter(|_| *kind == ShapeKind::Freeform); w.open("wps:wsp", &[]); if let Some(id) = id { @@ -117,16 +126,22 @@ impl Writer<'_> { ShapeKind::ArrowDown => "downArrow", ShapeKind::Star => "star5", ShapeKind::Heart => "heart", + ShapeKind::Frame => "frame", }; match geom { Some(f) => cust_geom(w, f, *sw, *sh), None => { w.open("a:prstGeom", &[("prst", prst)]); - match extra.corner.filter(|_| *kind == ShapeKind::RoundedRectangle) { - Some(c) => { + let adj = match kind { + ShapeKind::RoundedRectangle => Some("adj"), + ShapeKind::Frame => Some("adj1"), + _ => None, + }; + match adj.zip(extra.corner) { + Some((name, c)) => { w.open("a:avLst", &[]); let fmla = format!("val {}", c.min(craft_wordmodel::connector::MAX_CORNER)); - w.empty("a:gd", &[("name", "adj"), ("fmla", &fmla)]); + w.empty("a:gd", &[("name", name), ("fmla", &fmla)]); w.close("a:avLst"); } None => w.empty("a:avLst", &[]), @@ -181,6 +196,7 @@ impl Writer<'_> { // its place in it instead. let part = (*story).and_then(|id| self.doc.parts.get(&id).filter(|p| p.kind == craft_wordmodel::PartKind::TextBox).map(|p| (id, p))); let link = part.and_then(|(id, _)| self.txbx_links.get(&id).copied()); + let mut content = None; if let Some((n, seq)) = link.filter(|(_, seq)| *seq > 0) { w.empty("wps:linkedTxbx", &[("id", &n.to_string()), ("seq", &seq.to_string())]); } else if let Some((id, part)) = part @@ -190,6 +206,7 @@ impl Writer<'_> { Some((n, _)) => w.open("wps:txbx", &[("id", &n.to_string())]), None => w.open("wps:txbx", &[]), } + let start = w.s.len(); w.open("w:txbxContent", &[]); if self.written_boxes.insert(id) { let blocks = part.blocks.clone(); @@ -198,6 +215,7 @@ impl Writer<'_> { w.empty("w:p", &[]); } w.close("w:txbxContent"); + content = Some(start..w.s.len()); w.close("wps:txbx"); self.boxes.leave(); } @@ -231,6 +249,7 @@ impl Writer<'_> { w.close("wps:bodyPr"); } w.close("wps:wsp"); + content } /// A `w:drawing` holding `graphic` (an `a:graphic`) in a frame of the object's size and place. diff --git a/crates/docx/src/write/story/object.rs b/crates/docx/src/write/story/object.rs index 6cdd54f463..4b0ae856a6 100644 --- a/crates/docx/src/write/story/object.rs +++ b/crates/docx/src/write/story/object.rs @@ -1,7 +1,7 @@ use super::drawing::{DrawingInfo, shape_name, spin_attrs, write_fill, xfrm_spin_only}; use super::field::{FieldData, field_run}; use super::section::comment_reference_style; -use super::{CharProps, Fill, InlineObject, NoteKind, PartRels, TextColor, W, Wrap, Writer, emu, n, rpr}; +use super::{Anchor, CharProps, Fill, Float, InlineObject, NoteKind, PartRels, ShapeKind, TextColor, W, Wrap, Writer, emu, n, rpr}; impl Writer<'_> { /// Write an inline object (`Bookmark`, `Comment`, `Equation`, `Field`, `Shape`, etc.). @@ -362,10 +362,24 @@ impl Writer<'_> { } fn write_shape(&mut self, w: &mut W, o: &InlineObject, props: &CharProps, rels: &mut PartRels, depth: usize) { - let InlineObject::Shape { kind, w: sw, h: sh, float, effects, freeform, extra, .. } = o else { return }; + let InlineObject::Shape { kind, w: sw, h: sh, float, effects, freeform, extra, story, .. } = o else { return }; self.rev_open(w, props); w.open("w:r", &[]); self.rpr(w, props); + // A Word 2010 shape (`wps`) with a VML form goes in `mc:AlternateContent`, as Word writes + // it: a reader that doesn't know `wps` (Word 2007, the Office Compatibility Pack) takes the + // VML fallback instead of refusing the file. A shape without one stays bare: guarded with + // no fallback, that reader would open the file without the shape and drop it on its next + // save, which is worse than refusing the file. + // VML currently has no chain IDs or mso-next-textbox links. Keep every member of a + // linked story bare, including its head: an unlinked fallback would silently lose + // overflow text in older readers. Unlinked boxes still get the compatibility fallback. + let linked = story.is_some_and(|id| self.txbx_links.contains_key(&id)); + let fallback = freeform.is_none() && vml_tag(*kind).is_some() && !linked; + if fallback { + w.open("mc:AlternateContent", &[]); + w.open("mc:Choice", &[("Requires", "wps")]); + } w.open("w:drawing", &[]); let docpr = self.shape_docpr(extra.id); let link = Self::drawing_link(props, rels); @@ -384,18 +398,164 @@ impl Writer<'_> { } let float = &float; self.drawing_open(w, DrawingInfo { float, size: (*sw, *sh), docpr: &docpr, name: &name, alt: o.alt_text(), link: link.as_deref() }); + // This shape's stacking order: floating objects in its text box move `self.z` on. + let z = self.z; w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]); - self.wsp(w, o, None, (0.0, 0.0), rels, depth); + let content = self.wsp(w, o, None, (0.0, 0.0), rels, depth); w.close("a:graphicData"); w.close("a:graphic"); w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); w.close("w:drawing"); + if fallback { + w.close("mc:Choice"); + // The same text again: the fallback is a copy of the choice, not more of the story. + let content = content.and_then(|r| w.s.get(r)).map(str::to_owned); + w.open("mc:Fallback", &[]); + self.vml_shape(w, o, float, z, content.as_deref()); + w.close("mc:Fallback"); + w.close("mc:AlternateContent"); + } w.close("w:r"); self.rev_close(w, props); } + /// A shape as VML (`w:pict`), for readers older than Word 2010 shapes: its frame, place, + /// wrapping, fill, outline and text box. Only for a kind [`vml_tag`] names. + fn vml_shape(&self, w: &mut W, o: &InlineObject, float: &Float, z: u32, content: Option<&str>) { + let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, extra, .. } = o else { return }; + let Some(tag) = vml_tag(*kind) else { return }; + let pt = |v: f32| format!("{:.2}pt", craft_wordmodel::geom::finite(v)); + let mut style = Vec::new(); + if float.wrap != Wrap::Inline { + style.push("position:absolute".to_string()); + style.push(format!("margin-left:{}", pt(float.x))); + style.push(format!("margin-top:{}", pt(float.y))); + } + style.push(format!("width:{}", pt(sw.max(0.0)))); + style.push(format!("height:{}", pt(sh.max(0.0)))); + let spin = float.spin(); + if spin.deg != 0.0 { + style.push(format!("rotation:{}", spin.deg)); + } + match (spin.flip_h, spin.flip_v) { + (true, true) => style.push("flip:x y".into()), + (true, false) => style.push("flip:x".into()), + (false, true) => style.push("flip:y".into()), + (false, false) => {} + } + if float.wrap != Wrap::Inline { + // The stacking order the choice was given, as a signed 32-bit `z-index`. Behind the text + // is negative, shifted down rather than negated, so a higher `z` still stacks higher. + let z = i64::from(z.min(i32::MAX as u32)); + let z = if float.wrap == Wrap::BehindText { z - (i64::from(i32::MAX) + 1) } else { z }; + style.push(format!("z-index:{z}")); + // The same clearances from the text as the choice's `distL`/`distR`/`distT`/`distB`. + let d = pt(float.dist.clamp(0.0, 1584.0)); + style.push(format!("mso-wrap-distance-left:{d}")); + style.push(format!("mso-wrap-distance-right:{d}")); + style.push(format!("mso-wrap-distance-top:{}", pt(float.dist_top.clamp(0.0, 1584.0)))); + style.push(format!("mso-wrap-distance-bottom:{}", pt(float.dist_bottom.clamp(0.0, 1584.0)))); + if let Some(a) = float.h_align { + style.push(format!("mso-position-horizontal:{}", a.ooxml(true))); + } + style.push(format!("mso-position-horizontal-relative:{}", vml_rel(float.h_rel, true))); + if let Some(a) = float.v_align { + style.push(format!("mso-position-vertical:{}", a.ooxml(false))); + } + style.push(format!("mso-position-vertical-relative:{}", vml_rel(float.v_rel, false))); + } + let body = (*story).and_then(|id| self.doc.parts.get(&id)).map(|p| p.body).unwrap_or_default(); + style.push( + match body.anchor { + craft_wordmodel::props::VAlign::Top => "v-text-anchor:top", + craft_wordmodel::props::VAlign::Center => "v-text-anchor:middle", + craft_wordmodel::props::VAlign::Bottom => "v-text-anchor:bottom", + } + .into(), + ); + if float.hidden { + style.push("visibility:hidden".into()); + } + let style = style.join(";"); + let mut attrs: Vec<(&str, String)> = vec![("style", style)]; + if *kind == ShapeKind::RoundedRectangle { + // The same fraction of the shorter side: VML's in 1/65536ths, DrawingML's in 1/100000ths. + let c = match extra.corner { + Some(c) => c.min(craft_wordmodel::connector::MAX_CORNER) as f32 / 100_000.0, + None => craft_wordmodel::connector::DEFAULT_CORNER, + }; + attrs.push(("arcsize", format!("{}f", (c * 65_536.0).round() as u32))); + } + if float.wrap != Wrap::Inline { + attrs.push(("o:allowincell", (if float.outside_cell { "f" } else { "t" }).into())); + } + let opacity = match fill.as_ref() { + Some(f) => { + attrs.push(("fillcolor", format!("#{}", f.main_color().hex()))); + match f { + Fill::Solid { transparency, .. } if *transparency > 0.0 => Some(format!("{:.4}", (1.0 - transparency / 100.0).clamp(0.0, 1.0))), + _ => None, + } + } + None => { + attrs.push(("filled", "f".into())); + None + } + }; + match stroke { + Some(c) => { + attrs.push(("strokecolor", format!("#{}", c.hex()))); + attrs.push(("strokeweight", pt(stroke_width.clamp(0.0, 100.0)))); + } + None => attrs.push(("stroked", "f".into())), + } + let attrs: Vec<(&str, &str)> = attrs.iter().map(|(k, v)| (*k, v.as_str())).collect(); + w.open("w:pict", &[]); + w.open(tag, &attrs); + if let Some(opacity) = &opacity { + w.empty("v:fill", &[("opacity", opacity)]); + } + if let Some(content) = content { + let inset = body.inset.map(|i| i.map(|v| pt(v.min(craft_wordmodel::MAX_TEXT_BOX_INSET) as f32 / 12_700.0)).join(",")); + let mut tb: Vec<(&str, &str)> = Vec::new(); + if let Some(inset) = &inset { + tb.push(("inset", inset)); + } + // Text direction as the VML reader takes it (stacked letters have no VML form). + let mut tb_style = match body.vert { + craft_wordmodel::props::TextVert::Vert => vec!["layout-flow:vertical"], + craft_wordmodel::props::TextVert::Vert270 => vec!["layout-flow:vertical", "mso-layout-flow-alt:bottom-to-top"], + craft_wordmodel::props::TextVert::Horz | craft_wordmodel::props::TextVert::Stacked => Vec::new(), + }; + if body.auto_fit { + tb_style.push("mso-fit-shape-to-text:t"); + } + let tb_style = tb_style.join(";"); + if !tb_style.is_empty() { + tb.push(("style", &tb_style)); + } + w.open("v:textbox", &tb); + w.raw(content); + w.close("v:textbox"); + } + let wrap = match float.wrap { + Wrap::Square => Some("square"), + Wrap::Tight => Some("tight"), + Wrap::Through => Some("through"), + Wrap::TopAndBottom => Some("topAndBottom"), + Wrap::Inline | Wrap::BehindText | Wrap::InFrontOfText => None, + }; + if let Some(wrap) = wrap { + let side = float.wrap_text.ooxml(); + let attrs: &[(&str, &str)] = if float.wrap_text.is_both() { &[("type", wrap)] } else { &[("type", wrap), ("side", side)] }; + w.empty("w10:wrap", attrs); + } + w.close(tag); + w.close("w:pict"); + } + fn write_group(&mut self, w: &mut W, o: &InlineObject, props: &CharProps, rels: &mut PartRels, depth: usize) { let InlineObject::Group { w: gw, h: gh, float, ch_w, ch_h, children, canvas } = o else { return }; self.rev_open(w, props); @@ -487,6 +647,33 @@ impl Writer<'_> { } } +/// The VML element that draws a shape kind, for the kinds VML has one for. +fn vml_tag(kind: ShapeKind) -> Option<&'static str> { + match kind { + ShapeKind::Rectangle | ShapeKind::TextBox => Some("v:rect"), + ShapeKind::RoundedRectangle => Some("v:roundrect"), + ShapeKind::Ellipse => Some("v:oval"), + _ => None, + } +} + +/// A floating object's anchor as VML names it (`mso-position-horizontal-relative`, `-vertical-`). +fn vml_rel(a: Anchor, horiz: bool) -> &'static str { + match (a, horiz) { + (Anchor::Margin, _) => "margin", + (Anchor::Page, _) => "page", + (Anchor::InsideMargin, _) => "inner-margin-area", + (Anchor::OutsideMargin, _) => "outer-margin-area", + (Anchor::LeftMargin, true) => "left-margin-area", + (Anchor::RightMargin, true) => "right-margin-area", + (Anchor::Character, true) => "char", + (Anchor::TopMargin, false) => "top-margin-area", + (Anchor::BottomMargin, false) => "bottom-margin-area", + (Anchor::Line, false) => "line", + _ => "text", + } +} + pub(super) fn ink_name(tool: craft_wordmodel::freeform::InkTool) -> &'static str { match tool { craft_wordmodel::freeform::InkTool::Pen => "Pen", diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index e0242d8ebd..aa973184e2 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -76,6 +76,12 @@ impl Writer<'_> { a.push(("w:original", c.original.clone())); a }); + // `w:jc` encodes alignment and kashida length together. A justified paragraph + // whose kashida is unset (`None`) still inherits a length from its style; writing + // `both` would read back as `Some(Kashida::None)` and cancel that length. + if pp.align == Some(craft_wordmodel::props::Align::Justify) && pp.kashida.is_none() { + pp.kashida = Some(self.styles().resolve_para(&pp).kashida); + } ppr_inner(w, &pp, framed, num_change.as_ref()); if has_mark { self.write_mark_rpr(w, &p.mark, &mark_revs); diff --git a/crates/docx/src/write/styles.rs b/crates/docx/src/write/styles.rs index 3bcf9ab97f..0fddf33b49 100644 --- a/crates/docx/src/write/styles.rs +++ b/crates/docx/src/write/styles.rs @@ -184,7 +184,13 @@ fn style_property_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style) { let para_change = st.para_change.as_deref().filter(|ch| ch.old.formatting() != st.para.formatting()); if (!st.para.is_empty() || para_change.is_some()) && st.kind != StyleKind::Character { w.open("w:pPr", &[]); - props::ppr_inner(w, &st.para, false, None); + let mut ppr = st.para.clone(); + if ppr.align == Some(craft_wordmodel::props::Align::Justify) && ppr.kashida.is_none() { + let mut probe = ppr.clone(); + probe.style = Some(st.id.clone()); + ppr.kashida = Some(wr.styles().resolve_para(&probe).kashida); + } + props::ppr_inner(w, &ppr, false, None); if let Some(ch) = para_change { let a = wr.change_attrs(ch.rev); open_change(w, "w:pPrChange", &a); diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index bb86755d9a..fa50d217a0 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -52,8 +52,10 @@ pub const NAMESPACES: &[(&str, &str)] = &[ pub const DECORATIVE_EXT: &str = "{C183D7F6-B498-43B3-948B-1728B52AA6E4}"; pub const DECORATIVE_NS: &str = "http://schemas.microsoft.com/office/drawing/2017/decorative"; -/// Namespaces that only appear in non-body parts. +/// Namespaces that only appear in non-body parts, or that the reader reads but never writes. const OTHER_NAMESPACES: &[(&str, &str)] = &[ + // A locked canvas, read into a drawing group (wordcraft#5060). + ("lc", "http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"), ("b", "http://schemas.openxmlformats.org/officeDocument/2006/bibliography"), ("rel", "http://schemas.openxmlformats.org/package/2006/relationships"), ("ct", "http://schemas.openxmlformats.org/package/2006/content-types"), diff --git a/crates/docx/tests/application_name.rs b/crates/docx/tests/application_name.rs new file mode 100644 index 0000000000..1973e63ae3 --- /dev/null +++ b/crates/docx/tests/application_name.rs @@ -0,0 +1,19 @@ +//! An app that embeds the writer names itself in `docProps/app.xml` (its own test binary: the +//! name is set once per process). + +use std::io::Read; + +#[test] +fn the_embedding_app_names_itself_in_app_xml() { + assert_eq!(craft_docx::application_name(), "WordCraft", "the default"); + craft_docx::set_application_name("Example Writer"); + craft_docx::set_application_name("Other"); + assert_eq!(craft_docx::application_name(), "Example Writer", "only the first call counts"); + let mut d = craft_wordmodel::Document::new(); + d.body = vec![craft_wordmodel::para_block(craft_wordmodel::Paragraph::with_text("Text", Default::default()))]; + let bytes = craft_docx::write(&d).unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); + let mut app = String::new(); + z.by_name("docProps/app.xml").unwrap().read_to_string(&mut app).unwrap(); + assert!(app.contains("Example Writer"), "{app}"); +} diff --git a/crates/docx/tests/it/cell_margin_inheritance.rs b/crates/docx/tests/it/cell_margin_inheritance.rs index 83aafc7d0a..dc5cba6441 100644 --- a/crates/docx/tests/it/cell_margin_inheritance.rs +++ b/crates/docx/tests/it/cell_margin_inheritance.rs @@ -98,3 +98,18 @@ fn no_default_table_style_means_no_cell_margins() { let reopened = craft_docx::read(&bytes).unwrap(); assert_eq!(reopened.body[0].as_table().unwrap().props.cell_margins, Some([0.0; 4])); } + +#[test] +fn tracked_partial_table_margins_keep_the_old_styles_other_sides() { + let body = r#""#; + let styles = r#""#; + let doc = craft_docx::read(&package(body, Some(styles))).unwrap(); + let table = doc.body[0].as_table().unwrap(); + assert_eq!(table.props.cell_margins, Some([3.0, 5.0, 0.0, 9.0])); + let old = &table.props.fmt_change.as_ref().unwrap().old; + assert_eq!( + old.cell_margins, + Some([1.0, 0.0, 2.0, 8.0]), + "explicit zero overrides left, omitted sides come from the old style, not the current one" + ); +} diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 868e8cbb0e..b1e1eff0cd 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1861,6 +1861,67 @@ fn a_link_on_an_office_2016_charts_drawing_is_kept() { } } +/// A package with one invented waterfall chart (432 x 252 pt) whose `mc:Fallback` is `fallback`. +fn chartex_text_fallback_docx(fallback: &str) -> Vec { + let chart = r#"Steps"#; + let frame = r#""#; + let body = format!( + r#"Before{frame}{fallback}"# + ); + let doc = format!(r#"{body}"#); + let doc_rels = r#""#; + let types = format!( + r#""# + ); + zip(&[ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", ROOT_RELS.as_bytes()), + ("word/document.xml", doc.as_bytes()), + ("word/_rels/document.xml.rels", doc_rels.as_bytes()), + ("word/charts/chartEx1.xml", chart.as_bytes()), + ]) +} + +/// #6820: an Office 2016 chart whose fallback is only text keeps its 432 x 252 pt place (as a +/// placeholder) instead of becoming the fallback words, and is written back unchanged. +#[test] +fn office_2016_chart_with_a_text_fallback_keeps_its_size_through_saves() { + let mut d = craft_docx::read(&chartex_text_fallback_docx("Chart not available.")).unwrap(); + for _ in 0..2 { + let g = graphics(&d); + let [InlineObject::Graphic { w, h, graphic, .. }] = g.as_slice() else { panic!("the chart is an object: {g:?}") }; + assert_eq!((*w, *h), (432.0, 252.0)); + assert_eq!((graphic.w, graphic.h), (432.0, 252.0)); + assert!( + graphic + .items + .iter() + .any(|i| matches!(i, craft_wordmodel::graphic::GraphicItem::Text { text, .. } if text.starts_with("Waterfall chart"))), + "{:?}", + graphic.items + ); + assert!(!paras(&d).iter().any(|p| p.text.contains("not available")), "the fallback words are not body text"); + let files = unzip(&craft_docx::write(&d).unwrap()); + let body = text(&files, "word/document.xml"); + assert_eq!(attr_values(&body, "wp:extent", "cx"), ["5486400"], "the chart's frame; the text fallback has none: {body}"); + assert!(body.contains("Chart not available."), "the fallback is written back as it was: {body}"); + let [cx_id] = attr_values(&body, "cx:chart", "r:id").try_into().unwrap_or_else(|_| panic!("chart lost: {body}")); + let (kind, target) = rel(&text(&files, "word/_rels/document.xml.rels"), &cx_id); + assert!(kind.ends_with("/chartEx"), "{kind}"); + assert!(text(&files, &part_at("word", &target)).contains(r#"layoutId="waterfall""#)); + let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect(); + d = craft_docx::read(&zip(&entries)).unwrap(); + } +} + +/// Guard, not fix proof (it passes before the change too): a fallback that holds a run can't be +/// written back inside the object's own run, so it is not turned into a chart placeholder. +#[test] +fn office_2016_chart_with_a_run_fallback_is_not_made_a_placeholder() { + let d = craft_docx::read(&chartex_text_fallback_docx("Chart not available.")).unwrap(); + assert!(graphics(&d).is_empty(), "{:?}", graphics(&d)); +} + #[test] fn resized_office_2016_chart_resizes_its_fallback_too() { let mut d = craft_docx::read(&chartex_docx("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex")).unwrap(); @@ -2197,6 +2258,50 @@ fn formatting_revisions_round_trip() { assert_eq!(again.revisions, d.revisions); } +#[test] +fn numbering_change_without_active_list_roundtrips() { + let body = r#"Removed"#; + let d = read_body(body); + let p = paras(&d); + assert_eq!(p.len(), 1); + assert!(p[0].props.numbering.is_none()); + let nc = p[0].props.num_change.as_deref().expect("numberingChange read back"); + assert_eq!(nc.original, "%1:1:0:."); + + let bytes = craft_docx::write(&d).unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + assert!(xml.contains(r#""#), "{xml}"); + + let again = craft_docx::read(&bytes).unwrap(); + let ap = paras(&again); + assert!(ap[0].props.numbering.is_none()); + let anc = ap[0].props.num_change.as_deref().expect("numberingChange preserved after save"); + assert_eq!(anc.original, "%1:1:0:."); +} + +#[test] +fn numbering_change_original_preserves_long_values_within_bound() { + let long_orig = "%1:1:0:.".repeat(64); // 512 chars, well past the old 256-char cap + assert!(long_orig.len() > 256 && long_orig.len() < 4096); + let over_cap = "x".repeat(5000); + let body = format!( + r#"Long +Bounded"# + ); + let d = read_body(&body); + let p = paras(&d); + assert_eq!(p[0].props.num_change.as_deref().map(|n| n.original.as_str()), Some(long_orig.as_str())); + assert_eq!(p[1].props.num_change.as_deref().map(|n| n.original.chars().count()), Some(4096)); + + let bytes = craft_docx::write(&d).unwrap(); + let again = craft_docx::read(&bytes).unwrap(); + let ap = paras(&again); + assert_eq!(ap[0].props.num_change.as_deref().map(|n| n.original.as_str()), Some(long_orig.as_str())); +} + /// A package with `styles`, a theme (accent1 4472C4, accent2 ED7D31, major font "Major Face") and, /// when given, `settings`. fn themed_docx(body: &str, styles: &str, settings: Option<&str>) -> Document { @@ -2685,6 +2790,39 @@ fn rounded_rectangle_corners_are_read_and_saved() { assert_eq!(corners(&craft_docx::read(&bytes).unwrap()), expected); } +/// A `frame` preset (a letterhead's page border) is a frame, not a filled rectangle: its border +/// width is its `adj1`, read, capped and written back as the same preset. +#[test] +fn frame_presets_keep_their_hole_and_border_width() { + let geom = + |av: &str| format!(r#"{av}"#); + let gd = |fmla: &str| format!(r#""#); + let body = [geom(&gd("val 2604")), geom(""), geom(&gd("val 90000")), geom(r#""#)] + .iter() + .map(|sppr| anchored_wsp("Frame", 2540000, 1270000, sppr, "", "")) + .collect::(); + let frames = |d: &Document| -> Vec<(ShapeKind, Option)> { + paras(d)[0] + .objects + .iter() + .filter_map(|o| match o { + InlineObject::Shape { kind, extra, .. } => Some((*kind, extra.corner)), + _ => None, + }) + .collect() + }; + let f = ShapeKind::Frame; + let expected = vec![(f, Some(2604)), (f, None), (f, Some(50_000)), (f, None)]; + let d = read_body(&format!("{body}")); + assert_eq!(frames(&d), expected); + let bytes = craft_docx::write(&d).unwrap(); + let mut xml = String::new(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + assert!(xml.contains(r#""#), "{xml}"); + assert_eq!(frames(&craft_docx::read(&bytes).unwrap()), expected); +} + /// #611: legacy VML lines and rectangles (documents without DrawingML). #[test] fn vml_lines_and_rectangles() { diff --git a/crates/docx/tests/it/kashida.rs b/crates/docx/tests/it/kashida.rs new file mode 100644 index 0000000000..02eaf2a495 --- /dev/null +++ b/crates/docx/tests/it/kashida.rs @@ -0,0 +1,136 @@ +//! Justified paragraphs keep their kashida length (`ST_Jc` `lowKashida`, `mediumKashida`, +//! `highKashida`, and ordinary `both` / `justify`) through read and write. + +use std::io::{Read, Write}; + +use std::sync::Arc; + +use craft_wordmodel::props::{Align, Kashida, ParaProps}; +use craft_wordmodel::styles::{Style, StyleKind, StyleSheet}; +use craft_wordmodel::{Document, Paragraph, para_block}; + +fn zip(entries: &[(&str, &[u8])]) -> Vec { + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in entries { + zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(bytes).unwrap(); + } + zw.finish().unwrap().into_inner() +} + +fn docx(body: &str) -> Vec { + let root = r#""#; + let doc = format!( + r#"{body}"# + ); + zip(&[("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())]) +} + +fn paras(d: &Document) -> Vec<&Paragraph> { + d.body.iter().filter_map(|b| b.as_para()).collect() +} + +fn document_xml(bytes: &[u8]) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut s = String::new(); + z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap(); + s +} + +fn jc_para(body: &str, val: &str) -> String { + format!(r#"{body}"#) +} + +#[test] +fn kashida_jc_values_are_read() { + let body = [ + jc_para("both", "both"), + jc_para("justify", "justify"), + jc_para("low", "lowKashida"), + jc_para("medium", "mediumKashida"), + jc_para("high", "highKashida"), + jc_para("left", "left"), + ] + .join(""); + let d = craft_docx::read(&docx(&body)).unwrap(); + let ps = paras(&d); + let got: Vec<_> = ps.iter().map(|p| (p.props.align, p.props.kashida)).collect(); + assert_eq!( + got, + vec![ + (Some(Align::Justify), Some(Kashida::None)), + (Some(Align::Justify), Some(Kashida::None)), + (Some(Align::Justify), Some(Kashida::Short)), + (Some(Align::Justify), Some(Kashida::Medium)), + (Some(Align::Justify), Some(Kashida::Long)), + (Some(Align::Left), None), + ] + ); +} + +#[test] +fn kashida_length_round_trips() { + let cases = [ + (Some(Kashida::None), "w:val=\"both\""), + (Some(Kashida::Short), "w:val=\"lowKashida\""), + (Some(Kashida::Medium), "w:val=\"mediumKashida\""), + (Some(Kashida::Long), "w:val=\"highKashida\""), + ]; + for (kashida, token) in cases { + let mut p = Paragraph::with_text("مثال", Default::default()); + p.props = ParaProps { align: Some(Align::Justify), kashida, ..Default::default() }; + let mut d = Document::new(); + d.body = vec![para_block(p.clone())]; + let bytes = craft_docx::write(&d).unwrap(); + let xml = document_xml(&bytes); + assert!(xml.contains(token), "expected {token} in {xml}"); + let r = craft_docx::read(&bytes).unwrap(); + let q = paras(&r)[0]; + assert_eq!(q.props.align, Some(Align::Justify)); + assert_eq!(q.props.kashida, kashida, "round-trip of {token}"); + } +} + +fn body_style(kashida: Kashida) -> StyleSheet { + let mut sheet = StyleSheet::empty(); + sheet.styles.push(Style { + id: "Body".into(), + name: "Body".into(), + kind: StyleKind::Paragraph, + para: ParaProps { align: Some(Align::Justify), kashida: Some(kashida), ..ParaProps::default() }, + ..Style::default() + }); + sheet +} + +#[test] +fn style_kashida_length_survives_a_write_when_the_paragraph_has_no_direct_jc() { + let mut p = Paragraph::with_text("مثال", Default::default()); + p.props = ParaProps { style: Some("Body".into()), ..ParaProps::default() }; + let mut d = Document::new(); + d.styles = Arc::new(body_style(Kashida::Short)); + d.body = vec![para_block(p)]; + assert_eq!(d.styles.resolve_para(&d.body[0].as_para().unwrap().props).kashida, Kashida::Short); + let bytes = craft_docx::write(&d).unwrap(); + let r = craft_docx::read(&bytes).unwrap(); + let q = paras(&r)[0]; + assert_eq!(q.props.kashida, None, "no direct w:jc on the paragraph"); + assert_eq!(r.styles.resolve_para(&q.props).kashida, Kashida::Short); +} + +#[test] +fn writing_justify_without_a_local_kashida_keeps_the_style_length() { + let mut p = Paragraph::with_text("مثال", Default::default()); + p.props = ParaProps { style: Some("Body".into()), align: Some(Align::Justify), kashida: None, ..ParaProps::default() }; + let mut d = Document::new(); + d.styles = Arc::new(body_style(Kashida::Medium)); + d.body = vec![para_block(p)]; + let bytes = craft_docx::write(&d).unwrap(); + let xml = document_xml(&bytes); + assert!(xml.contains("w:val=\"mediumKashida\""), "expected mediumKashida in {xml}"); + let r = craft_docx::read(&bytes).unwrap(); + let q = paras(&r)[0]; + assert_eq!(q.props.align, Some(Align::Justify)); + assert_eq!(q.props.kashida, Some(Kashida::Medium)); + assert_eq!(r.styles.resolve_para(&q.props).kashida, Kashida::Medium); +} diff --git a/crates/docx/tests/it/locked_canvas.rs b/crates/docx/tests/it/locked_canvas.rs new file mode 100644 index 0000000000..fb01406a4d --- /dev/null +++ b/crates/docx/tests/it/locked_canvas.rs @@ -0,0 +1,163 @@ +//! A DrawingML locked canvas (`lc:lockedCanvas`, ECMA-376 Part 1 §20.3.2.1), as Word 2007 writes +//! shapes, pictures and WordArt in a drawing in compatibility mode (wordcraft#5060). Fixtures are +//! hand-written from ECMA-376 Part 1 §20.1 (DrawingML main) and §20.3 (locked canvas). + +use std::io::Write; + +use craft_wordmodel::para::ShapeKind; +use craft_wordmodel::props::{Rgb, TextColor}; +use craft_wordmodel::{Document, InlineObject, StoryRef}; + +const NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#; + +fn docx(body: &str) -> Vec { + let doc = format!(r#"{body}"#); + let types = + r#""#; + let root = r#""#; + let rels = r#""#; + let entries: [(&str, &[u8]); 5] = [ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", root.as_bytes()), + ("word/document.xml", doc.as_bytes()), + ("word/_rels/document.xml.rels", rels.as_bytes()), + ("word/media/image1.png", "\u{89}PNG stand-in".as_bytes()), + ]; + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in entries { + zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(bytes).unwrap(); + } + zw.finish().unwrap().into_inner() +} + +/// A floating drawing, 200 × 100 pt, holding `canvas` (the locked canvas's members) in a canvas +/// whose members' space starts at 10 pt, 10 pt. +fn drawing(canvas: &str) -> String { + format!( + r#"00{canvas}"# + ) +} + +const OVAL: &str = r#""#; + +/// WordArt in a nested group: bold, all-caps red text with a green outline and a reflection, +/// 32 pt, centred, bent by a chevron warp; a second paragraph takes the list style's size, and an +/// empty third one its mark's. +const WORD_ART: &str = r#"Youngkeepers"#; + +const PICTURE: &str = r#""#; + +/// A line glued to the oval by the canvas's own id, which isn't a document shape's. +const LINE: &str = r#""#; + +fn group(d: &Document) -> (f32, f32, Vec) { + let p = d.body.iter().find_map(|b| b.as_para()).unwrap(); + match p.objects.first() { + Some(InlineObject::Group { w, h, children, canvas: None, .. }) => (*w, *h, children.clone()), + o => panic!("{o:?}"), + } +} + +/// wordcraft#5060: the locked canvas is a group of its shapes, text, picture and line, each where the +/// canvas (and the group inside it) puts it, and nothing is lost on save. +#[test] +fn a_locked_canvas_reads_as_a_group_of_its_members() { + let d = craft_docx::read(&docx(&drawing(&[OVAL, WORD_ART, PICTURE, LINE].concat()))).unwrap(); + for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] { + let (w, h, children) = group(d); + assert_eq!((w, h), (200.0, 100.0)); + let at: Vec<(f32, f32)> = children.iter().map(|c| (c.x, c.y)).collect(); + assert_eq!(at, [(0.0, 0.0), (110.0, 60.0), (0.0, 50.0), (0.0, 80.0)]); + let [oval, art, picture, line] = &children[..] else { panic!("{children:?}") }; + let InlineObject::Shape { kind: ShapeKind::Ellipse, w: 100.0, h: 50.0, fill: Some(fill), stroke: Some(stroke), .. } = &oval.obj else { + panic!("{:?}", oval.obj) + }; + assert_eq!((fill.main_color(), *stroke), (Rgb(0xFF, 0xFF, 0x66), Rgb(0, 0, 0))); + let InlineObject::Shape { kind: ShapeKind::TextBox, w: 20.0, h: 10.0, story: Some(id), extra, .. } = &art.obj else { + panic!("{:?}", art.obj) + }; + assert_eq!(extra.warp.as_ref().map(|w| w.preset.as_str()), Some("textChevron")); + assert_eq!(d.plain_text(StoryRef::Part(*id)).trim_end(), "Young\nkeepers"); + let blocks = &d.parts.get(id).unwrap().blocks; + let first = blocks[0].as_para().unwrap(); + assert_eq!(first.props.align, Some(craft_wordmodel::props::Align::Center)); + assert_eq!((first.props.space_before, first.props.space_after), (Some(0.0), Some(0.0)), "DrawingML text has no paragraph spacing"); + let run = &first.runs[0].props; + assert_eq!((run.size, run.bold, run.caps, run.color), (Some(32.0), Some(true), Some(true), Some(TextColor::Rgb(Rgb(0xFF, 0, 0))))); + assert_eq!(run.font.as_deref(), Some("Corsiva Stand-in")); + let fx = run.text_effects.as_deref().unwrap(); + let outline = fx.outline.unwrap(); + assert_eq!((outline.color, outline.width), (Some(Rgb(0, 0xFF, 0)), 0.75)); + assert!(fx.reflection.is_some(), "{fx:?}"); + assert_eq!(blocks[1].as_para().unwrap().runs[0].props.size, Some(14.0), "the list style's size"); + assert_eq!(blocks[2].as_para().unwrap().mark.size, Some(10.0), "an empty paragraph's mark"); + let InlineObject::Image { w: 50.0, h: 50.0, alt, .. } = &picture.obj else { panic!("{:?}", picture.obj) }; + assert_eq!(alt, "A logo"); + let InlineObject::Shape { kind: ShapeKind::Line, stroke: Some(blue), extra, .. } = &line.obj else { panic!("{:?}", line.obj) }; + assert_eq!((*blue, extra.start), (Rgb(0, 0, 0xFF), None), "no glue to a canvas id"); + } +} + +/// A text shape as a member of the canvas (`a:txSp`, text with no shape of its own) is a text box +/// at its own rectangle. Runs take their paragraph's own defaults (`a:pPr/a:defRPr`) before the +/// list style's for the paragraph's level. +#[test] +fn a_locked_canvas_text_shape_and_paragraph_defaults() { + let text = r#"OwnLevelFirst"#; + let d = craft_docx::read(&docx(&drawing(text))).unwrap(); + for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] { + let (_, _, children) = group(d); + let [shape] = &children[..] else { panic!("{children:?}") }; + assert_eq!((shape.x, shape.y), (40.0, 20.0)); + let InlineObject::Shape { kind: ShapeKind::TextBox, w: 100.0, h: 40.0, fill: None, stroke: None, story: Some(id), .. } = &shape.obj else { + panic!("{:?}", shape.obj) + }; + assert_eq!(d.plain_text(StoryRef::Part(*id)).trim_end(), "Own\nLevel\nFirst"); + let blocks = &d.parts.get(id).unwrap().blocks; + let run = |i: usize| blocks[i].as_para().unwrap().runs[0].props.clone(); + assert_eq!((run(0).size, run(0).italic), (Some(32.0), Some(true)), "the paragraph's own size, the level's italic"); + assert_eq!((run(1).size, run(1).italic), (Some(20.0), None), "level 2's"); + assert_eq!((run(2).size, run(2).italic), (Some(14.0), Some(true)), "level 1's"); + } +} + +/// A paragraph's alignment and its runs' properties fall back on its level's style, then on the +/// list style's defaults (`a:defPPr`); a run's bold set off stays off. +#[test] +fn a_locked_canvas_paragraph_takes_its_level_and_the_list_defaults() { + use craft_wordmodel::props::Align; + let text = r#"PlainCentredOwn"#; + let d = craft_docx::read(&docx(&drawing(text))).unwrap(); + for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] { + let (_, _, children) = group(d); + let [shape] = &children[..] else { panic!("{children:?}") }; + let InlineObject::Shape { story: Some(id), .. } = &shape.obj else { panic!("{:?}", shape.obj) }; + let blocks = &d.parts.get(id).unwrap().blocks; + let para = |i: usize| blocks[i].as_para().unwrap(); + let aligns: Vec> = (0..3).map(|i| para(i).props.align).collect(); + assert_eq!(aligns, [Some(Align::Right), Some(Align::Center), Some(Align::Left)], "the list defaults', the level's, its own"); + let runs: Vec<(Option, Option)> = (0..3).map(|i| (para(i).runs[0].props.size, para(i).runs[0].props.bold)).collect(); + assert_eq!(runs, [(Some(16.0), Some(false)), (Some(16.0), Some(true)), (Some(16.0), Some(true))]); + } +} + +/// Before wordcraft#5060 only the canvas's first picture showed: the shapes and their text were dropped. +#[test] +fn a_locked_canvas_is_not_read_as_its_picture_alone() { + let d = craft_docx::read(&docx(&drawing(&[OVAL, PICTURE].concat()))).unwrap(); + let (_, _, children) = group(&d); + assert_eq!(children.len(), 2); +} + +/// Hostile canvases never panic: no members, groups nested past the limit, text with no runs, +/// huge and broken sizes. +#[test] +fn hostile_locked_canvases_never_panic() { + let deep = format!("{}{}{}", r#""#.repeat(40), OVAL, "".repeat(40)); + let odd = r#"f"#; + for canvas in ["", deep.as_str(), odd] { + let d = craft_docx::read(&docx(&drawing(canvas))).unwrap(); + let _ = craft_docx::write(&d).unwrap(); + } +} diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index b0bab58331..6d521effb7 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -20,13 +20,16 @@ mod emphasis_marks; mod fixtures; mod glossary; mod heading_levels; +mod kashida; mod legacy_forms; mod ligatures; mod line_numbering; +mod locked_canvas; mod malformed; mod missing_pictures; mod nested_block_controls; mod note_comments; +mod partial_table_margins; mod passthrough; mod picture_links; mod positional_tabs; @@ -49,3 +52,4 @@ mod undefined_style; mod vml_shapes; mod word_xml; mod wordml2003_write; +mod wps_fallback; diff --git a/crates/docx/tests/it/partial_table_margins.rs b/crates/docx/tests/it/partial_table_margins.rs new file mode 100644 index 0000000000..7cf3c5f491 --- /dev/null +++ b/crates/docx/tests/it/partial_table_margins.rs @@ -0,0 +1,36 @@ +//! a table's partial cell margins keep the other sides. + +use std::io::Write; + +#[test] +fn a_left_only_table_margin_keeps_the_other_sides() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let root = r#""#; + let rels = r#""#; + let styles = format!( + r#""# + ); + let table = |style: &str| { + format!( + r#"{style}Cell"# + ) + }; + let document = format!(r#"{}{}"#, table(r#""#), table("")); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, data) in [ + ("_rels/.rels", root), + ("word/_rels/document.xml.rels", rels), + ("word/document.xml", document.as_str()), + ("word/styles.xml", styles.as_str()), + ] { + zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(data.as_bytes()).unwrap(); + } + let doc = craft_docx::read(&zip.finish().unwrap().into_inner()).unwrap(); + let margins: Vec<_> = doc.body.iter().filter_map(|b| b.as_table()).map(|t| t.props.cell_margins).collect(); + assert_eq!( + margins, + vec![Some([1.0, 5.35, 2.0, 8.0]), Some([0.0, 5.35, 0.0, 0.0])], + "the left side is the table's, the rest the style's (none without one: the file has no default table style)" + ); +} diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 8f3bbdd0bd..a1314c40e4 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use craft_wordmodel::numbering::ListKind; use craft_wordmodel::para::{Anchor, Float, FloatAlign, NoteKind, ShapeKind, Wrap}; use craft_wordmodel::props::{ - Align, Border, BorderStyle, Borders, CharProps, HeightRule, Highlight, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, Rgb, RowProps, - TabAlign, TabLeader, TabStop, TableLook, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign, + Align, Border, BorderStyle, Borders, CharProps, HeightRule, Highlight, Kashida, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, Rgb, + RowProps, TabAlign, TabLeader, TabStop, TableLook, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign, }; use craft_wordmodel::section::{Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, NumFormat, PageVAlign, SectionProps, SectionStart}; use craft_wordmodel::styles::{Style, StyleKind}; @@ -163,6 +163,7 @@ fn every_para_prop_round_trips() { let pp = ParaProps { style: Some("Heading1".into()), align: Some(Align::Justify), + kashida: Some(Kashida::Medium), indent_left: Some(36.0), indent_right: Some(18.0), indent_first: Some(-18.0), @@ -956,7 +957,8 @@ fn toc_field_skips_nested_stories() { let mut xml = String::new(); std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); let boxes: Vec<(usize, usize)> = xml.match_indices("").map(|(a, _)| (a, a + xml[a..].find("").unwrap())).collect(); - assert_eq!(boxes.len(), 2, "{xml}"); + // Each box twice: its shape and its VML fallback. + assert_eq!(boxes.len(), 4, "{xml}"); let in_box = |i: usize| boxes.iter().any(|(a, b)| (*a..*b).contains(&i)); for kind in ["begin", "separate", "end"] { let at: Vec = xml.match_indices(&format!(r#"fldCharType="{kind}""#)).map(|(i, _)| i).collect(); @@ -964,7 +966,7 @@ fn toc_field_skips_nested_stories() { assert!(!in_box(at[0]), "field {kind} written inside a text box: {xml}"); } let (begin, end) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap()); - assert!(begin > boxes[0].1 && end > boxes[1].1 && end < xml.find("").unwrap(), "{xml}"); + assert!(begin > boxes[1].1 && end > boxes[3].1 && end < xml.find("").unwrap(), "{xml}"); } #[test] @@ -2926,3 +2928,100 @@ fn drop_cap_options_round_trip() { (Some(4), Some(true), None, None) ); } + +/// `word/settings.xml` of a saved package. +fn settings_part(bytes: &[u8]) -> String { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap(); + xml +} + +/// Page Setup's "Gutter position: Top" (`w:gutterAtTop`) is a document setting: off by default +/// (no element), written when on after `w:mirrorMargins` and before `w:attachedTemplate`, and +/// read back; the section's own gutter width is untouched. +#[test] +fn gutter_at_top_round_trips_and_is_off_by_default() { + let plain = craft_docx::write(&Document::new()).unwrap(); + assert!(!settings_part(&plain).contains("gutterAtTop")); + assert!(!craft_docx::read(&plain).unwrap().settings.gutter_at_top); + + let mut d = Document::new(); + d.settings.gutter_at_top = true; + d.settings.mirror_margins = true; + d.settings.attached_template = Some("file:///C:/Templates/Report.dotx".into()); + d.last_section.gutter = 50.0; + let bytes = craft_docx::write(&d).unwrap(); + let xml = settings_part(&bytes); + assert_eq!(xml.matches("").count(), 1, "{xml}"); + let at = |tag: &str| xml.find(tag).unwrap_or_else(|| panic!("{tag} missing: {xml}")); + assert!(at(""#; + assert!(xml.contains(zoom), "{xml}"); + for (element, expected) in [ + ("", false), + ("", true), + (r#""#, true), + (r#""#, true), + (r#""#, true), + (r#""#, false), + (r#""#, false), + (r#""#, false), + (r#""#, false), + (r#""#, false), + ] { + let file = replace_part(&plain, "word/settings.xml", xml.replace(zoom, &format!("{zoom}{element}")).as_bytes()); + assert_eq!(craft_docx::read(&file).unwrap().settings.gutter_at_top, expected, "{element:?}"); + } +} + +/// A settings part from another writer (proofing state, rsids, document variables…) is merged on +/// save, not regenerated: `w:gutterAtTop` stays once where it was, goes when the setting is turned +/// off, and is added at its schema position (after `w:mirrorMargins`, before `w:proofState`) when +/// the file had none. +#[test] +fn gutter_at_top_is_merged_into_a_foreign_settings_part() { + let plain = craft_docx::write(&Document::new()).unwrap(); + let xml = settings_part(&plain); + let zoom = r#""#; + let foreign = |element: &str| { + let extra = + format!(r#"{zoom}{element}"#); + replace_part(&plain, "word/settings.xml", xml.replace(zoom, &extra).as_bytes()) + }; + + let with = craft_docx::read(&foreign("")).unwrap(); + assert!(with.settings.gutter_at_top && with.settings.mirror_margins); + let saved = settings_part(&craft_docx::write(&with).unwrap()); + assert_eq!(saved.matches("").count(), 1, "{saved}"); + assert!(saved.contains("").count(), 1, "{saved}"); + let at = |tag: &str| saved.find(tag).unwrap_or_else(|| panic!("{tag} missing: {saved}")); + assert!(at(" String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut s = String::new(); + z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap(); + s +} + +fn shape(kind: ShapeKind, story: Option) -> InlineObject { + let float = craft_wordmodel::para::Float { + wrap: Wrap::Square, + h_rel: Anchor::Margin, + h_align: Some(FloatAlign::End), + v_rel: Anchor::Paragraph, + y: 0.05, + ..Default::default() + }; + InlineObject::Shape { + kind, + w: 10.7, + h: 12.2, + fill: None, + stroke: None, + stroke_width: 0.75, + float, + story, + effects: Default::default(), + freeform: None, + extra: Default::default(), + } +} + +/// A page number in a floating text box, as in a footer: the shape that made the +/// Compatibility Pack refuse the file. +#[test] +fn a_text_box_gets_a_vml_fallback_with_its_text() { + let mut d = Document::from_text("a"); + let id = d.add_part(PartKind::TextBox, vec![para_block(craft_wordmodel::Paragraph::with_text("29", Default::default()))]); + d.parts.get_mut(&id).unwrap().body = TextBody { auto_fit: true, inset: Some([0; 4]), ..Default::default() }; + let mut o = shape(ShapeKind::TextBox, Some(id)); + if let InlineObject::Shape { float, .. } = &mut o { + (float.dist, float.dist_top, float.dist_bottom) = (18.0, 12.0, 6.0); + } + d.insert_object(&craft_wordmodel::Pos::body(0, 1), o, &Default::default()).unwrap(); + let bytes = craft_docx::write(&d).unwrap(); + let xml = document_xml(&bytes); + assert!(xml.contains(r#""#), "{xml}"); + assert!(!xml.contains(""), "no bare Word 2010 shape: {xml}"); + let fallback = &xml[xml.find("").expect("a fallback")..]; + assert!(fallback.starts_with(""#, + r#""#, + ] { + assert!(fallback.contains(want), "{want} in {fallback}"); + } + assert_eq!(xml.matches(">29").count(), 2, "the text in the choice and again in the fallback"); + + // Read back: the choice, once. + let r = craft_docx::read(&bytes).unwrap(); + let mut boxes = Vec::new(); + r.objects_in_reading_order(&mut |o| boxes.extend(o.text_boxes())); + boxes.retain(|id| r.parts.get(id).is_some_and(|p| p.kind == PartKind::TextBox)); + assert_eq!(boxes.len(), 1, "one text box, not the fallback as well"); + assert_eq!(r.plain_text(craft_wordmodel::StoryRef::Part(boxes[0])), "29"); +} + +/// The fallback keeps the box's own stacking order (not that of a floating object inside it), +/// its hidden flag and its text direction. +#[test] +fn the_fallback_keeps_order_visibility_and_direction() { + let mut d = Document::from_text("a"); + let inner = d.add_part(PartKind::TextBox, vec![para_block(craft_wordmodel::Paragraph::with_text("inner", Default::default()))]); + let mut nested = shape(ShapeKind::TextBox, Some(inner)); + if let InlineObject::Shape { float, .. } = &mut nested { + float.z = 100; + } + let mut p = craft_wordmodel::Paragraph::with_text("outer", Default::default()); + p.insert_object(0, nested, &Default::default()).unwrap(); + let outer = d.add_part(PartKind::TextBox, vec![para_block(p)]); + d.parts.get_mut(&outer).unwrap().body = TextBody { vert: TextVert::Vert270, ..Default::default() }; + let mut o = shape(ShapeKind::TextBox, Some(outer)); + if let InlineObject::Shape { float, .. } = &mut o { + float.z = 10; + float.hidden = true; + } + d.insert_object(&craft_wordmodel::Pos::body(0, 1), o, &Default::default()).unwrap(); + let xml = document_xml(&craft_docx::write(&d).unwrap()); + // The outer box's VML: the `v:rect` holding the vertical text box (the inner box's fallback + // is copied into the outer one's text, so it comes after it). + let tb = xml.find(r#""#).expect("the outer box's text, turned"); + let rect = &xml[xml[..tb].rfind(" = xml + .match_indices("z-index:") + .map(|(i, m)| { + let v = &xml[i + m.len()..]; + v[..v.find([';', '"']).unwrap()].parse().unwrap() + }) + .collect(); + got.sort_unstable(); + let low = -(1i64 << 31); + assert_eq!(got, vec![low + 10, low + 20, -1], "{xml}"); +} + +/// A shape VML has no simple form for stays a bare `wps:wsp`: guarded without a fallback, an old +/// reader would open the file without it and drop it on its next save. +#[test] +fn a_shape_without_a_vml_form_is_not_guarded() { + let mut d = Document::from_text("a"); + d.insert_object(&craft_wordmodel::Pos::body(0, 1), shape(ShapeKind::Star, None), &Default::default()).unwrap(); + let bytes = craft_docx::write(&d).unwrap(); + let xml = document_xml(&bytes); + assert!(xml.contains("") && xml.contains(r#""#), "{xml}"); + assert!(!xml.contains(""), "{xml}"); + let r = craft_docx::read(&bytes).unwrap(); + let mut kinds = Vec::new(); + r.objects_in_reading_order(&mut |o| { + if let InlineObject::Shape { kind, .. } = o { + kinds.push(*kind); + } + }); + assert_eq!(kinds, vec![ShapeKind::Star]); +} + +/// A partial fallback must not turn a linked story into independent boxes in older readers. +#[test] +fn linked_boxes_stay_bare_while_unlinked_boxes_keep_their_fallback() { + let mut d = Document::from_text("a\nb\nc\nd"); + let mut ids = Vec::new(); + for (i, text) in ["Flows on", "", "", "Independent"].into_iter().enumerate() { + let id = d.add_part(PartKind::TextBox, vec![para_block(craft_wordmodel::Paragraph::with_text(text, Default::default()))]); + ids.push(id); + d.insert_object(&craft_wordmodel::Pos::body(i, 1), shape(ShapeKind::TextBox, Some(id)), &Default::default()).unwrap(); + } + d.parts.get_mut(&ids[0]).unwrap().body.next = Some(ids[1]); + d.parts.get_mut(&ids[1]).unwrap().body.next = Some(ids[2]); + let bytes = craft_docx::write(&d).unwrap(); + let xml = document_xml(&bytes); + assert_eq!(xml.matches("").count(), 1, "{xml}"); + assert_eq!(xml.matches("").count(), 1, "{xml}"); + let fallback = xml.split("").nth(1).unwrap().split("").next().unwrap(); + assert!(fallback.contains(">Independent"), "{fallback}"); + assert!(!fallback.contains("Flows on"), "the chain head must not get an unlinked fallback"); + assert_eq!(xml.matches(">Flows on").count(), 1); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + let read = craft_docx::read(&bytes).unwrap(); + let chains = read.text_box_chains(); + assert_eq!(chains.len(), 1); + assert_eq!(chains[0].len(), 3); + assert_eq!(read.plain_text(craft_wordmodel::StoryRef::Part(chains[0][0])), "Flows on"); +} diff --git a/crates/dpx/src/lib.rs b/crates/dpx/src/lib.rs index a762566f8f..26d9e8656f 100644 --- a/crates/dpx/src/lib.rs +++ b/crates/dpx/src/lib.rs @@ -34,6 +34,9 @@ //! Input is treated as hostile: every header read is bounds-checked, the picture size is capped //! by [`Limits`] and the image data must be present in full before anything is allocated. +/// RGBA8-to-10-bit DPX encoding. +pub mod rgba8_dpx10; + #[cfg(test)] mod tests; diff --git a/crates/dpx/src/rgba8_dpx10.rs b/crates/dpx/src/rgba8_dpx10.rs new file mode 100644 index 0000000000..8dec304eca --- /dev/null +++ b/crates/dpx/src/rgba8_dpx10.rs @@ -0,0 +1,122 @@ +//! Uncompressed RGB(A) output from top-down RGBA8 pixels. +/// Why the supplied frame cannot be encoded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Rgba8EncodeError { + /// Empty, overflowing, or mismatched dimensions. + FrameSize, + /// A dimension cannot fit the output format. + TooLarge, + /// The output buffer could not be allocated. + OutOfMemory, +} +/// Reserves the DPX output up front; a failed reservation becomes [`Rgba8EncodeError::OutOfMemory`]. +fn output_buffer(size: usize) -> std::result::Result, Rgba8EncodeError> { + let mut buf = Vec::new(); + match buf.try_reserve_exact(size) { + Ok(()) => Ok(buf), + Err(_) => Err(Rgba8EncodeError::OutOfMemory), + } +} +fn checked_len(rgba: &[u8], w: u32, h: u32) -> std::result::Result { + let n = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or(Rgba8EncodeError::FrameSize)?; + if w == 0 || h == 0 || rgba.len() != n { + return Err(Rgba8EncodeError::FrameSize); + } + Ok(n) +} +/// Header size of the DPX files we write (file + image + orientation + film + TV headers). +const DPX_HEADER: usize = 2048; + +/// A DPX file: 10-bit RGB (8-bit values widened by bit replication, so 0 → 0 and 255 → 1023). +pub fn encode_rgba8_dpx10(rgba: &[u8], w: u32, h: u32, creator: &str) -> std::result::Result, Rgba8EncodeError> { + let n = checked_len(rgba, w, h)?; + // one 32-bit word per pixel; `n` is already `w * h * 4` + let size = n.checked_add(DPX_HEADER).ok_or(Rgba8EncodeError::FrameSize)?; + let file_size = u32::try_from(size).map_err(|_| Rgba8EncodeError::TooLarge)?; + // SMPTE ST 268: undefined numeric fields are all ones, undefined text fields are NUL + let mut hd = vec![0xFF_u8; DPX_HEADER]; + for (a, b) in [ + (36, 660), // file name, creation time, creator, project, copyright + (664, 768), // reserved + (1356, 1408), // reserved + (1432, 1620), // source file name, time, input device, serial number + (1644, 1664), // reserved + (1664, 1712), // film manufacturer, type, offset, prefix, count, format + (1732, 1920), // frame id, slate, reserved + (1972, 2048), // reserved + ] { + hd[a..b].fill(0); + } + for e in 0..8 { + let d = 780 + e * 72 + 40; + hd[d..d + 32].fill(0); // element descriptions + } + let put32 = |hd: &mut Vec, at: usize, v: u32| hd[at..at + 4].copy_from_slice(&v.to_be_bytes()); + let put16 = |hd: &mut Vec, at: usize, v: u16| hd[at..at + 2].copy_from_slice(&v.to_be_bytes()); + // file information header + hd[0..4].copy_from_slice(b"SDPX"); + put32(&mut hd, 4, DPX_HEADER as u32); // offset to the image data + hd[8..16].copy_from_slice(b"V2.0\0\0\0\0"); + put32(&mut hd, 16, file_size); + put32(&mut hd, 20, 1); // ditto key: new frame + put32(&mut hd, 24, 1664); // generic header length + put32(&mut hd, 28, 384); // industry header length + put32(&mut hd, 32, 0); // user data length + let creator = creator.as_bytes(); + let n = creator.len().min(100); + hd[160..160 + n].copy_from_slice(&creator[..n]); + // image information header + put16(&mut hd, 768, 0); // orientation: left to right, top to bottom + put16(&mut hd, 770, 1); // one image element + put32(&mut hd, 772, w); + put32(&mut hd, 776, h); + let el = 780; + put32(&mut hd, el, 0); // unsigned + put32(&mut hd, el + 4, 0); // reference low data code + put32(&mut hd, el + 12, 1023); // reference high data code + hd[el + 20] = 50; // descriptor: RGB + hd[el + 21] = 6; // transfer: ITU-R BT.709 + hd[el + 22] = 6; // colorimetric: ITU-R BT.709 + hd[el + 23] = 10; // bit depth + put16(&mut hd, el + 24, 1); // packing: filled to 32-bit words, method A + put16(&mut hd, el + 26, 0); // no encoding (uncompressed) + put32(&mut hd, el + 28, DPX_HEADER as u32); // offset to the element's data + put32(&mut hd, el + 32, 0); // end-of-line padding + put32(&mut hd, el + 36, 0); // end-of-image padding + // image orientation header: no offset, square pixels + put32(&mut hd, 1408, 0); + put32(&mut hd, 1412, 0); + put32(&mut hd, 1424, w); + put32(&mut hd, 1428, h); + put32(&mut hd, 1628, 1); + put32(&mut hd, 1632, 1); + // television header: progressive + hd[1928] = 0; + // The caller already holds the frame; reserve the output fallibly so a large export reports + // an error instead of aborting the process. + let mut out = output_buffer(size)?; + out.extend_from_slice(&hd); + let ten = |v: u8| (u32::from(v) << 2) | (u32::from(v) >> 6); + for &[r, g, b, _] in rgba.as_chunks::<4>().0 { + out.extend_from_slice(&((ten(r) << 22) | (ten(g) << 12) | (ten(b) << 2)).to_be_bytes()); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn packed_rgb_and_creator() { + let bytes = encode_rgba8_dpx10(&[255, 0, 128, 255], 1, 1, "FilmCraft").unwrap(); + assert_eq!(&bytes[..4], b"SDPX"); + assert_eq!(&bytes[160..169], b"FilmCraft"); + assert_eq!(&bytes[2048..], &((1023u32 << 22) | (514u32 << 2)).to_be_bytes()); + assert_eq!(encode_rgba8_dpx10(&[], 0, 1, ""), Err(Rgba8EncodeError::FrameSize)); + } + #[test] + fn output_reservation_failure_maps_to_out_of_memory() { + assert!(matches!(output_buffer(usize::MAX), Err(Rgba8EncodeError::OutOfMemory))); + assert_eq!(output_buffer(DPX_HEADER).map(|b| b.capacity() >= DPX_HEADER), Ok(true)); + } +} diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index e575d10f22..9475d20548 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -354,6 +354,10 @@ pub struct Chart { pub legend: Option, /// `c:legend/c:overlay`: the legend is drawn over the plot instead of shrinking it. pub legend_overlay: bool, + /// `c:legend/c:legendEntry`: entries whose text has its own size, weight or colour, over + /// the legend's. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub legend_entries: Vec, /// Text size in points of the axis labels and legend (from their `c:txPr`, else the chart's); /// `None`: the file gives none. #[serde(skip_serializing_if = "Option::is_none")] @@ -431,6 +435,21 @@ pub struct Chart { pub kept: ChartKept, } +/// One legend entry's own text (`c:legendEntry/c:txPr`): what it sets wins over the legend's. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct LegendEntry { + /// The entry's place in the legend, from 0 (`c:idx`). + pub idx: u32, + /// Text size in points. + #[serde(skip_serializing_if = "Option::is_none")] + pub size: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub bold: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub color: Option, +} + /// One relationship of a chart part, with the target string as it was written. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -483,6 +502,7 @@ impl Default for Chart { series: vec![], legend: Some("b".into()), legend_overlay: false, + legend_entries: vec![], text_size: None, title_size: None, data_labels: false, diff --git a/crates/drawingml/src/chart/read.rs b/crates/drawingml/src/chart/read.rs index 38ce9f605d..3f2be736f8 100644 --- a/crates/drawingml/src/chart/read.rs +++ b/crates/drawingml/src/chart/read.rs @@ -143,6 +143,7 @@ fn chart_within(root: &El, mut budget: usize) -> Option { c.legend = ch.child(Local("legend")).map(|l| l.child(Local("legendPos")).and_then(|c| c.attr_local("val")).unwrap_or("r").to_string()); c.legend_overlay = ch.child(Local("legend")).and_then(|l| l.child(Local("overlay"))).and_then(|o| o.attr_local("val").and_then(value::to_bool)).unwrap_or(false); + c.legend_entries = legend_entries(ch.child(Local("legend"))); c.chart_fill = simple_fill(root.child(Local("spPr"))); c.plot_fill = simple_fill(pa.child(Local("spPr"))); @@ -552,6 +553,52 @@ fn text_color(e: Option<&El>) -> Option { rec(e?, 0) } +/// Legend entries read from one chart; a legend lists at most one per series or category. +const MAX_LEGEND_ENTRIES: usize = 1024; + +/// The legend's entries with text of their own (`c:legendEntry/c:txPr`), over the legend's. +fn legend_entries(legend: Option<&El>) -> Vec { + legend + .into_iter() + .flat_map(|l| l.children(Local("legendEntry"))) + .take(MAX_LEGEND_ENTRIES) + .filter_map(|e| { + // The paragraph's own run properties first, then the list style's defaults + // (`a:lstStyle` comes before `a:p`, and is the less specific of the two). + let tx = e.child(Local("txPr")); + let para = tx.and_then(|t| t.child(Local("p"))); + let entry = crate::chart::LegendEntry { + idx: e.child(Local("idx")).and_then(|i| i.attr_local("val")).and_then(|v| v.parse().ok())?, + size: text_size(para).or_else(|| text_size(tx)), + bold: text_bold(para).or_else(|| text_bold(tx)), + color: text_color(para).or_else(|| text_color(tx)), + }; + (entry.size.is_some() || entry.bold.is_some() || entry.color.is_some()).then_some(entry) + }) + .collect() +} + +/// The weight (`b`) of the first `a:defRPr` or `a:rPr` that sets one under `e`. +fn text_bold(e: Option<&El>) -> Option { + fn rec(e: &El, depth: usize) -> Option { + if depth > 8 { + return None; + } + for c in e.elements() { + if (c.is(Local("defRPr")) || c.is(Local("rPr"))) + && let Some(b) = c.attr_local("b").and_then(value::to_bool) + { + return Some(b); + } + if let Some(v) = rec(c, depth + 1) { + return Some(v); + } + } + None + } + rec(e?, 0) +} + /// The size in points of the first `a:defRPr` or `a:rPr` with one under `e` (`sz` in hundredths). fn text_size(e: Option<&El>) -> Option { fn rec(e: &El, depth: usize) -> Option { diff --git a/crates/drawingml/src/chart/write.rs b/crates/drawingml/src/chart/write.rs index d115c4a2cf..6993a6d219 100644 --- a/crates/drawingml/src/chart/write.rs +++ b/crates/drawingml/src/chart/write.rs @@ -101,6 +101,38 @@ fn tx_pr(w: &mut Writer, c: &Chart) { w.close(); } +/// `c:legendEntry` with the entry's own text size, weight and colour. +fn legend_entry(w: &mut Writer, e: &crate::chart::LegendEntry) { + w.open("c:legendEntry", &[]); + w.tag("c:idx").attr("val", e.idx).empty(); + w.open("c:txPr", &[]); + w.empty("a:bodyPr", &[]); + w.empty("a:lstStyle", &[]); + w.open("a:p", &[]); + w.open("a:pPr", &[]); + let mut run = w.tag("a:defRPr"); + if let Some(sz) = e.size.filter(|v| v.is_finite() && *v > 0.0) { + // 1 to 400 pt, as the reader takes it, so a size reads back as written. + run = run.attr("sz", (sz * 100.0).round().clamp(100.0, 40_000.0) as u32); + } + if let Some(b) = e.bold { + run = run.attr("b", u8::from(b)); + } + match &e.color { + Some(c) => { + run.open(); + dml::solid(w, c); + w.close(); + } + None => run.empty(), + } + w.close(); + w.tag("a:endParaRPr").attr("lang", "en-US").empty(); + w.close(); + w.close(); + w.close(); +} + fn rich(w: &mut Writer, text: &str, color: Option<&crate::style::ColorRef>) { w.open("c:tx", &[]); w.open("c:rich", &[]); @@ -781,6 +813,9 @@ pub fn chart_xml(c: &Chart) -> (Vec, bool) { }; w.open("c:legend", &[]); w.tag("c:legendPos").attr("val", p).empty(); + for e in &c.legend_entries { + legend_entry(&mut w, e); + } w.tag("c:overlay").attr("val", u8::from(c.legend_overlay)).empty(); tx_pr(&mut w, c); w.close(); @@ -1058,6 +1093,72 @@ mod tests { use crate::color::{ColorTransform, Rgba}; use crate::style::ColorRef; + /// A legend entry's own text (`c:legendEntry/c:txPr`: size, bold, colour) is read, and a + /// rebuilt part writes it back, in schema order before `c:overlay` (DeckCraft #2067). + #[test] + fn legend_entry_text_is_read_and_survives_an_edit() { + let read = |xml: &[u8]| crate::chart::read::read_chart_xml(xml).unwrap(); + let entry = |idx: u32, rgb: &str| { + format!( + r#""# + ) + }; + let xml = format!( + r#"1{}{}"#, + entry(0, "C00000"), + entry(1, "00B050") + ); + let c = read(xml.as_bytes()); + let want = |idx: u32, rgb: (u8, u8, u8)| crate::chart::LegendEntry { + idx, + size: Some(20.0), + bold: Some(true), + color: Some(ColorRef::rgb(Rgba::rgb(rgb.0, rgb.1, rgb.2))), + }; + // The third entry sets nothing of its own and is not kept. + assert_eq!(c.legend_entries, vec![want(0, (0xC0, 0, 0)), want(1, (0, 0xB0, 0x50))]); + assert_eq!(c.text_size, Some(12.0), "the legend's own size stays the legend's"); + let mut e = c.clone(); + e.title = Some("Units".into()); + e.raw = None; + let (out, kept) = super::chart_xml(&e); + assert!(!kept); + let s = String::from_utf8(out.clone()).unwrap(); + let legend = &s[s.find("").unwrap()..]; + let (pos, entry0, overlay) = + (legend.find("").unwrap(), legend.find(""#, + r#""#, + 1, + ); + assert_ne!(listed, xml, "the list style was put in"); + let c = read(listed.as_bytes()); + assert_eq!(c.legend_entries[0], want(0, (0xC0, 0, 0)), "the paragraph's 20 pt, bold, C00000"); + // The list style alone still counts. + let only_list = + listed.replacen(r#""#, "", 1); + let entry = &read(only_list.as_bytes()).legend_entries[0]; + assert_eq!((entry.size, entry.bold), (Some(12.0), Some(false))); + // A size reads back as it was written, within the reader's 1-400 pt. + for (size, back) in [(20.5, 20.5), (400.0, 400.0), (500.0, 400.0)] { + let mut e = c.clone(); + e.raw = None; + e.legend_entries = vec![crate::chart::LegendEntry { idx: 0, size: Some(size), bold: Some(false), color: None }]; + let written = super::chart_xml(&e).0; + let sz = format!(r#"sz="{}""#, (back * 100.0) as u32); + assert!(String::from_utf8_lossy(&written).contains(&sz), "{size} pt is written as {sz}"); + let back_entry = &read(&written).legend_entries[0]; + assert_eq!((back_entry.size, back_entry.bold), (Some(back), Some(false)), "{size} pt"); + } + } + #[test] fn export_cost_counts_the_caches_each_group_writes() { let s = Series { values: vec![Some(1.0); 600], ..Default::default() }; diff --git a/crates/drawingml/src/numfmt.rs b/crates/drawingml/src/numfmt.rs index b5db9667c0..7a7b866650 100644 --- a/crates/drawingml/src/numfmt.rs +++ b/crates/drawingml/src/numfmt.rs @@ -234,16 +234,18 @@ fn sci(toks: &[Tok], v: f64, sep: char, dec: char) -> Option { m *= 10.0; exp -= 1; } - // Rounding the mantissa to its digits can reach 10 (9.999 as `0.00`). - if format!("{m:.mant_frac$}").starts_with("10") { - m /= 10.0; - exp += 1; - } } let step = mant.iter().take_while(|t| **t != Tok::Dot).filter(|t| matches!(t, Tok::Digit(_))).count().max(1) as i32; let shift = exp.rem_euclid(step); exp -= shift; m *= 10f64.powi(shift); + // Round after forming the engineering mantissa: 999.94 as `##0.0` stays 999.9. + // Carry only when rounding exceeds all of the format's integer placeholders. + let carry = 10f64.powi(step); + if format!("{m:.mant_frac$}").parse::().is_ok_and(|rounded| rounded >= carry) { + m /= carry; + exp += step; + } let mantissa = fixed(mant, mfirst, mlast, m, sep, dec); let sign = if exp < 0 { "-" @@ -404,6 +406,21 @@ mod tests { assert_eq!(format("##0.0E+0", 999.96, None), "1.0E+3"); } + #[test] + fn engineering_formats_round_the_full_mantissa() { + for (code, value, expected) in [ + ("##0.0E+00", 999.94, "999.9E+00"), + ("##0.0E+00", 0.99994, "999.9E-03"), + ("##0.0E+00", -999.94, "-999.9E+00"), + ("#0.0E+00", 99.94, "99.9E+00"), + ("##0.0E+00", 999.96, "1.0E+03"), + ("#0.0E+00", 99.96, "1.0E+02"), + ] { + assert_eq!(format(code, value, None), expected, "{code}, {value}"); + } + assert_eq!(format("##0.0E+00", 999.94, Some("de-DE")), "999,9E+00"); + } + #[test] fn never_panics() { for code in ["", ";", ";;;", "\"", "[", "\\", "0.", ".", "#,", "%", "_", "*", "@", "0E+00", "[$", "\"unterminated"] { diff --git a/crates/drawingml/src/part.rs b/crates/drawingml/src/part.rs index 27215f85d4..af2f6b736b 100644 --- a/crates/drawingml/src/part.rs +++ b/crates/drawingml/src/part.rs @@ -239,4 +239,129 @@ mod tests { assert_eq!(back.extra.len(), MAX_EXTRA_COLORS); assert_eq!(back.extra[0].tints.as_deref(), Some(&long[..MAX_TINT_ROWS])); } + + const THEME_FILE: &str = r#" + + + + + +"#; + + fn theme_round_trip(t: &Theme) -> (String, Theme) { + let xml = String::from_utf8(crate::theme::theme_xml(&mut Part::new(), t)).unwrap(); + let back = crate::theme::read_theme(&mut Part::new(), &parse(xml.as_bytes()).unwrap()); + (xml, back) + } + + #[test] + fn a_theme_keeps_system_colours_custom_colours_family_id_and_font_panose() { + let t = crate::theme::read_theme(&mut Part::new(), &parse(THEME_FILE.as_bytes()).unwrap()); + assert_eq!(t.sys_colors.len(), 2); + let (xml, back) = theme_round_trip(&t); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains("Brand red") && xml.contains("C00000") && xml.contains("Brand teal") && xml.contains("008080"), "{xml}"); + assert!( + xml.contains("thm15:themeFamily") + && xml.contains("{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}") + && xml.contains("{4A3C46E8-61CC-4603-A589-7422A47A8E4A}"), + "{xml}" + ); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert_eq!( + (&back.sys_colors, &back.colors.colors, &back.fonts, &back.raw_extra), + (&t.sys_colors, &t.colors.colors, &t.fonts, &t.raw_extra), + "read, write, read changes nothing" + ); + // Order: the colour list comes before the extension list, both after the theme elements. + let at = |n: &str| xml.find(n).unwrap_or_else(|| panic!("{n} in {xml}")); + assert!(at("") < at("") && at("") < at(""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + let (plain, back) = theme_round_trip(&Theme::default()); + assert!(!plain.contains("sysClr") && !plain.contains("custClrLst") && !plain.contains("themeFamily") && !plain.contains("panose"), "{plain}"); + assert!(back.sys_colors.is_empty() && back.fonts.minor.latin_attrs.is_empty()); + } + + #[test] + fn font_panose_is_dropped_when_the_typeface_changes() { + let mut t = crate::theme::read_theme(&mut Part::new(), &parse(THEME_FILE.as_bytes()).unwrap()); + t.fonts.minor.latin = "Arial".into(); + let (xml, _) = theme_round_trip(&t); + assert!(xml.contains(r#""#), "{xml}"); + assert!(!xml.contains("020F0502020204030204"), "{xml}"); + assert!(xml.contains(r#""#, r#""#) + .replace(r#""#, r#""#); + let t = crate::theme::read_theme(&mut Part::new(), &parse(file.as_bytes()).unwrap()); + let (xml, _) = theme_round_trip(&t); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + } + + #[test] + fn custom_colours_and_family_id_without_object_defaults_follow_an_empty_one() { + let file = THEME_FILE.replace("", ""); + let t = crate::theme::read_theme(&mut Part::new(), &parse(file.as_bytes()).unwrap()); + let (xml, back) = theme_round_trip(&t); + let at = |n: &str| xml.find(n).unwrap_or_else(|| panic!("{n} in {xml}")); + assert!(at("") < at(""), "{xml}"); + assert!(at("") < at(""#; + let ls = crate::read::list_style(&mut Part::new(), &parse(src.as_bytes()).unwrap()); + let d = ls.default_level.as_ref().expect("defPPr read"); + assert_eq!( + (d.para.margin_left, d.para.align, d.run.lang.as_deref(), d.run.size), + (Some(36.0), Some(crate::text::Align::Center), Some("de-DE"), Some(18.0)) + ); + assert_eq!(ls.level(0).and_then(|l| l.run.size), Some(44.0)); + for tag in ["p:defaultTextStyle", "p:titleStyle", "p:bodyStyle", "p:otherStyle", "p:notesStyle", "a:lstStyle"] { + let mut w = craft_xml::Writer::new(); + crate::write::list_style(&mut w, &mut Part::new(), tag, &ls); + let xml = format!(r#"{}"#, w.finish()); + assert!(xml.find("{}"#, w.finish()); + let back = crate::read::text_body(&mut Part::new(), parse(xml.as_bytes()).unwrap().child(craft_xml::Local("txBody")).unwrap()); + assert_eq!(back.list_style, ls); + let empty = ListStyle { default_level: Some(Box::default()), ..Default::default() }; + assert!(!empty.is_empty()); + let mut w = craft_xml::Writer::new(); + crate::write::list_style(&mut w, &mut Part::new(), "p:defaultTextStyle", &empty); + assert_eq!(w.finish(), ""); + // Without `a:defPPr` none is written. + let mut w = craft_xml::Writer::new(); + crate::write::list_style(&mut w, &mut Part::new(), "p:defaultTextStyle", &ListStyle { default_level: None, ..ls }); + assert!(!w.finish().contains("defPPr")); + } } diff --git a/crates/drawingml/src/read.rs b/crates/drawingml/src/read.rs index 9e9f8ff3e6..f26bf20737 100644 --- a/crates/drawingml/src/read.rs +++ b/crates/drawingml/src/read.rs @@ -623,6 +623,11 @@ pub fn list_style(src: &mut dyn Source, ls: &El) -> ListStyle { let mut out = ListStyle::default(); for e in ls.elements() { let n = e.local(); + if n == "defPPr" { + let (_, para, run) = ppr(src, e); + out.default_level = Some(Box::new(LevelStyle { para, run: run.unwrap_or_default() })); + continue; + } let Some(l) = n.strip_prefix("lvl").and_then(|r| r.strip_suffix("pPr")).and_then(|d| d.parse::().ok()) else { continue }; if !(1..=9).contains(&l) { continue; diff --git a/crates/drawingml/src/text.rs b/crates/drawingml/src/text.rs index f60f232361..dc34cf10fa 100644 --- a/crates/drawingml/src/text.rs +++ b/crates/drawingml/src/text.rs @@ -706,6 +706,12 @@ pub struct LevelStyle { pub struct ListStyle { /// Levels 1–9 (index 0–8); `None` = not specified. pub levels: Vec>, + /// The default paragraph style (`a:defPPr`) that sits under levels 1–9; `None` = the list + /// style has no `a:defPPr`. Boxed: it sits inline in every `ListStyle`, hence in every text + /// body and shape, and the recursive group readers (pptx) would otherwise overflow the stack + /// of a debug build on Windows (1 MiB main thread) at the nesting depth the tests cut at. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_level: Option>, } impl ListStyle { @@ -722,7 +728,7 @@ impl ListStyle { } } pub fn is_empty(&self) -> bool { - self.levels.iter().all(Option::is_none) + self.default_level.is_none() && self.levels.iter().all(Option::is_none) } } @@ -759,6 +765,14 @@ mod tests { use super::*; use crate::color::Rgba; + /// `ListStyle` sits inline in every `TextBody`/`Shape`, which the pptx group reader holds on the + /// stack once per nesting level. Keep it at `Vec` (24) + `Option` (8) bytes (the `defPPr` + /// level is boxed) so a debug build does not overflow the 1 MiB Windows main-thread stack. + #[test] + fn list_style_stays_small() { + assert!(std::mem::size_of::() <= 32, "{}", std::mem::size_of::()); + } + #[test] fn alternate_language_inherits_and_native_input_is_bounded() { let mut child = RunProps::default(); diff --git a/crates/drawingml/src/theme.rs b/crates/drawingml/src/theme.rs index 69d7c2af69..bfe435be97 100644 --- a/crates/drawingml/src/theme.rs +++ b/crates/drawingml/src/theme.rs @@ -11,11 +11,37 @@ pub struct FontSet { pub latin: String, pub ea: String, pub cs: String, + /// The `panose`, `pitchFamily` and `charset` the file gives the Latin, East Asian and complex + /// script typefaces; `None` = the attribute is absent. + #[serde(skip_serializing_if = "TypefaceAttrs::is_empty")] + pub latin_attrs: TypefaceAttrs, + #[serde(skip_serializing_if = "TypefaceAttrs::is_empty")] + pub ea_attrs: TypefaceAttrs, + #[serde(skip_serializing_if = "TypefaceAttrs::is_empty")] + pub cs_attrs: TypefaceAttrs, /// Per-script typefaces (`a:font script="Arab" typeface="…"`), in document order. #[serde(skip_serializing_if = "Vec::is_empty")] pub scripts: Vec, } +/// The font-matching attributes of a theme typeface (`a:latin`, `a:ea`, `a:cs`). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct TypefaceAttrs { + /// The typeface name these attributes belong to; the writer drops them once the typeface changed. + pub typeface: String, + /// Ten hex byte pairs, as written. + pub panose: Option, + pub pitch_family: Option, + pub charset: Option, +} + +impl TypefaceAttrs { + pub fn is_empty(&self) -> bool { + self.panose.is_none() && self.pitch_family.is_none() && self.charset.is_none() + } +} + /// A theme font for one script (ISO 15924 tag, e.g. `Arab`). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -53,6 +79,17 @@ pub struct FormatScheme { pub bg_fills: Vec, } +/// A colour slot written as a system colour (``). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SysColor { + pub slot: SchemeSlot, + /// The `val` (`windowText`, `window`…). + pub name: String, + /// The `lastClr`. + pub last: Rgba, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Theme { @@ -60,7 +97,14 @@ pub struct Theme { pub colors: ColorScheme, pub fonts: FontScheme, pub format: FormatScheme, - /// Raw theme XML extras kept for round-trip (object defaults, extra colour lists). + /// The colour slots the file wrote as `a:sysClr` (`dk1` `windowText`, `lt1` `window`), in + /// document order. The writer keeps a slot as `a:sysClr` while its colour still equals + /// `last`; a slot whose colour was changed is written as `a:srgbClr`. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub sys_colors: Vec, + /// Raw theme XML extras kept for round-trip, in document order: object defaults, extra + /// colour lists, custom colours (`a:custClrLst`) and the extension list (`a:extLst`, which + /// holds the theme family id). #[serde(skip_serializing_if = "Option::is_none")] pub raw_extra: Option, } @@ -76,6 +120,7 @@ impl Default for Theme { colors: ColorScheme::new("Default", colors.map(hex)), fonts: FontScheme::default(), format: default_format(), + sys_colors: Vec::new(), raw_extra: None, } } diff --git a/crates/drawingml/src/theme/read.rs b/crates/drawingml/src/theme/read.rs index 29e49dc933..0f4e4b2f07 100644 --- a/crates/drawingml/src/theme/read.rs +++ b/crates/drawingml/src/theme/read.rs @@ -2,7 +2,7 @@ use crate::color::{ColorScheme, Rgba, SchemeSlot}; use crate::style::{ColorBase, Effects}; -use crate::theme::{FontScheme, FontSet, FormatScheme, ScriptFont, Theme, default_format}; +use crate::theme::{FontScheme, FontSet, FormatScheme, ScriptFont, SysColor, Theme, TypefaceAttrs, default_format}; use craft_xml::{El, Local}; @@ -21,7 +21,12 @@ fn font_set(e: Option<&El>) -> FontSet { .collect() }) .unwrap_or_default(); - FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), scripts } + let attrs = |n: &str| { + let c = e.and_then(|e| e.child(Local(n))); + let at = |a: &str| c.and_then(|c| c.attr_local(a)).map(String::from); + TypefaceAttrs { typeface: at("typeface").unwrap_or_default(), panose: at("panose"), pitch_family: at("pitchFamily"), charset: at("charset") } + }; + FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), latin_attrs: attrs("latin"), ea_attrs: attrs("ea"), cs_attrs: attrs("cs"), scripts } } pub fn read_theme(src: &mut dyn Source, root: &El) -> Theme { @@ -33,7 +38,10 @@ pub fn read_theme(src: &mut dyn Source, root: &El) -> Theme { if let Some(c) = cs.child(Local(slot.xml_name())).and_then(dml::color) { let rgb = match c.base { ColorBase::Rgb { rgb } => rgb, - ColorBase::System { last, .. } => last, + ColorBase::System { name, last } => { + t.sys_colors.push(SysColor { slot, name, last }); + last + } ColorBase::Preset { name } => crate::color::preset(&name).unwrap_or(Rgba::BLACK), ColorBase::Scheme { .. } => continue, }; @@ -90,7 +98,7 @@ pub fn read_theme(src: &mut dyn Source, root: &El) -> Theme { } let extra: String = root .elements() - .filter(|e| e.is(Local("objectDefaults")) || e.is(Local("extraClrSchemeLst"))) + .filter(|e| ["objectDefaults", "extraClrSchemeLst", "custClrLst", "extLst"].iter().any(|n| e.is(Local(n)))) .filter(|e| !crate::xmlx::has_rel_refs(e)) .map(|e| src.keep(e)) .collect(); diff --git a/crates/drawingml/src/theme/write.rs b/crates/drawingml/src/theme/write.rs index 5e95e57eb2..bc46d59e3a 100644 --- a/crates/drawingml/src/theme/write.rs +++ b/crates/drawingml/src/theme/write.rs @@ -2,7 +2,7 @@ use crate::color::{ColorScheme, Rgba, SchemeSlot}; use crate::style::{ColorRef, Effects, Fill}; -use crate::theme::{FontSet, Theme, default_format}; +use crate::theme::{FontSet, Theme, TypefaceAttrs, default_format}; use craft_xml::Writer; @@ -12,9 +12,20 @@ use crate::write as dml; fn font_set(w: &mut Writer, tag: &str, f: &FontSet) { w.open(tag, &[]); - w.tag("a:latin").attr("typeface", if f.latin.is_empty() { "Arial" } else { &f.latin }).empty(); - w.tag("a:ea").attr("typeface", &f.ea).empty(); - w.tag("a:cs").attr("typeface", &f.cs).empty(); + let face = |w: &mut Writer, tag: &str, name: &str, a: &TypefaceAttrs| { + // Panose and the like describe one font: a changed typeface does not keep them. + let none = TypefaceAttrs::default(); + let a = if a.typeface == name { a } else { &none }; + w.tag(tag) + .attr("typeface", name) + .attr_opt("panose", a.panose.as_deref()) + .attr_opt("pitchFamily", a.pitch_family.as_deref()) + .attr_opt("charset", a.charset.as_deref()) + .empty(); + }; + face(w, "a:latin", if f.latin.is_empty() { "Arial" } else { &f.latin }, &f.latin_attrs); + face(w, "a:ea", &f.ea, &f.ea_attrs); + face(w, "a:cs", &f.cs, &f.cs_attrs); for sf in &f.scripts { w.tag("a:font").attr("script", &sf.script).attr("typeface", &sf.typeface).empty(); } @@ -74,7 +85,11 @@ pub fn theme_xml(out: &mut dyn Sink, t: &Theme) -> Vec { for slot in SchemeSlot::THEME { let tag = format!("a:{}", slot.xml_name()); w.open(&tag, &[]); - w.tag("a:srgbClr").attr("val", t.colors.get(slot).hex()).empty(); + let rgb = t.colors.get(slot); + match t.sys_colors.iter().find(|s| s.slot == slot && s.last == rgb && crate::color::is_system_name(&s.name)) { + Some(s) => w.tag("a:sysClr").attr("val", &s.name).attr("lastClr", rgb.hex()).empty(), + None => w.tag("a:srgbClr").attr("val", rgb.hex()).empty(), + } w.close(); } extra_colors(&mut w, &t.colors); diff --git a/crates/drawingml/src/write.rs b/crates/drawingml/src/write.rs index 25bfb89dbe..da3f10d79e 100644 --- a/crates/drawingml/src/write.rs +++ b/crates/drawingml/src/write.rs @@ -777,6 +777,10 @@ pub fn list_style(w: &mut Writer, out: &mut dyn Sink, tag: &str, ls: &ListStyle) return; } w.open(tag, &[]); + if let Some(l) = &ls.default_level { + let def = (l.run != RunProps::default()).then_some(&l.run); + ppr(w, out, "a:defPPr", None, &l.para, def); + } for (i, l) in ls.levels.iter().enumerate().take(9) { if let Some(l) = l { let t = format!("a:lvl{}pPr", i + 1); diff --git a/crates/drawingml/src/xmlx.rs b/crates/drawingml/src/xmlx.rs index d31616b399..27fa58dc7d 100644 --- a/crates/drawingml/src/xmlx.rs +++ b/crates/drawingml/src/xmlx.rs @@ -156,7 +156,20 @@ fn used_prefixes(el: &El) -> HashSet<&str> { used } -/// Serialize `el`, declaring every prefix it uses that the source root declared. +/// Does `el` or a descendant have an unprefixed name that no `xmlns` inside `el` binds? Such a +/// name is in the default namespace of the part it was read from. Attributes never are. +fn uses_outer_default(el: &El) -> bool { + fn rec(e: &El, depth: usize) -> bool { + if depth > MAX_DEPTH || e.attrs.iter().any(|(k, _)| k == "xmlns") { + return false; + } + !e.name.contains(':') || e.elements().any(|c| rec(c, depth + 1)) + } + rec(el, 0) +} + +/// Serialize `el`, declaring every prefix it uses that the source root declared, and the +/// root's default namespace when an unprefixed name in `el` depends on it. pub fn keep_xml(el: &El, ns: &[(String, String)]) -> String { keep_with(el, &[ns], None) } @@ -166,11 +179,15 @@ pub fn keep_xml(el: &El, ns: &[(String, String)]) -> String { /// [`MAX_COPIED_NS_BYTES`]). pub fn keep_with(el: &El, decls: &[&[(String, String)]], budget: Option<&Cell>) -> String { let used = used_prefixes(el); + let default = uses_outer_default(el); let mut have: HashSet<&str> = el.attrs.iter().map(|(a, _)| a.as_str()).collect(); let mut extra = Vec::new(); for (k, v) in decls.iter().flat_map(|d| d.iter()) { - let p = k.strip_prefix("xmlns:").unwrap_or(""); - if !p.is_empty() && used.contains(p) && v.len() <= MAX_NS_VALUE && !have.contains(k.as_str()) { + let wanted = match k.strip_prefix("xmlns:") { + Some(p) => !p.is_empty() && used.contains(p), + None => k == "xmlns" && default, + }; + if wanted && v.len() <= MAX_NS_VALUE && !have.contains(k.as_str()) { let cost = k.len() + v.len(); if let Some(b) = budget { if b.get() < cost { @@ -324,6 +341,33 @@ mod tests { assert!(!has_rel_refs(root.child(Local("z")).unwrap())); } + /// A part written with a default namespace (``): an unprefixed + /// fragment, or one with an unprefixed descendant, carries that namespace; a prefixed one + /// and one that declares its own default are written as before. + #[test] + fn a_kept_fragment_carries_the_default_namespace_its_names_depend_on() { + let root = parse( + br#""#, + ) + .unwrap(); + let ns = ns_decls(&root); + let kid = |n: &str| root.child(Local(n)).unwrap(); + assert_eq!(keep_xml(kid("custClrLst"), &ns), r#""#); + assert_eq!(keep_xml(kid("y"), &ns), r#""#, "prefixed: as before"); + assert_eq!(keep_xml(kid("z"), &ns), r#""#, "an unprefixed descendant"); + assert_eq!(keep_xml(kid("own"), &ns), r#""#, "its own default wins"); + assert_eq!(keep_xml(kid("u"), &ns), r#""#, "an undeclared default stays"); + // A part with no default namespace: unprefixed names stay in no namespace. + let plain = parse(br#""#).unwrap(); + assert_eq!(keep_xml(plain.child(Local("x")).unwrap(), &ns_decls(&plain)), ""); + // The default declaration spends the budget like the others. + let budget = Cell::new(3); + assert_eq!( + keep_with(kid("custClrLst"), &[&ns], Some(&budget)), + r#""# + ); + } + #[test] fn inner_declarations_are_found_and_clashing_ones_dropped() { let root = parse(br#""#).unwrap(); diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 05c1a673c3..88e1e2a4a9 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -62,6 +62,10 @@ impl Limits { /// A byte count in megabytes for messages ("9.9 MB", "1024 MB"). #[cfg_attr(no_dwg_bridge, allow(dead_code))] +#[expect( + clippy::cast_precision_loss, + reason = "Megabyte formatting is rounded for display; exact integer precision beyond 2^53 bytes is not meaningful." +)] fn mb(n: u64) -> String { let m = n as f64 / f64::from(1u32 << 20); if m >= 100.0 { format!("{m:.0} MB") } else { format!("{m:.1} MB") } @@ -79,12 +83,17 @@ mod proxy_transport; #[cfg(not(no_dwg_bridge))] mod native { + use std::fmt::Write as _; use std::io::{Cursor, Write}; use std::panic::AssertUnwindSafe; use super::{Limits, mb}; /// Read DWG bytes and return an ASCII DXF rendition, within [`Limits::DEFAULT`]. + /// + /// # Errors + /// + /// Returns an error when the DWG cannot be read or post-processed, or its DXF rendition exceeds the default limits. pub fn dwg_to_dxf(bytes: &[u8]) -> Result, String> { dwg_to_dxf_with(bytes, Limits::DEFAULT) } @@ -92,6 +101,10 @@ mod native { /// [`dwg_to_dxf`] with explicit limits. Both are checked before the expensive step they /// guard: the input size before the DWG reader runs, the DXF size while it is written, so a /// runaway conversion stops at the limit instead of filling memory first. + /// + /// # Errors + /// + /// Returns an error when the input exceeds `limits`, decoding fails, or the DXF output exceeds `limits`. pub fn dwg_to_dxf_with(bytes: &[u8], limits: Limits) -> Result, String> { dwg_to_dxf_noted(bytes, limits).map(|(dxf, _)| dxf) } @@ -100,6 +113,10 @@ mod native { /// failsafe mode: an object record it can't decode is skipped instead of failing the whole /// file, and the notes say how many were skipped and of which types, so a partial read never /// passes for a complete one. + /// + /// # Errors + /// + /// Returns an error when the input exceeds `limits`, decoding fails, or the DXF output exceeds `limits`. pub fn dwg_to_dxf_noted(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { if bytes.len() > limits.max_dwg_bytes { return Err(format!( @@ -122,13 +139,13 @@ mod native { let mut notes = read_notes(&outcome.stats); let mut doc = outcome.document; notes.extend( - guarded(AssertUnwindSafe(|| application_objects(&mut doc))).map_err(|_| "the DWG application object conversion failed".to_string())?, + guarded(AssertUnwindSafe(|| application_objects(&mut doc))).map_err(|()| "the DWG application object conversion failed".to_string())?, ); // After application_objects, so the proxy objects it makes are numbered as the DXF's. notes.extend( - guarded(AssertUnwindSafe(|| super::proxy_transport::prepare(&mut doc))).map_err(|_| "the DWG proxy conversion failed".to_string())?, + guarded(AssertUnwindSafe(|| super::proxy_transport::prepare(&mut doc))).map_err(|()| "the DWG proxy conversion failed".to_string())?, ); - let orphans = guarded(AssertUnwindSafe(|| post_process(&mut doc))).map_err(|_| "the DWG post-processing failed on this file".to_string())?; + let orphans = guarded(AssertUnwindSafe(|| post_process(&mut doc))).map_err(|()| "the DWG post-processing failed on this file".to_string())?; if orphans > 0 { let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") }; notes.push(format!("DWG: {orphans} DGN line style component{s} that no line style definition uses {were} left out")); @@ -632,7 +649,7 @@ mod native { // A real table has at most one merge per cell; more ranges than that come from a // damaged file and would only make this rows × cols × ranges. let max_ranges = rows.saturating_mul(cols).min(1 << 16); - for r in t.merged_ranges.iter().take(max_ranges).cloned().collect::>() { + for r in t.merged_ranges.iter().take(max_ranges).copied().collect::>() { // Clamp to the table: the ranges come from the file. let (bottom, right) = (r.bottom_row.min(rows.saturating_sub(1)), r.right_col.min(cols.saturating_sub(1))); if r.top_row > bottom || r.left_col > right || rows == 0 || cols == 0 || (r.top_row, r.left_col) == (bottom, right) { @@ -703,6 +720,35 @@ mod native { } } + /// A FIELD's format string between the two places acadrust 0.6.6 keeps it. Its DXF reader + /// puts a pre-2007 field's format (group 4) only in `Field::format`, and its DWG writer + /// writes that one only for versions before 2007; from 2007 it writes `value.format`. A field + /// read from an older drawing and written as DWG 2007 or later would lose its format + /// (`dd/MM/yyyy`, `%lu2`). The child values hold no format of their own in the old DXF. + /// + /// `legacy`: the group 4 formats of a DXF that was read as a newer version than it declares + /// ([`legacy_field_formats`]), which the reader then skipped. They go back into an empty + /// `Field::format` first, as the reader puts them there under the DXF's own version, so a + /// DWG before 2007 keeps them too. + fn field_formats(doc: &mut acadrust::CadDocument, legacy: &[(acadrust::Handle, String)]) { + for (handle, format) in legacy { + if let Some(acadrust::objects::ObjectType::Field(f)) = doc.objects.get_mut(handle) + && f.format.is_empty() + { + f.format.clone_from(format); + } + } + if doc.version < acadrust::DxfVersion::AC1021 { + return; + } + for o in doc.objects.values_mut() { + let acadrust::objects::ObjectType::Field(f) = o else { continue }; + if f.value.format.is_empty() && !f.format.is_empty() { + f.value.format = f.format.clone(); + } + } + } + /// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification, /// common dimension data), which acadrust keeps no copy of from DXF: it is set here as /// CADCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128, @@ -715,8 +761,8 @@ mod native { } /// Leave out DGN line style components (`LS*COMPONENT`) that no line style definition uses - /// (#1482). A drawing that once came from MicroStation can carry hundreds of thousands of - /// them, orphaned copies piled up by earlier DGN imports and copy-pastes (AutoCAD's PURGE + /// (#1482). A drawing that once came from `MicroStation` can carry hundreds of thousands of + /// them, orphaned copies piled up by earlier DGN imports and copy-pastes (`AutoCAD`'s PURGE /// removes them as orphaned data): in a real 83 MB site plan they were 888,483 of 889,053 /// components and made its DXF rendition 1.2 GB, over [`Limits::DEFAULT`], so the file /// didn't open at all. No definition that was read refers to them (a definition the reader @@ -846,7 +892,7 @@ mod native { for (name, code, value) in unwritten_header_vars(h) { let written = section.windows(name.len() + 2).any(|w| w.starts_with(name.as_bytes()) && w.ends_with(b"\r\n")); if !written && value.parse::().is_ok_and(f64::is_finite) { - add.push_str(&format!(" 9\r\n{name}\r\n{code:>3}\r\n{value}\r\n")); + let _ = write!(add, " 9\r\n{name}\r\n{code:>3}\r\n{value}\r\n"); } } dxf.splice(end..end, add.into_bytes()); @@ -878,14 +924,22 @@ mod native { /// Oldest DWG version written; older DXF input is written as this version. const MIN_DWG_VERSION: acadrust::DxfVersion = acadrust::DxfVersion::AC1018; - /// Convert DXF bytes into a DWG file of the DXF's version, and at least AutoCAD 2004 + /// Convert DXF bytes into a DWG file of the DXF's version, and at least `AutoCAD` 2004 /// (AC1018). + /// + /// # Errors + /// + /// Returns an error when the DXF cannot be decoded or the DWG cannot be written, including oversized input. pub fn dxf_to_dwg(dxf: &[u8]) -> Result, String> { convert(dxf, None, None).map(|(dwg, _)| dwg) } /// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"), /// whatever version the DXF declares. + /// + /// # Errors + /// + /// Returns an error for an unsupported version, invalid DXF, oversized input, or a DWG write failure. pub fn dxf_to_dwg_as(dxf: &[u8], version: &str) -> Result, String> { dxf_to_dwg_noted(dxf, version).map(|(dwg, _)| dwg) } @@ -903,8 +957,9 @@ mod native { /// read from a file of version `kept` ("AC1032"), and acadrust reads several of those /// differently by version: read as R2000, an AC1032 file's mental ray render settings came out /// a class version too high, for which the ODA rejects the whole DWG, and a field lost its - /// cached value. So the DXF is read as `kept` declares. A `kept` version that is unknown, or - /// not newer than the DXF's own, changes nothing. + /// cached value. So the DXF is read as `kept` declares; the formats of the DXF's own pre-2007 + /// fields, which the reader skips then, are restored ([`legacy_field_formats`]). A `kept` + /// version that is unknown, or not newer than the DXF's own, changes nothing. pub fn dxf_to_dwg_kept_as(dxf: &[u8], version: &str, kept: &str) -> Result, String> { dxf_to_dwg_kept_noted(dxf, version, kept).map(|(dwg, _)| dwg) } @@ -970,6 +1025,35 @@ mod native { Some(out) } + /// The format (group 4) of each FIELD record in an ASCII DXF, by handle. acadrust 0.6.6 reads + /// it only from a DXF that declares a version before 2007 (AC1021), where it follows the + /// field code or the object handles, before group 91 (`read_field_object_dxf`). When + /// [`declare_version`] made an older DXF read as 2007 or later, a field the DXF wrote itself + /// would lose its format; a field carried over from a 2007+ file has none and keeps its own + /// `value.format`. + fn legacy_field_formats(dxf: &[u8]) -> Vec<(acadrust::Handle, String)> { + let Some(pairs) = super::proxy_transport::text_pairs(dxf) else { return Vec::new() }; + let mut formats = Vec::new(); + let (mut in_field, mut handle, mut format, mut past) = (false, None, None, false); + for pair in pairs { + let Some((code, value)) = pair else { break }; + match code { + 0 => { + if let (Some(h), Some(f)) = (handle.take(), format.take()) { + formats.push((h, f)); + } + in_field = value == "FIELD" || value == "ACDBFIELD"; + (handle, format, past) = (None, None, false); + } + 5 if in_field && handle.is_none() => handle = u64::from_str_radix(value.trim(), 16).ok().map(acadrust::Handle::new), + 4 if in_field && !past && format.is_none() => format = Some(value), + 91 if in_field => past = true, + _ => {} + } + } + formats + } + /// The byte offset and the trimmed value of header variable `name` in an ASCII DXF: the value /// of the group that follows the `9` group naming it. The file is read as (group code, /// value) line pairs, in one pass with no buffering, up to the first `0`/`ENDSEC`, the end @@ -1011,7 +1095,7 @@ mod native { /// The current dimension style (`$DIMSTYLE`) by its name: the DXF gives the name, and the /// handle read with it needn't be the style's in the document, in which case the DWG writer - /// fell back to Standard and AutoCAD opened the drawing with Standard current (#1051). + /// fell back to Standard and `AutoCAD` opened the drawing with Standard current (#1051). fn current_dimstyle(doc: &mut acadrust::CadDocument) { let name = doc.header.current_dimstyle_name.clone(); if let Some(h) = doc.dim_styles.iter().find(|ds| ds.name.eq_ignore_ascii_case(&name)).map(|ds| ds.handle) { @@ -1021,7 +1105,7 @@ mod native { /// The current text style (`$TEXTSTYLE`) by its name, the same way as [`current_dimstyle`]: /// the handle read with the DXF needn't be the style's in the document, in which case the DWG - /// writer fell back to Standard and AutoCAD opened the drawing with Standard current (#1650). + /// writer fell back to Standard and `AutoCAD` opened the drawing with Standard current (#1650). fn current_text_style(doc: &mut acadrust::CadDocument) { let name = doc.header.current_text_style_name.clone(); if let Some(h) = doc.text_styles.iter().find(|ts| ts.name.eq_ignore_ascii_case(&name)).map(|ts| ts.handle) { @@ -1198,20 +1282,24 @@ mod native { )); } // Decoding a code page to UTF-8 can grow the text, so the limit applies again. - let data = match kept.and_then(|k| declare_version(dxf, k)) { - Some(d) if d.len() > Limits::DEFAULT.max_dxf_bytes => { + let (data, legacy) = match kept.and_then(|k| declare_version(dxf, k).map(|d| (k, d))) { + Some((_, d)) if d.len() > Limits::DEFAULT.max_dxf_bytes => { return Err(format!( "DXF: the input is {} as UTF-8, larger than the {} accepted for DWG conversion", mb(d.len() as u64), mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } - Some(d) => d, - None => dxf.to_vec(), + // Read as 2007 or later, the DXF's own fields lose their formats: restored after. + Some((k, d)) => (d, k >= acadrust::DxfVersion::AC1021), + None => (dxf.to_vec(), false), }; - let (classes, source) = guarded(AssertUnwindSafe(|| (dxf_class_names(&data), super::proxy_transport::source_classes(&data)))) - .map_err(|_| "the DXF proxy class conversion failed".to_string())?; - let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) + let (classes, source, legacy) = guarded(AssertUnwindSafe(|| { + let legacy = if legacy { legacy_field_formats(&data) } else { Vec::new() }; + (dxf_class_names(&data), super::proxy_transport::source_classes(&data), legacy) + })) + .map_err(|_| "the DXF proxy class conversion failed".to_string())?; + let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(acadrust::DxfReader::read)) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; match version { @@ -1238,6 +1326,7 @@ mod native { }; other_layout_owners(&mut doc); table_style_rows(&mut doc, true); + field_formats(&mut doc, &legacy); dimension_flags(&mut doc); let mut unwritten = drop_unwritable(&mut doc); for (kind, n) in proxies { @@ -1250,14 +1339,14 @@ mod native { current_layer(&mut doc); unwritten })) - .map_err(|_| "the DXF to DWG conversion failed on this file".to_string())?; + .map_err(|()| "the DXF to DWG conversion failed on this file".to_string())?; let dwg = std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc))) .map_err(|_| "the DWG writer failed on this drawing".to_string())? .map_err(|e| format!("DWG write: {e}"))?; Ok((dwg, unwritten)) } - /// AutoCAD's entry name for the drawing variables dictionary (the DXF Reference calls it the + /// `AutoCAD`'s entry name for the drawing variables dictionary (the DXF Reference calls it the /// ACDBVARIABLEDICTIONARY; dictionary keys are case-insensitive). const VARIABLE_DICTIONARY: &str = "AcDbVariableDictionary"; @@ -1273,11 +1362,11 @@ mod native { if valid.contains(&value) { value.to_string() } else { default.to_string() } } - /// Add the drawing variables dictionary AutoCAD always writes into the named object + /// Add the drawing variables dictionary `AutoCAD` always writes into the named object /// dictionary, with the variables it keeps there, when the drawing has none (#1813). /// Vectric Aspire 10.5 reads a 2004 (AC1018) DWG without it as empty ("No data was imported /// from the DXF / DWG file"), though it reads the same drawing as DXF — which has no such - /// dictionary either, as CADCraft's and ezdxf's writers don't make one. AutoCAD's AC1032 DWGs + /// dictionary either, as CADCraft's and ezdxf's writers don't make one. `AutoCAD`'s AC1032 DWGs /// read there without it, so newer output is left as it was, and a dictionary the drawing /// does have keeps its own entries and values. fn add_variable_dictionary(doc: &mut acadrust::CadDocument) { @@ -1326,7 +1415,7 @@ mod native { /// Entities of a layout other than the one in `*Paper_Space` are written owned by their block /// (entity mode 0, with its handle). acadrust writes every paper-space entity with mode 1, - /// "paper space", which AutoCAD reads as the `*Paper_Space` block's: everything drawn on a + /// "paper space", which `AutoCAD` reads as the `*Paper_Space` block's: everything drawn on a /// second layout landed on the first one, and the second stayed empty (#1057). fn other_layout_owners(doc: &mut acadrust::CadDocument) { let others: std::collections::HashSet = doc @@ -1549,11 +1638,11 @@ thread_local! { /// Panics when a test asked for `stage` to fail (see [`PANIC_IN`]); does nothing otherwise. #[cfg(not(no_dwg_bridge))] #[allow(clippy::panic)] -fn fail_in_test(_stage: &str) { +fn fail_in_test(stage: &str) { + #[cfg(not(test))] + let _ = stage; #[cfg(test)] - if PANIC_IN.with(|p| p.get()) == Some(_stage) { - panic!("test-forced panic in {_stage}"); - } + assert!(PANIC_IN.with(std::cell::Cell::get) != Some(stage), "test-forced panic in {stage}"); } /// The error for a DWG version this writer can't create. @@ -1633,6 +1722,8 @@ pub fn dxf_to_dwg_kept_noted(_dxf: &[u8], _version: &str, _kept: &str) -> Result #[cfg(test)] mod tests { + use std::fmt::Write as _; + use super::*; /// The DXF of an empty drawing, enough for the bridge to make a small DWG. @@ -1726,9 +1817,9 @@ mod tests { let mut s = String::from(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n"); for (text, flags, sub, pts) in dims { s += " 0\nDIMENSION\n 8\n0\n100\nAcDbEntity\n100\nAcDbDimension\n 10\n0\n 20\n0\n 30\n0\n"; - s += &format!(" 11\n50\n 21\n-20\n 31\n0\n 70\n{flags}\n 1\n{text}\n 3\nStandard\n100\n{sub}\n"); - for (code, [x, y]) in pts.iter() { - s += &format!("{code:>3}\n{x}\n{:>3}\n{y}\n{:>3}\n0\n", code + 10, code + 20); + let _ = write!(s, " 11\n50\n 21\n-20\n 31\n0\n 70\n{flags}\n 1\n{text}\n 3\nStandard\n100\n{sub}\n"); + for (code, [x, y]) in *pts { + let _ = write!(s, "{code:>3}\n{x}\n{:>3}\n{y}\n{:>3}\n0\n", code + 10, code + 20); } } s + " 0\nENDSEC\n 0\nEOF\n" @@ -1797,13 +1888,17 @@ mod tests { .collect() } - /// Issue #1482: a DWG that once came from MicroStation can carry hundreds of thousands of DGN + /// Issue #1482: a DWG that once came from `MicroStation` can carry hundreds of thousands of DGN /// line style components no definition uses (a real 83 MB site plan: 888,483 of 889,053, a /// 1.2 GB DXF rendition over the limit, so it didn't open). They're left out with a note, and /// their dictionary entries with them; the definition and every component it reaches — /// through compound and point components, around a cycle — are kept. #[cfg(not(no_dwg_bridge))] #[test] + #[expect( + clippy::too_many_lines, + reason = "This integration test builds and verifies one complete DGN component graph; splitting the fixture would obscure reachability." + )] fn orphaned_dgn_line_style_components_are_left_out() { use acadrust::objects::*; let mut doc = acadrust::CadDocument::new(); @@ -2103,4 +2198,127 @@ mod tests { assert_eq!(frames, [vec![0xDE, 0xAD, 0xBE, 0xEF]], "{version}"); } } + + /// A FIELD read from a pre-2007 DXF keeps its format (group 4) only in `Field::format`, which + /// acadrust's DWG writer writes just for versions before 2007: saved as DWG 2007 or later the + /// format (`dd/MM/yyyy`) was lost. A 2007+ field with its own format is written as it is. + #[cfg(not(no_dwg_bridge))] + #[test] + fn field_formats_survive_saving_an_older_drawing_as_dwg_2007_or_later() { + let formats = |dwg: Vec| -> Vec { + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + back.objects + .values() + .filter_map(|o| match o { + acadrust::objects::ObjectType::Field(f) => Some(f.value.format.clone()), + _ => None, + }) + .collect() + }; + for source in ["AC1015", "AC1018"] { + let dxf = format!( + " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\n{source}\n 0\nENDSEC\n 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nFIELD\n 2\nAcDbField\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n 0\nENDSEC\n 0\nSECTION\n 2\nOBJECTS\n 0\nFIELD\n 5\nA1F\n330\n1F\n 1\nAcVar\n 2\n\\AcVar Date\n 4\ndd/MM/yyyy\n 90\n0\n 97\n0\n 91\n0\n 92\n0\n 94\n0\n 95\n0\n 96\n0\n300\n\n 0\nENDSEC\n 0\nEOF\n" + ); + assert_eq!(formats(dxf_to_dwg_as(dxf.as_bytes(), "AC1032").unwrap()), ["dd/MM/yyyy"], "{source}"); + } + let mut doc = acadrust::CadDocument::new(); + doc.classes.add_or_update(acadrust::classes::DxfClass::new("FIELD", "AcDbField")); + let handle = doc.allocate_handle(); + let field = acadrust::objects::Field { + handle, + owner: doc.header.named_objects_dict_handle, + evaluator_id: "AcVar".into(), + code: "\\AcVar Date".into(), + value: acadrust::entities::CellValue { format: "%lu2".into(), ..Default::default() }, + ..Default::default() + }; + doc.objects.insert(handle, acadrust::objects::ObjectType::Field(field)); + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); + assert_eq!(formats(dxf_to_dwg_as(&dxf, "AC1032").unwrap()), ["%lu2"]); + } + + /// A FIELD record as an AC1015/AC1018 DXF writes it, its format `dd/MM/yyyy` in group 4. + #[cfg(not(no_dwg_bridge))] + fn legacy_field(handle: acadrust::Handle, owner: acadrust::Handle) -> String { + format!( + " 0\r\nFIELD\r\n 5\r\n{handle:X}\r\n330\r\n{owner:X}\r\n 1\r\nAcVar\r\n 2\r\n\\AcVar Date\r\n 4\r\ndd/MM/yyyy\r\n 90\r\n0\r\n 97\r\n0\r\n 91\r\n0\r\n 92\r\n0\r\n 94\r\n0\r\n 95\r\n0\r\n 96\r\n0\r\n300\r\n\r\n" + ) + } + + /// The FIELD formats of a DWG by handle: `value.format` from 2007, `Field::format` before. + #[cfg(not(no_dwg_bridge))] + fn dwg_field_formats(dwg: Vec) -> Vec<(u64, String)> { + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let mut formats: Vec<(u64, String)> = back + .objects + .values() + .filter_map(|o| match o { + acadrust::objects::ObjectType::Field(f) => Some((f.handle.into(), f.pre2007_format().to_string())), + _ => None, + }) + .collect(); + formats.sort(); + formats + } + + /// CADCraft's R2000 DXF of a drawing with fields declares AC1015 (or the drawing's AC1018) + /// and is read as the `kept` version, for which acadrust skips group 4: an older drawing's own + /// field lost its format (`dd/MM/yyyy`) in the DWG (#1580 review). + #[cfg(not(no_dwg_bridge))] + #[test] + fn field_formats_survive_a_kept_version_newer_than_the_drawing() { + for source in ["AC1015", "AC1018"] { + for kept in ["AC1024", "AC1032"] { + let owner = acadrust::Handle::new(0x1F); + let legacy = legacy_field(acadrust::Handle::new(0xA1F), owner); + let dxf = format!( + " 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n{source}\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nFIELD\r\n 2\r\nAcDbField\r\n 3\r\nObjectDBX Classes\r\n 90\r\n0\r\n 91\r\n0\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nOBJECTS\r\n{legacy} 0\r\nENDSEC\r\n 0\r\nEOF\r\n" + ); + for version in ["AC1032", "AC1018"] { + let got = dwg_field_formats(dxf_to_dwg_kept_as(dxf.as_bytes(), version, kept).unwrap()); + assert_eq!(got, [(0xA1F, "dd/MM/yyyy".to_string())], "{source} kept {kept} as {version}"); + } + } + } + } + + /// The same DXF with a field carried over from a 2007+ file next to the drawing's own: the + /// carried-over one keeps its own `value.format` (`%lu2`), the drawing's own its group 4 + /// format (`dd/MM/yyyy`). + #[cfg(not(no_dwg_bridge))] + #[test] + fn field_formats_survive_a_kept_version_with_carried_over_and_own_fields() { + for source in ["AC1015", "AC1018"] { + for kept in ["AC1024", "AC1032"] { + // The carried-over field as acadrust writes 2007+ DXF, the drawing's own field in + // the old layout, under the older version. + let mut doc = acadrust::CadDocument::new(); + doc.classes.add_or_update(acadrust::classes::DxfClass::new("FIELD", "AcDbField")); + let (carried, own) = (doc.allocate_handle(), doc.allocate_handle()); + let field = acadrust::objects::Field { + handle: carried, + owner: doc.header.named_objects_dict_handle, + evaluator_id: "AcVar".into(), + code: "\\AcVar Date".into(), + value: acadrust::entities::CellValue { format: "%lu2".into(), ..Default::default() }, + ..Default::default() + }; + doc.objects.insert(carried, acadrust::objects::ObjectType::Field(field)); + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); + let dxf = String::from_utf8(dxf).unwrap(); + let dxf = dxf.replacen("$ACADVER\r\n 1\r\nAC1032\r\n", &format!("$ACADVER\r\n 1\r\n{source}\r\n"), 1); + let at = dxf.find(" 0\r\nFIELD\r\n").unwrap(); + let dxf = format!("{}{}{}", &dxf[..at], legacy_field(own, doc.header.named_objects_dict_handle), &dxf[at..]); + assert!(dxf.contains(&format!("$ACADVER\r\n 1\r\n{source}\r\n"))); + for version in ["AC1032", "AC1018"] { + let got = dwg_field_formats(dxf_to_dwg_kept_as(dxf.as_bytes(), version, kept).unwrap()); + let mut want = vec![(carried.into(), "%lu2".to_string()), (own.into(), "dd/MM/yyyy".to_string())]; + want.sort(); + assert_eq!(got, want, "mixed {source} kept {kept} as {version}"); + } + } + } + } } diff --git a/crates/dxf/src/drawing.rs b/crates/dxf/src/drawing.rs new file mode 100644 index 0000000000..0b52c337cf --- /dev/null +++ b/crates/dxf/src/drawing.rs @@ -0,0 +1,774 @@ +//! Incremental ASCII DXF file writer used by VectorCraft. +//! +//! This is the file skeleton around a pre-written `ENTITIES` section: group codes, handles, and +//! the HEADER / TABLES / BLOCKS / OBJECTS sections CAD apps expect. It is a different API from +//! [`crate::model::write`], which serializes a parsed [`crate::model`] drawing as tags. +//! +//! Moved from `vectorcraft-cad` (`crates/cad/src/writer.rs`). The bytes a [`Drawing`] writes must +//! stay the same: VectorCraft's export tests treat this as the format oracle. +//! +//! DXF R13 and later give every object a handle and subclass markers; R2000 and later add layouts +//! and plot styles. + +use std::fmt::Write as _; + +pub use crate::model::write::Format; + +/// An object handle (written in hex). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Handle(pub u32); + +/// The handles of the fixed objects every drawing has. Entities and table entries count up from +/// [`FIRST_FREE`]. +pub mod fixed { + use super::Handle; + pub const LAYER_TABLE: Handle = Handle(0x1); + pub const LTYPE_TABLE: Handle = Handle(0x2); + pub const APPID_TABLE: Handle = Handle(0x3); + pub const DIMSTYLE_TABLE: Handle = Handle(0x4); + pub const STYLE_TABLE: Handle = Handle(0x5); + pub const UCS_TABLE: Handle = Handle(0x6); + pub const VIEW_TABLE: Handle = Handle(0x7); + pub const VPORT_TABLE: Handle = Handle(0x8); + pub const BLOCK_RECORD_TABLE: Handle = Handle(0x9); + pub const ROOT: Handle = Handle(0xA); + pub const GROUPS: Handle = Handle(0xB); + pub const LAYOUTS: Handle = Handle(0xC); + pub const MODEL_RECORD: Handle = Handle(0xD); + pub const PAPER_RECORD: Handle = Handle(0xE); + pub const MODEL_BLOCK: Handle = Handle(0xF); + pub const MODEL_END: Handle = Handle(0x10); + pub const PAPER_BLOCK: Handle = Handle(0x11); + pub const PAPER_END: Handle = Handle(0x12); + pub const MODEL_LAYOUT: Handle = Handle(0x13); + pub const PAPER_LAYOUT: Handle = Handle(0x14); + pub const ACTIVE_VPORT: Handle = Handle(0x15); + pub const ACAD_APPID: Handle = Handle(0x16); + pub const STANDARD_DIMSTYLE: Handle = Handle(0x17); + pub const IMAGE_DICT: Handle = Handle(0x18); + pub const IMAGE_VARS: Handle = Handle(0x19); + pub const PLOT_STYLES: Handle = Handle(0x1A); + pub const PLOT_NORMAL: Handle = Handle(0x1B); + pub const FIRST_FREE: u32 = 0x30; +} + +/// A number as DXF writes it: up to 6 decimals, no trailing zeros, 0 for anything not finite. +pub fn num(v: f64) -> String { + if !v.is_finite() { + return "0".into(); + } + let s = format!("{v:.6}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" || s.is_empty() { "0".into() } else { s.into() } +} + +/// Text as a DXF string value: one line, `^` escaped, and before DXF 2007 (which reads UTF-8) +/// every character outside ASCII as `\U+XXXX`. +pub fn text(s: &str, utf8: bool) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '\r' | '\n' | '\t' => out.push(' '), + c if c.is_control() => {} + '^' => out.push_str("^ "), + c if !utf8 && !c.is_ascii() => match u16::try_from(u32::from(c)) { + Ok(u) => _ = write!(out, "\\U+{u:04X}"), + Err(_) => out.push('?'), + }, + c => out.push(c), + } + } + out +} + +/// Group-code/value pairs in the order they are written. +pub struct Codes { + pub v: Format, + out: String, +} + +impl Codes { + pub fn new(v: Format) -> Self { + Self { v, out: String::new() } + } + + pub fn into_string(self) -> String { + self.out + } + + pub fn append(&mut self, other: &str) { + self.out.push_str(other); + } + + /// A value written as it is (names and keywords the writer itself chose). + pub fn raw(&mut self, code: u16, value: &str) { + _ = writeln!(self.out, "{code:>3}\n{value}"); + } + + /// Text from the document, encoded for the version (see [`text`]). + pub fn str(&mut self, code: u16, value: &str) { + let t = text(value, self.v.utf8()); + self.raw(code, &t); + } + + pub fn int(&mut self, code: u16, value: i64) { + _ = writeln!(self.out, "{code:>3}\n{value}"); + } + + pub fn num(&mut self, code: u16, value: f64) { + _ = writeln!(self.out, "{code:>3}\n{}", num(value)); + } + + pub fn handle(&mut self, code: u16, h: Handle) { + _ = writeln!(self.out, "{code:>3}\n{:X}", h.0); + } + + /// A 2D point at `code` (x), `code + 10` (y). + pub fn xy(&mut self, code: u16, x: f64, y: f64) { + self.num(code, x); + self.num(code + 10, y); + } + + /// A 3D point at `code`, `code + 10`, `code + 20` (z = 0). + pub fn xyz(&mut self, code: u16, x: f64, y: f64) { + self.xy(code, x, y); + self.num(code + 20, 0.0); + } + + /// The extrusion direction of planar entities: the z axis. + pub fn normal(&mut self) { + self.num(210, 0.0); + self.num(220, 0.0); + self.num(230, 1.0); + } + + /// The start of an object: its type, and from R13 its handle, owner and first subclass. + fn object(&mut self, kind: &str, h: Handle, owner: Handle, subclass: &str) { + self.raw(0, kind); + if self.v.handles() { + self.handle(if kind == "DIMSTYLE" { 105 } else { 5 }, h); + self.handle(330, owner); + self.raw(100, subclass); + } + } + + /// A table entry: the shared record subclass, then the table's own (from R13). + fn record(&mut self, kind: &str, h: Handle, table: Handle, subclass: &str) { + self.object(kind, h, table, "AcDbSymbolTableRecord"); + if self.v.handles() { + self.raw(100, subclass); + } + } + + fn section(&mut self, name: &str) { + self.raw(0, "SECTION"); + self.raw(2, name); + } + + fn end_section(&mut self) { + self.raw(0, "ENDSEC"); + } + + fn table(&mut self, name: &str, h: Handle, count: usize) { + self.raw(0, "TABLE"); + self.raw(2, name); + if self.v.handles() { + self.handle(5, h); + self.raw(330, "0"); + self.raw(100, "AcDbSymbolTable"); + } + self.int(70, count as i64); + if name == "DIMSTYLE" && self.v.r2000() { + self.raw(100, "AcDbDimStyleTable"); + } + } + + fn end_table(&mut self) { + self.raw(0, "ENDTAB"); + } +} + +/// How an entity is drawn: its colour index, true colour, lineweight, linetype and transparency. +#[derive(Clone, Debug, Default)] +pub struct EntityStyle { + pub aci: u8, + /// `0xRRGGBB` (DXF 2004 and later). + pub rgb: Option, + /// Hundredths of a millimetre (DXF 2000 and later). + pub lineweight: Option, + pub linetype: Option, + /// Opacity 0–255 (DXF 2004 and later; opaque is left out). + pub alpha: Option, +} + +impl Codes { + /// The start of an entity of `kind` owned by `owner` (model space, or a polyline for its + /// vertices) on `layer` with its style, ending with `subclass` (none when empty). + pub fn entity(&mut self, kind: &str, h: Handle, owner: Handle, layer: &str, style: &EntityStyle, subclass: &str) { + self.object(kind, h, owner, "AcDbEntity"); + self.str(8, layer); + if let Some(lt) = &style.linetype { + self.str(6, lt); + } + self.int(62, i64::from(style.aci)); + if self.v.r2000() + && let Some(lw) = style.lineweight + { + self.int(370, i64::from(lw)); + } + if self.v.true_color() { + if let Some(rgb) = style.rgb { + self.int(420, i64::from(rgb)); + } + if let Some(a) = style.alpha { + self.int(440, 0x0200_0000 | i64::from(a)); + } + } + if self.v.handles() && !subclass.is_empty() { + self.raw(100, subclass); + } + } +} + +/// A DXF layer. +#[derive(Clone, Debug)] +pub struct Layer { + pub name: String, + pub aci: u8, + /// Switched off (a hidden layer). + pub off: bool, + pub locked: bool, + /// Plotted (printable). + pub plot: bool, +} + +/// A dash pattern: dash, gap, dash… lengths in drawing units. +#[derive(Clone, Debug)] +pub struct LineType { + pub name: String, + pub pattern: Vec, +} + +/// A placed image file and the image entities that show it. +#[derive(Clone, Debug)] +pub struct ImageDef { + pub name: String, + pub size: (u32, u32), + pub handle: Handle, + /// `(reactor, image entity)` per image entity. + pub reactors: Vec<(Handle, Handle)>, +} + +/// Everything around the entities, collected while they were written. +pub struct Drawing { + pub version: Format, + pub layers: Vec, + pub linetypes: Vec, + /// Text styles: (style name, font family). + pub styles: Vec<(String, String)>, + pub images: Vec, + /// The entities' group codes. + pub entities: String, + /// `[x0, y0, x1, y1]` of everything written (drawing units). + pub extents: [f64; 4], + /// The export region (drawing units). + pub limits: [f64; 4], + /// `$INSUNITS`. + pub insunits: u8, + pub metric: bool, + /// The next free handle. + pub next: u32, +} + +/// The text style every drawing has. +pub const STANDARD_STYLE: &str = "Standard"; + +impl Drawing { + /// The whole file. + pub fn write(self) -> String { + let v = self.version; + let mut c = Codes::new(v); + // Table entries get the handles after the entities'. + let mut next = self.next; + let mut take = |n: usize| { + let start = next; + next = next.saturating_add(u32::try_from(n).unwrap_or(u32::MAX)); + start + }; + let ltype_base = take(3 + self.linetypes.len()); + let layer_base = take(1 + self.layers.len()); + let style_base = take(1 + self.styles.len()); + self.header(&mut c, next); + if v.handles() { + self.classes(&mut c); + } + c.section("TABLES"); + self.vport(&mut c); + self.ltypes(&mut c, ltype_base); + self.layer_table(&mut c, layer_base); + self.style_table(&mut c, style_base); + if v.handles() { + for (name, h) in [("VIEW", fixed::VIEW_TABLE), ("UCS", fixed::UCS_TABLE)] { + c.table(name, h, 0); + c.end_table(); + } + c.table("APPID", fixed::APPID_TABLE, 1); + c.record("APPID", fixed::ACAD_APPID, fixed::APPID_TABLE, "AcDbRegAppTableRecord"); + c.raw(2, "ACAD"); + c.int(70, 0); + c.end_table(); + c.table("DIMSTYLE", fixed::DIMSTYLE_TABLE, 1); + c.record("DIMSTYLE", fixed::STANDARD_DIMSTYLE, fixed::DIMSTYLE_TABLE, "AcDbDimStyleTableRecord"); + c.raw(2, "Standard"); + c.int(70, 0); + c.end_table(); + c.table("BLOCK_RECORD", fixed::BLOCK_RECORD_TABLE, 2); + for (name, h, layout) in + [("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_LAYOUT), ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_LAYOUT)] + { + c.record("BLOCK_RECORD", h, fixed::BLOCK_RECORD_TABLE, "AcDbBlockTableRecord"); + c.raw(2, name); + if v.r2000() { + c.handle(340, layout); + c.int(70, 0); + c.int(280, 1); + c.int(281, 0); + } + } + c.end_table(); + } + c.end_section(); + if v.handles() { + c.section("BLOCKS"); + for (name, record, begin, end) in [ + ("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_BLOCK, fixed::MODEL_END), + ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_BLOCK, fixed::PAPER_END), + ] { + c.object("BLOCK", begin, record, "AcDbEntity"); + c.raw(8, "0"); + c.raw(100, "AcDbBlockBegin"); + c.raw(2, name); + c.int(70, 0); + c.xyz(10, 0.0, 0.0); + c.raw(3, name); + c.raw(1, ""); + c.object("ENDBLK", end, record, "AcDbEntity"); + c.raw(8, "0"); + c.raw(100, "AcDbBlockEnd"); + } + c.end_section(); + } + c.section("ENTITIES"); + c.append(&self.entities); + c.end_section(); + if v.handles() { + self.objects(&mut c); + } + c.raw(0, "EOF"); + c.into_string() + } + + fn header(&self, c: &mut Codes, handseed: u32) { + let v = self.version; + let var = |c: &mut Codes, name: &str| c.raw(9, name); + c.section("HEADER"); + var(c, "$ACADVER"); + c.raw(1, v.acadver()); + var(c, "$DWGCODEPAGE"); + c.raw(3, "ANSI_1252"); + var(c, "$INSBASE"); + c.xyz(10, 0.0, 0.0); + let [x0, y0, x1, y1] = self.extents; + var(c, "$EXTMIN"); + c.xyz(10, x0, y0); + var(c, "$EXTMAX"); + c.xyz(10, x1, y1); + let [lx0, ly0, lx1, ly1] = self.limits; + var(c, "$LIMMIN"); + c.xy(10, lx0, ly0); + var(c, "$LIMMAX"); + c.xy(10, lx1, ly1); + if v.r2000() { + var(c, "$LWDISPLAY"); + c.int(290, 1); + var(c, "$INSUNITS"); + c.int(70, i64::from(self.insunits)); + var(c, "$MEASUREMENT"); + c.int(70, i64::from(self.metric)); + } + if v.handles() { + var(c, "$HANDSEED"); + c.handle(5, Handle(handseed)); + } + c.end_section(); + } + + fn classes(&self, c: &mut Codes) { + let mut classes: Vec<(&str, &str, &str, i64, bool)> = vec![]; + if self.version.r2000() { + classes.extend([ + ("ACDBDICTIONARYWDFLT", "AcDbDictionaryWithDefault", "ObjectDBX Classes", 0, false), + ("ACDBPLACEHOLDER", "AcDbPlaceHolder", "ObjectDBX Classes", 0, false), + ("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false), + ]); + } + if !self.images.is_empty() { + classes.extend([ + ("RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, false), + ("IMAGE", "AcDbRasterImage", "ISM", 2175, true), + ("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false), + ("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false), + ]); + } + c.section("CLASSES"); + for (name, cpp, app, flags, entity) in classes { + c.raw(0, "CLASS"); + c.raw(1, name); + c.raw(2, cpp); + c.raw(3, app); + c.int(90, flags); + if self.version.true_color() { + c.int(91, 0); + } + c.int(280, 0); + c.int(281, i64::from(entity)); + } + c.end_section(); + } + + /// The active viewport, zoomed to the drawing's extents. + fn vport(&self, c: &mut Codes) { + let [x0, y0, x1, y1] = self.extents; + c.table("VPORT", fixed::VPORT_TABLE, 1); + c.record("VPORT", fixed::ACTIVE_VPORT, fixed::VPORT_TABLE, "AcDbViewportTableRecord"); + c.raw(2, if self.version.handles() { "*Active" } else { "*ACTIVE" }); + c.int(70, 0); + c.xy(10, 0.0, 0.0); + c.xy(11, 1.0, 1.0); + c.xy(12, (x0 + x1) / 2.0, (y0 + y1) / 2.0); + c.xy(13, 0.0, 0.0); + c.xy(14, 1.0, 1.0); + c.xy(15, 10.0, 10.0); + // The view direction looks down the z axis: (0, 0, 1), each code once. + c.xy(16, 0.0, 0.0); + c.num(36, 1.0); + c.xyz(17, 0.0, 0.0); + let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs()); + // The view's height, with a margin; its width follows from the aspect ratio. + c.num(40, (h.max(w / 1.5) * 1.1).max(1.0)); + c.num(41, 1.5); + c.num(42, 50.0); + c.num(43, 0.0); + c.num(44, 0.0); + c.num(50, 0.0); + c.num(51, 0.0); + for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] { + c.int(code, value); + } + if self.version.r2000() { + c.int(281, 0); + c.int(65, 0); + c.num(146, 0.0); + } + c.end_table(); + } + + fn ltypes(&self, c: &mut Codes, base: u32) { + c.table("LTYPE", fixed::LTYPE_TABLE, 3 + self.linetypes.len()); + let solid = [("ByBlock", ""), ("ByLayer", ""), ("Continuous", "Solid line")]; + let rows = solid.iter().map(|(n, d)| (*n, *d, &[][..])).chain(self.linetypes.iter().map(|l| (l.name.as_str(), "", l.pattern.as_slice()))); + for (i, (name, desc, pattern)) in rows.enumerate() { + c.record("LTYPE", Handle(base.saturating_add(i as u32)), fixed::LTYPE_TABLE, "AcDbLinetypeTableRecord"); + c.str(2, name); + c.int(70, 0); + c.str(3, if pattern.is_empty() { desc } else { "Dashed" }); + c.int(72, 65); + c.int(73, pattern.len() as i64); + c.num(40, pattern.iter().map(|v| v.abs()).sum()); + for v in pattern { + c.num(49, *v); + if self.version.handles() { + c.int(74, 0); + } + } + } + c.end_table(); + } + + fn layer_table(&self, c: &mut Codes, base: u32) { + let zero = Layer { name: "0".into(), aci: 7, off: false, locked: false, plot: true }; + c.table("LAYER", fixed::LAYER_TABLE, 1 + self.layers.len()); + for (i, l) in std::iter::once(&zero).chain(&self.layers).enumerate() { + c.record("LAYER", Handle(base.saturating_add(i as u32)), fixed::LAYER_TABLE, "AcDbLayerTableRecord"); + c.str(2, &l.name); + c.int(70, if l.locked { 4 } else { 0 }); + // A negative colour switches the layer off. + let aci = i64::from(l.aci.max(1)); + c.int(62, if l.off { -aci } else { aci }); + c.raw(6, "Continuous"); + if self.version.r2000() { + c.int(290, i64::from(l.plot)); + c.int(370, -3); + c.handle(390, fixed::PLOT_NORMAL); + } + } + c.end_table(); + } + + fn style_table(&self, c: &mut Codes, base: u32) { + c.table("STYLE", fixed::STYLE_TABLE, 1 + self.styles.len()); + let standard = (STANDARD_STYLE.to_string(), String::new()); + for (i, (name, family)) in std::iter::once(&standard).chain(&self.styles).enumerate() { + c.record("STYLE", Handle(base.saturating_add(i as u32)), fixed::STYLE_TABLE, "AcDbTextStyleTableRecord"); + c.str(2, name); + c.int(70, 0); + c.num(40, 0.0); + c.num(41, 1.0); + c.num(50, 0.0); + c.int(71, 0); + c.num(42, 2.5); + // The font file; from 2000 the family name too, which is how CAD apps find a TrueType font. + if family.is_empty() { + c.raw(3, "txt"); + } else { + c.str(3, &format!("{family}.ttf")); + } + c.raw(4, ""); + if self.version.r2000() && !family.is_empty() { + c.raw(1001, "ACAD"); + c.str(1000, family); + c.int(1071, 0); + } + } + c.end_table(); + } + + fn objects(&self, c: &mut Codes) { + let v = self.version; + let images = !self.images.is_empty(); + c.section("OBJECTS"); + let dict = |c: &mut Codes, h: Handle, owner: Handle, entries: &[(&str, Handle)]| { + c.object("DICTIONARY", h, owner, "AcDbDictionary"); + c.int(281, 1); + for (name, e) in entries { + c.str(3, name); + c.handle(350, *e); + } + }; + let mut root = vec![("ACAD_GROUP", fixed::GROUPS)]; + if images { + root.extend([("ACAD_IMAGE_DICT", fixed::IMAGE_DICT), ("ACAD_IMAGE_VARS", fixed::IMAGE_VARS)]); + } + if v.r2000() { + root.extend([("ACAD_LAYOUT", fixed::LAYOUTS), ("ACAD_PLOTSTYLENAME", fixed::PLOT_STYLES)]); + } + dict(c, fixed::ROOT, Handle(0), &root); + dict(c, fixed::GROUPS, fixed::ROOT, &[]); + if v.r2000() { + dict(c, fixed::LAYOUTS, fixed::ROOT, &[("Layout1", fixed::PAPER_LAYOUT), ("Model", fixed::MODEL_LAYOUT)]); + c.object("ACDBDICTIONARYWDFLT", fixed::PLOT_STYLES, fixed::ROOT, "AcDbDictionary"); + c.int(281, 1); + c.raw(3, "Normal"); + c.handle(350, fixed::PLOT_NORMAL); + c.raw(100, "AcDbDictionaryWithDefault"); + c.handle(340, fixed::PLOT_NORMAL); + // A placeholder has no data and no subclass marker of its own. + c.raw(0, "ACDBPLACEHOLDER"); + c.handle(5, fixed::PLOT_NORMAL); + c.handle(330, fixed::PLOT_STYLES); + self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD); + self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD); + } + if images { + c.object("RASTERVARIABLES", fixed::IMAGE_VARS, fixed::ROOT, "AcDbRasterVariables"); + c.int(90, 0); + c.int(70, 0); + c.int(71, 1); + c.int(72, 0); + let keys: Vec = self.images.iter().map(|i| format!("IMAGE_{:X}", i.handle.0)).collect(); + let entries: Vec<(&str, Handle)> = keys.iter().zip(&self.images).map(|(key, image)| (key.as_str(), image.handle)).collect(); + dict(c, fixed::IMAGE_DICT, fixed::ROOT, &entries); + for img in &self.images { + c.raw(0, "IMAGEDEF"); + c.handle(5, img.handle); + c.raw(102, "{ACAD_REACTORS"); + c.handle(330, fixed::IMAGE_DICT); + for (reactor, _) in &img.reactors { + c.handle(330, *reactor); + } + c.raw(102, "}"); + c.handle(330, fixed::IMAGE_DICT); + c.raw(100, "AcDbRasterImageDef"); + c.int(90, 0); + c.str(1, &img.name); + c.xy(10, f64::from(img.size.0), f64::from(img.size.1)); + c.xy(11, 1.0, 1.0); + c.int(280, 1); + c.int(281, 0); + for (reactor, image) in &img.reactors { + c.object("IMAGEDEF_REACTOR", *reactor, *image, "AcDbRasterImageDefReactor"); + c.int(90, 2); + c.handle(330, *image); + } + } + } + c.end_section(); + } + + /// A layout (DXF 2000 and later): its plot settings, then the layout itself. + fn layout(&self, c: &mut Codes, h: Handle, name: &str, tab: i64, record: Handle) { + let [x0, y0, x1, y1] = self.extents; + c.object("LAYOUT", h, fixed::LAYOUTS, "AcDbPlotSettings"); + c.raw(1, ""); + c.raw(2, "none_device"); + c.raw(4, ""); + c.raw(6, ""); + for code in 40..=49 { + c.num(code, 0.0); + } + c.num(140, 0.0); + c.num(141, 0.0); + c.num(142, 1.0); + c.num(143, 1.0); + // Plot flags; 1024 marks the model space layout. + c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 }); + c.int(72, 1); + c.int(73, 0); + c.int(74, 5); + c.raw(7, ""); + c.int(75, 16); + if self.version.true_color() { + // Shade plot mode (as displayed), resolution level (normal) and custom DPI. + c.int(76, 0); + c.int(77, 2); + c.int(78, 300); + } + c.num(147, 1.0); + // The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158. + c.num(148, 0.0); + c.num(149, 0.0); + c.raw(100, "AcDbLayout"); + c.raw(1, name); + c.int(70, 1); + c.int(71, tab); + let [lx0, ly0, lx1, ly1] = self.limits; + c.xy(10, lx0, ly0); + c.xy(11, lx1, ly1); + c.xyz(12, 0.0, 0.0); + c.xyz(14, x0, y0); + c.xyz(15, x1, y1); + c.num(146, 0.0); + c.xyz(13, 0.0, 0.0); + c.xyz(16, 1.0, 0.0); + c.xyz(17, 0.0, 1.0); + c.int(76, 1); + c.handle(330, record); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numbers_and_text_are_written_plainly() { + assert_eq!(num(1.5), "1.5"); + assert_eq!(num(-0.0000001), "0"); + assert_eq!(num(2.0), "2"); + assert_eq!(num(f64::NAN), "0"); + assert_eq!(text("a^b\nc", true), "a^ b c"); + assert_eq!(text("Größe 😀", false), "Gr\\U+00F6\\U+00DFe ?"); + assert_eq!(text("Größe", true), "Größe"); + } + + /// A line from (0, 0) to (10, 20) on layer `Layer1`, in the style scene.rs writes entities. + fn line_entities(v: Format) -> String { + let mut e = Codes::new(v); + let style = EntityStyle { aci: 1, rgb: Some(0xFF0000), lineweight: Some(25), linetype: None, alpha: None }; + e.entity("LINE", Handle(fixed::FIRST_FREE), fixed::MODEL_RECORD, "Layer1", &style, "AcDbLine"); + e.xyz(10, 0.0, 0.0); + e.xyz(11, 10.0, 20.0); + e.into_string() + } + + fn sample(v: Format, with_line: bool) -> Drawing { + Drawing { + version: v, + layers: vec![Layer { name: "Layer1".into(), aci: 1, off: false, locked: false, plot: true }], + linetypes: vec![], + styles: vec![], + images: vec![], + entities: if with_line { line_entities(v) } else { String::new() }, + extents: [0.0, 0.0, 200.0, 100.0], + limits: [0.0, 0.0, 200.0, 100.0], + insunits: 4, + metric: true, + next: fixed::FIRST_FREE + if with_line { 1 } else { 0 }, + } + } + + fn assert_golden(name: &str, got: &str) { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data").join(name); + if std::env::var_os("WRITE_DXF_GOLDENS").is_some() { + std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir"); + std::fs::write(&path, got).expect("write golden"); + return; + } + let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())); + assert_eq!(got, expected, "bytes changed versus {}", path.display()); + } + + use std::path::PathBuf; + + #[test] + fn empty_and_line_drawings_match_goldens() { + for (name, v, line) in [ + ("drawing_empty_r12.dxf", Format::R12, false), + ("drawing_empty_r2018.dxf", Format::R2018, false), + ("drawing_line_r12.dxf", Format::R12, true), + ("drawing_line_r2000.dxf", Format::R2000, true), + ("drawing_line_r2018.dxf", Format::R2018, true), + ] { + assert_golden(name, &sample(v, line).write()); + } + } + + #[test] + fn entity_preserves_byblock_colour() { + for v in Format::ALL { + let mut c = Codes::new(v); + c.entity("LINE", Handle(fixed::FIRST_FREE), fixed::MODEL_RECORD, "0", &EntityStyle::default(), "AcDbLine"); + assert!(c.into_string().contains(" 62\n0\n"), "{v:?}"); + } + } + + #[test] + fn image_dictionary_keys_are_independent_of_filenames() { + let mut drawing = sample(Format::R2018, false); + for (index, name) in [r"C:\images\scan,1.png", "scan,1.png"].into_iter().enumerate() { + drawing.images.push(ImageDef { name: name.into(), size: (10, 20), handle: Handle(fixed::FIRST_FREE + index as u32), reactors: vec![] }); + } + drawing.next = fixed::FIRST_FREE + 2; + let images = drawing.images.clone(); + let output = drawing.write(); + for image in &images { + assert!(output.contains(&format!(" 3\nIMAGE_{:X}\n350\n{:X}\n", image.handle.0, image.handle.0))); + assert!(output.contains(&format!(" 1\n{}\n", image.name))); + assert!(!output.contains(&format!(" 3\n{}\n", image.name))); + } + } + + #[test] + fn every_format_writes_its_acadver_and_ends_at_eof() { + for v in Format::ALL { + let s = sample(v, true).write(); + assert!(s.contains(&format!(" 1\n{}\n", v.acadver())), "{v:?}"); + assert!(s.ends_with(" 0\nEOF\n"), "{v:?}"); + if v.handles() { + assert!(s.contains(" 0\nSECTION\n 2\nCLASSES\n"), "{v:?}"); + } else { + assert!(!s.contains("\nCLASSES\n"), "{v:?}"); + } + } + } +} diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 4cf3e46e9c..c4595bef9f 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -3,14 +3,18 @@ //! DXF is a sequence of (group code, value) pairs. This crate parses ASCII and binary DXF into a //! flat list of [`Tag`]s, splits them into sections and entities, and writes tags back. [`model`] //! reads the tags as a drawing (header variables, tables, blocks, entities, objects); mapping -//! that onto an application's own document is left to the caller. Written from Autodesk's +//! that onto an application's own document is left to the caller. [`drawing`] writes an ASCII +//! file around a pre-built `ENTITIES` section (VectorCraft's writer). Written from Autodesk's //! published DXF Reference; depends on no other Craft crate. Moved from CADCraft's `cadcraft-dxf`. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] use std::io::Write as _; +pub mod drawing; pub mod model; +pub mod mtext; +pub mod mtext_tokens; pub mod paths; mod version; pub use version::Version; @@ -195,8 +199,9 @@ pub use codepage::decode_code_page; /// # Errors /// /// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair, -/// truncated binary data, or more than [`MAX_TAGS`] group codes. For ASCII input, invalid numeric -/// text becomes `0.0` for real values or `0` for integer values, and an EOF tag is not required. +/// truncated binary data, or more group codes than the limit returned by [`max_tags()`], which is +/// [`MAX_TAGS`] by default. For ASCII input, invalid numeric text becomes `0.0` for real values or +/// `0` for integer values, and an EOF tag is not required. pub fn parse(bytes: &[u8]) -> Result> { parse_with_limit(bytes, max_tags()) } diff --git a/crates/dxf/src/mtext.rs b/crates/dxf/src/mtext.rs new file mode 100644 index 0000000000..9b113aa6cb --- /dev/null +++ b/crates/dxf/src/mtext.rs @@ -0,0 +1,103 @@ +//! MTEXT inline-escape handling independent of drawing and text layout. +//! +//! Unicode and MIF escapes are decoded to literal characters, with markup-significant +//! characters re-escaped so subsequent MTEXT parsers cannot treat them as commands. + +/// Whether an inline command takes an argument terminated by `;`. +pub fn takes_arg(code: char) -> bool { + matches!(code, 'f' | 'F' | 'H' | 'W' | 'Q' | 'T' | 'A' | 'C' | 'c' | 'p') +} + +/// Four hex digits at `chars[at..at + 4]`. +fn hex4(chars: &[char], at: usize) -> Option { + let digits = chars.get(at..at.checked_add(4)?)?; + digits.iter().try_fold(0u32, |acc, c| Some(acc * 16 + c.to_digit(16)?)) +} + +/// Push a decoded character so that the tokenizers read it as text, never as markup. +fn push_literal(out: &mut String, c: char) { + if matches!(c, '\\' | '{' | '}') { + out.push('\\'); + } + out.push(c); +} + +/// Decode `\U+hhhh` (one UTF-16 unit; a surrogate pair gives one character, a lone surrogate +/// U+FFFD) and `\M+nhhhh` (double-byte East Asian characters) to the characters they stand +/// for. Malformed escapes remain unchanged for the caller to interpret. +/// An escaped backslash (`\\U+0041`) is not an escape. +pub fn unescape_codes(s: &str) -> std::borrow::Cow<'_, str> { + if !s.contains("\\U+") && !s.contains("\\M+") { + return std::borrow::Cow::Borrowed(s); + } + let chars: Vec = s.chars().collect(); + let mut out = String::with_capacity(s.len()); + let mut i = 0; + while let Some(&c) = chars.get(i) { + if c != '\\' { + out.push(c); + i += 1; + continue; + } + let (n, plus) = (chars.get(i + 1).copied(), chars.get(i + 2).copied()); + if n == Some('U') && plus == Some('+') { + if let Some(unit) = hex4(&chars, i + 3) { + i += 7; + let low = |at: usize| { + (chars.get(at) == Some(&'\\') && chars.get(at + 1) == Some(&'U') && chars.get(at + 2) == Some(&'+')) + .then(|| hex4(&chars, at + 3)) + .flatten() + .filter(|u| (0xDC00..0xE000).contains(u)) + }; + let ch = if (0xD800..0xDC00).contains(&unit) { + match low(i) { + Some(lo) => { + i += 7; + char::from_u32(0x10000 + ((unit - 0xD800) << 10) + (lo - 0xDC00)) + } + None => None, + } + } else { + char::from_u32(unit) + }; + push_literal(&mut out, ch.unwrap_or('\u{fffd}')); + continue; + } + } else if n == Some('M') && plus == Some('+') && chars.get(i + 3).is_some_and(char::is_ascii_digit) && hex4(&chars, i + 4).is_some() { + push_literal(&mut out, crate::mif_escape_at(&chars, i).unwrap_or('\u{fffd}')); + i += 8; + continue; + } + // Any other backslash pair stays as it is (and an escaped backslash stays one). + out.push('\\'); + i += 1; + if let Some(&next) = chars.get(i) { + out.push(next); + i += 1; + } + } + std::borrow::Cow::Owned(out) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn unicode_and_mif_escapes_remain_literal_markup() { + assert_eq!(unescape_codes(r"a\U+0041\U+D83D\U+DE00"), "aA😀"); + assert_eq!(unescape_codes(r"\M+5BCFE"), "件"); + assert_eq!(unescape_codes(r"\U+005C\U+007B\U+007D"), r"\\\{\}"); + assert_eq!(unescape_codes(r"\\U+0041"), r"\\U+0041"); + assert_eq!(unescape_codes(r"\U+12"), r"\U+12"); + assert_eq!(unescape_codes(r"\U+D800"), "�"); + } + #[test] + fn parameterized_commands_are_classified_without_relaxing_others() { + for c in "fFHWQTACcp".chars() { + assert!(takes_arg(c)); + } + for c in ['S', 'P', 'Z', '\\'] { + assert!(!takes_arg(c)); + } + } +} diff --git a/crates/dxf/src/mtext_tokens.rs b/crates/dxf/src/mtext_tokens.rs new file mode 100644 index 0000000000..b07a9c2e0c --- /dev/null +++ b/crates/dxf/src/mtext_tokens.rs @@ -0,0 +1,132 @@ +//! Streaming lexical tokens for MTEXT inline markup. +//! +//! Apply [`crate::mtext::unescape_codes`] first when Unicode/MIF escapes should become literal +//! characters. Tokens borrow their source and scanning allocates no memory. The consumer owns +//! formatting, line layout, paragraph policy and how unknown commands are displayed. + +/// How a stacked-text argument finds its closing semicolon. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StackMode { + /// The first semicolon ends the stack, as plain-text extraction historically did. + Plain, + /// A backslash quotes the next character, as the structured layout parser does. + Structured, +} +/// One lexical unit. Unknown commands retain their letter so the caller chooses compatibility. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Token<'a> { + Char(char), + OpenGroup, + CloseGroup, + Control(char), + Argument(char, &'a str), + Stack(&'a str), + Unknown(char), +} +/// A bounded-memory walk of UTF-8 MTEXT markup. +pub struct Tokens<'a> { + source: &'a str, + offset: usize, + stack_mode: StackMode, +} +impl<'a> Tokens<'a> { + pub fn new(source: &'a str, stack_mode: StackMode) -> Self { + Self { source, offset: 0, stack_mode } + } + fn next_char(&mut self) -> Option { + let c = self.source.get(self.offset..)?.chars().next()?; + self.offset += c.len_utf8(); + Some(c) + } + fn argument(&mut self, structured: bool) -> &'a str { + let start = self.offset; + let mut end = start; + while let Some(c) = self.next_char() { + if c == ';' { + return self.source.get(start..end).unwrap_or_default(); + } + if structured && c == '\\' { + let _ = self.next_char(); + } + end = self.offset; + } + self.source.get(start..end).unwrap_or_default() + } +} +impl<'a> Iterator for Tokens<'a> { + type Item = Token<'a>; + fn next(&mut self) -> Option { + let c = self.next_char()?; + Some(match c { + '{' => Token::OpenGroup, + '}' => Token::CloseGroup, + '\\' => { + let code = self.next_char()?; + match code { + 'S' => Token::Stack(self.argument(self.stack_mode == StackMode::Structured)), + c if crate::mtext::takes_arg(c) => Token::Argument(c, self.argument(false)), + c @ ('P' | 'N' | '~' | '\\' | '{' | '}' | 'L' | 'l' | 'O' | 'o' | 'K' | 'k') => Token::Control(c), + c => Token::Unknown(c), + } + } + c => Token::Char(c), + }) + } +} +/// Split a structured stack into top, bottom and separator, unquoting escaped characters. +pub fn split_stack(raw: &str) -> (String, String, Option) { + let (mut top, mut bottom, mut separator) = (String::new(), String::new(), None); + let mut chars = raw.chars(); + while let Some(c) = chars.next() { + if c == '\\' { + if let Some(c) = chars.next() { + if separator.is_none() { + top.push(c); + } else { + bottom.push(c); + } + } + } else if separator.is_none() && matches!(c, '/' | '#' | '^') { + separator = Some(c); + } else if separator.is_none() { + top.push(c); + } else { + bottom.push(c); + } + } + (top, bottom, separator) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn tokens_borrow_text_and_preserve_unknown_commands() { + let got: Vec<_> = Tokens::new(r"A\Z\P{\H2x;x}\S1/2;", StackMode::Structured).collect(); + assert_eq!( + got, + [ + Token::Char('A'), + Token::Unknown('Z'), + Token::Control('P'), + Token::OpenGroup, + Token::Argument('H', "2x"), + Token::Char('x'), + Token::CloseGroup, + Token::Stack("1/2") + ] + ); + assert_eq!(split_stack("1/2"), ("1".into(), "2".into(), Some('/'))); + } + #[test] + fn stacked_text_uses_the_requested_terminator_rules() { + let text = r"\Sa\;b/c;X"; + assert_eq!(Tokens::new(text, StackMode::Plain).next(), Some(Token::Stack(r"a\"))); + assert_eq!(Tokens::new(text, StackMode::Structured).next(), Some(Token::Stack(r"a\;b/c"))); + assert_eq!(split_stack(r"a\;b/c"), ("a;b".into(), "c".into(), Some('/'))); + } + #[test] + fn missing_terminator_and_trailing_backslash_are_bounded() { + assert_eq!(Tokens::new("\\H2x", StackMode::Structured).collect::>(), [Token::Argument('H', "2x")]); + assert_eq!(Tokens::new("a\\", StackMode::Structured).collect::>(), [Token::Char('a')]); + } +} diff --git a/crates/dxf/tests/data/drawing_empty_r12.dxf b/crates/dxf/tests/data/drawing_empty_r12.dxf new file mode 100644 index 0000000000..402512d9ec --- /dev/null +++ b/crates/dxf/tests/data/drawing_empty_r12.dxf @@ -0,0 +1,250 @@ + 0 +SECTION + 2 +HEADER + 9 +$ACADVER + 1 +AC1009 + 9 +$DWGCODEPAGE + 3 +ANSI_1252 + 9 +$INSBASE + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMIN + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMAX + 10 +200 + 20 +100 + 30 +0 + 9 +$LIMMIN + 10 +0 + 20 +0 + 9 +$LIMMAX + 10 +200 + 20 +100 + 0 +ENDSEC + 0 +SECTION + 2 +TABLES + 0 +TABLE + 2 +VPORT + 70 +1 + 0 +VPORT + 2 +*ACTIVE + 70 +0 + 10 +0 + 20 +0 + 11 +1 + 21 +1 + 12 +100 + 22 +50 + 13 +0 + 23 +0 + 14 +1 + 24 +1 + 15 +10 + 25 +10 + 16 +0 + 26 +0 + 36 +1 + 17 +0 + 27 +0 + 37 +0 + 40 +146.666667 + 41 +1.5 + 42 +50 + 43 +0 + 44 +0 + 50 +0 + 51 +0 + 71 +0 + 72 +1000 + 73 +1 + 74 +3 + 75 +0 + 76 +0 + 77 +0 + 78 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LTYPE + 70 +3 + 0 +LTYPE + 2 +ByBlock + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 2 +ByLayer + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 2 +Continuous + 70 +0 + 3 +Solid line + 72 +65 + 73 +0 + 40 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LAYER + 70 +2 + 0 +LAYER + 2 +0 + 70 +0 + 62 +7 + 6 +Continuous + 0 +LAYER + 2 +Layer1 + 70 +0 + 62 +1 + 6 +Continuous + 0 +ENDTAB + 0 +TABLE + 2 +STYLE + 70 +1 + 0 +STYLE + 2 +Standard + 70 +0 + 40 +0 + 41 +1 + 50 +0 + 71 +0 + 42 +2.5 + 3 +txt + 4 + + 0 +ENDTAB + 0 +ENDSEC + 0 +SECTION + 2 +ENTITIES + 0 +ENDSEC + 0 +EOF diff --git a/crates/dxf/tests/data/drawing_empty_r2018.dxf b/crates/dxf/tests/data/drawing_empty_r2018.dxf new file mode 100644 index 0000000000..01e9d07b32 --- /dev/null +++ b/crates/dxf/tests/data/drawing_empty_r2018.dxf @@ -0,0 +1,972 @@ + 0 +SECTION + 2 +HEADER + 9 +$ACADVER + 1 +AC1032 + 9 +$DWGCODEPAGE + 3 +ANSI_1252 + 9 +$INSBASE + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMIN + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMAX + 10 +200 + 20 +100 + 30 +0 + 9 +$LIMMIN + 10 +0 + 20 +0 + 9 +$LIMMAX + 10 +200 + 20 +100 + 9 +$LWDISPLAY +290 +1 + 9 +$INSUNITS + 70 +4 + 9 +$MEASUREMENT + 70 +1 + 9 +$HANDSEED + 5 +36 + 0 +ENDSEC + 0 +SECTION + 2 +CLASSES + 0 +CLASS + 1 +ACDBDICTIONARYWDFLT + 2 +AcDbDictionaryWithDefault + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +ACDBPLACEHOLDER + 2 +AcDbPlaceHolder + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +LAYOUT + 2 +AcDbLayout + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +ENDSEC + 0 +SECTION + 2 +TABLES + 0 +TABLE + 2 +VPORT + 5 +8 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +VPORT + 5 +15 +330 +8 +100 +AcDbSymbolTableRecord +100 +AcDbViewportTableRecord + 2 +*Active + 70 +0 + 10 +0 + 20 +0 + 11 +1 + 21 +1 + 12 +100 + 22 +50 + 13 +0 + 23 +0 + 14 +1 + 24 +1 + 15 +10 + 25 +10 + 16 +0 + 26 +0 + 36 +1 + 17 +0 + 27 +0 + 37 +0 + 40 +146.666667 + 41 +1.5 + 42 +50 + 43 +0 + 44 +0 + 50 +0 + 51 +0 + 71 +0 + 72 +1000 + 73 +1 + 74 +3 + 75 +0 + 76 +0 + 77 +0 + 78 +0 +281 +0 + 65 +0 +146 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LTYPE + 5 +2 +330 +0 +100 +AcDbSymbolTable + 70 +3 + 0 +LTYPE + 5 +30 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByBlock + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +31 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByLayer + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +32 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +Continuous + 70 +0 + 3 +Solid line + 72 +65 + 73 +0 + 40 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LAYER + 5 +1 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +LAYER + 5 +33 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +0 + 70 +0 + 62 +7 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +LAYER + 5 +34 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +Layer1 + 70 +0 + 62 +1 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +ENDTAB + 0 +TABLE + 2 +STYLE + 5 +5 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +STYLE + 5 +35 +330 +5 +100 +AcDbSymbolTableRecord +100 +AcDbTextStyleTableRecord + 2 +Standard + 70 +0 + 40 +0 + 41 +1 + 50 +0 + 71 +0 + 42 +2.5 + 3 +txt + 4 + + 0 +ENDTAB + 0 +TABLE + 2 +VIEW + 5 +7 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +UCS + 5 +6 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +APPID + 5 +3 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +APPID + 5 +16 +330 +3 +100 +AcDbSymbolTableRecord +100 +AcDbRegAppTableRecord + 2 +ACAD + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +DIMSTYLE + 5 +4 +330 +0 +100 +AcDbSymbolTable + 70 +1 +100 +AcDbDimStyleTable + 0 +DIMSTYLE +105 +17 +330 +4 +100 +AcDbSymbolTableRecord +100 +AcDbDimStyleTableRecord + 2 +Standard + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +BLOCK_RECORD + 5 +9 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +BLOCK_RECORD + 5 +D +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Model_Space +340 +13 + 70 +0 +280 +1 +281 +0 + 0 +BLOCK_RECORD + 5 +E +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Paper_Space +340 +14 + 70 +0 +280 +1 +281 +0 + 0 +ENDTAB + 0 +ENDSEC + 0 +SECTION + 2 +BLOCKS + 0 +BLOCK + 5 +F +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Model_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Model_Space + 1 + + 0 +ENDBLK + 5 +10 +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +BLOCK + 5 +11 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Paper_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Paper_Space + 1 + + 0 +ENDBLK + 5 +12 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +ENDSEC + 0 +SECTION + 2 +ENTITIES + 0 +ENDSEC + 0 +SECTION + 2 +OBJECTS + 0 +DICTIONARY + 5 +A +330 +0 +100 +AcDbDictionary +281 +1 + 3 +ACAD_GROUP +350 +B + 3 +ACAD_LAYOUT +350 +C + 3 +ACAD_PLOTSTYLENAME +350 +1A + 0 +DICTIONARY + 5 +B +330 +A +100 +AcDbDictionary +281 +1 + 0 +DICTIONARY + 5 +C +330 +A +100 +AcDbDictionary +281 +1 + 3 +Layout1 +350 +14 + 3 +Model +350 +13 + 0 +ACDBDICTIONARYWDFLT + 5 +1A +330 +A +100 +AcDbDictionary +281 +1 + 3 +Normal +350 +1B +100 +AcDbDictionaryWithDefault +340 +1B + 0 +ACDBPLACEHOLDER + 5 +1B +330 +1A + 0 +LAYOUT + 5 +13 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +1712 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 + 76 +0 + 77 +2 + 78 +300 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Model + 70 +1 + 71 +0 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +0 + 24 +0 + 34 +0 + 15 +200 + 25 +100 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +D + 0 +LAYOUT + 5 +14 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +688 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 + 76 +0 + 77 +2 + 78 +300 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Layout1 + 70 +1 + 71 +1 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +0 + 24 +0 + 34 +0 + 15 +200 + 25 +100 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +E + 0 +ENDSEC + 0 +EOF diff --git a/crates/dxf/tests/data/drawing_line_r12.dxf b/crates/dxf/tests/data/drawing_line_r12.dxf new file mode 100644 index 0000000000..6810c07cb6 --- /dev/null +++ b/crates/dxf/tests/data/drawing_line_r12.dxf @@ -0,0 +1,268 @@ + 0 +SECTION + 2 +HEADER + 9 +$ACADVER + 1 +AC1009 + 9 +$DWGCODEPAGE + 3 +ANSI_1252 + 9 +$INSBASE + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMIN + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMAX + 10 +200 + 20 +100 + 30 +0 + 9 +$LIMMIN + 10 +0 + 20 +0 + 9 +$LIMMAX + 10 +200 + 20 +100 + 0 +ENDSEC + 0 +SECTION + 2 +TABLES + 0 +TABLE + 2 +VPORT + 70 +1 + 0 +VPORT + 2 +*ACTIVE + 70 +0 + 10 +0 + 20 +0 + 11 +1 + 21 +1 + 12 +100 + 22 +50 + 13 +0 + 23 +0 + 14 +1 + 24 +1 + 15 +10 + 25 +10 + 16 +0 + 26 +0 + 36 +1 + 17 +0 + 27 +0 + 37 +0 + 40 +146.666667 + 41 +1.5 + 42 +50 + 43 +0 + 44 +0 + 50 +0 + 51 +0 + 71 +0 + 72 +1000 + 73 +1 + 74 +3 + 75 +0 + 76 +0 + 77 +0 + 78 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LTYPE + 70 +3 + 0 +LTYPE + 2 +ByBlock + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 2 +ByLayer + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 2 +Continuous + 70 +0 + 3 +Solid line + 72 +65 + 73 +0 + 40 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LAYER + 70 +2 + 0 +LAYER + 2 +0 + 70 +0 + 62 +7 + 6 +Continuous + 0 +LAYER + 2 +Layer1 + 70 +0 + 62 +1 + 6 +Continuous + 0 +ENDTAB + 0 +TABLE + 2 +STYLE + 70 +1 + 0 +STYLE + 2 +Standard + 70 +0 + 40 +0 + 41 +1 + 50 +0 + 71 +0 + 42 +2.5 + 3 +txt + 4 + + 0 +ENDTAB + 0 +ENDSEC + 0 +SECTION + 2 +ENTITIES + 0 +LINE + 8 +Layer1 + 62 +1 + 10 +0 + 20 +0 + 30 +0 + 11 +10 + 21 +20 + 31 +0 + 0 +ENDSEC + 0 +EOF diff --git a/crates/dxf/tests/data/drawing_line_r2000.dxf b/crates/dxf/tests/data/drawing_line_r2000.dxf new file mode 100644 index 0000000000..173a9b4270 --- /dev/null +++ b/crates/dxf/tests/data/drawing_line_r2000.dxf @@ -0,0 +1,982 @@ + 0 +SECTION + 2 +HEADER + 9 +$ACADVER + 1 +AC1015 + 9 +$DWGCODEPAGE + 3 +ANSI_1252 + 9 +$INSBASE + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMIN + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMAX + 10 +200 + 20 +100 + 30 +0 + 9 +$LIMMIN + 10 +0 + 20 +0 + 9 +$LIMMAX + 10 +200 + 20 +100 + 9 +$LWDISPLAY +290 +1 + 9 +$INSUNITS + 70 +4 + 9 +$MEASUREMENT + 70 +1 + 9 +$HANDSEED + 5 +37 + 0 +ENDSEC + 0 +SECTION + 2 +CLASSES + 0 +CLASS + 1 +ACDBDICTIONARYWDFLT + 2 +AcDbDictionaryWithDefault + 3 +ObjectDBX Classes + 90 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +ACDBPLACEHOLDER + 2 +AcDbPlaceHolder + 3 +ObjectDBX Classes + 90 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +LAYOUT + 2 +AcDbLayout + 3 +ObjectDBX Classes + 90 +0 +280 +0 +281 +0 + 0 +ENDSEC + 0 +SECTION + 2 +TABLES + 0 +TABLE + 2 +VPORT + 5 +8 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +VPORT + 5 +15 +330 +8 +100 +AcDbSymbolTableRecord +100 +AcDbViewportTableRecord + 2 +*Active + 70 +0 + 10 +0 + 20 +0 + 11 +1 + 21 +1 + 12 +100 + 22 +50 + 13 +0 + 23 +0 + 14 +1 + 24 +1 + 15 +10 + 25 +10 + 16 +0 + 26 +0 + 36 +1 + 17 +0 + 27 +0 + 37 +0 + 40 +146.666667 + 41 +1.5 + 42 +50 + 43 +0 + 44 +0 + 50 +0 + 51 +0 + 71 +0 + 72 +1000 + 73 +1 + 74 +3 + 75 +0 + 76 +0 + 77 +0 + 78 +0 +281 +0 + 65 +0 +146 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LTYPE + 5 +2 +330 +0 +100 +AcDbSymbolTable + 70 +3 + 0 +LTYPE + 5 +31 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByBlock + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +32 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByLayer + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +33 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +Continuous + 70 +0 + 3 +Solid line + 72 +65 + 73 +0 + 40 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LAYER + 5 +1 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +LAYER + 5 +34 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +0 + 70 +0 + 62 +7 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +LAYER + 5 +35 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +Layer1 + 70 +0 + 62 +1 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +ENDTAB + 0 +TABLE + 2 +STYLE + 5 +5 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +STYLE + 5 +36 +330 +5 +100 +AcDbSymbolTableRecord +100 +AcDbTextStyleTableRecord + 2 +Standard + 70 +0 + 40 +0 + 41 +1 + 50 +0 + 71 +0 + 42 +2.5 + 3 +txt + 4 + + 0 +ENDTAB + 0 +TABLE + 2 +VIEW + 5 +7 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +UCS + 5 +6 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +APPID + 5 +3 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +APPID + 5 +16 +330 +3 +100 +AcDbSymbolTableRecord +100 +AcDbRegAppTableRecord + 2 +ACAD + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +DIMSTYLE + 5 +4 +330 +0 +100 +AcDbSymbolTable + 70 +1 +100 +AcDbDimStyleTable + 0 +DIMSTYLE +105 +17 +330 +4 +100 +AcDbSymbolTableRecord +100 +AcDbDimStyleTableRecord + 2 +Standard + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +BLOCK_RECORD + 5 +9 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +BLOCK_RECORD + 5 +D +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Model_Space +340 +13 + 70 +0 +280 +1 +281 +0 + 0 +BLOCK_RECORD + 5 +E +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Paper_Space +340 +14 + 70 +0 +280 +1 +281 +0 + 0 +ENDTAB + 0 +ENDSEC + 0 +SECTION + 2 +BLOCKS + 0 +BLOCK + 5 +F +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Model_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Model_Space + 1 + + 0 +ENDBLK + 5 +10 +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +BLOCK + 5 +11 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Paper_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Paper_Space + 1 + + 0 +ENDBLK + 5 +12 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +ENDSEC + 0 +SECTION + 2 +ENTITIES + 0 +LINE + 5 +30 +330 +D +100 +AcDbEntity + 8 +Layer1 + 62 +1 +370 +25 +100 +AcDbLine + 10 +0 + 20 +0 + 30 +0 + 11 +10 + 21 +20 + 31 +0 + 0 +ENDSEC + 0 +SECTION + 2 +OBJECTS + 0 +DICTIONARY + 5 +A +330 +0 +100 +AcDbDictionary +281 +1 + 3 +ACAD_GROUP +350 +B + 3 +ACAD_LAYOUT +350 +C + 3 +ACAD_PLOTSTYLENAME +350 +1A + 0 +DICTIONARY + 5 +B +330 +A +100 +AcDbDictionary +281 +1 + 0 +DICTIONARY + 5 +C +330 +A +100 +AcDbDictionary +281 +1 + 3 +Layout1 +350 +14 + 3 +Model +350 +13 + 0 +ACDBDICTIONARYWDFLT + 5 +1A +330 +A +100 +AcDbDictionary +281 +1 + 3 +Normal +350 +1B +100 +AcDbDictionaryWithDefault +340 +1B + 0 +ACDBPLACEHOLDER + 5 +1B +330 +1A + 0 +LAYOUT + 5 +13 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +1712 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Model + 70 +1 + 71 +0 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +0 + 24 +0 + 34 +0 + 15 +200 + 25 +100 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +D + 0 +LAYOUT + 5 +14 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +688 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Layout1 + 70 +1 + 71 +1 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +0 + 24 +0 + 34 +0 + 15 +200 + 25 +100 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +E + 0 +ENDSEC + 0 +EOF diff --git a/crates/dxf/tests/data/drawing_line_r2018.dxf b/crates/dxf/tests/data/drawing_line_r2018.dxf new file mode 100644 index 0000000000..8318c1c5e9 --- /dev/null +++ b/crates/dxf/tests/data/drawing_line_r2018.dxf @@ -0,0 +1,1002 @@ + 0 +SECTION + 2 +HEADER + 9 +$ACADVER + 1 +AC1032 + 9 +$DWGCODEPAGE + 3 +ANSI_1252 + 9 +$INSBASE + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMIN + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMAX + 10 +200 + 20 +100 + 30 +0 + 9 +$LIMMIN + 10 +0 + 20 +0 + 9 +$LIMMAX + 10 +200 + 20 +100 + 9 +$LWDISPLAY +290 +1 + 9 +$INSUNITS + 70 +4 + 9 +$MEASUREMENT + 70 +1 + 9 +$HANDSEED + 5 +37 + 0 +ENDSEC + 0 +SECTION + 2 +CLASSES + 0 +CLASS + 1 +ACDBDICTIONARYWDFLT + 2 +AcDbDictionaryWithDefault + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +ACDBPLACEHOLDER + 2 +AcDbPlaceHolder + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +LAYOUT + 2 +AcDbLayout + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +ENDSEC + 0 +SECTION + 2 +TABLES + 0 +TABLE + 2 +VPORT + 5 +8 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +VPORT + 5 +15 +330 +8 +100 +AcDbSymbolTableRecord +100 +AcDbViewportTableRecord + 2 +*Active + 70 +0 + 10 +0 + 20 +0 + 11 +1 + 21 +1 + 12 +100 + 22 +50 + 13 +0 + 23 +0 + 14 +1 + 24 +1 + 15 +10 + 25 +10 + 16 +0 + 26 +0 + 36 +1 + 17 +0 + 27 +0 + 37 +0 + 40 +146.666667 + 41 +1.5 + 42 +50 + 43 +0 + 44 +0 + 50 +0 + 51 +0 + 71 +0 + 72 +1000 + 73 +1 + 74 +3 + 75 +0 + 76 +0 + 77 +0 + 78 +0 +281 +0 + 65 +0 +146 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LTYPE + 5 +2 +330 +0 +100 +AcDbSymbolTable + 70 +3 + 0 +LTYPE + 5 +31 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByBlock + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +32 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByLayer + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +33 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +Continuous + 70 +0 + 3 +Solid line + 72 +65 + 73 +0 + 40 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LAYER + 5 +1 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +LAYER + 5 +34 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +0 + 70 +0 + 62 +7 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +LAYER + 5 +35 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +Layer1 + 70 +0 + 62 +1 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +ENDTAB + 0 +TABLE + 2 +STYLE + 5 +5 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +STYLE + 5 +36 +330 +5 +100 +AcDbSymbolTableRecord +100 +AcDbTextStyleTableRecord + 2 +Standard + 70 +0 + 40 +0 + 41 +1 + 50 +0 + 71 +0 + 42 +2.5 + 3 +txt + 4 + + 0 +ENDTAB + 0 +TABLE + 2 +VIEW + 5 +7 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +UCS + 5 +6 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +APPID + 5 +3 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +APPID + 5 +16 +330 +3 +100 +AcDbSymbolTableRecord +100 +AcDbRegAppTableRecord + 2 +ACAD + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +DIMSTYLE + 5 +4 +330 +0 +100 +AcDbSymbolTable + 70 +1 +100 +AcDbDimStyleTable + 0 +DIMSTYLE +105 +17 +330 +4 +100 +AcDbSymbolTableRecord +100 +AcDbDimStyleTableRecord + 2 +Standard + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +BLOCK_RECORD + 5 +9 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +BLOCK_RECORD + 5 +D +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Model_Space +340 +13 + 70 +0 +280 +1 +281 +0 + 0 +BLOCK_RECORD + 5 +E +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Paper_Space +340 +14 + 70 +0 +280 +1 +281 +0 + 0 +ENDTAB + 0 +ENDSEC + 0 +SECTION + 2 +BLOCKS + 0 +BLOCK + 5 +F +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Model_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Model_Space + 1 + + 0 +ENDBLK + 5 +10 +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +BLOCK + 5 +11 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Paper_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Paper_Space + 1 + + 0 +ENDBLK + 5 +12 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +ENDSEC + 0 +SECTION + 2 +ENTITIES + 0 +LINE + 5 +30 +330 +D +100 +AcDbEntity + 8 +Layer1 + 62 +1 +370 +25 +420 +16711680 +100 +AcDbLine + 10 +0 + 20 +0 + 30 +0 + 11 +10 + 21 +20 + 31 +0 + 0 +ENDSEC + 0 +SECTION + 2 +OBJECTS + 0 +DICTIONARY + 5 +A +330 +0 +100 +AcDbDictionary +281 +1 + 3 +ACAD_GROUP +350 +B + 3 +ACAD_LAYOUT +350 +C + 3 +ACAD_PLOTSTYLENAME +350 +1A + 0 +DICTIONARY + 5 +B +330 +A +100 +AcDbDictionary +281 +1 + 0 +DICTIONARY + 5 +C +330 +A +100 +AcDbDictionary +281 +1 + 3 +Layout1 +350 +14 + 3 +Model +350 +13 + 0 +ACDBDICTIONARYWDFLT + 5 +1A +330 +A +100 +AcDbDictionary +281 +1 + 3 +Normal +350 +1B +100 +AcDbDictionaryWithDefault +340 +1B + 0 +ACDBPLACEHOLDER + 5 +1B +330 +1A + 0 +LAYOUT + 5 +13 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +1712 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 + 76 +0 + 77 +2 + 78 +300 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Model + 70 +1 + 71 +0 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +0 + 24 +0 + 34 +0 + 15 +200 + 25 +100 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +D + 0 +LAYOUT + 5 +14 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +688 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 + 76 +0 + 77 +2 + 78 +300 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Layout1 + 70 +1 + 71 +1 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +0 + 24 +0 + 34 +0 + 15 +200 + 25 +100 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +E + 0 +ENDSEC + 0 +EOF diff --git a/crates/elf/Cargo.toml b/crates/elf/Cargo.toml new file mode 100644 index 0000000000..e982689e4f --- /dev/null +++ b/crates/elf/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "craft-elf" +description = "ELF program headers and dynamic section entries from hostile bytes, from Craft Anything: 32/64-bit, either byte order, with bounded counts and overflow-checked offsets, plus segment, permission and dynamic tag names. Pure Rust, no I/O." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +thiserror = { workspace = true } +# `serde`: `Serialize` on `ProgramHeader` (addresses as `0x…` strings), for apps that report +# segments as JSON. +serde = { workspace = true, optional = true } + +[features] +serde = ["dep:serde"] + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/elf/src/bytes.rs b/crates/elf/src/bytes.rs new file mode 100644 index 0000000000..c78b9b5a8e --- /dev/null +++ b/crates/elf/src/bytes.rs @@ -0,0 +1,37 @@ +//! Bounds-checked reads of fixed-width integers in both byte orders: out of range is `None`. + +#[derive(Debug, Clone, Copy)] +pub(crate) struct Reader<'a> { + buf: &'a [u8], +} + +macro_rules! int { + ($le:ident, $be:ident, $ty:ty) => { + pub(crate) fn $le(&self, at: usize) -> Option<$ty> { + self.take(at).map(<$ty>::from_le_bytes) + } + + pub(crate) fn $be(&self, at: usize) -> Option<$ty> { + self.take(at).map(<$ty>::from_be_bytes) + } + }; +} + +impl<'a> Reader<'a> { + pub(crate) fn new(buf: &'a [u8]) -> Self { + Self { buf } + } + + pub(crate) fn u8(&self, at: usize) -> Option { + self.buf.get(at).copied() + } + + fn take(&self, at: usize) -> Option<[u8; N]> { + let end = at.checked_add(N)?; + self.buf.get(at..end)?.try_into().ok() + } + + int!(u16_le, u16_be, u16); + int!(u32_le, u32_be, u32); + int!(u64_le, u64_be, u64); +} diff --git a/crates/elf/src/hex.rs b/crates/elf/src/hex.rs new file mode 100644 index 0000000000..82dfd4bba5 --- /dev/null +++ b/crates/elf/src/hex.rs @@ -0,0 +1,5 @@ +//! Addresses serialised as `0x…` strings, as Craft Anything reports them. + +pub(crate) fn serialize(value: &u64, serializer: S) -> Result { + serializer.serialize_str(&format!("{value:#x}")) +} diff --git a/crates/elf/src/lib.rs b/crates/elf/src/lib.rs new file mode 100644 index 0000000000..b8868f7345 --- /dev/null +++ b/crates/elf/src/lib.rs @@ -0,0 +1,244 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! ELF program headers and dynamic section entries from untrusted bytes, 32- or 64-bit in either +//! byte order: [`program_headers`], [`dynamic_entries`], [`va_to_off`], and the segment type, +//! permission and dynamic tag names. +//! +//! From Craft Anything (`crates/formats/src/elf.rs`), where the mitigations, dynamic symbols, +//! symbol versions and core-file notes built on these stay. With the `serde` feature, +//! [`ProgramHeader`] is `Serialize` with `vaddr` as a `0x…` string. + +mod bytes; +#[cfg(feature = "serde")] +mod hex; + +use crate::bytes::Reader; + +/// Program headers read from one table. +pub const MAX_PHDRS: usize = 4096; + +/// Dynamic entries read from one segment. +pub const MAX_DYN: usize = 65_536; + +/// Why a read gave up. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ElfError { + /// The ELF header ends before the file does. + #[error("the file ends early ({0})")] + Truncated(&'static str), + /// No ELF magic, or an invalid class, encoding or field. + #[error("the file is malformed ({0})")] + Malformed(String), +} + +/// Endian/class-aware reads over an ELF image. +#[derive(Clone, Copy)] +struct E<'a> { + r: Reader<'a>, + is64: bool, + le: bool, +} + +impl<'a> E<'a> { + fn new(data: &'a [u8]) -> Result { + if !data.starts_with(b"\x7fELF") { + return Err(ElfError::Malformed("no ELF magic".into())); + } + let r = Reader::new(data); + let class = r.u8(4).ok_or(ElfError::Truncated("ELF ident"))?; + let enc = r.u8(5).ok_or(ElfError::Truncated("ELF ident"))?; + if !matches!(class, 1 | 2) || !matches!(enc, 1 | 2) { + return Err(ElfError::Malformed("bad ELF class or data encoding".into())); + } + Ok(E { r, is64: class == 2, le: enc == 1 }) + } + + fn u16(&self, off: usize) -> Option { + if self.le { self.r.u16_le(off) } else { self.r.u16_be(off) } + } + + fn u32(&self, off: usize) -> Option { + if self.le { self.r.u32_le(off) } else { self.r.u32_be(off) } + } + + fn u64(&self, off: usize) -> Option { + if self.le { self.r.u64_le(off) } else { self.r.u64_be(off) } + } + + fn word(&self, off: usize) -> Option { + if self.is64 { self.u64(off) } else { self.u32(off).map(u64::from) } + } + + fn word_size(&self) -> usize { + if self.is64 { 8 } else { 4 } + } +} + +/// One program header. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct ProgramHeader { + /// [`segment_type_name`] of `p_type`. + pub kind: String, + /// [`permissions`] of `p_flags`. + pub flags: String, + pub offset: u64, + #[cfg_attr(feature = "serde", serde(serialize_with = "hex::serialize"))] + pub vaddr: u64, + pub file_size: u64, + pub mem_size: u64, + pub align: u64, + /// The raw segment type. + #[cfg_attr(feature = "serde", serde(skip))] + pub p_type: u32, + /// The raw `PF_R`/`PF_W`/`PF_X` flags. + #[cfg_attr(feature = "serde", serde(skip))] + pub p_flags: u32, +} + +/// A segment type's `PT_` name without the prefix (`LOAD`, `GNU_RELRO`…), or its number in hex. +pub fn segment_type_name(t: u32) -> String { + match t { + 0 => "NULL".into(), + 1 => "LOAD".into(), + 2 => "DYNAMIC".into(), + 3 => "INTERP".into(), + 4 => "NOTE".into(), + 5 => "SHLIB".into(), + 6 => "PHDR".into(), + 7 => "TLS".into(), + 0x6474_e550 => "GNU_EH_FRAME".into(), + 0x6474_e551 => "GNU_STACK".into(), + 0x6474_e552 => "GNU_RELRO".into(), + 0x6474_e553 => "GNU_PROPERTY".into(), + 0x7000_0001 => "ARM_EXIDX".into(), + other => format!("{other:#x}"), + } +} + +/// `p_flags` as `rwx`, with `-` for each permission missing. +pub fn permissions(f: u32) -> String { + format!("{}{}{}", if f & 4 != 0 { 'r' } else { '-' }, if f & 2 != 0 { 'w' } else { '-' }, if f & 1 != 0 { 'x' } else { '-' }) +} + +/// The program headers of an ELF file, at most [`MAX_PHDRS`]. A table that runs past the file +/// ends at the last complete entry. +pub fn program_headers(data: &[u8]) -> Result, ElfError> { + let e = E::new(data)?; + let (phoff, phentsize, phnum) = if e.is64 { (e.u64(32), e.u16(54), e.u16(56)) } else { (e.u32(28).map(u64::from), e.u16(42), e.u16(44)) }; + let phoff = usize::try_from(phoff.ok_or(ElfError::Truncated("ELF header"))?).map_err(|_| ElfError::Malformed("phoff".into()))?; + let phentsize = usize::from(phentsize.unwrap_or(0)); + let phnum = usize::from(phnum.unwrap_or(0)).min(MAX_PHDRS); + let min = if e.is64 { 56 } else { 32 }; + if phnum > 0 && phentsize < min { + return Err(ElfError::Malformed("program header entry too small".into())); + } + let mut out = Vec::new(); + for i in 0..phnum { + // The fields below sit within `phentsize` bytes of `o`, so their offsets can't overflow either. + let Some(o) = i.checked_mul(phentsize).and_then(|x| x.checked_add(phoff)).filter(|&o| o.checked_add(phentsize).is_some()) else { break }; + let ph = if e.is64 { + (e.u32(o), e.u32(o + 4), e.u64(o + 8), e.u64(o + 16), e.u64(o + 32), e.u64(o + 40), e.u64(o + 48)) + } else { + ( + e.u32(o), + e.u32(o + 24), + e.u32(o + 4).map(u64::from), + e.u32(o + 8).map(u64::from), + e.u32(o + 16).map(u64::from), + e.u32(o + 20).map(u64::from), + e.u32(o + 28).map(u64::from), + ) + }; + let (Some(t), Some(f), Some(off), Some(va), Some(fs), Some(ms), Some(al)) = ph else { break }; + out.push(ProgramHeader { + kind: segment_type_name(t), + flags: permissions(f), + offset: off, + vaddr: va, + file_size: fs, + mem_size: ms, + align: al, + p_type: t, + p_flags: f, + }); + } + Ok(out) +} + +/// A dynamic tag's `DT_` name without the prefix (`NEEDED`, `GNU_HASH`…), or its number in hex. +pub fn dynamic_tag_name(tag: u64) -> String { + match tag { + 0 => "NULL", + 1 => "NEEDED", + 2 => "PLTRELSZ", + 3 => "PLTGOT", + 4 => "HASH", + 5 => "STRTAB", + 6 => "SYMTAB", + 7 => "RELA", + 8 => "RELASZ", + 9 => "RELAENT", + 10 => "STRSZ", + 11 => "SYMENT", + 12 => "INIT", + 13 => "FINI", + 14 => "SONAME", + 15 => "RPATH", + 16 => "SYMBOLIC", + 17 => "REL", + 18 => "RELSZ", + 19 => "RELENT", + 20 => "PLTREL", + 21 => "DEBUG", + 22 => "TEXTREL", + 23 => "JMPREL", + 24 => "BIND_NOW", + 25 => "INIT_ARRAY", + 26 => "FINI_ARRAY", + 27 => "INIT_ARRAYSZ", + 28 => "FINI_ARRAYSZ", + 29 => "RUNPATH", + 30 => "FLAGS", + 0x6fff_fef5 => "GNU_HASH", + 0x6fff_fffb => "FLAGS_1", + 0x6fff_fff0 => "VERSYM", + 0x6fff_fffe => "VERNEED", + 0x6fff_ffff => "VERNEEDNUM", + _ => return format!("{tag:#x}"), + } + .into() +} + +/// Map a virtual address to a file offset using `PT_LOAD` headers. Addresses in a segment's +/// zero-filled tail, or whose offset would overflow, map to nothing. +pub fn va_to_off(phdrs: &[ProgramHeader], va: u64) -> Option { + phdrs.iter().filter(|p| p.p_type == 1).find(|p| va >= p.vaddr && va - p.vaddr < p.file_size).and_then(|p| p.offset.checked_add(va - p.vaddr)) +} + +/// The (tag, value) pairs of the `PT_DYNAMIC` segment in `phdrs`, up to its `DT_NULL`, at most +/// [`MAX_DYN`]. Empty without a dynamic segment. +pub fn dynamic_entries(data: &[u8], phdrs: &[ProgramHeader]) -> Result, ElfError> { + Ok(entries(&E::new(data)?, phdrs)) +} + +fn entries(e: &E<'_>, phdrs: &[ProgramHeader]) -> Vec<(u64, u64)> { + let mut out = Vec::new(); + let Some(d) = phdrs.iter().find(|p| p.p_type == 2) else { return out }; + let ent = 2 * e.word_size(); + let n = usize::try_from(d.file_size).unwrap_or(0) / ent; + let start = usize::try_from(d.offset).unwrap_or(usize::MAX); + for i in 0..n.min(MAX_DYN) { + let Some(o) = i.checked_mul(ent).and_then(|x| start.checked_add(x)) else { break }; + let (Some(tag), Some(val)) = (e.word(o), o.checked_add(e.word_size()).and_then(|v| e.word(v))) else { break }; + if tag == 0 { + break; + } + out.push((tag, val)); + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/elf/src/tests.rs b/crates/elf/src/tests.rs new file mode 100644 index 0000000000..a5aaf2060f --- /dev/null +++ b/crates/elf/src/tests.rs @@ -0,0 +1,201 @@ +//! Program header and dynamic section tests. `an_address_past_the_last_file_offset_maps_to_nothing` +//! is from Craft Anything's `elf.rs`; the image builder is a small stand-in for its testkit's. + +use super::*; + +/// Field writer in the image's class and byte order. +struct Image { + d: Vec, + is64: bool, + le: bool, +} + +impl Image { + fn put(&mut self, at: usize, value: u64, width: usize) { + let bytes = value.to_le_bytes(); + let mut field = bytes[..width].to_vec(); + if !self.le { + field.reverse(); + } + self.d[at..at + width].copy_from_slice(&field); + } + + fn word(&mut self, at: usize, value: u64) { + self.put(at, value, if self.is64 { 8 } else { 4 }); + } +} + +/// An executable with PT_PHDR, PT_LOAD (r-x, whole file at 0x40_0000), PT_DYNAMIC at file 0x200 +/// and PT_GNU_STACK (rw-). The dynamic section holds NEEDED, STRTAB and a DT_NULL, then junk. +fn elf(is64: bool, le: bool) -> Vec { + let mut img = Image { d: vec![0u8; 0x300], is64, le }; + img.d[..4].copy_from_slice(b"\x7fELF"); + img.d[4] = if is64 { 2 } else { 1 }; + img.d[5] = if le { 1 } else { 2 }; + img.d[6] = 1; + let (phoff_at, entsize_at, num_at, phoff, entsize) = if is64 { (32, 54, 56, 64, 56) } else { (28, 42, 44, 52, 32) }; + img.word(phoff_at, phoff as u64); + img.put(entsize_at, entsize as u64, 2); + img.put(num_at, 4, 2); + let headers = [ + (6u32, 4u32, phoff as u64, 0x40_0040, 4 * entsize as u64), + (1, 5, 0, 0x40_0000, 0x300), + (2, 6, 0x200, 0x40_0200, 0x60), + (0x6474_e551, 6, 0, 0, 0), + ]; + for (i, (t, f, off, va, size)) in headers.into_iter().enumerate() { + let o = phoff + i * entsize; + img.put(o, u64::from(t), 4); + if is64 { + img.put(o + 4, u64::from(f), 4); + img.word(o + 8, off); + img.word(o + 16, va); + img.word(o + 32, size); + img.word(o + 40, size); + img.word(o + 48, 0x1000); + } else { + img.word(o + 4, off); + img.word(o + 8, va); + img.word(o + 16, size); + img.word(o + 20, size); + img.put(o + 24, u64::from(f), 4); + img.word(o + 28, 0x1000); + } + } + let w = if is64 { 8 } else { 4 }; + for (i, (tag, value)) in [(1u64, 1u64), (5, 0x40_0280), (0, 0), (1, 9)].into_iter().enumerate() { + img.word(0x200 + i * 2 * w, tag); + img.word(0x200 + i * 2 * w + w, value); + } + img.d +} + +#[test] +fn program_headers_in_every_class_and_byte_order() { + for is64 in [false, true] { + for le in [false, true] { + let ph = program_headers(&elf(is64, le)).unwrap(); + let kinds: Vec<(&str, &str)> = ph.iter().map(|p| (p.kind.as_str(), p.flags.as_str())).collect(); + assert_eq!(kinds, [("PHDR", "r--"), ("LOAD", "r-x"), ("DYNAMIC", "rw-"), ("GNU_STACK", "rw-")], "is64={is64} le={le}"); + assert_eq!((ph[1].offset, ph[1].vaddr, ph[1].file_size, ph[1].mem_size, ph[1].align), (0, 0x40_0000, 0x300, 0x300, 0x1000)); + assert_eq!((ph[2].p_type, ph[2].p_flags), (2, 6)); + let dynamic = dynamic_entries(&elf(is64, le), &ph).unwrap(); + assert_eq!(dynamic, [(1, 1), (5, 0x40_0280)], "stops at DT_NULL"); + assert_eq!(va_to_off(&ph, 0x40_0280), Some(0x280)); + } + } +} + +#[test] +fn bad_idents_and_headers_are_errors() { + assert_eq!(program_headers(b"\x7fELX\x02\x01"), Err(ElfError::Malformed("no ELF magic".into()))); + assert_eq!(program_headers(b"\x7fELF"), Err(ElfError::Truncated("ELF ident"))); + assert_eq!(program_headers(b"\x7fELF\x02"), Err(ElfError::Truncated("ELF ident"))); + assert_eq!(program_headers(b"\x7fELF\x03\x01"), Err(ElfError::Malformed("bad ELF class or data encoding".into()))); + assert_eq!(program_headers(b"\x7fELF\x01\x00"), Err(ElfError::Malformed("bad ELF class or data encoding".into()))); + assert_eq!(program_headers(&elf(true, true)[..20]), Err(ElfError::Truncated("ELF header"))); + assert_eq!(ElfError::Truncated("ELF header").to_string(), "the file ends early (ELF header)"); + let mut small = elf(true, true); + small[54] = 40; + assert_eq!(program_headers(&small).unwrap_err().to_string(), "the file is malformed (program header entry too small)"); + assert!(dynamic_entries(b"nope", &[]).is_err()); +} + +#[test] +fn a_table_cut_short_keeps_its_complete_entries() { + let d = elf(true, true); + assert_eq!(program_headers(&d[..64 + 56 * 2 + 10]).unwrap().len(), 2); + let mut none = d.clone(); + none[56] = 0; + none[54] = 0; + assert!(program_headers(&none).unwrap().is_empty(), "no headers need no entry size"); + let mut far = d.clone(); + far[32..40].copy_from_slice(&u64::MAX.to_le_bytes()); + assert!(program_headers(&far).unwrap().is_empty(), "offsets that overflow stop the walk"); +} + +#[test] +fn dynamic_entries_need_a_dynamic_segment_inside_the_file() { + let d = elf(false, true); + let mut ph = program_headers(&d).unwrap(); + assert!(dynamic_entries(&d, &ph[..2]).unwrap().is_empty()); + ph[2].offset = 0x2f8; + assert!(dynamic_entries(&d, &ph).unwrap().is_empty(), "an entry cut off by the end of the file"); + ph[2].offset = u64::MAX; + assert!(dynamic_entries(&d, &ph).unwrap().is_empty()); +} + +fn load(offset: u64, vaddr: u64, file_size: u64) -> ProgramHeader { + ProgramHeader { kind: "LOAD".into(), flags: String::new(), offset, vaddr, file_size, mem_size: file_size, align: 0, p_type: 1, p_flags: 0 } +} + +#[test] +fn an_address_past_the_last_file_offset_maps_to_nothing() { + assert_eq!(va_to_off(&[load(0x200, 0x1000, 0x100)], 0x1010), Some(0x210)); + assert_eq!(va_to_off(&[load(u64::MAX, 0x1000, 0x100)], 0x1000), Some(u64::MAX)); + assert_eq!(va_to_off(&[load(u64::MAX, 0x1000, 0x100)], 0x1001), None, "the offset would pass u64::MAX"); + assert_eq!(va_to_off(&[load(0x200, 0x1000, 0x100)], 0x1100), None, "the zero-filled tail has no file bytes"); + let mut dynamic = load(0, 0x1000, 0x100); + dynamic.p_type = 2; + assert_eq!(va_to_off(&[dynamic], 0x1010), None, "only PT_LOAD maps"); +} + +#[test] +fn names() { + let segments: Vec = + [0, 1, 2, 3, 4, 5, 6, 7, 0x6474_e550, 0x6474_e551, 0x6474_e552, 0x6474_e553, 0x7000_0001, 0x99].into_iter().map(segment_type_name).collect(); + assert_eq!( + segments, + [ + "NULL", + "LOAD", + "DYNAMIC", + "INTERP", + "NOTE", + "SHLIB", + "PHDR", + "TLS", + "GNU_EH_FRAME", + "GNU_STACK", + "GNU_RELRO", + "GNU_PROPERTY", + "ARM_EXIDX", + "0x99" + ] + ); + assert_eq!([0, 1, 2, 4, 7].map(permissions), ["---", "--x", "-w-", "r--", "rwx"]); + let tags: Vec = + (0..=30).chain([0x6fff_fef5, 0x6fff_fffb, 0x6fff_fff0, 0x6fff_fffe, 0x6fff_ffff, 0x7000_0000]).map(dynamic_tag_name).collect(); + assert_eq!(tags[..3], ["NULL", "NEEDED", "PLTRELSZ"]); + assert_eq!(tags[29..], ["RUNPATH", "FLAGS", "GNU_HASH", "FLAGS_1", "VERSYM", "VERNEED", "VERNEEDNUM", "0x70000000"]); + assert!(tags.iter().all(|t| !t.is_empty())); +} + +#[cfg(feature = "serde")] +#[test] +fn program_headers_serialize_with_hex_addresses() { + let ph = program_headers(&elf(true, true)).unwrap(); + let value = serde_json::to_value(&ph[1]).unwrap(); + assert_eq!(value["kind"], "LOAD"); + assert_eq!(value["vaddr"], "0x400000"); + assert!(value.get("p_type").is_none()); +} + +#[test] +fn damaged_input_never_panics() { + for sample in [elf(true, true), elf(false, false)] { + for i in 0..sample.len() { + if let Ok(ph) = program_headers(&sample[..i]) { + let _ = dynamic_entries(&sample[..i], &ph); + } + for v in [0x00, 0x7f, 0xff] { + let mut m = sample.clone(); + m[i] = v; + if let Ok(ph) = program_headers(&m) { + let _ = dynamic_entries(&m, &ph); + let _ = va_to_off(&ph, 0x40_0280); + } + } + } + } +} diff --git a/crates/exr/src/channels.rs b/crates/exr/src/channels.rs index 32e460e460..32287f5f82 100644 --- a/crates/exr/src/channels.rs +++ b/crates/exr/src/channels.rs @@ -146,6 +146,53 @@ pub fn color_channels<'a>(names: impl IntoIterator) -> Option<(C best.or_else(|| (count == 1).then(|| (ColorLayout::Y, vec![0]))) } +/// The main picture of a file by the OpenEXR convention, the one compositing applications show +/// when a file is imported: the channels without a layer prefix, `R`, `G`, `B` (and `A` when +/// present), of the first part that has all three; else the first part's unprefixed `Y` (and +/// `A`). Named layers never stand in for it: a file of named layers only (Blender's +/// `ViewLayer.Combined.R`, a part that stores `beauty.R`) has no main picture, and its layers +/// are reached by name, as in After Effects (EXtractoR) and Nuke (the `rgba` layer stays empty). +/// +/// `parts` gives each part's channel names as stored, in file order. Returns the part's index +/// and the channels' indices in that part, in layout order (R, G, B, A or Y, A). The names are +/// matched exactly, as the specification spells them; the first of duplicate names counts. +pub fn main_picture<'a, P, C>(parts: P) -> Option<(usize, ColorLayout, Vec)> +where + P: IntoIterator, + C: IntoIterator, +{ + let mut luminance: Option<(usize, ColorLayout, Vec)> = None; + for (part, names) in parts.into_iter().enumerate() { + let (mut r, mut g, mut b, mut a, mut y) = (None, None, None, None, None); + for (index, name) in names.into_iter().enumerate() { + let slot = match name { + "R" => &mut r, + "G" => &mut g, + "B" => &mut b, + "A" => &mut a, + "Y" => &mut y, + _ => continue, + }; + slot.get_or_insert(index); + } + if let (Some(r), Some(g), Some(b)) = (r, g, b) { + return Some(match a { + Some(a) => (part, ColorLayout::Rgba, vec![r, g, b, a]), + None => (part, ColorLayout::Rgb, vec![r, g, b]), + }); + } + if luminance.is_none() + && let Some(y) = y + { + luminance = Some(match a { + Some(a) => (part, ColorLayout::YA, vec![y, a]), + None => (part, ColorLayout::Y, vec![y]), + }); + } + } + luminance +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] @@ -235,4 +282,46 @@ mod tests { assert_eq!(pick(&[]), None); assert_eq!(pick(&["r", "g", "b"]), None); } + + #[test] + fn the_main_picture_is_the_unprefixed_colour_of_the_first_part_that_has_it() { + let main = |parts: &[&[&str]]| main_picture(parts.iter().map(|p| p.iter().copied())); + // One part: the bare channels, whatever else is there, also before them alphabetically. + assert_eq!( + main(&[&["A", "B", "CryptoMaterial00.A", "CryptoMaterial00.B", "CryptoMaterial00.G", "CryptoMaterial00.R", "G", "R", "Z"]]), + Some((0, ColorLayout::Rgba, vec![7, 6, 1, 0])) + ); + assert_eq!(main(&[&["B", "G", "R", "diffuse.A", "diffuse.B", "diffuse.G", "diffuse.R"]]), Some((0, ColorLayout::Rgb, vec![2, 1, 0]))); + // Named layers only (Blender multilayer): no main picture, however good a layer looks. + assert_eq!( + main(&[&[ + "ViewLayer.AO.B", + "ViewLayer.AO.G", + "ViewLayer.AO.R", + "ViewLayer.Combined.A", + "ViewLayer.Combined.B", + "ViewLayer.Combined.G", + "ViewLayer.Combined.R" + ]]), + None + ); + assert_eq!( + main(&[&["ViewLayer.Combined.A", "ViewLayer.Combined.B", "ViewLayer.Combined.G", "ViewLayer.Combined.R"], &["ViewLayer.Depth.Z"]]), + None + ); + // Multi-part: the first part with bare R, G and B, not the first part. + assert_eq!(main(&[&["Z"], &["A", "B", "G", "R"], &["B", "G", "R"]]), Some((1, ColorLayout::Rgba, vec![3, 2, 1, 0]))); + assert_eq!(main(&[&["B", "G", "R"], &["A", "B", "G", "R"]]), Some((0, ColorLayout::Rgb, vec![2, 1, 0]))); + // Colour wins over an earlier luminance part; luminance when there is no colour. + assert_eq!(main(&[&["Y"], &["B", "G", "R"]]), Some((1, ColorLayout::Rgb, vec![2, 1, 0]))); + assert_eq!(main(&[&["Z"], &["A", "Y"], &["Y"]]), Some((1, ColorLayout::YA, vec![1, 0]))); + // Incomplete colour, other spellings and lone data channels are no picture. + assert_eq!(main(&[&["G", "R"]]), None); + assert_eq!(main(&[&["b", "g", "r"]]), None); + assert_eq!(main(&[&["Z"]]), None); + assert_eq!(main(&[&["A"]]), None); + assert_eq!(main(&[]), None); + // The first of duplicate names counts. + assert_eq!(main(&[&["R", "G", "B", "R"]]), Some((0, ColorLayout::Rgb, vec![0, 1, 2]))); + } } diff --git a/crates/exr/src/decode.rs b/crates/exr/src/decode.rs index ab21064ce4..04d135e27d 100644 --- a/crates/exr/src/decode.rs +++ b/crates/exr/src/decode.rs @@ -7,7 +7,7 @@ //! - [`decode_part`] decodes the channels of one flat part that a filter keeps, in their stored //! sample type, over the part's data window. Every compression the `exr` crate reads is read, //! scan lines and tiles alike (the largest resolution level). Other parts' chunks are skipped -//! unread, and channels the filter drops are never allocated. +//! unread, and channels the filter drops are never allocated. Other parts may be deep. //! - [`write`] writes one scan-line part. //! //! The `exr` crate sizes buffers from headers before it reads pixels, so everything that reaches @@ -18,7 +18,7 @@ use std::io::Cursor; use exr::block::UncompressedBlock; -use exr::block::chunk::TileCoordinates; +use exr::block::chunk::{Chunk, CompressedBlock, CompressedScanLineBlock, CompressedTileBlock, TileCoordinates}; use exr::image::read::image::ReadImage; use exr::image::read::layers::{ChannelsReader, ReadAllLayers, ReadChannels}; use exr::meta::MetaData; @@ -245,11 +245,21 @@ fn window_size(size: exr::math::Vec2) -> (u32, u32) { /// Reads the headers and checks every part's declared size, alone and together, before any pixel /// allocation. Headers are read without the crate's validation, which refuses deep parts. -fn read_meta(bytes: &[u8], limits: &Limits) -> Result { +pub(super) fn read_meta(bytes: &[u8], limits: &Limits) -> Result { check_previews(bytes)?; let meta = MetaData::read_from_buffered(Cursor::new(bytes), false).map_err(map_exr)?; - let (mut total, mut dwa) = (0u64, 0u64); - for header in meta.headers.iter() { + let (mut total, mut flat, mut dwa) = (0u64, 0u64, 0u64); + for (index, header) in meta.headers.iter().enumerate() { + // The crate sizes a flat chunk's bound as a block's pixels times the bytes a pixel takes, + // without checking the product, before it reads the chunk. + let block_pixels = match header.blocks { + exr::meta::BlockDescription::Tiles(tiles) => (tiles.tile_size.0 as u64).checked_mul(tiles.tile_size.1 as u64), + exr::meta::BlockDescription::ScanLines => (header.compression.scan_lines_per_block() as u64).checked_mul(header.layer_size.0 as u64), + }; + let block_bytes = block_pixels.and_then(|n| n.checked_mul(header.channels.bytes_per_pixel as u64)).and_then(|n| usize::try_from(n).ok()); + if !header.deep && block_bytes.is_none() { + return Err(Error::LimitExceeded(format!("a block of part {index} holds more bytes than this platform can address"))); + } let (w, h) = window_size(header.layer_size); if w > limits.max_width || h > limits.max_height { return Err(Error::LimitExceeded(format!("a {w}x{h} part exceeds {}x{}", limits.max_width, limits.max_height))); @@ -260,23 +270,25 @@ fn read_meta(bytes: &[u8], limits: &Limits) -> Result { } let bytes = pixels.saturating_mul(header.channels.list.len().max(1) as u64 * 4); total = total.saturating_add(bytes); - if matches!(header.compression, ExrCompression::DWAA(_) | ExrCompression::DWAB(_)) { - dwa = dwa.saturating_add(bytes); + if !header.deep { + flat = flat.saturating_add(bytes); + if matches!(header.compression, ExrCompression::DWAA(_) | ExrCompression::DWAB(_)) { + dwa = dwa.saturating_add(bytes); + } } } if total > limits.max_bytes { return Err(Error::LimitExceeded(format!("{total} bytes across {} parts exceed {}", meta.headers.len(), limits.max_bytes))); } - // The crate allocates a flat part's samples before reading its chunks, so the file must be - // able to hold them. DWA's run-length channels are zlib-packed on top and reach about - // 132000:1, so DWA parts are counted at a quarter. Deep parts size their samples from the - // file's own counts. - if !meta.requirements.has_deep_data { - let declared = total.saturating_sub(dwa).saturating_add(dwa / 4); - let capacity = (bytes.len() as u64).saturating_mul(limits.max_ratio).saturating_add(1 << 20); - if declared > capacity { - return Err(Error::LimitExceeded(format!("a {} byte file cannot hold {declared} bytes of samples", bytes.len()))); - } + // A flat part's samples are allocated before its chunks are read, so the file must be able + // to hold the flat parts' samples. DWA's run-length channels are zlib-packed on top (RLE up to + // 64:1, zlib up to about 1032:1, about 66000:1 together), so DWA parts are counted at a quarter + // (with room to spare). Deep parts size their samples from + // the file's own counts and are not counted here. + let declared = flat.saturating_sub(dwa).saturating_add(dwa / 4); + let capacity = (bytes.len() as u64).saturating_mul(limits.max_ratio).saturating_add(1 << 20); + if declared > capacity { + return Err(Error::LimitExceeded(format!("a {} byte file cannot hold {declared} bytes of samples", bytes.len()))); } Ok(meta) } @@ -297,7 +309,7 @@ fn text_attributes(header: &Header) -> Vec<(String, String)> { out } -fn part_info(index: usize, header: &Header) -> PartInfo { +pub(crate) fn part_info(index: usize, header: &Header) -> PartInfo { let (w, h) = window_size(header.layer_size); let display = &header.shared_attributes.display_window; let (dw, dh) = window_size(display.size); @@ -438,6 +450,7 @@ pub fn decode_display_part( header_limits.max_pixels = u64::MAX; header_limits.max_bytes = u64::MAX; let meta = read_meta(bytes, &header_limits)?; + check_dwa_chunks(bytes, &meta)?; let info = meta.headers.get(index).map(|header| part_info(index, header)).ok_or_else(|| malformed(format!("part {index}")))?; if info.deep { return Err(Error::Unsupported("deep data (use the deep reader)".into())); @@ -459,19 +472,24 @@ pub fn decode_display_part( } let block_limit = std::cell::Cell::new(None); let select = DisplaySelect { index, keep, fill, limits, seen: std::cell::Cell::new(0), block_limit: &block_limit }; - let image = ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}) - .from_buffered(Cursor::new(bytes)) - .map_err(|error| block_limit.take().map(Error::LimitExceeded).unwrap_or_else(|| map_exr(error)))?; - let channels = image - .layer_data - .into_iter() - .nth(index) - .ok_or_else(|| malformed("the part was not read"))? - .channel_data - .into_iter() - .flatten() - .map(|(name, samples)| DisplayChannel { name, samples }) - .collect(); + let exr_error = |error| block_limit.take().map(Error::LimitExceeded).unwrap_or_else(|| map_exr(error)); + let planes = if meta.headers.iter().any(|header| header.deep) { + let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?; + select.seen.set(index); + let mut reader = select.create_channels_reader(header).map_err(exr_error)?; + read_flat_part_chunks(bytes, &meta, index, &mut reader, limits)?; + reader.into_channels() + } else { + ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}) + .from_buffered(Cursor::new(bytes)) + .map_err(exr_error)? + .layer_data + .into_iter() + .nth(index) + .ok_or_else(|| malformed("the part was not read"))? + .channel_data + }; + let channels = planes.into_iter().flatten().map(|(name, samples)| DisplayChannel { name, samples }).collect(); Ok(DisplayPart { info, channels }) } @@ -515,18 +533,23 @@ impl<'s> ReadChannels<'s> for DisplaySelect<'_> { u32s: vec![], }); } - // The EXR crate decompresses each accepted block before `read_block` can discard ignored - // channels. Bound that all-channel input separately from the selected output planes. - let Some(block_bytes) = layer_w - .checked_mul(layer_h) - .and_then(|pixels| pixels.checked_mul(header.channels.list.len().max(1))) - .and_then(|samples| samples.checked_mul(std::mem::size_of::())) - else { + // The EXR crate decompresses each accepted block, with every channel, before `read_block` + // can discard the ignored ones, so bound that all-channel block separately from the + // selected output planes. Blocks are decompressed one at a time, so the bound is the + // largest block (a tile within the data window, or a scan-line group across it), not the + // whole part: a part whose full channel set is larger than `max_bytes` still decodes when + // the kept planes and each block fit. + let block_pixels = match header.blocks { + exr::meta::BlockDescription::Tiles(tiles) => tiles.tile_size.0.min(layer_w).checked_mul(tiles.tile_size.1.min(layer_h)), + // a part shorter than its compression's scan-line group has only its own rows + exr::meta::BlockDescription::ScanLines => header.compression.scan_lines_per_block().min(layer_h).checked_mul(layer_w), + }; + let Some(block_bytes) = block_pixels.and_then(|pixels| pixels.checked_mul(header.channels.bytes_per_pixel.max(1))) else { self.block_limit.set(Some(format!("data-window block size exceeds {}", self.limits.max_bytes))); return Err(exr::error::Error::Invalid("data-window block size overflow".into())); }; if u64::try_from(block_bytes).map_or(true, |bytes| bytes > self.limits.max_bytes) || block_bytes > isize::MAX as usize { - self.block_limit.set(Some(format!("{block_bytes} data-window bytes exceed {}", self.limits.max_bytes))); + self.block_limit.set(Some(format!("{block_bytes} bytes in one data-window block exceed {}", self.limits.max_bytes))); return Err(exr::error::Error::Invalid("data-window blocks exceed limit".into())); } let pixels = display_w.checked_mul(display_h).filter(|n| *n > 0).ok_or(exr::error::Error::Invalid("display window".into()))?; @@ -727,22 +750,231 @@ impl ChannelsReader for SelectReader { } } +/// Where the headers end and the offset tables begin: [`MetaData::read_from_buffered`] consumes +/// exactly the version field and the headers. +fn tables_start(bytes: &[u8]) -> Result { + let mut cursor = Cursor::new(bytes); + MetaData::read_from_buffered(&mut cursor, false).map_err(map_exr)?; + Ok(cursor.position()) +} + +/// Checks the chunks of the file's DWAA/DWAB parts before the `exr` crate decompresses them (see +/// [`crate::dwa_guard`]: a few bytes of counters can make it allocate terabytes and abort). +fn check_dwa_chunks(bytes: &[u8], meta: &MetaData) -> Result<()> { + if !meta.headers.iter().any(|h| crate::dwa_guard::is_dwa(h.compression)) { + return Ok(()); + } + let tables = usize::try_from(tables_start(bytes)?).map_err(|_| malformed("header size"))?; + crate::dwa_guard::check_file(bytes, meta, tables).map_err(malformed) +} + +/// Stable dense ordinal without materializing every tile. The library's block iterator +/// internally allocates a Vec of all coordinates, which is unsuitable for cropped reads. +pub(super) fn flat_block_ordinal(header: &Header, tile: TileCoordinates) -> Result { + use exr::math::Vec2; + use exr::meta::attribute::LevelMode; + let mut start = 0usize; + let tile_size = header.max_block_pixel_size(); + if tile_size.0 == 0 || tile_size.1 == 0 { + return Err(malformed("flat block has a zero dimension")); + } + let mut visit = |level: Vec2, size: Vec2| -> Result> { + let nx = size.0.div_ceil(tile_size.0); + let ny = size.1.div_ceil(tile_size.1); + if tile.level_index == level { + if tile.tile_index.0 >= nx || tile.tile_index.1 >= ny { + return Err(malformed("flat tile lies outside its level")); + } + return tile + .tile_index + .1 + .checked_mul(nx) + .and_then(|n| n.checked_add(tile.tile_index.0)) + .and_then(|n| start.checked_add(n)) + .map(Some) + .ok_or_else(|| malformed("block ordinal overflow")); + } + start = nx.checked_mul(ny).and_then(|n| start.checked_add(n)).ok_or_else(|| malformed("block count overflow"))?; + Ok(None) + }; + match header.blocks { + exr::meta::BlockDescription::Tiles(tiles) => match tiles.level_mode { + LevelMode::Singular => { + if let Some(i) = visit(Vec2(0, 0), header.layer_size)? { + return Ok(i); + } + } + LevelMode::MipMap => { + for (level, size) in exr::meta::mip_map_levels(tiles.rounding_mode, header.layer_size) { + if let Some(i) = visit(Vec2(level, level), size)? { + return Ok(i); + } + } + } + LevelMode::RipMap => { + for (level, size) in exr::meta::rip_map_levels(tiles.rounding_mode, header.layer_size) { + if let Some(i) = visit(level, size)? { + return Ok(i); + } + } + } + }, + exr::meta::BlockDescription::ScanLines => { + if let Some(i) = visit(Vec2(0, 0), header.layer_size)? { + return Ok(i); + } + } + } + Err(malformed("flat tile names a missing level")) +} + +/// Reads the chunks of flat part `index` of a file that also holds deep parts into `reader`. +/// +/// The `exr` crate's image reader validates every header before it reads a chunk and refuses +/// deep headers, so here only the flat headers are validated, the offset tables (one `u64` per +/// chunk, a table per part in header order) are walked from the end of the headers, and only the +/// selected part's chunks are read. Each chunk must start past the last offset table and inside +/// the file, carry the selected part's number, and hold one of the part's blocks that no other +/// chunk of the part holds, so the part's chunks hold every one of its blocks. A scan-line +/// chunk's y must be the first line of its block, and no chunk may declare more bytes than the +/// file has left after it. +fn read_flat_part_chunks(bytes: &[u8], meta: &MetaData, index: usize, reader: &mut impl ChannelsReader, limits: &Limits) -> Result<()> { + let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?; + let multipart = meta.requirements.is_multilayer(); + let mut long_names = false; + for flat in meta.headers.iter().filter(|h| !h.deep) { + flat.validate(multipart, &mut long_names, false).map_err(map_exr)?; + } + let truncated = || malformed("the offset tables run past the end of the file"); + let (mut table, mut tables_end) = (0u64, tables_start(bytes)?); + for (i, h) in meta.headers.iter().enumerate() { + if i == index { + table = tables_end; + } + let len = u64::try_from(h.chunk_count).ok().and_then(|n| n.checked_mul(8)).ok_or_else(truncated)?; + tables_end = tables_end.checked_add(len).filter(|end| *end <= bytes.len() as u64).ok_or_else(truncated)?; + } + let offsets = usize::try_from(table) + .ok() + .and_then(|start| bytes.get(start..start.checked_add(header.chunk_count.checked_mul(8)?)?)) + .ok_or_else(truncated)?; + // One bit per block, not a Vec/HashSet of every coordinate. A cropped display must not + // permit unbounded bookkeeping for an enormous data window of tiny tiles. + let tracking_bytes = header.chunk_count.div_ceil(8); + if tracking_bytes as u64 > limits.max_bytes || tracking_bytes > isize::MAX as usize { + return Err(Error::LimitExceeded("block tracking exceeds the byte budget".into())); + } + let mut seen = Vec::new(); + seen.try_reserve_exact(tracking_bytes).map_err(|_| Error::LimitExceeded("cannot allocate block tracking".into()))?; + seen.resize(tracking_bytes, 0u8); + for &entry in offsets.as_chunks::<8>().0 { + let offset = u64::from_le_bytes(entry); + let chunk = usize::try_from(offset) + .ok() + .filter(|_| offset >= tables_end) + .and_then(|start| bytes.get(start..)) + .filter(|rest| !rest.is_empty()) + .ok_or_else(|| malformed(format!("chunk offset {offset} is outside the chunk area of the file")))?; + if multipart { + let part = chunk.get(..4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes); + let part = part.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?; + if usize::try_from(part).ok() != Some(index) { + return Err(malformed(format!("the chunk at offset {offset} belongs to part {part}, not part {index}"))); + } + } + // The crate allocates a chunk's declared payload before it reads it, so the payload must + // fit in the rest of the file. The length follows the part number and the block's y, or + // its four tile coordinates. + let fields = if matches!(header.blocks, exr::meta::BlockDescription::Tiles(_)) { 16 } else { 4 }; + let size_at = if multipart { 4 } else { 0 } + fields; + let size = chunk.get(size_at..size_at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes); + let size = size.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?; + let left = chunk.len() - (size_at + 4); + if usize::try_from(size).is_ok_and(|size| size > left) { + return Err(malformed(format!("the chunk at offset {offset} declares {size} bytes, but {left} remain in the file"))); + } + let size = usize::try_from(size).map_err(|_| malformed("negative packed chunk length"))?; + // Read coordinates without allocating the payload. Validate their real clipped block + // and budgets before Chunk::read uses the nominal (possibly huge) tile dimensions. + let coordinate_at = if multipart { 4 } else { 0 }; + let shape = if matches!(header.blocks, exr::meta::BlockDescription::Tiles(_)) { + let coordinates = TileCoordinates::read(&mut Cursor::new(&chunk[coordinate_at..])).map_err(map_exr)?; + CompressedBlock::Tile(CompressedTileBlock { coordinates, compressed_pixels_le: Vec::new() }) + } else { + let y = chunk + .get(coordinate_at..coordinate_at + 4) + .and_then(|b| <[u8; 4]>::try_from(b).ok()) + .ok_or_else(|| malformed("truncated scan-line coordinate"))?; + CompressedBlock::ScanLine(CompressedScanLineBlock { y_coordinate: i32::from_le_bytes(y), compressed_pixels_le: Vec::new() }) + }; + let tile = header.get_block_data_indices(&shape).map_err(map_exr)?; + if let CompressedBlock::ScanLine(block) = &shape { + // The block index is rounded toward zero, so a y that is not the first line of a + // block, or lies just above the data window, would still name a block. + let lines = header.compression.scan_lines_per_block() as i64; + let first = i64::from(header.own_attributes.layer_position.y()) + tile.tile_index.y() as i64 * lines; + if i64::from(block.y_coordinate) != first { + return Err(malformed(format!( + "the scan-line chunk at offset {offset} starts at y {}, which is not the first line of a block", + block.y_coordinate + ))); + } + } + let ordinal = flat_block_ordinal(header, tile)?; + let flag = 1u8 << (ordinal % 8); + let byte = seen.get_mut(ordinal / 8).ok_or_else(|| malformed("block is outside its chunk table"))?; + if *byte & flag != 0 { + return Err(malformed("duplicate flat block")); + } + *byte |= flag; + if reader.filter_block(tile) { + let area = header.get_absolute_block_pixel_coordinates(tile).map_err(map_exr)?.size; + let raw_size = area + .0 + .checked_mul(area.1) + .and_then(|n| n.checked_mul(header.channels.bytes_per_pixel)) + .ok_or_else(|| Error::LimitExceeded("flat block byte size overflows".into()))?; + if raw_size as u64 > limits.max_bytes || raw_size > isize::MAX as usize { + return Err(Error::LimitExceeded("flat block exceeds the byte budget".into())); + } + // Packed size need not be less than raw size for every accepted compression. + // Bound its allocation independently, rather than rejecting valid compressed data + // solely because a clipped edge block has fewer raw bytes. + if size as u64 > limits.max_bytes || size > isize::MAX as usize { + return Err(Error::LimitExceeded("packed flat block exceeds the byte budget".into())); + } + let chunk = Chunk::read(&mut Cursor::new(chunk), meta).map_err(map_exr)?; + let block = UncompressedBlock::decompress_chunk(chunk, meta, false).map_err(map_exr)?; + reader.read_block(header, block).map_err(map_exr)?; + } + } + Ok(()) +} + /// Decodes the channels of flat part `index` that `keep` accepts (by the name as stored), in -/// their stored type. A file with deep parts, or a kept channel that is subsampled, is -/// [`Error::Unsupported`]. +/// their stored type. A deep part, or a kept channel that is subsampled, is +/// [`Error::Unsupported`]; the file's other parts may be deep. pub fn decode_part(bytes: &[u8], index: usize, keep: &dyn Fn(&str) -> bool, limits: &Limits) -> Result { let meta = read_meta(bytes, limits)?; - if meta.requirements.has_deep_data { + check_dwa_chunks(bytes, &meta)?; + let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index} of {}", meta.headers.len())))?; + if header.deep { return Err(Error::Unsupported("deep data (use the deep reader)".into())); } - let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index} of {}", meta.headers.len())))?; if matches!(header.compression, ExrCompression::HTJ2K32 | ExrCompression::HTJ2K256) { return Err(Error::Unsupported("HTJ2K compression".into())); } let info = part_info(index, header); let select = Select { index, keep, seen: std::cell::Cell::new(0) }; - let image = ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}).from_buffered(Cursor::new(bytes)).map_err(map_exr)?; - let planes = image.layer_data.into_iter().nth(index).map(|l| l.channel_data).ok_or_else(|| malformed("the part was not read"))?; + let planes = if meta.headers.iter().any(|header| header.deep) { + select.seen.set(index); + let mut reader = select.create_channels_reader(header).map_err(map_exr)?; + read_flat_part_chunks(bytes, &meta, index, &mut reader, limits)?; + reader.into_channels() + } else { + let image = ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}).from_buffered(Cursor::new(bytes)).map_err(map_exr)?; + image.layer_data.into_iter().nth(index).map(|l| l.channel_data).ok_or_else(|| malformed("the part was not read"))? + }; let channels = info.channels.iter().zip(planes).filter_map(|(c, p)| Some(Channel { name: c.name.clone(), samples: p? })).collect(); Ok(Part { info, channels }) } diff --git a/crates/exr/src/decode_tests.rs b/crates/exr/src/decode_tests.rs index 54c28d9aa4..0f63d8108f 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -1,4 +1,5 @@ -//! The preview check is PhotoCraft's test; the rest builds files with the `exr` crate. +//! The preview check is PhotoCraft's test; the rest builds files with the `exr` crate, except the +//! files that mix flat and deep parts, which are built by hand. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use exr::meta::attribute::{Preview, Text}; @@ -129,10 +130,30 @@ fn decoded_display_part_places_selected_channels_and_checks_total_budget() { let limits = Limits { max_bytes: 6 * 4 - 1, ..Limits::default() }; assert!(matches!(decode_display_part(&bytes, 0, &all, &|_| 0.0, &limits), Err(Error::LimitExceeded(_)))); - // One selected display plane fits exactly, but the EXR decoder must decompress both data - // channels in its input block before discarding the ignored one. + // One selected display plane fits exactly. Both data channels together (2x2x2 f32, 32 bytes) + // don't, but they are decompressed one scan-line block (2 pixels x 2 channels) at a time. let block_limits = Limits { max_bytes: 6 * 4, ..Limits::default() }; - assert!(matches!(decode_display_part(&bytes, 0, &|name| name == "R", &|_| 0.0, &block_limits), Err(Error::LimitExceeded(_)))); + let part = decode_display_part(&bytes, 0, &|name| name == "R", &|_| 9.0, &block_limits).unwrap(); + assert_eq!(part.channels[0].samples, [0.0, 1.0, 9.0, 2.0, 3.0, 9.0]); +} + +#[test] +fn decoded_display_part_bounds_each_all_channel_block() { + // The kept R plane is 4 pixels of f32 (16 bytes), but each scan-line block carries all four + // channels (64 bytes) before the ignored ones are discarded. + let bytes = file(vec![layer(None, 4, 1, &["R", "G", "B", "A"], false, exr::prelude::Compression::ZIP1)], (4, 1)); + let r = |name: &str| name == "R"; + assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &Limits { max_bytes: 16, ..Limits::default() }), Err(Error::LimitExceeded(_)))); + assert_eq!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &Limits { max_bytes: 64, ..Limits::default() }).unwrap().channels.len(), 1); + // ZIP groups 16 scan lines, but a one-row part's block is that row: still 64 bytes, not 1024 + let zip16 = file(vec![layer(None, 4, 1, &["R", "G", "B", "A"], false, exr::prelude::Compression::ZIP16)], (4, 1)); + assert!(matches!(decode_display_part(&zip16, 0, &r, &|_| 0.0, &Limits { max_bytes: 63, ..Limits::default() }), Err(Error::LimitExceeded(_)))); + assert_eq!(decode_display_part(&zip16, 0, &r, &|_| 0.0, &Limits { max_bytes: 64, ..Limits::default() }).unwrap().channels.len(), 1); + // A tile is the block of a tiled part: a 4x4 tile of four f32 channels is 256 bytes, while + // the whole 8x8 part is 1024 and the kept R plane of the 2x2 display window only 16. + let tiled = file(vec![layer(None, 8, 8, &["R", "G", "B", "A"], true, exr::prelude::Compression::ZIP1)], (2, 2)); + assert!(matches!(decode_display_part(&tiled, 0, &r, &|_| 0.0, &Limits { max_bytes: 255, ..Limits::default() }), Err(Error::LimitExceeded(_)))); + assert_eq!(decode_display_part(&tiled, 0, &r, &|_| 0.0, &Limits { max_bytes: 256, ..Limits::default() }).unwrap().channels[0].samples.len(), 4); } #[test] @@ -238,3 +259,451 @@ fn hostile_files_never_panic() { } assert!(parts(b"not exr", &limits).is_err()); } + +// A multi-part file with a flat part and a deep scan-line part, built by hand per the OpenEXR file +// layout (the `exr` crate's writer refuses deep headers): version 2 with the deep and multi-part +// flags, the headers and an empty header, one offset table per part, then chunks that each start +// with their part number. Both parts are uncompressed, two chunks a part: the deep part and a +// scan-line flat part hold one scan line a chunk, and a tiled flat part one 2 × 2 tile a chunk. + +fn mixed_attr(out: &mut Vec, name: &str, ty: &str, payload: &[u8]) { + out.extend_from_slice(name.as_bytes()); + out.push(0); + out.extend_from_slice(ty.as_bytes()); + out.push(0); + out.extend_from_slice(&(payload.len() as i32).to_le_bytes()); + out.extend_from_slice(payload); +} + +/// The version field and the headers of a mixed file whose flat part is `w × h` with float +/// `B`, `G`, `R` channels, in scan lines or (with `tiled`) in one level of 2 × 2 tiles, and whose +/// deep part is 3 × 2 with one float `A` channel. Both parts are uncompressed. +fn mixed_headers(deep_first: bool, tiled: bool, (w, h): (usize, usize)) -> Vec { + mixed_headers_with(deep_first, tiled, (w, h), 0, &["B", "G", "R"], 2) +} + +/// [`mixed_headers`] with the flat part's compression code (0 for none, or 3 for ZIP, which +/// holds 16 scan lines a block), its float channels, and the width and height of its tiles. +fn mixed_headers_with(deep_first: bool, tiled: bool, (w, h): (usize, usize), compression: u8, flat_channels: &[&str], tile: u32) -> Vec { + mixed_headers_with_deep_size(deep_first, tiled, (w, h), compression, flat_channels, tile, (3, 2)) +} + +fn mixed_headers_with_deep_size( + deep_first: bool, + tiled: bool, + (w, h): (usize, usize), + compression: u8, + flat_channels: &[&str], + tile: u32, + deep_size: (usize, usize), +) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(&0x0131_2f76u32.to_le_bytes()); + out.extend_from_slice(&(2u32 | 0x800 | 0x1000).to_le_bytes()); + for deep in if deep_first { [true, false] } else { [false, true] } { + let (w, h, channels): (usize, usize, &[&str]) = if deep { (deep_size.0, deep_size.1, &["A"]) } else { (w, h, flat_channels) }; + let mut chlist = Vec::new(); + for name in channels { + chlist.extend_from_slice(name.as_bytes()); + chlist.push(0); + chlist.extend_from_slice(&2i32.to_le_bytes()); // float + chlist.extend_from_slice(&[0u8; 4]); // pLinear and reserved + chlist.extend_from_slice(&1i32.to_le_bytes()); + chlist.extend_from_slice(&1i32.to_le_bytes()); + } + chlist.push(0); + let window: Vec = [0i32, 0, w as i32 - 1, h as i32 - 1].iter().flat_map(|v| v.to_le_bytes()).collect(); + let tiled = tiled && !deep; + let compression = if deep { 0 } else { compression }; + let lines = if compression == 3 { 16 } else { 1 }; + let chunks = if tiled { w.div_ceil(tile as usize) * h.div_ceil(tile as usize) } else { h.div_ceil(lines) }; + mixed_attr(&mut out, "channels", "chlist", &chlist); + mixed_attr(&mut out, "chunkCount", "int", &(chunks as i32).to_le_bytes()); + mixed_attr(&mut out, "compression", "compression", &[compression]); + mixed_attr(&mut out, "dataWindow", "box2i", &window); + mixed_attr(&mut out, "displayWindow", "box2i", &window); + mixed_attr(&mut out, "lineOrder", "lineOrder", &[0]); + if deep { + mixed_attr(&mut out, "maxSamplesPerPixel", "int", &1i32.to_le_bytes()); + } + mixed_attr(&mut out, "name", "string", if deep { b"deep" } else { b"flat" }); + mixed_attr(&mut out, "pixelAspectRatio", "float", &1f32.to_le_bytes()); + mixed_attr(&mut out, "screenWindowCenter", "v2f", &[0u8; 8]); + mixed_attr(&mut out, "screenWindowWidth", "float", &1f32.to_le_bytes()); + if tiled { + // `tile` × `tile` tiles, one level, rounded down. + let mut desc: Vec = [tile, tile].iter().flat_map(|v| v.to_le_bytes()).collect(); + desc.push(0); + mixed_attr(&mut out, "tiles", "tiledesc", &desc); + } + let ty: &[u8] = if deep { + b"deepscanline" + } else if tiled { + b"tiledimage" + } else { + b"scanlineimage" + }; + mixed_attr(&mut out, "type", "string", ty); + if deep { + mixed_attr(&mut out, "version", "int", &1i32.to_le_bytes()); + } + out.push(0); // end of this header + } + out.push(0); // end of the header list + out +} + +/// Sample `i` of a flat channel: `R` is 1, 2, 3, …, `G` 10 more and `B` 100 more, top row first. +pub(super) fn mixed_flat(channel: f32, i: usize) -> f32 { + channel + 1.0 + i as f32 +} + +/// A mixed file with a 3 × 2 flat part, and its chunk offsets as `offsets[part][chunk]`. The +/// tiled flat part's chunks hold the tiles at (0, 0) and (1, 0). +pub(super) fn mixed_file(deep_first: bool, tiled: bool) -> (Vec, [[usize; 2]; 2]) { + let (w, h) = (3usize, 2usize); + let mut out = mixed_headers(deep_first, tiled, (w, h)); + let chunks: Vec>> = (0..2i32) + .map(|part| { + let deep = (part == 0) == deep_first; + (0..h) + .map(|y| { + let mut c = Vec::new(); + c.extend_from_slice(&part.to_le_bytes()); + if tiled && !deep { + // Tile (y, 0) at level (0, 0): columns 2y and 2y + 1 that lie inside. + [y as i32, 0, 0, 0].iter().for_each(|v| c.extend_from_slice(&v.to_le_bytes())); + let xs = 2 * y..(2 * y + 2).min(w); + c.extend_from_slice(&((xs.len() * h * 3 * 4) as i32).to_le_bytes()); + for row in 0..h { + for channel in [100.0, 10.0, 0.0] { + xs.clone().for_each(|x| c.extend_from_slice(&mixed_flat(channel, row * w + x).to_le_bytes())); + } + } + return c; + } + c.extend_from_slice(&(y as i32).to_le_bytes()); + if deep { + // Packed count table, packed and unpacked sample data: one sample a pixel. + for size in [w * 4, w * 4, w * 4] { + c.extend_from_slice(&(size as u64).to_le_bytes()); + } + (1..=w as u32).for_each(|n| c.extend_from_slice(&n.to_le_bytes())); + (0..w).for_each(|_| c.extend_from_slice(&0.5f32.to_le_bytes())); + } else { + c.extend_from_slice(&((w * 3 * 4) as i32).to_le_bytes()); + for channel in [100.0, 10.0, 0.0] { + (0..w).for_each(|x| c.extend_from_slice(&mixed_flat(channel, y * w + x).to_le_bytes())); + } + } + c + }) + .collect() + }) + .collect(); + let mut offsets = [[0usize; 2]; 2]; + let mut at = out.len() + 2 * h * 8; + for (part, lines) in chunks.iter().enumerate() { + for (y, c) in lines.iter().enumerate() { + offsets[part][y] = at; + out.extend_from_slice(&(at as u64).to_le_bytes()); + at += c.len(); + } + } + chunks.into_iter().flatten().for_each(|c| out.extend_from_slice(&c)); + (out, offsets) +} + +#[test] +fn a_flat_part_beside_a_deep_part_decodes() { + let limits = Limits::default(); + for (deep_first, tiled) in [(false, false), (true, false), (false, true), (true, true)] { + let (bytes, _) = mixed_file(deep_first, tiled); + let (flat, deep) = if deep_first { (1, 0) } else { (0, 1) }; + let parts = parts(&bytes, &limits).unwrap(); + assert_eq!((parts[flat].deep, parts[deep].deep, parts[flat].name.as_deref()), (false, true, Some("flat"))); + + let part = decode_part(&bytes, flat, &all, &limits).unwrap(); + for (name, channel) in [("R", 0.0), ("G", 10.0), ("B", 100.0)] { + let expected: Vec = (0..6).map(|i| mixed_flat(channel, i)).collect(); + assert_eq!(part.channel(name).unwrap().samples, Samples::F32(expected), "deep first {deep_first} tiled {tiled} {name}"); + } + let only_g = decode_part(&bytes, flat, &|n| n == "G", &limits).unwrap(); + assert_eq!(only_g.channels.iter().map(|c| c.name.as_str()).collect::>(), ["G"]); + + let display = decode_display_part(&bytes, flat, &|n| n == "flat.R", &|_| 9.0, &limits).unwrap(); + assert_eq!(display.channels.len(), 1); + assert_eq!((display.channels[0].name.as_str(), display.channels[0].samples.as_slice()), ("flat.R", &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0][..])); + + assert!(matches!(decode_part(&bytes, deep, &all, &limits), Err(Error::Unsupported(_)))); + assert!(matches!(decode_display_part(&bytes, deep, &all, &|_| 0.0, &limits), Err(Error::Unsupported(_)))); + assert!(matches!(decode_part(&bytes, 2, &all, &limits), Err(Error::Malformed(_)))); + let deep_image = crate::deep::decode_deep(&bytes, &limits).unwrap(); + assert_eq!((deep_image.width, deep_image.height), (3, 2)); + } +} + +#[test] +fn a_flat_part_s_chunks_beside_a_deep_part_are_checked_before_they_are_read() { + let limits = Limits::default(); + for deep_first in [false, true] { + let (good, offsets) = mixed_file(deep_first, false); + let (flat, deep) = if deep_first { (1, 0) } else { (0, 1) }; + let tables = mixed_headers(deep_first, false, (3, 2)).len(); + let entry = tables + flat * 2 * 8; + let with_offset = |slot: usize, value: u64| { + let mut b = good.clone(); + b[entry + slot * 8..entry + slot * 8 + 8].copy_from_slice(&value.to_le_bytes()); + b + }; + let refused = |b: &[u8]| { + for r in [decode_part(b, flat, &all, &limits).map(|_| ()), decode_display_part(b, flat, &all, &|_| 0.0, &limits).map(|_| ())] { + assert!(matches!(&r, Err(Error::Malformed(_))), "deep first {deep_first}: {r:?}"); + } + }; + // The deep part's chunk, the end of the file and past it, the offset tables, the same + // chunk twice. + refused(&with_offset(0, offsets[deep][0] as u64)); + refused(&with_offset(0, good.len() as u64)); + refused(&with_offset(0, u64::MAX)); + refused(&with_offset(0, (tables + 8) as u64)); + refused(&with_offset(1, offsets[flat][0] as u64)); + // A chunk naming another part, and one declaring more bytes than a block holds. + let mut b = good.clone(); + b[offsets[flat][1]..offsets[flat][1] + 4].copy_from_slice(&(deep as i32).to_le_bytes()); + refused(&b); + let mut b = good.clone(); + b[offsets[flat][0] + 8..offsets[flat][0] + 12].copy_from_slice(&i32::MAX.to_le_bytes()); + refused(&b); + // Offset tables longer than the file. + refused(&good[..tables + 20]); + + for n in 0..good.len() { + let _ = decode_part(&good[..n], flat, &all, &limits); + let _ = decode_display_part(&good[..n], flat, &all, &|_| 0.0, &limits); + } + for i in 0..good.len() { + for v in [0u8, 1, 0x7F, 0xFF] { + let mut b = good.clone(); + b[i] = v; + if let Ok(p) = decode_part(&b, flat, &all, &limits) { + let n = p.info.data_window.width as usize * p.info.data_window.height as usize; + assert!(p.channels.iter().all(|c| c.samples.len() == n)); + } + let _ = decode_display_part(&b, flat, &all, &|_| 0.0, &limits); + } + } + } +} + +#[test] +fn a_tiled_flat_part_beside_a_deep_part_must_hold_each_of_its_tiles() { + let limits = Limits::default(); + for deep_first in [false, true] { + let (good, offsets) = mixed_file(deep_first, true); + let flat = usize::from(deep_first); + // The second chunk names tile (0, 0) at level (1, 1), which a one-level part does not + // have, or tile (0, 0) again, so tile (1, 0) has no chunk. + for coordinates in [[0i32, 0, 1, 1], [0, 0, 0, 0]] { + let mut b = good.clone(); + let at = offsets[flat][1] + 4; + coordinates.iter().enumerate().for_each(|(i, v)| b[at + i * 4..at + i * 4 + 4].copy_from_slice(&v.to_le_bytes())); + for r in [decode_part(&b, flat, &all, &limits).map(|_| ()), decode_display_part(&b, flat, &all, &|_| 0.0, &limits).map(|_| ())] { + assert!(matches!(&r, Err(Error::Malformed(_))), "deep first {deep_first} {coordinates:?}: {r:?}"); + } + } + } +} + +#[test] +fn a_scan_line_chunk_beside_a_deep_part_must_start_at_its_block_s_first_line() { + // A ZIP flat part (16 lines a block) holds its 3 × 2 pixels in one chunk, stored raw, as a + // block is when compressing it does not make it smaller; the deep part follows. + let limits = Limits::default(); + let (w, h) = (3usize, 2usize); + let (plain, offsets) = mixed_file(false, false); + let deep = &plain[offsets[1][0]..]; + let with_y = |y: i32| { + let mut out = mixed_headers_with(false, false, (w, h), 3, &["B", "G", "R"], 2); + let mut chunk = Vec::new(); + chunk.extend_from_slice(&0i32.to_le_bytes()); + chunk.extend_from_slice(&y.to_le_bytes()); + chunk.extend_from_slice(&((w * h * 3 * 4) as i32).to_le_bytes()); + for row in 0..h { + for channel in [100.0, 10.0, 0.0] { + (0..w).for_each(|x| chunk.extend_from_slice(&mixed_flat(channel, row * w + x).to_le_bytes())); + } + } + let flat_at = out.len() + 3 * 8; + let deep_at = flat_at + chunk.len(); + for at in [flat_at, deep_at, deep_at + offsets[1][1] - offsets[1][0]] { + out.extend_from_slice(&(at as u64).to_le_bytes()); + } + out.extend_from_slice(&chunk); + out.extend_from_slice(deep); + out + }; + let part = decode_part(&with_y(0), 0, &all, &limits).unwrap(); + assert_eq!(part.channel("R").unwrap().samples, Samples::F32((0..6).map(|i| mixed_flat(0.0, i)).collect())); + // Each of these y values rounds to block 0, but none is that block's first line. + for y in [-15, -1, 1, 15] { + let b = with_y(y); + for r in [decode_part(&b, 0, &all, &limits).map(|_| ()), decode_display_part(&b, 0, &all, &|_| 0.0, &limits).map(|_| ())] { + assert!(matches!(&r, Err(Error::Malformed(_))), "y {y}: {r:?}"); + } + } +} + +/// A mixed file whose flat part, first, is one pixel of these float channels (each 1.0) in one +/// `tile` × `tile` tile, held by a chunk that declares `size` payload bytes. +fn mixed_one_tile(channels: &[&str], tile: u32, size: i32) -> Vec { + let (plain, offsets) = mixed_file(false, false); + let mut out = mixed_headers_with(false, true, (1, 1), 0, channels, tile); + let mut chunk = Vec::new(); + [0i32, 0, 0, 0, 0, size].iter().for_each(|v| chunk.extend_from_slice(&v.to_le_bytes())); + channels.iter().for_each(|_| chunk.extend_from_slice(&1f32.to_le_bytes())); + let flat_at = out.len() + 3 * 8; + let deep_at = flat_at + chunk.len(); + for at in [flat_at, deep_at, deep_at + offsets[1][1] - offsets[1][0]] { + out.extend_from_slice(&(at as u64).to_le_bytes()); + } + out.extend_from_slice(&chunk); + out.extend_from_slice(&plain[offsets[1][0]..]); + out +} + +#[test] +fn a_chunk_beside_a_deep_part_must_fit_the_rest_of_the_file() { + // 2^14 × 2^14 tiles of three floats let a chunk hold up to 3 GiB (also on 32-bit), so the crate would + // allocate the 2 GiB this chunk declares before it found the file too short. + let limits = Limits::default(); + let channels = ["B", "G", "R"]; + let good = mixed_one_tile(&channels, 1 << 14, 12); + assert_eq!(decode_part(&good, 0, &all, &limits).unwrap().channel("R").unwrap().samples, Samples::F32(vec![1.0])); + let b = mixed_one_tile(&channels, 1 << 14, i32::MAX); + for r in [decode_part(&b, 0, &all, &limits).map(|_| ()), decode_display_part(&b, 0, &all, &|_| 0.0, &limits).map(|_| ())] { + assert!(matches!(&r, Err(Error::Malformed(m)) if m.contains("remain in the file")), "{r:?}"); + } +} + +#[test] +fn a_tile_too_large_to_address_is_refused_before_a_chunk_is_read() { + // Five float channels in 10^9 × 10^9 tiles: 20 bytes a pixel times 10^18 pixels does not fit + // in a 64-bit size, though the 1 × 1 part passes every size limit. + let limits = Limits::default(); + let channels = ["A", "B", "C", "D", "E"]; + let tile = 1_000_000_000u32; + let mixed = mixed_one_tile(&channels, tile, 20); + + // A file of flat parts only, read by the crate's own reader, with its 4 × 4 tiles widened. + let mut flat_only = file(vec![layer(None, 1, 1, &channels, true, exr::prelude::Compression::Uncompressed)], (1, 1)); + let at = flat_only.windows(9).position(|w| w == b"tiledesc\0").unwrap() + 9 + 4; + [tile, tile].iter().enumerate().for_each(|(i, v)| flat_only[at + i * 4..at + i * 4 + 4].copy_from_slice(&v.to_le_bytes())); + + for (name, b) in [("mixed", &mixed), ("flat only", &flat_only)] { + let results = [ + parts(b, &limits).map(|_| ()), + decode_part(b, 0, &all, &limits).map(|_| ()), + decode_display_part(b, 0, &all, &|_| 0.0, &limits).map(|_| ()), + ]; + for r in results { + assert!(matches!(&r, Err(Error::LimitExceeded(_))), "{name}: {r:?}"); + } + } +} + +#[test] +fn the_flat_parts_of_a_mixed_file_must_fit_the_file() { + // 1024 × 1024 × 3 float samples (12 MiB) declared in a file of a few hundred bytes: over a + // ratio of 1 plus the 1 MiB slack, though another part is deep. + let headers = mixed_headers(false, false, (1024, 1024)); + assert!(parts(&headers, &Limits::default()).is_ok()); + let tight = Limits { max_ratio: 1, ..Limits::default() }; + for r in [parts(&headers, &tight).map(|_| ()), decode_part(&headers, 0, &all, &tight).map(|_| ())] { + assert!(matches!(&r, Err(Error::LimitExceeded(_))), "{r:?}"); + } + // The deep part's samples are not counted, and a small flat part passes the same ratio. + assert!(parts(&mixed_file(false, false).0, &tight).is_ok()); +} + +#[test] +fn deep_samples_do_not_count_against_the_flat_expansion_ratio() { + // The 4 MiB deep plane would exceed max_ratio=1 plus the 1 MiB slack if counted. + // Header inspection does not allocate those samples; deep decoding bounds its own counts. + let headers = mixed_headers_with_deep_size(false, false, (1, 1), 0, &["R"], 2, (1024, 1024)); + let limits = Limits { max_ratio: 1, max_bytes: 8 * 1024 * 1024, ..Limits::default() }; + assert!(parts(&headers, &limits).is_ok()); +} + +#[test] +fn mixed_display_decode_bounds_each_block_not_the_whole_flat_part() { + for (tiled, block_bytes) in [(false, 36), (true, 48)] { + for deep_first in [false, true] { + let (bytes, _) = mixed_file(deep_first, tiled); + let flat = usize::from(deep_first); + let keep = |name: &str| name == "flat.R"; + // The full flat part is 72 bytes; the selected plane is 24 bytes. + let limits = Limits { max_bytes: block_bytes, ..Limits::default() }; + let part = decode_display_part(&bytes, flat, &keep, &|_| 0.0, &limits).unwrap(); + assert_eq!(part.channels[0].samples, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]); + let tight = Limits { max_bytes: block_bytes - 1, ..limits }; + assert!(matches!(decode_display_part(&bytes, flat, &keep, &|_| 0.0, &tight), Err(Error::LimitExceeded(_)))); + } + } +} + +#[test] +fn present_packed_payload_is_bounded_before_allocation() { + let packed = 1024 * 1024; + let mut bytes = mixed_one_tile(&["R"], 1 << 15, packed); + // Make the declared payload present, not merely a truncated-file error. The nominal + // huge tile allows this size in exr::Chunk::read, but the actual flat image is 1x1. + bytes.resize(bytes.len() + packed as usize, 0); + let limits = Limits { max_bytes: 4, ..Limits::default() }; + assert!(matches!( + decode_display_part(&bytes, 0, &|_| true, &|_| 0.0, &limits), + Err(Error::LimitExceeded(message)) if message.contains("packed flat block") + )); + // decode_part also includes the deep header's 24 bytes in its aggregate header budget. + let limits = Limits { max_bytes: 32, ..limits }; + assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(message)) if message.contains("packed flat block"))); +} + +#[test] +fn cropped_mixed_display_bounds_block_tracking() { + let mut bytes = mixed_headers_with(false, true, (100, 100), 0, &["R"], 1); + // Both display windows are 1x1; the flat data window still has 10,000 one-pixel tiles. + let needle = b"displayWindow\0box2i\0"; + let positions: Vec = bytes.windows(needle.len()).enumerate().filter_map(|(i, w)| (w == needle).then_some(i + needle.len() + 4)).collect(); + for at in positions { + bytes[at..at + 16].fill(0); + } + // Supply all offset-table bytes so validation reaches bookkeeping, not truncation. + bytes.resize(bytes.len() + (10_000 + 2) * 8, 0); + let limits = Limits { max_bytes: 4, ..Limits::default() }; + assert!(matches!( + decode_display_part(&bytes, 0, &|_| true, &|_| 0.0, &limits), + Err(Error::LimitExceeded(message)) if message.contains("block tracking") + )); +} + +#[test] +fn dense_block_ordinals_cover_scan_lines_and_all_tile_levels() { + use exr::block::chunk::TileCoordinates; + use exr::meta::attribute::LevelMode; + for tiled in [false, true] { + let bytes = file(vec![layer(None, 9, 7, &["R"], tiled, exr::prelude::Compression::ZIP1)], (9, 7)); + let mut meta = read_meta(&bytes, &Limits::default()).unwrap(); + let header = &mut meta.headers[0]; + for mode in [LevelMode::Singular, LevelMode::MipMap, LevelMode::RipMap] { + if let exr::meta::BlockDescription::Tiles(tiles) = &mut header.blocks { + tiles.level_mode = mode; + } + for (i, block) in header.blocks_increasing_y_order().enumerate() { + assert_eq!(flat_block_ordinal(header, block.location).unwrap(), i); + } + let absent = TileCoordinates { tile_index: exr::math::Vec2(0, 0), level_index: exr::math::Vec2(100, 100) }; + assert!(flat_block_ordinal(header, absent).is_err()); + } + } +} diff --git a/crates/exr/src/deep.rs b/crates/exr/src/deep.rs index b86d497c80..ad2ab00b5a 100644 --- a/crates/exr/src/deep.rs +++ b/crates/exr/src/deep.rs @@ -391,19 +391,14 @@ fn decode_deep_meta(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Result Result { Ok(cur.position()) } +/// Where part `header_index`'s offset table starts and where the last part's table ends. The +/// tables follow the headers, `chunk_count` u64 per header in header order, and the chunks +/// follow the last table. Sizes that overflow, or tables that run past the end of the file, +/// are errors. +fn offset_tables(meta: &MetaData, bytes: &[u8], header_index: usize) -> Result<(u64, u64)> { + let mut table_pos = header_end(bytes)?; + let mut tables_end = table_pos; + for (i, h) in meta.headers.iter().enumerate() { + let len = u64::try_from(h.chunk_count).ok().and_then(|n| n.checked_mul(8)); + tables_end = len.and_then(|len| tables_end.checked_add(len)).ok_or_else(|| err("the offset tables are too large"))?; + if i < header_index { + table_pos = tables_end; + } + } + if tables_end > bytes.len() as u64 { + return Err(err(format!("the offset tables end at byte {tables_end}, past the end of the file"))); + } + Ok((table_pos, tables_end)) +} + /// Composite the deep samples into a flat image: per pixel, samples sorted by Z (stable; the /// file is assumed messy), front-to-back `over` with premultiplied colour, un-premultiplied /// into straight alpha at the end. Without any alpha channel the front-most sample wins, diff --git a/crates/exr/src/deep_tests.rs b/crates/exr/src/deep_tests.rs index cb17218096..bdbfa0d688 100644 --- a/crates/exr/src/deep_tests.rs +++ b/crates/exr/src/deep_tests.rs @@ -886,6 +886,106 @@ fn inconsistent_count_table_errors() { assert!(matches!(decode_deep_exr(&bytes, &Limits::none()), Err(CodecError::Malformed(_)))); } +/// A two-part file made from the single-part deep file `deep` and a 1×1 flat scan-line part, +/// the deep part first when `deep_first`: each header gains `name` and `chunkCount`, the +/// version field the multipart bit, and each chunk its part number. The offset tables follow +/// the headers in header order, then the chunks. Returns the file, where the first table +/// starts, where the second table starts and where the last table ends. +fn two_part(deep: &[u8], deep_first: bool) -> (Vec, usize, usize, usize) { + let end = header_end_of(deep); + let first = u64::from_le_bytes(deep[end..end + 8].try_into().expect("8")) as usize; + let offsets: Vec = + (0..(first - end) / 8).map(|i| u64::from_le_bytes(deep[end + 8 * i..end + 8 * i + 8].try_into().expect("8")) as usize).collect(); + let deep_chunks: Vec<&[u8]> = offsets.iter().enumerate().map(|(i, &o)| &deep[o..offsets.get(i + 1).copied().unwrap_or(deep.len())]).collect(); + + let mut deep_header = deep[8..end - 1].to_vec(); + attr(&mut deep_header, "name", "string", b"deep"); + attr(&mut deep_header, "chunkCount", "int", &(deep_chunks.len() as i32).to_le_bytes()); + let mut flat_header = Vec::new(); + let mut chlist = b"R\0".to_vec(); + chlist.extend_from_slice(&1i32.to_le_bytes()); // half + chlist.extend_from_slice(&[0u8; 4]); // pLinear, reserved + chlist.extend_from_slice(&1i32.to_le_bytes()); + chlist.extend_from_slice(&1i32.to_le_bytes()); + chlist.push(0); + attr(&mut flat_header, "channels", "chlist", &chlist); + attr(&mut flat_header, "compression", "compression", &[0]); + let dw: Vec = [0i32; 4].iter().flat_map(|v| v.to_le_bytes()).collect(); + attr(&mut flat_header, "dataWindow", "box2i", &dw); + attr(&mut flat_header, "displayWindow", "box2i", &dw); + attr(&mut flat_header, "lineOrder", "lineOrder", &[0]); + attr(&mut flat_header, "pixelAspectRatio", "float", &1f32.to_le_bytes()); + attr(&mut flat_header, "screenWindowCenter", "v2f", &[0f32.to_le_bytes(), 0f32.to_le_bytes()].concat()); + attr(&mut flat_header, "screenWindowWidth", "float", &1f32.to_le_bytes()); + attr(&mut flat_header, "name", "string", b"flat"); + attr(&mut flat_header, "type", "string", b"scanlineimage"); + attr(&mut flat_header, "chunkCount", "int", &1i32.to_le_bytes()); + // The flat part's one chunk: y, the data size, one half sample. + let mut flat_chunk = 0i32.to_le_bytes().to_vec(); + flat_chunk.extend_from_slice(&2i32.to_le_bytes()); + flat_chunk.extend_from_slice(&f16::from_f32(0.5).to_le_bytes()); + let flat_chunks: Vec<&[u8]> = vec![&flat_chunk]; + + let parts: [(&[u8], &[&[u8]]); 2] = if deep_first { + [(&deep_header, &deep_chunks), (&flat_header, &flat_chunks)] + } else { + [(&flat_header, &flat_chunks), (&deep_header, &deep_chunks)] + }; + let mut out = deep[..4].to_vec(); + out.extend_from_slice(&(2u32 | 0x800 | 0x1000).to_le_bytes()); + for (header, _) in &parts { + out.extend_from_slice(header); + out.push(0); // end of this header + } + out.push(0); // end of the headers + let first_table = out.len(); + let second_table = first_table + parts[0].1.len() * 8; + let tables_end = second_table + parts[1].1.len() * 8; + let mut pos = tables_end; + for (_, chunks) in &parts { + for c in chunks.iter() { + out.extend_from_slice(&(pos as u64).to_le_bytes()); + pos += 4 + c.len(); + } + } + for (part, (_, chunks)) in parts.iter().enumerate() { + for c in chunks.iter() { + out.extend_from_slice(&(part as i32).to_le_bytes()); + out.extend_from_slice(c); + } + } + (out, first_table, second_table, tables_end) +} + +/// The deep part of a two-part file decodes as the single-part file does, first or second. +/// Its chunks start after every part's offset table: a chunk offset into the other part's +/// table, or one byte before the end of the last table, is refused as table data, and a file +/// that ends inside the last table is refused even when the deep part's own table is whole. +#[test] +fn multipart_deep_chunks_start_after_every_offset_table() { + let single = gen_deep(4, 4, &RGBAZ, 0, None, COUNTS_ONE, &sample_rgba); + let want = decode_deep_exr(&single, &Limits::none()).expect("single part"); + for deep_first in [true, false] { + let (bytes, ..) = two_part(&single, deep_first); + let deep = decode_deep_exr(&bytes, &Limits::none()).expect("two parts"); + assert_eq!(deep.counts, want.counts); + assert_eq!(deep.channel("Z").expect("Z").samples, want.channel("Z").expect("Z").samples); + } + + let refused = |bytes: &[u8], what: &str| match decode_deep_exr(bytes, &Limits::none()) { + Err(e @ CodecError::Malformed(_)) => assert!(e.to_string().contains(what), "{e}"), + Err(e) => panic!("{e}, want an error about {what}"), + Ok(_) => panic!("decoded, want an error about {what}"), + }; + let (bytes, first_table, second_table, tables_end) = two_part(&single, true); + for off in [second_table, tables_end - 1] { + let mut into_table = bytes.clone(); + into_table[first_table..first_table + 8].copy_from_slice(&(off as u64).to_le_bytes()); + refused(&into_table, "outside the chunk area"); + } + refused(&bytes[..tables_end - 4], "past the end of the file"); +} + /// `gen_deep` for a cropped render: the data window sits at `(dwx, dwy)` inside a larger /// display window of `sw × sh` (the stage the renderer composed onto). Scanline chunk Y /// coordinates are absolute display rows, so they carry the data-window offset. diff --git a/crates/exr/src/dwa_guard.rs b/crates/exr/src/dwa_guard.rs new file mode 100644 index 0000000000..a0b9c75462 --- /dev/null +++ b/crates/exr/src/dwa_guard.rs @@ -0,0 +1,161 @@ +//! A check of DWAA/DWAB chunks before the `exr` crate decompresses them. +//! +//! A DWA payload starts with eleven little-endian `u64` counters, which the `exr` crate (1.74.3, +//! `src/compression/dwa/chunk_header.rs`, `DwaHeader::parse`) reads in this order: version, +//! unknown uncompressed size, unknown compressed size, AC compressed size, DC compressed size, +//! RLE compressed size, RLE uncompressed size, RLE raw size, AC count, DC count, AC compression. +//! The crate checks them only against `i64::MAX`, then inflates sections with these sizes as the +//! size hint (`src/compression/dwa/section_stream.rs`: `inflate(section, expected)` with the +//! unknown uncompressed size, `ac_count * 2` for deflated AC, `dc_count * 2`, and the RLE +//! uncompressed size), and its inflater allocates the hint up front. A 100-byte chunk declaring +//! 2^44 DC values makes it allocate 32 TiB: the process aborts, which `catch_unwind` can't stop. +//! +//! What a valid chunk declares is bounded by its block (`width × height` pixels of all the +//! part's channels, `raw` bytes uncompressed): +//! - the unknown (losslessly zipped) channels and the RLE channels are some of the block's +//! channels stored planar, so their uncompressed sizes are at most `raw`; +//! - the RLE token stream adds at most one count byte per 127 literal bytes (runs of three or +//! more shrink), so it stays within `2 × raw`, a bound that leaves room for any encoder; +//! - the lossy channels are cut into 8 × 8 DCT blocks over the block padded to multiples of 8: +//! one DC value and at most 63 AC values per DCT block and channel. + +use exr::block::chunk::{CompressedBlock, CompressedScanLineBlock, CompressedTileBlock, TileCoordinates}; +use exr::math::Vec2; +use exr::meta::header::Header; +use exr::prelude::Compression; + +/// The counters' bytes at the start of a DWA payload. +const COUNTERS: usize = 11 * 8; + +/// Whether chunks of `compression` go through this check. +pub(crate) fn is_dwa(compression: Compression) -> bool { + matches!(compression, Compression::DWAA(_) | Compression::DWAB(_)) +} + +/// What the check needs of a DWA part: the bytes of one pixel of all its channels, and how many +/// channels it has. `None` when the pixel's bytes overflow. +fn shape(header: &Header) -> Option<(usize, usize)> { + let pixel_bytes = header.channels.list.iter().map(|c| c.sample_type.bytes_per_sample()).try_fold(0usize, usize::checked_add)?; + Some((pixel_bytes, header.channels.list.len())) +} + +/// Checks the DWA payload `payload` of a block of `width × height` pixels of the part `header` +/// describes: an error message when a counter declares more than a valid chunk of that block +/// can hold. A payload as long as the block's raw bytes is stored uncompressed (the crate doesn't +/// read counters then); one shorter than the counters is left to the crate, which refuses it. +pub(crate) fn check_payload(header: &Header, size: (usize, usize), payload: &[u8]) -> Result<(), String> { + if !is_dwa(header.compression) { + return Ok(()); + } + check_shaped(shape(header).ok_or("a DWA pixel size overflows")?, size, payload) +} + +/// [`check_payload`] with the part's [`shape`] worked out already. +fn check_shaped((pixel_bytes, channels): (usize, usize), (width, height): (usize, usize), payload: &[u8]) -> Result<(), String> { + let raw = pixel_bytes.checked_mul(width).and_then(|b| b.checked_mul(height)).ok_or("a DWA block size overflows")?; + if payload.len() == raw { + return Ok(()); + } + let Some(counters) = payload.get(..COUNTERS) else { return Ok(()) }; + let counter = |i: usize| counters.get(i * 8..i * 8 + 8).and_then(|b| <[u8; 8]>::try_from(b).ok()).map_or(u64::MAX, u64::from_le_bytes); + let dct_blocks = width.div_ceil(8).checked_mul(height.div_ceil(8)).and_then(|n| n.checked_mul(channels)).ok_or("a DWA block size overflows")?; + let raw = raw as u64; + let bounds: [(usize, &str, u64); 5] = [ + (1, "unknown uncompressed size", raw), + (6, "RLE uncompressed size", raw.saturating_mul(2)), + (7, "RLE raw size", raw), + (8, "AC count", (dct_blocks as u64).saturating_mul(63)), + (9, "DC count", dct_blocks as u64), + ]; + for (i, name, most) in bounds { + let value = counter(i); + // (also keeps `count * 2` within a 32-bit usize: the bounds are block sizes, which fit) + if value > most || usize::try_from(value.saturating_mul(2)).is_err() { + return Err(format!("a DWA chunk declares a {name} of {value}, more than its {width} × {height} block can hold ({most})")); + } + } + Ok(()) +} + +/// The pixel size of the block the `exr` crate decompresses a chunk of the part `header` +/// describes into, from the chunk's coordinates: the crate's own placement +/// (`Header::get_block_data_indices`, then `get_absolute_block_pixel_coordinates`), so a scan-line +/// `y` the crate rounds into a block (it divides toward zero: rows just above the data window land +/// in block 0) is sized as that block. An error where the crate can't place the chunk. +fn block_size(header: &Header, block: &CompressedBlock) -> Result<(usize, usize), String> { + if let CompressedBlock::Tile(tile) = block { + // (the crate's level size asserts on levels of 64 and more; no valid file has 32) + if tile.coordinates.level_index.0 >= 32 || tile.coordinates.level_index.1 >= 32 { + return Err("a DWA tile of an impossible level".into()); + } + } + let tile = header.get_block_data_indices(block).map_err(|e| format!("a DWA chunk the decoder can't place: {e}"))?; + let bounds = header.get_absolute_block_pixel_coordinates(tile).map_err(|e| format!("a DWA chunk the decoder can't place: {e}"))?; + Ok((bounds.size.0, bounds.size.1)) +} + +/// Checks every chunk the offset tables point at that is, or names, a flat DWA part (`tables` is +/// where the offset tables start), before the `exr` crate's whole-image reader, which offers no +/// hook between reading a chunk and decompressing it, gets the bytes. It fails closed: a chunk of +/// a DWA part whose part number, coordinates, size or payload can't be read, or whose block can't +/// be placed, is an error, not left to the crate. +pub(crate) fn check_file(bytes: &[u8], meta: &exr::meta::MetaData, tables: usize) -> Result<(), String> { + if !meta.headers.iter().any(|h| !h.deep && is_dwa(h.compression)) { + return Ok(()); + } + let multipart = meta.requirements.is_multilayer(); + let word = |at: usize| bytes.get(at..at.checked_add(4)?).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes); + let cut = || "a DWA chunk cut off by the end of the file".to_string(); + // Per part: its shape when it is a flat DWA part (worked out once, not per chunk). + let shapes: Vec> = meta + .headers + .iter() + .map(|h| if !h.deep && is_dwa(h.compression) { shape(h).ok_or("a DWA pixel size overflows").map(Some) } else { Ok(None) }) + .collect::>()?; + let mut table = tables; + for (table_part, header) in meta.headers.iter().enumerate() { + let entries = + bytes.get(table..table.saturating_add(header.chunk_count.saturating_mul(8))).ok_or("the offset tables run past the end of the file")?; + table = table.saturating_add(header.chunk_count.saturating_mul(8)); + for entry in entries.as_chunks::<8>().0 { + let offset = usize::try_from(u64::from_le_bytes(*entry)).ok(); + // The part the crate decodes the chunk as: the one it names (multi-part files). + let (part, mut at) = match (multipart, offset) { + (false, Some(at)) => (Some(table_part), at), + (true, Some(at)) => (word(at).and_then(|p| usize::try_from(p).ok()), at.saturating_add(4)), + (_, None) => (None, 0), + }; + let named = part.and_then(|p| shapes.get(p).copied().flatten().map(|s| (p, s))); + let Some((part, shape)) = named else { + // (not a DWA chunk, unless it sits in a DWA part's table and can't be read) + if shapes.get(table_part).copied().flatten().is_some() && part.is_none_or(|p| p >= meta.headers.len()) { + return Err(cut()); + } + continue; + }; + let header = meta.headers.get(part).ok_or_else(cut)?; + let block = match header.blocks { + exr::meta::BlockDescription::ScanLines => { + let y = word(at).ok_or_else(cut)?; + at = at.saturating_add(4); + CompressedBlock::ScanLine(CompressedScanLineBlock { y_coordinate: y, compressed_pixels_le: Vec::new() }) + } + exr::meta::BlockDescription::Tiles(_) => { + let tile = [word(at), word(at.saturating_add(4)), word(at.saturating_add(8)), word(at.saturating_add(12))]; + at = at.saturating_add(16); + let [Some(x), Some(y), Some(lx), Some(ly)] = tile else { return Err(cut()) }; + let index = |v: i32| usize::try_from(v).map_err(|_| "a DWA tile at a negative position".to_string()); + let coordinates = TileCoordinates { tile_index: Vec2(index(x)?, index(y)?), level_index: Vec2(index(lx)?, index(ly)?) }; + CompressedBlock::Tile(CompressedTileBlock { coordinates, compressed_pixels_le: Vec::new() }) + } + }; + let size = block_size(header, &block)?; + let len = word(at).ok_or_else(cut)?; + let len = usize::try_from(len).map_err(|_| "a DWA chunk declaring a negative size".to_string())?; + let start = at.saturating_add(4); + let payload = bytes.get(start..start.saturating_add(len)).ok_or_else(cut)?; + check_shaped(shape, size, payload)?; + } + } + Ok(()) +} diff --git a/crates/exr/src/lib.rs b/crates/exr/src/lib.rs index baaf3d3f15..9ff66f95d3 100644 --- a/crates/exr/src/lib.rs +++ b/crates/exr/src/lib.rs @@ -15,9 +15,16 @@ //! - [`decode`]: bounded part listing, flat decoding (scan lines and tiles, every compression the //! `exr` crate reads) and writing, on top of the `exr` crate. //! - [`deep`]: deep scan lines and tiles (NONE, RLE, ZIPS) and their flattening. +//! - [`seek`]: any channels, display rows and reduced resolution of a file's flat parts, read from +//! a seekable source and delivered band by band (or collected into planes). //! - [`stream`]: one flat scan-line part read block by block, for pictures larger than memory. //! - [`cryptomatte_samples`]: a file's Cryptomatte layers and their per-pixel (ID, coverage) ranks. +/// Scanline OpenEXR writer using a caller-supplied linearization table. +pub mod rgba8; +/// RFC 1950/1951 compressor for ZIP-compressed EXR chunks. +pub mod zlib; + pub mod channels; pub mod cryptomatte; #[cfg(feature = "decode")] @@ -31,4 +38,10 @@ pub mod deep; #[cfg(all(test, feature = "decode"))] mod deep_tests; #[cfg(feature = "decode")] +mod dwa_guard; +#[cfg(feature = "decode")] +pub mod seek; +#[cfg(all(test, feature = "decode"))] +mod seek_tests; +#[cfg(feature = "decode")] pub mod stream; diff --git a/crates/exr/src/rgba8.rs b/crates/exr/src/rgba8.rs new file mode 100644 index 0000000000..6dc4bde4c3 --- /dev/null +++ b/crates/exr/src/rgba8.rs @@ -0,0 +1,235 @@ +//! Single-part scanline OpenEXR output from RGBA8 pixels. + +/// Scanline chunk compression. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Compression { + /// Uncompressed. + None, + /// OpenEXR RLE. + Rle, + /// zlib per scanline. + Zips, + /// zlib per 16 scanlines. + Zip, +} +impl Compression { + fn code(self) -> u8 { + match self { + Self::None => 0, + Self::Rle => 1, + Self::Zips => 2, + Self::Zip => 3, + } + } + fn lines(self) -> usize { + if self == Self::Zip { 16 } else { 1 } + } +} +/// Why a frame cannot be encoded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Error { + /// Empty, overflowing or mismatched RGBA dimensions. + FrameSize, + /// Dimensions exceed the OpenEXR signed-size fields. + TooLarge, +} +fn checked_len(rgba: &[u8], w: u32, h: u32) -> Result { + let n = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or(Error::FrameSize)?; + if w == 0 || h == 0 || rgba.len() != n { + return Err(Error::FrameSize); + } + Ok(n) +} + +/// IEEE 754 binary16 bits of `v`, rounded to nearest even (overflow → infinity, NaN → quiet NaN). +pub fn half(v: f32) -> u16 { + let b = v.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let exp = ((b >> 23) & 0xFF) as i32; + let man = b & 0x7F_FFFF; + if exp == 0xFF { + return sign | 0x7C00 | if man != 0 { 0x200 } else { 0 }; + } + // rounds `m >> shift` to nearest, ties to even (`shift` is 1..=24) + let round = |m: u32, shift: u32| { + let (q, rem, mid) = (m >> shift, m & ((1 << shift) - 1), 1 << (shift - 1)); + if rem > mid || (rem == mid && q & 1 == 1) { q + 1 } else { q } + }; + let e = exp - 127 + 15; + if e >= 0x1F { + sign | 0x7C00 + } else if e <= 0 { + if e < -10 { + return sign; + } + // subnormal half: the 24-bit significand scaled by 2^(e - 14); rounding up may carry + // into the smallest normal, which is the right encoding + sign | round(man | 0x80_0000, (14 - e) as u32) as u16 + } else { + // a carry out of the mantissa bumps the exponent (up to infinity), as it should + sign | round(((e as u32) << 23) | man, 13) as u16 + } +} + +/// An OpenEXR file: half-float scene-linear Rec.709 RGB, or RGBA with `alpha` (premultiplied, as +/// EXR defines alpha; the frame's straight alpha is multiplied in after linearisation). +pub fn write_rgba8(rgba: &[u8], w: u32, h: u32, alpha: bool, compression: Compression, linear: &[f32; 256]) -> Result, Error> { + let n = checked_len(rgba, w, h)?; + let too_large = || Error::TooLarge; + let (Ok(x_max), Ok(y_max)) = (i32::try_from(w - 1), i32::try_from(h - 1)) else { + return Err(too_large()); + }; + // channels in the alphabetical order the file layout requires + let names: &[u8] = if alpha { b"ABGR" } else { b"BGR" }; + let line = (w as usize).checked_mul(names.len() * 2).ok_or(Error::FrameSize)?; + // a chunk's byte count is a signed 32-bit field + let lines = compression.lines(); + if line.checked_mul(lines).and_then(|c| i32::try_from(c).ok()).is_none() { + return Err(too_large()); + } + + let mut hd = Vec::with_capacity(512); + hd.extend_from_slice(&[0x76, 0x2F, 0x31, 0x01]); // magic number 20000630 + hd.extend_from_slice(&[2, 0, 0, 0]); // version 2, single-part scan-line file, short names + let attr = |hd: &mut Vec, name: &str, ty: &str, value: &[u8]| { + for s in [name, ty] { + hd.extend_from_slice(s.as_bytes()); + hd.push(0); + } + hd.extend_from_slice(&(value.len() as i32).to_le_bytes()); + hd.extend_from_slice(value); + }; + let le = |v: &[f32]| v.iter().flat_map(|f| f.to_le_bytes()).collect::>(); + let mut channels = Vec::new(); + for &c in names { + channels.extend_from_slice(&[c, 0]); + channels.extend_from_slice(&1_i32.to_le_bytes()); // pixel type HALF + channels.extend_from_slice(&[0, 0, 0, 0]); // pLinear 0, reserved + channels.extend_from_slice(&1_i32.to_le_bytes()); // x sampling + channels.extend_from_slice(&1_i32.to_le_bytes()); // y sampling + } + channels.push(0); + let window: Vec = [0, 0, x_max, y_max].iter().flat_map(|v| v.to_le_bytes()).collect(); + attr(&mut hd, "channels", "chlist", &channels); + attr(&mut hd, "chromaticities", "chromaticities", &le(&[0.64, 0.33, 0.30, 0.60, 0.15, 0.06, 0.3127, 0.3290])); + attr(&mut hd, "compression", "compression", &[compression.code()]); + attr(&mut hd, "dataWindow", "box2i", &window); + attr(&mut hd, "displayWindow", "box2i", &window); + attr(&mut hd, "lineOrder", "lineOrder", &[0]); // INCREASING_Y + attr(&mut hd, "pixelAspectRatio", "float", &le(&[1.0])); + attr(&mut hd, "screenWindowCenter", "v2f", &le(&[0.0, 0.0])); + attr(&mut hd, "screenWindowWidth", "float", &le(&[1.0])); + hd.push(0); // end of header + + // offset table (one entry per chunk), then the chunks: first y, data size, data + let chunks = (h as usize).div_ceil(lines); + let table = chunks.checked_mul(8); + let body = (h as usize).checked_mul(line + 8); + let size = table.zip(body).and_then(|(t, b)| hd.len().checked_add(t)?.checked_add(b)).ok_or(Error::FrameSize)?; + // the uncompressed size: compressed chunks only shrink it + let mut out = Vec::with_capacity(size); + out.extend_from_slice(&hd); + let table_at = out.len(); + out.resize(table_at + chunks * 8, 0); + let lin = linear; + let opaque: [u16; 256] = std::array::from_fn(|i| half(lin[i])); + let row = w as usize * 4; + let wn = w as usize; + let mut px = vec![0_u16; wn * names.len()]; + let mut raw = Vec::with_capacity(line * lines); + // the deflate hash tables, shared by the frame's chunks instead of zeroed for each one + let mut tables = crate::zlib::Tables::default(); + for (k, block) in rgba[..n].chunks(row * lines).enumerate() { + raw.clear(); + for src in block.chunks_exact(row) { + // planar per line: every pixel of the first channel, then the next channel … + for (x, &[r, g, b, a]) in src.as_chunks::<4>().0.iter().enumerate() { + let rgb = [b, g, r]; + if alpha { + let k = f32::from(a) / 255.0; + px[x] = half(k); + for (c, &v) in rgb.iter().enumerate() { + px[(c + 1) * wn + x] = if a == 255 { opaque[v as usize] } else { half(lin[v as usize] * k) }; + } + } else { + for (c, &v) in rgb.iter().enumerate() { + px[c * wn + x] = opaque[v as usize]; + } + } + } + raw.extend(px.iter().flat_map(|v| v.to_le_bytes())); + } + let packed = match compression { + Compression::None => None, + Compression::Rle => Some(rle(&predict(&raw))), + Compression::Zips | Compression::Zip => Some(crate::zlib::zlib(&predict(&raw), &mut tables)), + }; + // a chunk that does not shrink is stored as it is (readers compare the sizes) + let data = packed.as_deref().filter(|p| p.len() < raw.len()).unwrap_or(&raw); + let offset = (out.len() as u64).to_le_bytes(); + out[table_at + k * 8..table_at + k * 8 + 8].copy_from_slice(&offset); + out.extend_from_slice(&((k * lines) as i32).to_le_bytes()); + out.extend_from_slice(&(data.len() as i32).to_le_bytes()); + out.extend_from_slice(data); + } + Ok(out) +} + +/// The OpenEXR RLE / ZIP predictor: bytes split into even and odd halves, then each byte replaced +/// by its difference from the previous one, plus 128. +fn predict(raw: &[u8]) -> Vec { + let half = raw.len().div_ceil(2); + let mut t = vec![0_u8; raw.len()]; + for (i, &b) in raw.iter().enumerate() { + t[if i % 2 == 0 { i / 2 } else { half + i / 2 }] = b; + } + let mut p = t.first().copied().unwrap_or(0); + for v in t.iter_mut().skip(1) { + let d = v.wrapping_sub(p).wrapping_add(128); + p = *v; + *v = d; + } + t +} + +/// OpenEXR run-length coding: a signed count byte, then either `count + 1` copies of one byte +/// (count ≥ 0, runs of 3 to 128) or `-count` literal bytes (1 to 127). +pub fn rle(src: &[u8]) -> Vec { + let mut out = Vec::with_capacity(src.len() + src.len() / 127 + 1); + let mut i = 0; + while i < src.len() { + let b = src[i]; + let run = src[i..].iter().take(128).take_while(|&&x| x == b).count(); + if run >= 3 { + out.extend_from_slice(&[(run - 1) as u8, b]); + i += run; + continue; + } + // literals up to the next run of three (or 127 bytes) + let s = i; + while i < src.len() && i - s < 127 { + if src.get(i..i + 3).is_some_and(|t| t[0] == t[1] && t[1] == t[2]) { + break; + } + i += 1; + } + out.push(((i - s) as u8).wrapping_neg()); + out.extend_from_slice(&src[s..i]); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn writes_all_scanline_compressions() { + let linear = std::array::from_fn(|i| i as f32 / 255.0); + for c in [Compression::None, Compression::Rle, Compression::Zips, Compression::Zip] { + let bytes = write_rgba8(&[128; 16 * 16 * 4], 16, 16, true, c, &linear).unwrap(); + assert_eq!(&bytes[..4], &[0x76, 0x2f, 0x31, 1]); + assert!(bytes.len() > 100); + } + assert_eq!(write_rgba8(&[], 1, 1, false, Compression::None, &linear), Err(Error::FrameSize)); + } +} diff --git a/crates/exr/src/seek.rs b/crates/exr/src/seek.rs new file mode 100644 index 0000000000..03f0fa506b --- /dev/null +++ b/crates/exr/src/seek.rs @@ -0,0 +1,1551 @@ +//! Selective reading of flat OpenEXR parts from a seekable source (feature `decode`): the headers +//! are indexed once, then any channels, any display rows and a reduced resolution are read from +//! the file without loading the rest of it. +//! +//! - [`Index::build`] reads the headers and the offset tables only, through `Read + Seek`, after +//! checking what they declare against [`Limits`] and the source's length. It allocates nothing +//! sized by pixels, and the index holds no pixel data, so it can be kept per file. +//! - [`read_bands`] reads what a [`Request`] asks for and delivers it incrementally: each +//! compression block becomes [`Band`]s (one per requested channel: a rectangle of rows) handed +//! to a callback on the calling thread, in file order. Blocks are decoded on worker threads; the +//! calling thread hands over what has been decoded each time it has read a piece of the file +//! and while it waits, so the first bands arrive long before the request has been read. A +//! caller that writes into tiles or shows lines while the rest is still being read never holds +//! a whole plane. +//! - [`read_planes`] is a collector over [`read_bands`]: the same request delivered as one +//! display-window plane per channel once everything is read. +//! +//! A request names channels as `(part, channel)` pairs (positions in [`Index::parts`]), a range of +//! display-window rows, and a level: level `n` keeps every `2^n`-th row and column of the display +//! window, so a reduced picture is made without allocating the full-resolution one. Rows and band +//! positions count from the display window's top-left corner (0, 0), not in the file's absolute +//! coordinates (which [`PartInfo`]'s windows use). Only the chunks that hold a requested channel +//! and a requested row are fetched, chunks that follow each other in the file in one read, and +//! they are decompressed on several threads while the next ones are being read. Samples are +//! converted to `f32` (integer samples above 2^24 lose precision); outside a part's data window +//! (and in rows no chunk holds) a plane has the channel's fill value. +//! +//! A tile writer (an image editor storing a picture in tiles at its own depth) uses it like this: +//! [`Index::build`], then [`Index::estimate`] to reserve the working memory and size a progress +//! bar (one step per chunk), then [`read_bands_try`] with the colour channels as one group +//! ([`Request::groups`]), so each block arrives as one band of interleaved pixels to write into +//! the tiles it covers. Its sink checks the tile budget or scratch disk before each band and +//! returns its own error to stop the read; the read winds down and hands that error back. +//! +//! Deep parts are not read here (see [`crate::deep`]); a flat part beside them is. Tiled parts +//! are read from their largest resolution level. Every size a header declares is checked before +//! it is used and every allocation is bounded by a limit or reserved fallibly. +//! +//! Panics: the `exr` crate's header parser and decompressors can panic on some damaged input. +//! Where panics unwind (native targets), those calls are wrapped in `catch_unwind` and a panic +//! becomes [`Error::Malformed`]. Where panics abort (`wasm32-unknown-unknown`), `catch_unwind` +//! does nothing, so this module checks beforehand what it knows the crate would panic on: the +//! chunk layout is computed here with checked arithmetic instead of the crate's (which panics on +//! some sizes), the crate's block-size formula is checked for overflow, and a chunk's part, +//! coordinates, level and declared size are checked before the crate reads it. A panic inside +//! the crate's header +//! parsing or a decompressor on damaged data is not ruled out there. + +use std::io::{Cursor, Read, Seek, SeekFrom}; +use std::ops::Range; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use exr::block::UncompressedBlock; +use exr::block::chunk::Chunk; +use exr::math::Vec2; +use exr::meta::MetaData; +use exr::meta::attribute::SampleType as ExrSample; +use exr::meta::header::Header; + +use crate::decode::{Limits, PartInfo, Window, check_previews, part_info}; + +/// Why a read failed. More kinds may be added: a `match` needs a catch-all arm. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + /// The file is damaged, or a chunk can't be decompressed. + #[error("OpenEXR: {0}")] + Malformed(String), + /// A valid file this reader does not cover (subsampled channels, channels of deep parts). + #[error("unsupported OpenEXR: {0}")] + Unsupported(String), + /// A valid file whose compression this reader does not decode (HTJ2K): the name of the + /// compression. An app may hand such a file to another decoder. + #[error("unsupported OpenEXR compression: {0}")] + UnsupportedCompression(String), + /// The file declares more than [`Limits`] (or this module's own bounds) allow, or the request + /// needs more than [`Request::max_bytes`]: a lasting refusal of this file or request. + #[error("OpenEXR exceeds a limit: {0}")] + LimitExceeded(String), + /// The system could not give memory the read needed (within its limits) just now: another + /// attempt, with more memory free, may succeed. + #[error("OpenEXR: out of memory: {0}")] + OutOfMemory(String), + /// The source failed just now (a seek or read error other than the file ending early): + /// another attempt may succeed. + #[error("OpenEXR: cannot read: {0}")] + Io(String), + /// The `cancel` callback asked to stop. + #[error("OpenEXR: cancelled")] + Cancelled, +} + +/// Result of this module's functions. +pub type Result = std::result::Result; + +fn malformed(e: impl std::fmt::Display) -> Error { + Error::Malformed(e.to_string()) +} + +fn io(e: impl std::fmt::Display) -> Error { + Error::Io(e.to_string()) +} + +/// A failed `read_exact` of the headers or tables: the file ending early is a damaged file, any +/// other error is the source failing. +fn read_failed(e: std::io::Error) -> Error { + if e.kind() == std::io::ErrorKind::UnexpectedEof { malformed(e) } else { io(e) } +} + +fn exr_error(e: exr::error::Error) -> Error { + match e { + exr::error::Error::NotSupported(message) => Error::Unsupported(message.to_string()), + exr::error::Error::Io(e) => io(e), + e => malformed(e), + } +} + +const MAGIC: [u8; 4] = [0x76, 0x2f, 0x31, 0x01]; +/// Headers of all parts together: at most this many bytes, parts, and attributes per part. +const META_BYTES: usize = 8 << 20; +const MAX_PARTS: usize = 1024; +const MAX_ATTRIBUTES: usize = 4096; +/// The most chunks all parts of a file may have together. The offset tables and the index hold +/// a few bytes per chunk, so a header declaring billions of tiny tiles (whose tables a short file +/// can't hold anyway) is refused before anything is sized by it. 16 million chunks is a 64K × +/// 64K picture in 16 × 16 tiles. +const MAX_CHUNKS: usize = 1 << 24; +/// The most bytes one decompressed block may take in a read that sets no +/// [`Request::max_block_bytes`] and whose [`Request::max_bytes`] is smaller: the decompressor +/// allocates a block's bytes before it looks at the data, so a hostile header (a data window a +/// billion pixels wide over one tiny chunk) would otherwise ask for gigabytes. Such a read allows +/// blocks up to `max(this, max_bytes)`: a caller that budgets more memory can read files with +/// larger blocks (wide DWAB parts with many channels hold 512 MiB a block). +const MAX_BLOCK_BYTES: usize = 256 << 20; +/// Chunks are read in pieces: a run of chunks that follow each other in the file, read with one +/// request (one round trip to a network share, not one per chunk). The first piece is small so +/// the first bands arrive early; each later one may be twice as large, up to [`PIECE_BYTES`], so +/// a long read makes few requests. A piece holds at most [`PIECE_CHUNKS`] chunks, and a single +/// chunk larger than the limit is read alone. +const FIRST_PIECE_BYTES: u64 = 256 << 10; +const PIECE_BYTES: u64 = 4 << 20; +const PIECE_CHUNKS: usize = 256; +/// The most decoded bytes a read keeps in flight: the decompressed blocks and the bands of the +/// chunks read but not yet handed to the sink. Compressed bytes say little about this (a flat +/// colour compresses a thousandfold), so the reader estimates each chunk's decoded size from its +/// header and waits for the sink to catch up before reading more. +const IN_FLIGHT_BYTES: u64 = 64 << 20; +/// How often a wait for the workers polls `cancel`. +const CANCEL_POLL: Duration = Duration::from_millis(50); + +/// One chunk of a part's full-resolution level, as [`Index::chunks`] lists it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ChunkInfo { + /// Where the chunk starts in the file. + pub offset: u64, + /// The bytes read for it: up to the next chunk in the file (or the file's end), at most a + /// block's bytes plus its header; 0 when its offset lies outside the chunk area (past the + /// file's end, or in the headers or offset tables): a read that needs it fails. + pub len: u64, + /// The column of its top-left pixel in the part's data window, counted from the data + /// window's left edge (0). + pub x: usize, + /// The row of its top-left pixel, counted from the data window's top edge (0). + pub y: usize, + /// Its width in pixels (a tile at the right edge, or a scan-line block, may be narrower than + /// the tile size; a scan-line block is as wide as the data window). + pub width: usize, + /// Its height in pixels (the last scan-line block or the bottom tiles may hold fewer rows). + pub height: usize, +} + +/// One chunk of the full-resolution level of a part, in offset-table order. +#[derive(Debug, Clone, Copy)] +struct ChunkRef { + /// Where it starts in the file, and how many bytes to read for it (0: its offset is not valid, + /// it is never read). + offset: u64, + len: u64, + /// Its top-left pixel in the part's data window (0-based) and its size. + x: usize, + y: usize, + cols: usize, + rows: usize, + /// Its tile column and row (scan-line blocks: column 0, row = block number). + tile: (usize, usize), +} + +/// Where one part's samples go in the display window, and its chunks. +#[derive(Debug, Clone)] +struct PartLayout { + /// The part's data window position in the display window. + offset: (i64, i64), + /// The data window's size. + size: (usize, usize), + /// The bytes of one pixel of all its channels, uncompressed. + pixel_bytes: usize, + /// The chunks of the full-resolution level (smaller levels of tiled parts are never read). + chunks: Vec, +} + +/// What an OpenEXR file holds, from its headers and offset tables: the facts [`read_bands`] needs +/// to fetch only the chunks a request touches. Holds no pixel data. +#[derive(Debug, Clone)] +pub struct Index { + meta: MetaData, + parts: Vec, + layout: Vec, + display: Window, + len: u64, + /// [`Limits::max_ratio`] at build: how many bytes one byte of a chunk may decompress to. + max_ratio: u64, +} + +impl Index { + /// Reads the headers and offset tables of the file in `source` and checks them against + /// `limits`: the window and pixel limits. `max_bytes` bounds what the whole file may decode + /// to in [`crate::decode`] and plays no part here (a read is bounded by + /// [`Request::max_bytes`]); `max_ratio` is kept in the index, and a read refuses a chunk whose + /// block is more than its bytes can decompress to (see [`Index::check_blocks`]). Nothing is + /// sized by pixels. + /// `cancel` is polled while reading. + /// The display window and every data window are held to `limits.max_pixels`; see + /// [`Index::build_with_display_limit`] to hold the display window to its own bound. + pub fn build(source: &mut R, limits: &Limits, cancel: &dyn Fn() -> bool) -> Result { + Index::build_with_display_limit(source, limits, limits.max_pixels, cancel) + } + + /// [`Index::build`] with the display window held to `max_display_pixels` instead of + /// `limits.max_pixels`, which then bounds the data windows only: an app may allow parts larger + /// than the picture it shows (overscan) while keeping the planes it allocates smaller. + pub fn build_with_display_limit( + source: &mut R, + limits: &Limits, + max_display_pixels: u64, + cancel: &dyn Fn() -> bool, + ) -> Result { + let len = source.seek(SeekFrom::End(0)).map_err(io)?; + source.seek(SeekFrom::Start(0)).map_err(io)?; + let prefix = read_headers(source, cancel)?; + check_previews(&prefix).map_err(malformed)?; + // (the crate's own parsing panics on some malformed headers: reported, never raised, + // where panics unwind) + let meta = catch_unwind(AssertUnwindSafe(|| MetaData::read_from_buffered(Cursor::new(&prefix), false))) + .map_err(|_| malformed("invalid OpenEXR headers"))? + .map_err(exr_error)?; + if meta.headers.is_empty() || meta.headers.len() > MAX_PARTS { + return Err(malformed("part count")); + } + for (i, h) in meta.headers.iter().enumerate() { + if matches!(h.compression, exr::prelude::Compression::HTJ2K32 | exr::prelude::Compression::HTJ2K256) { + return Err(Error::UnsupportedCompression("HTJ2K".into())); + } + check_part(i, h, limits)?; + } + let first = meta.headers.first().ok_or_else(|| malformed("missing header"))?; + let display = first.shared_attributes.display_window; + let (dw, dh) = (display.size.0, display.size.1); + let display_pixels = (dw as u64).saturating_mul(dh as u64); + if dw == 0 || dh == 0 || dw > limits.max_width as usize || dh > limits.max_height as usize || display_pixels > max_display_pixels { + return Err(Error::LimitExceeded(format!("display window of {dw}x{dh}"))); + } + let tables = read_tables(source, &meta, prefix.len() as u64, len, cancel)?; + let chunks_start = prefix.len() as u64 + tables.iter().map(|t| t.len() as u64 * 8).sum::(); + let layout = layout_of(&meta, &tables, chunks_start, len)?; + let mut parts: Vec = meta.headers.iter().enumerate().map(|(i, h)| part_info(i, h)).collect(); + // (an index stays small however much a renderer writes into the headers: the text + // attributes are kept in the part infos, the crate's own copies are dropped) + let mut meta = meta; + for h in &mut meta.headers { + h.shared_attributes.other.clear(); + h.own_attributes.other.clear(); + h.own_attributes.preview = None; + } + for (info, h) in parts.iter_mut().zip(&meta.headers) { + info.deep = h.deep; + } + let display = parts.first().map_or(Window { x: 0, y: 0, width: 0, height: 0 }, |p| p.display_window); + Ok(Index { meta, parts, layout, display, len, max_ratio: limits.max_ratio }) + } + + /// Every part's header facts: channels (in the order a request's `(part, channel)` pairs + /// count them), windows (in the file's absolute coordinates), compression and text attributes. + pub fn parts(&self) -> &[PartInfo] { + &self.parts + } + + /// The display window of the file (the first part's, in absolute coordinates): every plane + /// covers it, and a request's rows and a band's position count from its top-left corner. + pub fn display(&self) -> Window { + self.display + } + + /// The chunks of part `part`'s full-resolution level, in offset-table order (none for a deep + /// part or a part that doesn't exist): where each lies in the file and which pixels of the + /// part's data window it holds. For diagnostics and tests; [`read_bands`] picks the chunks a + /// request needs by itself. + pub fn chunks(&self, part: usize) -> impl Iterator + '_ { + self.layout.get(part).map_or(&[][..], |p| p.chunks.as_slice()).iter().map(|c| ChunkInfo { + offset: c.offset, + len: c.len, + x: c.x, + y: c.y, + width: c.cols, + height: c.rows, + }) + } + + /// Checks every chunk of the full-resolution level of every flat part against what its bytes + /// can decompress to (see [`Index::build`]'s `max_ratio`), from the index alone: an app can + /// refuse a file before another decoder allocates by its headers. A chunk's bytes are counted + /// here as the gap to the next chunk in the file (the index holds no payload sizes); a read + /// makes the same check for the chunks it needs, and again, once a chunk is read, against the + /// payload size the chunk declares, and also holds each block to its own byte limit. + pub fn check_blocks(&self) -> Result<()> { + for (pi, part) in self.layout.iter().enumerate() { + let Some(header) = self.meta.headers.get(pi).filter(|h| !h.deep) else { continue }; + for c in &part.chunks { + self.check_ratio(pi, header, part, c, c.len)?; + } + } + Ok(()) + } + + /// Refuses chunk `c` of part `pi` when its decompressed block is more than `len` bytes can + /// hold: at most `max_ratio` bytes per byte (four times that for DWA, whose RLE stage, up to + /// 64 : 1, and zlib, up to about 1032 : 1, together reach about 66 000 : 1), plus 1 MiB. A + /// hostile header can declare a block of gigabytes over a chunk of a few bytes, and the + /// decompressors allocate the whole block first. + fn check_ratio(&self, pi: usize, header: &Header, part: &PartLayout, c: &ChunkRef, len: u64) -> Result<()> { + let block = (c.cols as u64).saturating_mul(c.rows as u64).saturating_mul(part.pixel_bytes as u64); + let ratio = if crate::dwa_guard::is_dwa(header.compression) { self.max_ratio.saturating_mul(4) } else { self.max_ratio }; + let most = len.checked_mul(ratio).and_then(|b| b.checked_add(1 << 20)).unwrap_or(u64::MAX); + if block > most { + return Err(Error::LimitExceeded(format!( + "a block of part {pi} decompresses to {block} bytes, more than its {len}-byte chunk can hold ({most})" + ))); + } + Ok(()) + } + + /// The file's length when it was indexed. + pub fn file_len(&self) -> u64 { + self.len + } + + /// About the bytes the index holds in memory. + pub fn bytes(&self) -> usize { + let chunks: usize = self.layout.iter().map(|p| p.chunks.len()).sum(); + let infos: usize = self + .parts + .iter() + .map(|p| { + let channels: usize = p.channels.iter().map(|c| c.name.len() + 48).sum(); + let text: usize = p.text_attributes.iter().map(|(k, v)| k.len() + v.len() + 48).sum(); + channels + text + p.compression.len() + 256 + }) + .sum(); + chunks.saturating_mul(std::mem::size_of::()).saturating_add(infos).saturating_add(self.meta.headers.len().saturating_mul(1024)) + } +} + +/// The headers of the file in `r` (up to and including the empty name that ends them), as raw +/// bytes: bounded in size, parts and attributes before anything parses them. +fn read_headers(r: &mut R, cancel: &dyn Fn() -> bool) -> Result> { + let mut start = [0u8; 8]; + r.read_exact(&mut start).map_err(read_failed)?; + if start.get(..4) != Some(&MAGIC[..]) { + return Err(malformed("OpenEXR signature")); + } + let version = start.get(4..8).and_then(|v| <[u8; 4]>::try_from(v).ok()).map(u32::from_le_bytes).ok_or_else(|| malformed("version"))?; + let multipart = version & 0x1000 != 0; + let mut prefix = start.to_vec(); + let mut headers = 0usize; + let mut pending: Option = None; + loop { + let mut attributes = 0usize; + // One header: attributes (name, type, size, value) up to an empty name. + loop { + if cancel() { + return Err(Error::Cancelled); + } + if !read_name(r, &mut prefix, pending.take())? { + break; + } + attributes += 1; + if attributes > MAX_ATTRIBUTES { + return Err(Error::LimitExceeded("more than 4096 attributes in a header".into())); + } + read_name(r, &mut prefix, None)?; + let mut size = [0u8; 4]; + r.read_exact(&mut size).map_err(read_failed)?; + prefix.extend_from_slice(&size); + let n = usize::try_from(i32::from_le_bytes(size)).map_err(malformed)?; + let end = + prefix.len().checked_add(n).filter(|end| *end <= META_BYTES).ok_or_else(|| Error::LimitExceeded("headers over 8 MiB".into()))?; + let begin = prefix.len(); + prefix.try_reserve_exact(n).map_err(|_| Error::OutOfMemory("header allocation".into()))?; + prefix.resize(end, 0); + for bytes in prefix.get_mut(begin..).ok_or_else(|| malformed("attribute size"))?.chunks_mut(64 << 10) { + if cancel() { + return Err(Error::Cancelled); + } + r.read_exact(bytes).map_err(read_failed)?; + } + } + headers += 1; + if headers > MAX_PARTS { + return Err(Error::LimitExceeded("more than 1024 parts".into())); + } + if !multipart { + return Ok(prefix); + } + // A multi-part header list ends with one more empty name. + let mut next = [0u8; 1]; + r.read_exact(&mut next).map_err(read_failed)?; + match next.first().copied() { + Some(0) | None => { + prefix.push(0); + return Ok(prefix); + } + Some(b) => pending = Some(b), + } + } +} + +/// One NUL-terminated name (at most 255 bytes) appended to `prefix`, `first` already read; `false` +/// for the empty name that ends a header. +fn read_name(r: &mut R, prefix: &mut Vec, first: Option) -> Result { + let mut i = 0usize; + let mut next = first; + loop { + let b = match next.take() { + Some(b) => b, + None => { + let mut one = [0u8; 1]; + r.read_exact(&mut one).map_err(read_failed)?; + one.first().copied().unwrap_or(0) + } + }; + prefix.push(b); + if b == 0 { + return Ok(i != 0); + } + i += 1; + if i > 255 { + return Err(Error::LimitExceeded("an attribute name over 255 bytes".into())); + } + } +} + +/// What a header may declare before any chunk of the part is sized by it. +fn check_part(index: usize, h: &Header, limits: &Limits) -> Result<()> { + if h.deep { + // (flat parts beside it are read; a request for a channel of this one is refused) + return Ok(()); + } + let (w, ht) = (h.layer_size.0, h.layer_size.1); + if w == 0 || ht == 0 { + return Err(malformed(format!("empty data window of part {index}"))); + } + if w > limits.max_width as usize || ht > limits.max_height as usize || (w as u64).saturating_mul(ht as u64) > limits.max_pixels { + return Err(Error::LimitExceeded(format!("part {index} of {w}x{ht}"))); + } + if h.channels.list.is_empty() || h.channels.list.len() > 4096 { + return Err(malformed(format!("channel count of part {index}"))); + } + // (the decompressor's actual block is no larger than the crate's bound, so it fits too; how + // large a block may be depends on the read: see `read_bands`) + if !crate_bound_fits(h) { + return Err(malformed(format!("the block size of part {index} overflows"))); + } + Ok(()) +} + +/// The bytes of all channels of one pixel of `h`, checked. +fn pixel_bytes(h: &Header) -> Option { + h.channels.list.iter().map(|c| c.sample_type.bytes_per_sample()).try_fold(0usize, usize::checked_add) +} + +/// The bytes of the largest block the decompressor allocates for a chunk of `h`: a pixel's bytes +/// times a tile's area, or times the width and the rows of a scan-line block (no more than the +/// part has). `None` when it overflows. +fn block_bytes(h: &Header) -> Option { + let pixels = match h.blocks { + exr::meta::BlockDescription::Tiles(t) => t.tile_size.0.checked_mul(t.tile_size.1)?, + exr::meta::BlockDescription::ScanLines => h.compression.scan_lines_per_block().min(h.layer_size.1).checked_mul(h.layer_size.0)?, + }; + pixel_bytes(h)?.checked_mul(pixels) +} + +/// Whether the `exr` crate's own bound on a chunk of `h` (`Header::max_block_byte_size`: like +/// [`block_bytes`] but with every scan line a block may hold, even past the part's last row) can +/// be computed: the crate computes it without overflow checks. It is not a limit here: before +/// the crate reads a chunk, [`check_chunk_header`] has made sure the size the chunk declares is +/// no more than the bytes it holds, so the crate never allocates by that bound. +fn crate_bound_fits(h: &Header) -> bool { + let pixels = match h.blocks { + exr::meta::BlockDescription::Tiles(t) => t.tile_size.0.checked_mul(t.tile_size.1), + exr::meta::BlockDescription::ScanLines => h.compression.scan_lines_per_block().checked_mul(h.layer_size.0), + }; + pixels.zip(pixel_bytes(h)).and_then(|(pixels, bytes)| pixels.checked_mul(bytes)).is_some() +} + +/// The offset tables, one per part, read from where the headers end. +fn read_tables(r: &mut R, meta: &MetaData, headers_end: u64, len: u64, cancel: &dyn Fn() -> bool) -> Result>> { + let chunks: usize = meta.headers.iter().map(|h| h.chunk_count).fold(0, usize::saturating_add); + if chunks > MAX_CHUNKS { + return Err(Error::LimitExceeded(format!("{chunks} chunks, more than {MAX_CHUNKS}"))); + } + // Eight bytes of table per chunk: a header can't claim more chunks than the file holds. + if (chunks as u64).saturating_mul(8) > len.saturating_sub(headers_end) { + return Err(malformed("offset tables longer than the file")); + } + r.seek(SeekFrom::Start(headers_end)).map_err(io)?; + let mut tables = Vec::new(); + tables.try_reserve_exact(meta.headers.len()).map_err(|_| Error::OutOfMemory("offset table allocation".into()))?; + let mut buf = vec![0u8; 8 * 8192]; + for h in &meta.headers { + let mut table: Vec = Vec::new(); + table.try_reserve_exact(h.chunk_count).map_err(|_| Error::OutOfMemory("offset table allocation".into()))?; + let mut left = h.chunk_count; + while left > 0 { + if cancel() { + return Err(Error::Cancelled); + } + let take = left.min(8192); + let bytes = buf.get_mut(..take * 8).ok_or_else(|| malformed("table buffer"))?; + r.read_exact(bytes).map_err(read_failed)?; + table.extend(bytes.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c))); + left -= take; + } + tables.push(table); + } + Ok(tables) +} + +/// Each part's chunks of the full-resolution level: where they are and which pixels they hold. A +/// chunk ends where the next one in the file starts (or at the end of the file); an offset +/// outside the chunk area is kept as a chunk that is never read. +/// +/// The layout is computed here rather than with the `exr` crate's block iterator, which allocates +/// for every level and panics on some sizes. The full-resolution level comes first in the offset +/// table of every level mode (scan lines, single-level tiles, mip and rip maps), its blocks row by +/// row and left to right. +fn layout_of(meta: &MetaData, tables: &[Vec], chunks_start: u64, len: u64) -> Result> { + let allocation = |_| Error::OutOfMemory("chunk layout allocation".into()); + let first = meta.headers.first().ok_or_else(|| malformed("missing header"))?; + let display = first.shared_attributes.display_window; + let mut starts: Vec = Vec::new(); + starts.try_reserve_exact(tables.iter().map(Vec::len).fold(0, usize::saturating_add)).map_err(allocation)?; + starts.extend(tables.iter().flatten().copied().filter(|o| *o >= chunks_start && *o < len)); + starts.sort_unstable(); + starts.dedup(); + let end_of = |offset: u64| match starts.binary_search(&offset) { + Ok(i) => starts.get(i + 1).copied().unwrap_or(len), + Err(_) => offset, + }; + let mut out = Vec::new(); + out.try_reserve_exact(meta.headers.len()).map_err(allocation)?; + for (pi, h) in meta.headers.iter().enumerate() { + let pos = h.own_attributes.layer_position; + let offset = (i64::from(pos.0) - i64::from(display.position.0), i64::from(pos.1) - i64::from(display.position.1)); + if h.deep { + out.push(PartLayout { offset, size: (0, 0), pixel_bytes: 0, chunks: Vec::new() }); + continue; + } + let table = tables.get(pi).ok_or_else(|| malformed("offset table"))?; + // A chunk is at most its block's bytes plus its own small header (part number, position + // and sizes): never read more for one. + let most = (block_bytes(h).ok_or_else(|| malformed("block size"))? as u64).saturating_add(64); + let (w, ht) = (h.layer_size.0, h.layer_size.1); + let (bw, bh) = match h.blocks { + exr::meta::BlockDescription::Tiles(t) => (t.tile_size.0, t.tile_size.1), + exr::meta::BlockDescription::ScanLines => (w, h.compression.scan_lines_per_block()), + }; + if bw == 0 || bh == 0 { + return Err(malformed(format!("block size of part {pi}"))); + } + let across = w.div_ceil(bw); + let count = + across.checked_mul(ht.div_ceil(bh)).filter(|n| *n <= table.len()).ok_or_else(|| malformed(format!("chunk count of part {pi}")))?; + let mut chunks = Vec::new(); + chunks.try_reserve_exact(count).map_err(allocation)?; + for (i, at) in table.iter().copied().enumerate().take(count) { + let tile = (i % across, i / across); + // (inside the data window: a tile index is below the count of blocks across or down) + let (x, y) = (tile.0.saturating_mul(bw), tile.1.saturating_mul(bh)); + let valid = at >= chunks_start && at < len; + let bytes = if valid { end_of(at).saturating_sub(at).min(most) } else { 0 }; + chunks.push(ChunkRef { offset: at, len: bytes, x, y, cols: bw.min(w.saturating_sub(x)), rows: bh.min(ht.saturating_sub(y)), tile }); + } + let pixel_bytes = pixel_bytes(h).ok_or_else(|| malformed("pixel size"))?; + out.push(PartLayout { offset, size: (w, ht), pixel_bytes, chunks }); + } + Ok(out) +} + +/// What to read. +#[derive(Debug, Clone)] +pub struct Request<'a> { + /// The channels wanted as `(part, channel)` (positions in [`Index::parts`] and in the part's + /// [`PartInfo::channels`]), in the order [`Band::slot`] and the planes of [`read_planes`] count + /// them. A channel may be named more than once (each slot gets its own bands). A channel of a + /// deep part is refused. + pub channels: &'a [(usize, usize)], + /// The value of each requested channel (same order) where the file has no samples; missing + /// entries count as 0. Only [`read_planes`] uses it ([`read_bands`] delivers samples only). + pub fill: &'a [f32], + /// The rows to read, counted from the display window's top row (0, whatever the display + /// window's absolute position), at full resolution; `None`: all. + pub rows: Option>, + /// Every `2^level`-th row and column of the display window (0: full resolution, at most 16). + pub level: u32, + /// The most bytes of samples the read may produce: [`read_bands`] checks the requested rows + /// at the level, [`read_planes`] the whole display-window planes it allocates. Without + /// [`Request::max_block_bytes`], it also raises the most one decompressed block may take + /// above the 256 MiB default. + pub max_bytes: usize, + /// The most threads that decompress (`None`: as many as the machine runs at once; `Some(0)`: + /// none, everything is decoded on the calling thread). Never more than the chunks need. + pub workers: Option, + /// The most bytes one decompressed block may take (`None`: `max(256 MiB, max_bytes)`). A + /// needed chunk whose block is larger is refused before anything is read. + /// + /// It is a limit of its own because the `exr` crate's decompressors allocate a whole block at + /// once and can't report that the memory isn't there: the process aborts. A block must stay + /// below what the caller is sure the system can give, even when the read's total budget + /// (`max_bytes`, which allocations this module makes fallibly count against) is far larger. A + /// block is one strip of the file (at most 256 scan lines, for DWAB): 8 GiB is a 16K-wide + /// strip of 256 lines of 512 f32 channels. + pub max_block_bytes: Option, + /// Runs of request slots delivered together, as one band per block whose pixels hold the + /// slots' values in slot order (`0..4` over R, G, B, A of a part: one RGBA band): for a caller + /// that stores pixels interleaved. Every slot of a group must name a channel of the same part + /// (they then share every block), and no slot may be in two groups; slots in no group come one + /// band each, as without groups. Empty: no groups. [`read_planes`] ignores it. + pub groups: &'a [Range], +} + +impl<'a> Request<'a> { + /// Every row of `channels` at full resolution, fill 0, up to `max_bytes` of samples, with as + /// many decoding threads as the machine runs at once. + pub fn new(channels: &'a [(usize, usize)], max_bytes: usize) -> Request<'a> { + Request { channels, fill: &[], rows: None, level: 0, max_bytes, workers: None, max_block_bytes: None, groups: &[] } + } +} + +/// The size of the planes of a read at `level` of a `width` × `height` display window. +pub fn level_size((width, height): (usize, usize), level: u32) -> (usize, usize) { + let stride = 1usize << level.min(16); + (width.div_ceil(stride), height.div_ceil(stride)) +} + +/// A rectangle of rows of one requested channel, or of a group of them ([`Request::groups`]), +/// decoded: `samples` holds `height` rows of `width` pixels, row by row, each pixel +/// `values_per_pixel` values in slot order. `x` and `y` are in the output grid, counted from the +/// display window's top-left corner (0, 0, not its absolute position): display-window pixels at +/// level 0, every `2^level`-th pixel above. +#[derive(Debug, Clone, PartialEq)] +pub struct Band { + /// The position of the channel in [`Request::channels`]; for a group, its first slot. + pub slot: usize, + pub x: usize, + pub y: usize, + pub width: usize, + pub height: usize, + /// The values per pixel: 1, or the size of the group the band is of. + pub values_per_pixel: usize, + /// The chunk the band was decoded from: its number in the read, from 0 in file order, counting + /// the chunks [`Index::estimate`] counts. A chunk may give no band (none of its rows on the + /// level's grid, say) or several; the bands of a chunk come together, so progress is the + /// highest `chunk` seen plus one, out of [`Estimate::chunks`]. + pub chunk: usize, + pub samples: Vec, +} + +/// What a read did, for measurements and tests. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Stats { + /// Chunks fetched, per part. + pub chunks: Vec, + /// Bytes of chunks read from the source. + pub bytes: u64, + /// Scan lines (or tile rows) decompressed. + pub lines: usize, + /// The most decoded bytes the read had in flight at once, as estimated from the headers: the + /// decompressed blocks and the bands of the chunks read but not yet handed to the sink. + pub in_flight: u64, +} + +/// What a read will take, from [`Index::estimate`], before anything is read. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Estimate { + /// The chunks it fetches: one unit of progress each (a read hands every chunk's bands over + /// together). + pub chunks: usize, + /// The bytes of those chunks it reads from the source. + pub compressed_bytes: u64, + /// An upper estimate of the most memory the read holds at once besides what the sink keeps: + /// the decoded bytes in flight (as [`Stats::in_flight`] counts them: each chunk's + /// decompressed block and its bands, exactly as large as they are made, grouped or not), as + /// much again for the decompressors' scratch, two pieces of compressed bytes, and each + /// worker's copy of the chunk it decodes. + pub working_bytes: u64, + /// The bytes of the planes [`read_planes`] would allocate for the request (whole display + /// window planes, one per slot: it ignores [`Request::groups`]). Not part of `working_bytes`, + /// and not checked here: [`read_planes`] checks it against [`Request::max_bytes`] when it + /// runs, a caller that collects bands itself checks what it allocates. + pub planes_bytes: u64, +} + +/// The planes of [`read_planes`]: one per requested channel, `width` × `height` (the display +/// window at the request's level). +#[derive(Debug, Clone, PartialEq)] +pub struct Planes { + pub width: usize, + pub height: usize, + pub planes: Vec>, + pub stats: Stats, +} + +/// How a read with a fallible sink ([`read_bands_try`]) ended early. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Stop { + /// The read failed. + Read(Error), + /// The sink returned this error; nothing was handed to it after. + Sink(E), +} + +impl From for Stop { + fn from(e: Error) -> Self { + Stop::Read(e) + } +} + +impl std::fmt::Display for Stop { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Stop::Read(e) => e.fmt(f), + Stop::Sink(e) => e.fmt(f), + } + } +} + +impl std::error::Error for Stop { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Stop::Read(e) => Some(e), + Stop::Sink(_) => None, + } + } +} + +/// The planes' geometry for [`chunk_bands`]. +struct Geometry<'a> { + /// The display window's size and the output's (at the level). + size: (usize, usize), + out: (usize, usize), + stride: i64, + /// The display rows read. + rows: Range, + /// Each part's channel → the request slots that name it. + slots: &'a [Vec>], + /// Per request slot: the band it goes into (the first slot of its group, or itself), that + /// band's values per pixel, and the slot's place among them. + units: &'a [(usize, usize, usize)], +} + +impl Geometry<'_> { + /// A display row is read: in the rows, on the level's grid. + fn wanted(&self, row: i64) -> bool { + row >= self.rows.start && row < self.rows.end && row.rem_euclid(self.stride) == 0 + } + + /// A chunk holding display rows `a..b` has a row read. + fn any_wanted(&self, a: i64, b: i64) -> bool { + let first = a.max(self.rows.start); + // (saturating: the rows are clamped to the display window, but the chunk's top may not be) + let first = first.saturating_add((self.stride - first.rem_euclid(self.stride)) % self.stride); + first < b.min(self.rows.end) + } + + /// How many rows are read (in the rows, on the level's grid). + fn rows_read(&self) -> usize { + let (a, b) = (self.rows.start.max(0), self.rows.end.max(0)); + let count = |n: i64| n.saturating_add(self.stride - 1) / self.stride; + usize::try_from(count(b).saturating_sub(count(a))).unwrap_or(0) + } +} + +/// A chunk the request needs, in the order the jobs are numbered (file order). +struct Planned { + part: usize, + offset: u64, + len: u64, + chunk: ChunkRef, + /// Its estimated decoded bytes: the decompressed block and the bands of the requested slots. + cost: u64, +} + +/// What a request needs, worked out from the index alone: the shared first step of a read and of +/// [`Index::estimate`]. +struct Plan { + /// Per part and channel: the request slots that name it. + slots: Vec>>, + size: (usize, usize), + out: (usize, usize), + stride: i64, + rows: Range, + /// The chunks to read, in file order. + jobs: Vec, + /// The decoding threads to start. + workers: usize, + /// Per request slot: see [`Geometry::units`]. + units: Vec<(usize, usize, usize)>, +} + +impl Plan { + fn geometry(&self) -> Geometry<'_> { + Geometry { size: self.size, out: self.out, stride: self.stride, rows: self.rows.clone(), slots: &self.slots, units: &self.units } + } +} + +/// Checks `request` against `index` and lists the chunks it needs (see [`read_bands`] for the +/// checks): nothing is read. +fn plan(index: &Index, request: &Request) -> Result { + let level = request.level.min(16); + let stride = 1i64 << level; + let (w, h) = (index.display.width as usize, index.display.height as usize); + let out = level_size((w, h), level); + // Per part and channel: the request slots that name it. + let mut slots: Vec>> = index.parts.iter().map(|p| vec![Vec::new(); p.channels.len()]).collect(); + for (slot, (part, channel)) in request.channels.iter().enumerate() { + let info = index.parts.get(*part).ok_or_else(|| malformed("no such part"))?; + if info.deep { + return Err(Error::Unsupported("a channel of a deep part".into())); + } + let c = info.channels.get(*channel).ok_or_else(|| malformed("no such channel"))?; + if c.sampling != (1, 1) { + return Err(Error::Unsupported("a subsampled channel".into())); + } + if let Some(s) = slots.get_mut(*part).and_then(|p| p.get_mut(*channel)) { + s.push(slot); + } + } + // Groups: slots of one part (so they share every block), none in two groups. + let mut units: Vec<(usize, usize, usize)> = (0..request.channels.len()).map(|slot| (slot, 1, 0)).collect(); + let mut grouped = vec![false; request.channels.len()]; + for group in request.groups { + let members = request + .channels + .get(group.clone()) + .filter(|m| !m.is_empty()) + .ok_or_else(|| malformed(format!("channel group {group:?} is empty or past the requested channels")))?; + if members.iter().any(|(part, _)| Some(*part) != members.first().map(|m| m.0)) { + return Err(Error::Unsupported(format!("channel group {group:?} spans parts"))); + } + for taken in grouped.get_mut(group.clone()).unwrap_or_default() { + if std::mem::replace(taken, true) { + return Err(malformed(format!("channel group {group:?} overlaps another"))); + } + } + for (k, unit) in units.get_mut(group.clone()).unwrap_or_default().iter_mut().enumerate() { + *unit = (group.start, group.len(), k); + } + } + let rows = request.rows.clone().unwrap_or(0..h as i64); + // (both ends inside the display window, so an empty or reversed range at either end of i64 + // stays empty instead of overflowing when aligned to the level's grid) + let rows = rows.start.clamp(0, h as i64)..rows.end.clamp(0, h as i64); + let geometry = Geometry { size: (w, h), out, stride, rows: rows.clone(), slots: &slots, units: &units }; + // What the request delivers: the rows read, at the level, of every requested channel. + let need = plane_bytes((out.0, geometry.rows_read()), request.channels.len()); + if need > request.max_bytes { + return Err(Error::LimitExceeded(format!("the requested rows need {need} bytes, more than the {} the read may use", request.max_bytes))); + } + // The chunks to read, in file order. The decompressor allocates each one's whole block, so a + // block may take no more than the read allows (see `Request::max_block_bytes`). + let most_block = request.max_block_bytes.unwrap_or(MAX_BLOCK_BYTES.max(request.max_bytes)) as u64; + let mut jobs: Vec = Vec::new(); + for (pi, part) in index.layout.iter().enumerate() { + let requested = slots.get(pi).map_or(0, |s| s.iter().map(Vec::len).sum::()); + if requested == 0 { + continue; + } + for c in &part.chunks { + let top = (c.y as i64).saturating_add(part.offset.1); + if !geometry.any_wanted(top, top.saturating_add(c.rows as i64)) { + continue; + } + if c.len == 0 { + return Err(malformed("a chunk offset outside the chunk area of the file")); + } + if let Some(header) = index.meta.headers.get(pi) { + index.check_ratio(pi, header, part, c, c.len)?; + } + let pixels = (c.cols as u64).saturating_mul(c.rows as u64); + let block = pixels.saturating_mul(part.pixel_bytes as u64); + if block > most_block { + return Err(Error::LimitExceeded(format!( + "a block of part {pi} decompresses to {block} bytes, more than the {most_block} one block of this read may use" + ))); + } + let cost = block.saturating_add(pixels.saturating_mul(requested as u64).saturating_mul(4)); + jobs.try_reserve(1).map_err(|_| Error::OutOfMemory("chunk list allocation".into()))?; + jobs.push(Planned { part: pi, offset: c.offset, len: c.len, chunk: *c, cost }); + } + } + jobs.sort_by_key(|j| j.offset); + // (no more threads than chunks can be in flight: two pieces) + let workers = + request.workers.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, usize::from)).min(jobs.len()).min(2 * PIECE_CHUNKS); + Ok(Plan { slots, size: (w, h), out, stride, rows, jobs, workers, units }) +} + +impl Index { + /// What reading `request` will take, before anything is read: the chunks (one unit of + /// progress each), their bytes, the most memory the read holds at once, and the planes + /// [`read_planes`] allocates. Fails as the read would on the same request (limits, unknown or + /// deep channels), so an app can reserve memory and size a progress bar first. + pub fn estimate(&self, request: &Request) -> Result { + estimate_within(self, request, IN_FLIGHT_BYTES) + } +} + +/// [`Index::estimate`] for a read keeping at most `budget` decoded bytes in flight. +pub(crate) fn estimate_within(index: &Index, request: &Request, budget: u64) -> Result { + let plan = plan(index, request)?; + let sum = |f: fn(&Planned) -> u64| plan.jobs.iter().map(f).fold(0u64, u64::saturating_add); + let most = |f: fn(&Planned) -> u64| plan.jobs.iter().map(f).max().unwrap_or(0); + let (compressed, longest) = (sum(|j| j.len), most(|j| j.len)); + // As the read bounds them: decoded bytes within the budget or one chunk, two pieces. + let decoded = sum(|j| j.cost).min(budget.max(most(|j| j.cost))); + let pieces = compressed.min(PIECE_BYTES.max(longest).saturating_mul(2)); + let copies = (plan.workers.max(1) as u64).saturating_mul(longest).min(compressed); + let (w, h) = level_size(plan.size, request.level.min(16)); + Ok(Estimate { + chunks: plan.jobs.len(), + compressed_bytes: compressed, + working_bytes: decoded.saturating_mul(2).saturating_add(pieces).saturating_add(copies), + planes_bytes: plane_bytes((w, h), request.channels.len()) as u64, + }) +} + +/// The bands of what `request` asks for, handed to `sink` one decoded block at a time, in file +/// order: by offset in the file, so a part written bottom-up (`LineOrder::Decreasing`) arrives +/// bottom-up, and the chunks of several parts arrive interleaved as the file stores them. Within +/// a block, the bands come by request slot (a group at its first slot). +/// +/// The chunks are read on the calling thread, in pieces of chunks that follow each other in the +/// file, and decompressed on worker threads ([`Request::workers`]) while the next piece is read. +/// Each time a piece has been read, and while waiting, the calling thread hands every band that +/// is next in file order to `sink`, so the first bands arrive after the first few hundred +/// kilobytes have been read, not after the whole request, and `sink` needs to be neither `Send` +/// nor `Sync`. +/// +/// Memory is bounded. At most one piece is read ahead of what has been delivered, so at most two +/// pieces of compressed bytes (8 MiB, or one larger chunk) are held. Each chunk's decoded bytes +/// are estimated from the headers as its decompressed block plus 4 bytes per pixel for each +/// requested slot of its part (see [`Stats::in_flight`]); the chunks in flight stay within +/// 64 MiB of that, and a chunk whose estimate alone is over 64 MiB is decoded alone, once +/// everything before it has been delivered, so however many workers run, at most one such chunk +/// is held at a time. A block may take no more than [`Request::max_block_bytes`] (by default +/// 256 MiB, or [`Request::max_bytes`] if that is more); a needed chunk over it is refused +/// ([`Error::LimitExceeded`]) before anything is read. +/// For one big chunk the real peak is several times its block: its compressed bytes in the +/// piece, the `exr` crate's copy of its payload (a chunk's declared size is checked against the +/// bytes it holds first, so that copy is no larger than the chunk), the decompressed block, the +/// decompressor's scratch buffers, and the `f32` bands; roughly 3 to 4 times +/// `max(256 MiB, max_bytes)` at worst ([`Index::estimate`] gives the bound for a request). Where +/// threads can't be started (WebAssembly) the chunks are decoded on the calling thread instead. +/// `cancel` is polled before each piece, before each chunk is handed to `sink`, and at least +/// every 50 ms while waiting for the workers. +/// +/// A band lies inside the planes the request describes ([`level_size`] of the display window); +/// rows or columns no chunk or data window covers are not delivered. A chunk the request needs +/// whose offset lies outside the file fails the read before anything is read or delivered +/// ([`Error::Malformed`]). A chunk that can't be decoded or isn't the block its offset-table +/// entry stands for fails the read when its turn comes: the bands before it have been delivered +/// by then. +pub fn read_bands( + source: &mut R, + index: &Index, + request: &Request, + cancel: &dyn Fn() -> bool, + sink: &mut dyn FnMut(Band), +) -> Result { + read_bands_within(source, index, request, cancel, sink, IN_FLIGHT_BYTES) +} + +/// [`read_bands`] that keeps what it did in `stats` as it goes, so the counts are there also when +/// the read fails or is cancelled (they then say how far it got). `stats` is reset first. +pub fn read_bands_with_stats( + source: &mut R, + index: &Index, + request: &Request, + cancel: &dyn Fn() -> bool, + sink: &mut dyn FnMut(Band), + stats: &mut Stats, +) -> Result<()> { + read_infallible(source, index, request, cancel, sink, IN_FLIGHT_BYTES, stats) +} + +/// [`read_bands_with_stats`] with a sink that can stop the read with an error of its own (a tile +/// store out of room, a full scratch disk): nothing more is read or handed to the sink after it +/// fails, the decoding threads wind down as on a cancel, and the sink's error comes back as +/// [`Stop::Sink`], unchanged. `stats` says how far the read got either way; after a sink error +/// its `lines` include the chunk whose band the sink refused (the chunk was decoded whole). +/// +/// This is also the way to pull: a caller that wants to decide band by band whether to go on (and +/// check a budget before each one) does that in the sink. A pulling iterator would have to run the +/// read on a thread of its own, because the read hands bands over from the middle of its loop. +pub fn read_bands_try( + source: &mut R, + index: &Index, + request: &Request, + cancel: &dyn Fn() -> bool, + sink: &mut dyn FnMut(Band) -> std::result::Result<(), E>, + stats: &mut Stats, +) -> std::result::Result<(), Stop> { + read_into(source, index, request, cancel, sink, IN_FLIGHT_BYTES, stats) +} + +/// [`read_bands`] keeping at most `budget` decoded bytes in flight (the tests use a small one). +pub(crate) fn read_bands_within( + source: &mut R, + index: &Index, + request: &Request, + cancel: &dyn Fn() -> bool, + sink: &mut dyn FnMut(Band), + budget: u64, +) -> Result { + let mut stats = Stats::default(); + read_infallible(source, index, request, cancel, sink, budget, &mut stats)?; + Ok(stats) +} + +/// [`read_into`] with a sink that can't fail. +fn read_infallible( + source: &mut R, + index: &Index, + request: &Request, + cancel: &dyn Fn() -> bool, + sink: &mut dyn FnMut(Band), + budget: u64, + stats: &mut Stats, +) -> Result<()> { + let mut sink = |band: Band| -> std::result::Result<(), std::convert::Infallible> { + sink(band); + Ok(()) + }; + read_into(source, index, request, cancel, &mut sink, budget, stats).map_err(|stop| match stop { + Stop::Read(e) => e, + Stop::Sink(never) => match never {}, + }) +} + +/// The read behind [`read_bands`], counting into `stats`. +fn read_into( + source: &mut R, + index: &Index, + request: &Request, + cancel: &dyn Fn() -> bool, + sink: &mut dyn FnMut(Band) -> std::result::Result<(), E>, + budget: u64, + stats: &mut Stats, +) -> std::result::Result<(), Stop> { + *stats = Stats { chunks: vec![0; index.layout.len()], ..Default::default() }; + let plan = plan(index, request)?; + let geometry = plan.geometry(); + let jobs = &plan.jobs; + if jobs.is_empty() { + return Ok(()); + } + // (declared outside the scope because the workers borrow the receiving end) + let (to_workers, queue) = mpsc::channel::(); + let queue = Mutex::new(queue); + std::thread::scope(|scope| { + // Owned by this closure so that every way out of it (an error, a cancel, the sink's + // error) drops the sending end, which ends the workers' loops before the scope waits. + let to_workers = to_workers; + let (done, results) = mpsc::channel(); + let mut started = 0usize; + for _ in 0..plan.workers { + let (queue, done, geometry) = (&queue, done.clone(), &geometry); + let worker = + std::thread::Builder::new().name("exr-decode".into()).spawn_scoped(scope, move || decode_worker(index, geometry, queue, &done)); + started += usize::from(worker.is_ok()); + } + // (only the workers hold senders now: if they all stop, waiting for a result fails + // instead of blocking forever) + drop(done); + let mut order = InOrder::default(); + let mut pos: Option = None; + let mut most = FIRST_PIECE_BYTES; + let mut submitted = 0usize; + // The decoded bytes of the chunks submitted and not yet delivered. + let mut in_flight = 0u64; + // The sequence number of the first chunk of the piece read last. + let mut last_piece = 0usize; + // Hands over what is next in order and takes it off the bytes in flight. + let mut deliver = |order: &mut InOrder, in_flight: &mut u64, stats: &mut Stats| -> std::result::Result<(), Stop> { + let before = order.next; + let delivered = order.deliver(sink, stats, cancel); + let done: u64 = jobs.get(before..order.next).unwrap_or_default().iter().map(|j| j.cost).fold(0, u64::saturating_add); + *in_flight = in_flight.saturating_sub(done); + delivered + }; + while submitted < jobs.len() { + if cancel() { + return Err(Error::Cancelled.into()); + } + let rest = jobs.get(submitted..).unwrap_or_default(); + let take = piece_len(rest, most, budget); + let piece = rest.get(..take).unwrap_or_default(); + let cost = piece.iter().map(|j| j.cost).fold(0, u64::saturating_add); + // Read ahead by one piece at most, and keep the decoded bytes in flight within the + // budget (a piece over it alone is read once everything before it is delivered). + // (`order.next` is a chunk not received yet whenever this waits, so a result is on + // its way: everything decoded on this thread is delivered at once.) + while order.next < last_piece || (order.next < submitted && in_flight.saturating_add(cost) > budget) { + let (seq, result) = next_result(&results, cancel)?; + order.accept(seq, result); + deliver(&mut order, &mut in_flight, stats)?; + if cancel() { + return Err(Error::Cancelled.into()); + } + } + most = most.saturating_mul(2).min(PIECE_BYTES); + let Piece { data, chunks } = read_piece(source, piece, &mut pos, stats)?; + let data = Arc::new(data); + last_piece = submitted; + in_flight = in_flight.saturating_add(cost); + stats.in_flight = stats.in_flight.max(in_flight); + for (planned, range) in piece.iter().zip(chunks) { + let job = Job { seq: submitted, part: planned.part, chunk: planned.chunk, data: Arc::clone(&data), range }; + submitted += 1; + if started == 0 { + order.accept(job.seq, decode_job(index, &geometry, &job)); + } else if let Err(mpsc::SendError(job)) = to_workers.send(job) { + // (the queue outlives this loop, so a send doesn't fail; if it ever did, the + // chunk is decoded here rather than lost) + order.accept(job.seq, decode_job(index, &geometry, &job)); + } + } + while let Ok((seq, result)) = results.try_recv() { + order.accept(seq, result); + } + deliver(&mut order, &mut in_flight, stats)?; + } + // Everything is read: the rest as it is decoded. + while order.next < submitted { + if cancel() { + return Err(Error::Cancelled.into()); + } + let (seq, result) = next_result(&results, cancel)?; + order.accept(seq, result); + deliver(&mut order, &mut in_flight, stats)?; + } + Ok(()) + }) +} + +/// The next decoded chunk from the workers, polling `cancel` while waiting. (Only called while a +/// worker holds a chunk: on the calling thread everything is decoded before it would wait.) +fn next_result(results: &Receiver<(usize, Decoded)>, cancel: &dyn Fn() -> bool) -> Result<(usize, Decoded)> { + loop { + match results.recv_timeout(CANCEL_POLL) { + Ok(result) => return Ok(result), + Err(RecvTimeoutError::Timeout) => { + if cancel() { + return Err(Error::Cancelled); + } + } + Err(RecvTimeoutError::Disconnected) => return Err(malformed("a decoding thread stopped")), + } + } +} + +/// [`read_bands`] collected: one plane per requested channel covering the whole display window +/// at the request's level (also when [`Request::rows`] selects only some rows: the other rows +/// keep the fill value), filled with [`Request::fill`] where nothing was read. The planes are +/// reserved up front and count against [`Request::max_bytes`] (an allocation the system refuses +/// is [`Error::OutOfMemory`], not an abort), so the cost is known before the first chunk is +/// read. +pub fn read_planes(source: &mut R, index: &Index, request: &Request, cancel: &dyn Fn() -> bool) -> Result { + let (w, h) = (index.display.width as usize, index.display.height as usize); + let (ow, oh) = level_size((w, h), request.level.min(16)); + let n = ow.checked_mul(oh).ok_or_else(|| Error::LimitExceeded("display window".into()))?; + let need = plane_bytes((ow, oh), request.channels.len()); + if need > request.max_bytes { + return Err(Error::LimitExceeded(format!("{w}×{h} channels need {need} bytes, more than the {} the read may use", request.max_bytes))); + } + let mut planes: Vec> = Vec::new(); + planes.try_reserve_exact(request.channels.len()).map_err(|_| Error::OutOfMemory("plane list allocation".into()))?; + for slot in 0..request.channels.len() { + let mut plane: Vec = Vec::new(); + plane.try_reserve_exact(n).map_err(|_| Error::OutOfMemory(format!("{need} bytes of planes: the system can't give that memory now")))?; + plane.resize(n, request.fill.get(slot).copied().unwrap_or(0.0)); + planes.push(plane); + } + // (one plane per slot: groups would interleave) + let request = Request { groups: &[], ..request.clone() }; + let stats = read_bands(source, index, &request, cancel, &mut |band: Band| { + let Some(plane) = planes.get_mut(band.slot) else { return }; + for r in 0..band.height { + let start = (band.y + r).checked_mul(ow).and_then(|row| row.checked_add(band.x)); + let (Some(start), Some(from)) = (start, r.checked_mul(band.width)) else { continue }; + if let (Some(dst), Some(src)) = + (plane.get_mut(start..start.saturating_add(band.width)), band.samples.get(from..from.saturating_add(band.width))) + { + dst.copy_from_slice(src); + } + } + })?; + Ok(Planes { width: ow, height: oh, planes, stats }) +} + +/// The bytes of `count` planes of `size`, saturating. +fn plane_bytes((w, h): (usize, usize), count: usize) -> usize { + w.saturating_mul(h).saturating_mul(count).saturating_mul(std::mem::size_of::()) +} + +/// One chunk to decode: its sequence number in file order, its part, where it belongs, and where +/// its bytes lie in the piece it was read with (shared by all the chunks of that piece). +struct Job { + seq: usize, + part: usize, + chunk: ChunkRef, + data: Arc>, + range: Range, +} + +/// What decoding one chunk gives: its bands and the scan lines decompressed. +type Decoded = Result<(Vec, usize)>; + +/// A decoding thread: takes chunks from `queue` until it is closed, and sends each one's bands +/// back through `done` (until nobody listens any more: the read has ended early). +fn decode_worker(index: &Index, g: &Geometry, queue: &Mutex>, done: &Sender<(usize, Decoded)>) { + loop { + // (the lock is held while waiting for the next chunk, so the workers take turns waiting; + // a poisoned lock can't happen, no worker panics while holding it, and would end this one) + let next = match queue.lock() { + Ok(queue) => queue.recv(), + Err(_) => return, + }; + let Ok(job) = next else { return }; + let seq = job.seq; + let mut report = Report { seq, done, sent: false }; + let decoded = decode_job(index, g, &job); + // (its share of the piece's bytes goes now, not after the result is taken: the two-pieces + // bound counts on it) + drop(job); + report.sent = true; + if done.send((seq, decoded)).is_err() { + return; + } + } +} + +/// Reports a chunk as failed if the worker decoding it unwinds before sending its result, so the +/// calling thread, which waits for every chunk in order, never waits for one that won't come. +struct Report<'a> { + seq: usize, + done: &'a Sender<(usize, Decoded)>, + sent: bool, +} + +impl Drop for Report<'_> { + fn drop(&mut self) { + if !self.sent { + let _ = self.done.send((self.seq, Err(malformed("a decoding thread stopped")))); + } + } +} + +/// The bands of one chunk. A panic in the `exr` crate's decompressors is reported as a damaged +/// chunk, never raised (where panics unwind). +fn decode_job(index: &Index, g: &Geometry, job: &Job) -> Decoded { + let buf = job.data.get(job.range.clone()).unwrap_or_default(); + let decoded = catch_unwind(AssertUnwindSafe(|| chunk_bands(index, job.part, &job.chunk, buf, g))) + .unwrap_or_else(|_| Err(malformed("a chunk could not be decompressed"))); + decoded.map(|(mut bands, lines)| { + for band in &mut bands { + band.chunk = job.seq; + } + (bands, lines) + }) +} + +/// Puts decoded chunks back into file order: the workers finish them in any order, the sink gets +/// them by sequence number. +#[derive(Default)] +struct InOrder { + /// The sequence number of the next chunk to deliver. + next: usize, + /// Chunks decoded ahead of it. + waiting: std::collections::BTreeMap, +} + +impl InOrder { + fn accept(&mut self, seq: usize, decoded: Decoded) { + self.waiting.insert(seq, decoded); + } + + /// Hands every chunk that is next in order to `sink`, polling `cancel` before each one; the + /// first chunk that failed to decode ends the read with its error (after the chunks before it + /// were delivered). + /// The sink's error stops the delivery at once (no band after it). + fn deliver( + &mut self, + sink: &mut dyn FnMut(Band) -> std::result::Result<(), E>, + stats: &mut Stats, + cancel: &dyn Fn() -> bool, + ) -> std::result::Result<(), Stop> { + while self.waiting.contains_key(&self.next) { + if cancel() { + return Err(Error::Cancelled.into()); + } + let Some(decoded) = self.waiting.remove(&self.next) else { break }; + self.next += 1; + let (bands, lines) = decoded?; + stats.lines = stats.lines.saturating_add(lines); + for band in bands { + sink(band).map_err(Stop::Sink)?; + } + } + Ok(()) + } +} + +/// The bytes of a piece, and each of its chunks' range in them (in the piece's order). +struct Piece { + data: Vec, + chunks: Vec>, +} + +/// How many of `jobs` (chunks in file order) the next piece takes: chunks that each start where +/// the one before ends, up to [`PIECE_CHUNKS`] of them, `most` bytes or `budget` decoded bytes, +/// at least one. +fn piece_len(jobs: &[Planned], most: u64, budget: u64) -> usize { + let mut take = 0; + let (mut bytes, mut cost) = (0u64, 0u64); + let mut end = None; + while let Some(job) = jobs.get(take) { + if take > 0 + && (take >= PIECE_CHUNKS || end != Some(job.offset) || bytes.saturating_add(job.len) > most || cost.saturating_add(job.cost) > budget) + { + break; + } + bytes = bytes.saturating_add(job.len); + cost = cost.saturating_add(job.cost); + end = Some(job.offset.saturating_add(job.len)); + take += 1; + } + take +} + +/// The raw bytes of the chunks `piece` (in file order, each starting where the one before ends), +/// read with one request after a seek when the source stands elsewhere (`pos`), and each chunk's +/// range in them. A chunk the file ends in keeps the bytes there are. +fn read_piece(source: &mut R, piece: &[Planned], pos: &mut Option, stats: &mut Stats) -> Result { + let Some(start) = piece.first().map(|j| j.offset) else { return Ok(Piece { data: Vec::new(), chunks: Vec::new() }) }; + let total = piece.iter().map(|j| j.len).fold(0u64, u64::saturating_add); + let mut data = Vec::new(); + data.try_reserve_exact(usize::try_from(total).map_err(|_| malformed("chunk size"))?) + .map_err(|_| Error::OutOfMemory("chunk allocation".into()))?; + if *pos != Some(start) { + source.seek(SeekFrom::Start(start)).map_err(io)?; + } + (&mut *source).take(total).read_to_end(&mut data).map_err(io)?; + *pos = Some(start.saturating_add(data.len() as u64)); + stats.bytes = stats.bytes.saturating_add(data.len() as u64); + let mut chunks = Vec::new(); + chunks.try_reserve_exact(piece.len()).map_err(|_| Error::OutOfMemory("chunk allocation".into()))?; + for job in piece { + let a = usize::try_from(job.offset.saturating_sub(start)).unwrap_or(usize::MAX).min(data.len()); + let b = usize::try_from(job.len).map_or(data.len(), |l| a.saturating_add(l)).min(data.len()); + chunks.push(a..b); + if let Some(c) = stats.chunks.get_mut(job.part) { + *c += 1; + } + } + Ok(Piece { data, chunks }) +} + +/// Checks the header of the chunk `buf` of flat part `pi` (`header`), which its offset table +/// says is `expected`, before the `exr` crate reads it: the crate allocates and zero-fills the +/// payload size a chunk declares (up to its own bound per block, which can be hundreds of +/// megabytes) before reading it, and computes a tile's position from the level it declares +/// (panicking on some). The header is the part number (in multi-part files), then the first +/// scan line's y or the tile's column, row and level (x, y), then the payload size, all `i32`. +fn check_chunk_header(meta: &MetaData, header: &Header, pi: usize, expected: &ChunkRef, buf: &[u8]) -> Result> { + let word = |i: usize| buf.get(i * 4..i * 4 + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes); + let short = || malformed("a chunk shorter than its header"); + let mut at = 0usize; + if meta.requirements.is_multilayer() { + if usize::try_from(word(0).ok_or_else(short)?).ok() != Some(pi) { + return Err(malformed("a chunk of another part where its offset table points")); + } + at = 1; + } + let in_place = match header.blocks { + exr::meta::BlockDescription::ScanLines => { + let y = word(at).ok_or_else(short)?; + at += 1; + i64::from(y) == i64::from(header.own_attributes.layer_position.1).saturating_add(expected.y as i64) + } + exr::meta::BlockDescription::Tiles(_) => { + let tile = [word(at), word(at + 1), word(at + 2), word(at + 3)]; + at += 4; + let [Some(x), Some(y), Some(lx), Some(ly)] = tile else { return Err(short()) }; + (usize::try_from(x).ok(), usize::try_from(y).ok()) == (Some(expected.tile.0), Some(expected.tile.1)) && (lx, ly) == (0, 0) + } + }; + if !in_place { + return Err(malformed("a chunk is not the block its offset table entry stands for")); + } + let size = usize::try_from(word(at).ok_or_else(short)?).map_err(|_| malformed("a chunk declaring a negative size"))?; + if size > buf.len().saturating_sub((at + 1) * 4) { + return Err(malformed("a chunk declaring more bytes than it holds")); + } + let start = (at + 1) * 4; + Ok(start..start + size) +} + +/// Decompress the chunk `buf` of part `pi`, which its offset table says is `expected`, and convert +/// the lines of the requested channels to bands (`g.slots`: each channel's request slots): the +/// bands, and the scan lines decompressed. A chunk that names another part, level or position +/// than its offset-table entry, or declares more bytes than it holds, is refused before the +/// `exr` crate reads it. +fn chunk_bands(index: &Index, pi: usize, expected: &ChunkRef, buf: &[u8], g: &Geometry) -> Result<(Vec, usize)> { + let meta = &index.meta; + let (Some(header), Some(part)) = (meta.headers.get(pi), index.layout.get(pi)) else { return Err(malformed("no such part")) }; + let payload = check_chunk_header(meta, header, pi, expected, buf)?; + // (a DWA chunk's counters can make the crate allocate terabytes: see `crate::dwa_guard`) + let payload = buf.get(payload).unwrap_or_default(); + // (planned against the gap to the next chunk; the payload the chunk declares may be smaller) + index.check_ratio(pi, header, part, expected, payload.len() as u64)?; + crate::dwa_guard::check_payload(header, (expected.cols, expected.rows), payload).map_err(malformed)?; + let mut read = buf; + let chunk = Chunk::read(&mut read, meta).map_err(exr_error)?; + let block = UncompressedBlock::decompress_chunk(chunk, meta, false).map_err(exr_error)?; + if block.index.level != Vec2(0, 0) || block.index.pixel_position != Vec2(expected.x, expected.y) { + return Err(malformed("a chunk is not the block its offset table entry stands for")); + } + let slots = g.slots.get(pi).map_or(&[][..], Vec::as_slice); + let lines = block.index.pixel_size.1; + let ((lw, lh), (w, h)) = (part.size, g.size); + let (ow, _) = g.out; + // The output rows of the block: its data-window rows that land in the display window on a + // wanted row. They are consecutive in the output grid (wanted rows are every stride-th). + let (by, bh) = (block.index.pixel_position.1, block.index.pixel_size.1); + let out_rows: Vec = (by..by.saturating_add(bh)) + .filter_map(|y| usize::try_from(y as i64 + part.offset.1).ok()) + .filter(|ty| *ty < h && g.wanted(*ty as i64)) + .map(|ty| ty / g.stride as usize) + .collect(); + let (Some(&top), Some(&bottom)) = (out_rows.first(), out_rows.last()) else { return Ok((Vec::new(), lines)) }; + let height = bottom.saturating_sub(top).saturating_add(1); + // One band per output unit (a group, or a slot of its own), each row written straight into it + // at its place: no band is copied or regrown. + let mut bands: std::collections::BTreeMap = std::collections::BTreeMap::new(); + // (typed: the line reader is generic over the sample type, and an untyped `0` would make the + // integer buffer `i32`, turning ids from 2^31 up negative) + let (mut f16s, mut f32s, mut u32s): (Vec, Vec, Vec) = (Vec::new(), Vec::new(), Vec::new()); + for line in block.lines(&header.channels) { + let Some(wanted) = slots.get(line.location.channel).filter(|s| !s.is_empty()) else { continue }; + let Some(kind) = header.channels.list.get(line.location.channel).map(|c| c.sample_type) else { continue }; + let (x0, y, count) = (line.location.position.0, line.location.position.1, line.location.sample_count); + // The samples of data-window row `y`, columns `x0..x0 + count`, at display row `ty` from + // display column `tx0`; clipped to the display window. + if y >= lh || x0.checked_add(count).is_none_or(|end| end > lw) { + continue; + } + let Some(ty) = usize::try_from(y as i64 + part.offset.1).ok().filter(|ty| *ty < h) else { continue }; + if !g.wanted(ty as i64) { + continue; + } + let tx0 = x0 as i64 + part.offset.0; + let skip = usize::try_from(-tx0).unwrap_or(0).min(count); + let tx = usize::try_from(tx0.max(0)).unwrap_or(usize::MAX); + let take = (count - skip).min(w.saturating_sub(tx)); + if take == 0 { + continue; + } + let samples: Vec = match kind { + ExrSample::F16 => { + f16s.resize(count, exr::prelude::f16::ZERO); + line.read_samples_into_slice(&mut f16s).map_err(exr_error)?; + let mut out = vec![0.0; take]; + if let Some(src) = f16s.get(skip..skip + take) { + half::slice::HalfFloatSliceExt::convert_to_f32_slice(src, &mut out); + } + out + } + ExrSample::F32 => { + f32s.resize(count, 0.0); + line.read_samples_into_slice(&mut f32s).map_err(exr_error)?; + f32s.iter().skip(skip).take(take).copied().collect() + } + ExrSample::U32 => { + u32s.resize(count, 0); + line.read_samples_into_slice(&mut u32s).map_err(exr_error)?; + u32s.iter().skip(skip).take(take).map(|s| *s as f32).collect() + } + }; + let (row, col, values) = if g.stride == 1 { + (ty, tx, samples) + } else { + // A reduced level: every stride-th column of the row, on the level's grid. + let stride = g.stride as usize; + let first = tx.div_ceil(stride) * stride; + let values: Vec = samples.iter().enumerate().filter(|(j, _)| (tx + j) % stride == 0).map(|(_, v)| *v).collect(); + (ty / stride, first / stride, values) + }; + if values.is_empty() || col.saturating_add(values.len()) > ow { + continue; + } + // (a channel requested more than once goes into each of its slots) + for slot in wanted { + let Some(&(unit, n, k)) = g.units.get(*slot) else { continue }; + let band = match bands.entry(unit) { + std::collections::btree_map::Entry::Occupied(band) => band.into_mut(), + std::collections::btree_map::Entry::Vacant(place) => { + let len = height.saturating_mul(values.len()).saturating_mul(n); + let mut samples = Vec::new(); + samples.try_reserve_exact(len).map_err(|_| Error::OutOfMemory("band allocation".into()))?; + samples.resize(len, 0.0); + place.insert(Band { slot: unit, x: col, y: top, width: values.len(), height, values_per_pixel: n, chunk: 0, samples }) + } + }; + // (every line of a block covers the same columns; a block whose lines don't is damaged) + if band.x != col || band.width != values.len() || row < top || row > bottom { + return Err(malformed("the lines of a block disagree on where they lie")); + } + let base = (row - top).saturating_mul(band.width).saturating_mul(n); + for (i, v) in values.iter().enumerate() { + if let Some(slot) = band.samples.get_mut(base + i * n + k) { + *slot = *v; + } + } + } + } + drop(block); + Ok((bands.into_values().collect(), lines)) +} diff --git a/crates/exr/src/seek_tests.rs b/crates/exr/src/seek_tests.rs new file mode 100644 index 0000000000..0104922351 --- /dev/null +++ b/crates/exr/src/seek_tests.rs @@ -0,0 +1,1525 @@ +//! Tests of [`crate::seek`]: files are built with the `exr` crate and read back through the +//! seekable reader; the whole-part decoder ([`crate::decode`]) is the oracle for what a channel +//! should hold. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +// (lists of channel groups with one group are arrays of one range on purpose) +#![allow(clippy::single_range_in_vec_init)] + +use std::cell::Cell; +use std::io::{Cursor, Read, Seek, SeekFrom}; + +use exr::math::Vec2; +use exr::prelude::{ + AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, ImageAttributes, IntegerBounds, Layer, LayerAttributes, LineOrder, + WritableImage, +}; + +use super::decode::{Limits, decode_display_part}; +use super::seek::*; + +fn value(i: usize, k: usize) -> f32 { + (i * 7 + k * 1000) as f32 / 4.0 +} + +/// A layer of `w × h` at `at` in the display window, with these channels (f32 ramps, each its own). +fn layer( + name: Option<&str>, + at: (i32, i32), + (w, h): (usize, usize), + channels: &[&str], + tiles: bool, + compression: Compression, +) -> Layer> { + let mut attrs = name.map_or_else(LayerAttributes::default, LayerAttributes::named); + attrs.layer_position = Vec2(at.0, at.1); + let list = channels.iter().enumerate().map(|(k, n)| AnyChannel::new(*n, FlatSamples::F32((0..w * h).map(|i| value(i, k)).collect()))).collect(); + let blocks = if tiles { Blocks::Tiles(Vec2(4, 4)) } else { Blocks::ScanLines }; + Layer::new((w, h), attrs, Encoding { compression, blocks, line_order: LineOrder::Increasing }, AnyChannels::sort(list)) +} + +fn file(layers: Vec>>, display: (usize, usize)) -> Vec { + let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), display)), layers); + let mut out = Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).unwrap(); + out.into_inner() +} + +fn never() -> bool { + false +} + +fn indexed(bytes: &[u8]) -> Index { + Index::build(&mut Cursor::new(bytes), &Limits::default(), &never).unwrap() +} + +/// What the whole-part decoder places in the display window for each channel of part `part`. +fn oracle(bytes: &[u8], part: usize, fill: f32) -> Vec> { + decode_display_part(bytes, part, &|_| true, &|_| fill, &Limits::default()).unwrap().channels.into_iter().map(|c| c.samples).collect() +} + +fn channels_of(index: &Index, part: usize) -> Vec<(usize, usize)> { + (0..index.parts()[part].channels.len()).map(|c| (part, c)).collect() +} + +#[test] +fn every_compression_scan_lines_and_tiles_read_like_the_whole_part_decoder() { + for compression in + [Compression::Uncompressed, Compression::RLE, Compression::ZIP1, Compression::ZIP16, Compression::PIZ, Compression::PXR24, Compression::B44] + { + for tiles in [false, true] { + let bytes = file(vec![layer(None, (0, 0), (9, 7), &["R", "G", "B", "A"], tiles, compression)], (9, 7)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&channels, usize::MAX), &never).unwrap(); + assert_eq!((read.width, read.height), (9, 7)); + assert_eq!(read.planes, oracle(&bytes, 0, 0.0), "{compression:?} tiles {tiles}"); + } + } +} + +#[test] +fn only_the_requested_channels_are_returned_in_the_requested_order() { + let bytes = file(vec![layer(None, (0, 0), (8, 4), &["R", "G", "B", "A"], false, Compression::ZIP1)], (8, 4)); + let index = indexed(&bytes); + let names: Vec<&str> = index.parts()[0].channels.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["A", "B", "G", "R"]); + let whole = oracle(&bytes, 0, 0.0); + // R, then A (stored first), the others not read. + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 3), (0, 0)], usize::MAX), &never).unwrap(); + assert_eq!(read.planes, [whole[3].clone(), whole[0].clone()]); +} + +#[test] +fn a_part_with_no_requested_channel_is_not_read() { + let bytes = file( + vec![ + layer(Some("depth"), (0, 0), (16, 16), &["Z"], false, Compression::ZIP1), + layer(Some("beauty"), (0, 0), (16, 16), &["R", "G", "B", "A"], true, Compression::PIZ), + ], + (16, 16), + ); + let index = indexed(&bytes); + assert_eq!(index.parts().len(), 2); + let depth = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &never).unwrap(); + assert_eq!(depth.planes, oracle(&bytes, 0, 0.0)); + assert!(depth.stats.chunks[0] > 0); + assert_eq!(depth.stats.chunks[1], 0, "the beauty part was never touched"); + // Channels of both parts in one read, in request order. + let both = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(1, 3), (0, 0)], usize::MAX), &never).unwrap(); + assert_eq!(both.planes, [oracle(&bytes, 1, 0.0)[3].clone(), oracle(&bytes, 0, 0.0)[0].clone()]); +} + +#[test] +fn only_the_chunks_holding_the_requested_rows_are_read() { + // One line per chunk (ZIPS-like layout through ZIP1): rows 4..8 are four chunks. + let bytes = file(vec![layer(None, (0, 0), (8, 16), &["Y"], false, Compression::ZIP1)], (8, 16)); + let index = indexed(&bytes); + let whole = oracle(&bytes, 0, 0.0)[0].clone(); + let request = Request { rows: Some(4..8), fill: &[-1.0], ..Request::new(&[(0, 0)], usize::MAX) }; + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never).unwrap(); + assert_eq!(read.stats.chunks[0], 4); + for row in 0..16 { + let got = &read.planes[0][row * 8..row * 8 + 8]; + if (4..8).contains(&row) { + assert_eq!(got, &whole[row * 8..row * 8 + 8], "row {row}"); + } else { + assert_eq!(got, [-1.0; 8], "row {row} keeps the fill value"); + } + } + // Tiles: rows 5..6 touch the one tile row (4..8) only. + let tiled = file(vec![layer(None, (0, 0), (8, 16), &["Y"], true, Compression::ZIP1)], (8, 16)); + let tiled_index = indexed(&tiled); + let request = Request { rows: Some(5..6), ..Request::new(&[(0, 0)], usize::MAX) }; + let read = read_planes(&mut Cursor::new(&tiled[..]), &tiled_index, &request, &never).unwrap(); + assert_eq!(read.stats.chunks[0], 2, "two 4-wide tiles of the one tile row"); + assert_eq!(&read.planes[0][5 * 8..6 * 8], &oracle(&tiled, 0, 0.0)[0][5 * 8..6 * 8]); +} + +#[test] +fn a_reduced_level_keeps_every_nth_row_and_column() { + // 9 × 7: level 1 is 5 × 4, level 2 is 3 × 2. + for tiles in [false, true] { + let bytes = file(vec![layer(None, (0, 0), (9, 7), &["Y"], tiles, Compression::ZIP1)], (9, 7)); + let index = indexed(&bytes); + let whole = oracle(&bytes, 0, 0.0)[0].clone(); + for level in 0..=3u32 { + let stride = 1usize << level; + let request = Request { level, ..Request::new(&[(0, 0)], usize::MAX) }; + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never).unwrap(); + assert_eq!((read.width, read.height), level_size((9, 7), level)); + let expected: Vec = + (0..7).step_by(stride).flat_map(|y| (0..9).step_by(stride).map(move |x| (y, x))).map(|(y, x)| whole[y * 9 + x]).collect(); + assert_eq!(read.planes[0], expected, "level {level} tiles {tiles}"); + } + } +} + +#[test] +fn a_reduced_level_reads_only_the_chunks_with_a_row_on_its_grid() { + // One line per chunk: level 2 needs every 4th row of 16. + let bytes = file(vec![layer(None, (0, 0), (8, 16), &["Y"], false, Compression::ZIP1)], (8, 16)); + let index = indexed(&bytes); + let request = Request { level: 2, ..Request::new(&[(0, 0)], usize::MAX) }; + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never).unwrap(); + assert_eq!(read.stats.chunks[0], 4); +} + +#[test] +fn a_part_inside_a_larger_display_window_is_placed_and_clipped_like_the_whole_part_decoder() { + // Data window 3 × 2 at (2, 1) in a 6 × 4 display window; another at (-1, -1) cut by the edge. + for (at, size) in [((2, 1), (3, 2)), ((-1, -1), (4, 3)), ((5, 3), (4, 4)), ((-9, 0), (2, 2))] { + let bytes = file(vec![layer(None, at, size, &["R", "G"], false, Compression::ZIP1)], (6, 4)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let request = Request { fill: &[9.0, 9.0], ..Request::new(&channels, usize::MAX) }; + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never).unwrap(); + assert_eq!(read.planes, oracle(&bytes, 0, 9.0), "data window {size:?} at {at:?}"); + } +} + +#[test] +fn bands_cover_the_planes_exactly_and_arrive_in_row_order() { + for tiles in [false, true] { + let bytes = file(vec![layer(None, (0, 0), (12, 10), &["R", "G"], tiles, Compression::ZIP16)], (12, 10)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let mut planes = [vec![f32::NAN; 120], vec![f32::NAN; 120]]; + let mut seen = 0usize; + // Per slot, the (row, column) of the last band: file order is block row by block row, + // and left to right within one (tiles), so it only grows. + let mut last: [Option<(usize, usize)>; 2] = [None, None]; + let stats = read_bands(&mut Cursor::new(&bytes[..]), &index, &Request::new(&channels, usize::MAX), &never, &mut |band: Band| { + assert!(last[band.slot] < Some((band.y, band.x)), "slot {}: {:?} after {:?}", band.slot, (band.y, band.x), last[band.slot]); + last[band.slot] = Some((band.y, band.x)); + assert_eq!(band.samples.len(), band.width * band.height); + assert!(band.x + band.width <= 12 && band.y + band.height <= 10); + for r in 0..band.height { + for c in 0..band.width { + planes[band.slot][(band.y + r) * 12 + band.x + c] = band.samples[r * band.width + c]; + seen += 1; + } + } + }) + .unwrap(); + assert_eq!(seen, 240, "every sample once"); + assert!(stats.chunks[0] > 0 && stats.lines > 0); + assert_eq!(planes.to_vec(), oracle(&bytes, 0, 0.0), "tiles {tiles}"); + } +} + +/// A source that counts the bytes read from it. +struct Counting<'a> { + inner: Cursor<&'a [u8]>, + read: &'a Cell, +} + +impl Read for Counting<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.read.set(self.read.get() + n as u64); + Ok(n) + } +} + +impl Seek for Counting<'_> { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } +} + +#[test] +fn the_first_bands_arrive_before_the_whole_request_has_been_read() { + // Uncompressed lines of 1024 f32 (one chunk each): about 5 MiB in all, more than the first + // two batches. + let bytes = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let read = Cell::new(0u64); + let mut at_first_band = None; + let mut source = Counting { inner: Cursor::new(&bytes[..]), read: &read }; + let before = read.get(); + // The rows each channel's bands have reached: they must keep growing (file order). + let mut reached = [0usize; 2]; + let mut bands = 0usize; + read_bands(&mut source, &index, &Request::new(&channels, usize::MAX), &never, &mut |band: Band| { + at_first_band.get_or_insert(read.get() - before); + assert_eq!(band.y, reached[band.slot], "slot {} out of order", band.slot); + reached[band.slot] = band.y + band.height; + bands += 1; + }) + .unwrap(); + let total = read.get() - before; + let first = at_first_band.unwrap(); + assert!(first < total / 2, "first band after {first} of {total} bytes"); + assert_eq!((reached, bands), ([600, 600], 1200), "every row of both channels, one band per chunk and channel"); +} + +#[test] +fn without_threads_the_chunks_are_decoded_on_the_calling_thread_with_the_same_result() { + // (where threads can't be started, as in WebAssembly, no worker runs) + let bytes = file(vec![layer(None, (0, 0), (1024, 300), &["R", "G"], false, Compression::Uncompressed)], (1024, 300)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let whole = oracle(&bytes, 0, 0.0); + let read = Cell::new(0u64); + let mut source = Counting { inner: Cursor::new(&bytes[..]), read: &read }; + let mut planes = vec![vec![f32::NAN; 1024 * 300]; 2]; + let mut reached = [0usize; 2]; + let mut at_first_band = None; + let request = Request { workers: Some(0), ..Request::new(&channels, usize::MAX) }; + let stats = read_bands(&mut source, &index, &request, &never, &mut |band: Band| { + at_first_band.get_or_insert(read.get()); + assert_eq!(band.y, reached[band.slot], "file order"); + reached[band.slot] = band.y + band.height; + let plane = &mut planes[band.slot]; + plane[band.y * 1024..(band.y + band.height) * 1024].copy_from_slice(&band.samples); + }) + .unwrap(); + assert_eq!(planes, whole); + assert_eq!(stats.chunks[0], 300); + assert!(at_first_band.unwrap() < stats.bytes / 2, "delivered piece by piece"); +} + +#[test] +fn a_read_can_be_called_off() { + let bytes = file(vec![layer(None, (0, 0), (16, 16), &["R"], false, Compression::ZIP1)], (16, 16)); + let index = indexed(&bytes); + let count = Cell::new(0usize); + let cancel = || { + count.set(count.get() + 1); + count.get() > 1 + }; + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &cancel); + assert_eq!(got.err(), Some(Error::Cancelled)); + let building = Index::build(&mut Cursor::new(&bytes[..]), &Limits::default(), &|| true); + assert_eq!(building.err(), Some(Error::Cancelled)); +} + +#[test] +fn a_request_over_the_byte_limit_is_refused_before_anything_is_read() { + let bytes = file(vec![layer(None, (0, 0), (16, 16), &["R", "G"], false, Compression::ZIP1)], (16, 16)); + let index = indexed(&bytes); + let read = Cell::new(0u64); + let mut source = Counting { inner: Cursor::new(&bytes[..]), read: &read }; + // Two planes of 16 × 16 f32 are 2048 bytes. + let got = read_planes(&mut source, &index, &Request::new(&[(0, 0), (0, 1)], 2047), &never); + assert!(matches!(got, Err(Error::LimitExceeded(_))), "{got:?}"); + assert_eq!(read.get(), 0, "no chunk was fetched"); + let got = read_planes(&mut source, &index, &Request::new(&[(0, 0), (0, 1)], 2048), &never).unwrap(); + assert_eq!(got.planes.len(), 2); + // A reduced level counts its smaller planes. + let request = Request { level: 1, ..Request::new(&[(0, 0), (0, 1)], 512) }; + assert_eq!(read_planes(&mut source, &index, &request, &never).unwrap().width, 8); +} + +#[test] +fn requests_for_channels_that_do_not_exist_are_refused() { + let bytes = file(vec![layer(None, (0, 0), (4, 4), &["R"], false, Compression::ZIP1)], (4, 4)); + let index = indexed(&bytes); + for channels in [[(1, 0)], [(0, 1)]] { + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&channels, usize::MAX), &never); + assert!(matches!(got, Err(Error::Malformed(_))), "{channels:?}: {got:?}"); + } + // Nothing requested is an empty read. + let none = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[], usize::MAX), &never).unwrap(); + assert!(none.planes.is_empty() && none.stats.bytes == 0); +} + +#[test] +fn headers_declaring_more_than_the_limits_are_refused_before_any_allocation() { + // An 8 × 8 data window, but the limits allow 4 × 4 only. + let bytes = file(vec![layer(None, (0, 0), (8, 8), &["R"], false, Compression::ZIP1)], (8, 8)); + let limits = Limits { max_width: 4, max_height: 4, ..Limits::default() }; + let got = Index::build(&mut Cursor::new(&bytes[..]), &limits, &never); + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("part 0")), "{got:?}"); + // A 2 × 2 data window (within the limit) in an 8 × 8 display window over it. + let small = file(vec![layer(None, (0, 0), (2, 2), &["R"], false, Compression::ZIP1)], (8, 8)); + let limits = Limits { max_pixels: 16, ..Limits::default() }; + let got = Index::build(&mut Cursor::new(&small[..]), &limits, &never); + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("display window")), "{got:?}"); + assert!(Index::build(&mut Cursor::new(&small[..]), &Limits { max_pixels: 64, ..Limits::default() }, &never).is_ok()); +} + +#[test] +fn hostile_files_are_refused_and_never_panic() { + let bytes = file( + vec![ + layer(Some("a"), (0, 0), (9, 7), &["R", "G"], false, Compression::ZIP1), + layer(Some("b"), (1, 1), (5, 5), &["Z"], true, Compression::PIZ), + ], + (9, 7), + ); + let try_read = |data: &[u8]| { + let Ok(index) = Index::build(&mut Cursor::new(data), &Limits::default(), &never) else { return }; + let channels: Vec<(usize, usize)> = (0..index.parts().len()).flat_map(|p| channels_of(&index, p)).collect(); + let _ = read_planes(&mut Cursor::new(data), &index, &Request::new(&channels, 1 << 24), &never); + }; + // Every truncation. + for n in 0..bytes.len() { + try_read(&bytes[..n]); + } + // A flipped byte at every position (headers, tables and chunks). + for at in 0..bytes.len() { + let mut broken = bytes.clone(); + broken[at] ^= 0xFF; + try_read(&broken); + } + // Garbage and an empty source. + try_read(&[]); + try_read(&[0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]); + try_read(&vec![0xAB; 4096]); +} + +#[test] +fn headers_over_the_attribute_and_size_bounds_are_refused() { + let mut bytes = vec![0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]; + // An attribute that claims 100 MB. + bytes.extend_from_slice(b"comments\0string\0"); + bytes.extend_from_slice(&100_000_000i32.to_le_bytes()); + bytes.extend_from_slice(&[0; 64]); + assert!(matches!(Index::build(&mut Cursor::new(&bytes[..]), &Limits::default(), &never), Err(Error::LimitExceeded(_)))); + // A name that never ends. + let mut bytes = vec![0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]; + bytes.extend_from_slice(&[b'a'; 1000]); + assert!(matches!(Index::build(&mut Cursor::new(&bytes[..]), &Limits::default(), &never), Err(Error::LimitExceeded(_)))); +} + +#[test] +fn a_tiled_file_with_mip_levels_is_read_from_its_largest_level_only() { + use exr::math::RoundingMode; + use exr::prelude::Levels; + // 9 × 7 in 4 × 4 tiles: level 0 is 3 × 2 tiles, then 4 × 3, 2 × 1 and 1 × 1 pixels in one + // tile each. The smaller levels hold a value no full-resolution pixel has, so a wrong level + // would show in the planes. + let (w, h) = (9usize, 7usize); + let sizes: Vec = exr::meta::mip_map_levels(RoundingMode::Down, Vec2(w, h)).map(|(_, size)| size.area()).collect(); + assert!(sizes.len() > 1); + let levels = |k: usize| Levels::Mip { + rounding_mode: RoundingMode::Down, + level_data: sizes + .iter() + .enumerate() + .map(|(level, n)| FlatSamples::F32(if level == 0 { (0..*n).map(|i| value(i, k)).collect() } else { vec![1e9; *n] })) + .collect(), + }; + let channels = AnyChannels::sort(vec![AnyChannel::new("R", levels(0)), AnyChannel::new("G", levels(1))].into()); + let encoding = Encoding { compression: Compression::ZIP1, blocks: Blocks::Tiles(Vec2(4, 4)), line_order: LineOrder::Increasing }; + let image = exr::image::Image::from_layers( + ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), + vec![Layer::new((w, h), LayerAttributes::default(), encoding, channels)], + ); + let mut out = Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).unwrap(); + let bytes = out.into_inner(); + let index = indexed(&bytes); + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0), (0, 1)], usize::MAX), &never).unwrap(); + // (the part stores G before R) + let expected = |k: usize| (0..w * h).map(|i| value(i, k)).collect::>(); + assert_eq!(read.planes, [expected(1), expected(0)]); + assert_eq!(read.stats.chunks[0], 6, "the six tiles of level 0, none of the smaller levels"); + // A reduced read takes its rows from the largest level too. + let half = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request { level: 1, ..Request::new(&[(0, 1)], usize::MAX) }, &never).unwrap(); + let every_other: Vec = (0..h).step_by(2).flat_map(|y| (0..w).step_by(2).map(move |x| value(y * w + x, 0))).collect(); + assert_eq!(half.planes[0], every_other); +} + +#[test] +fn a_flat_part_beside_a_deep_part_is_read_and_the_deep_part_is_refused() { + use super::decode_tests::{mixed_file, mixed_flat}; + for (deep_first, tiled) in [(false, false), (true, false), (false, true), (true, true)] { + let (bytes, _) = mixed_file(deep_first, tiled); + let (flat, deep) = if deep_first { (1, 0) } else { (0, 1) }; + let index = indexed(&bytes); + assert_eq!((index.parts()[flat].deep, index.parts()[deep].deep), (false, true)); + let names: Vec<&str> = index.parts()[flat].channels.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["B", "G", "R"]); + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(flat, 2), (flat, 0)], usize::MAX), &never).unwrap(); + let expected = |channel: f32| (0..6).map(|i| mixed_flat(channel, i)).collect::>(); + assert_eq!(read.planes, [expected(0.0), expected(100.0)], "deep first {deep_first} tiled {tiled}"); + assert_eq!((read.stats.chunks[flat], read.stats.chunks[deep]), (2, 0), "the deep part's chunks are never read"); + for channels in [vec![(deep, 0)], vec![(flat, 0), (deep, 0)]] { + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&channels, usize::MAX), &never); + assert!(matches!(got, Err(Error::Unsupported(_))), "{channels:?}: {got:?}"); + } + } +} + +#[test] +fn a_subsampled_channel_is_refused() { + let mut bytes = file(vec![layer(None, (0, 0), (4, 2), &["R"], false, Compression::Uncompressed)], (4, 2)); + // The `exr` crate's writer emits no subsampling: the x sampling of the one channel in the + // channel list is patched to 2 (the 4 × 2 window is a multiple of it). + let tag = b"channels\0chlist\0"; + let attr = bytes.windows(tag.len()).position(|window| window == tag).unwrap(); + let payload = attr + tag.len() + 4; + let name_end = payload + bytes[payload..].iter().position(|byte| *byte == 0).unwrap(); + let x_sampling = name_end + 1 + 4 + 1 + 3; + bytes[x_sampling..x_sampling + 4].copy_from_slice(&2u32.to_le_bytes()); + let index = indexed(&bytes); + assert_eq!(index.parts()[0].channels[0].sampling, (2, 1)); + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &never); + assert!(matches!(got, Err(Error::Unsupported(_))), "{got:?}"); +} + +#[test] +fn half_float_and_integer_channels_convert_like_the_whole_part_decoder() { + use exr::prelude::f16; + let (w, h) = (7usize, 5usize); + let halves: Vec = (0..w * h).map(|i| f16::from_f32(i as f32 / 8.0 - 2.0)).collect(); + // Integers beyond f32's exact range too (object ids): they round like the oracle's. + let ids: Vec = (0..w * h).map(|i| (i as u32).wrapping_mul(2_654_435_761)).collect(); + for tiles in [false, true] { + let list = vec![ + AnyChannel::new("Y", FlatSamples::F16(halves.clone())), + AnyChannel::new("id", FlatSamples::U32(ids.clone())), + AnyChannel::new("Z", FlatSamples::F32(vec![0.5; w * h])), + ]; + let blocks = if tiles { Blocks::Tiles(Vec2(4, 4)) } else { Blocks::ScanLines }; + let layer = Layer::new( + (w, h), + LayerAttributes::default(), + Encoding { compression: Compression::ZIP16, blocks, line_order: LineOrder::Increasing }, + AnyChannels::sort(list.into()), + ); + // Placed partly outside the display window, so the conversion and the clipping meet. + let mut layer = layer; + layer.attributes.layer_position = Vec2(-2, 1); + let bytes = file(vec![layer], (6, 5)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let request = Request { fill: &[7.0, 7.0, 7.0], ..Request::new(&channels, usize::MAX) }; + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never).unwrap(); + assert_eq!(read.planes, oracle(&bytes, 0, 7.0), "tiles {tiles}"); + assert!(read.planes.iter().all(|p| p.iter().any(|v| *v != 7.0))); + } +} + +#[test] +fn the_index_reports_its_parts_and_a_size() { + let bytes = file(vec![layer(Some("beauty"), (0, 0), (8, 8), &["R", "G", "B"], false, Compression::ZIP16)], (8, 8)); + let index = indexed(&bytes); + assert_eq!(index.parts()[0].name.as_deref(), Some("beauty")); + assert_eq!((index.display().width, index.display().height), (8, 8)); + assert_eq!(index.file_len(), bytes.len() as u64); + assert!(index.bytes() > 0 && index.bytes() < 64 << 10, "{}", index.bytes()); +} + +/// Writes `layers` into a file whose display window is `display` (absolute position and size). +fn file_at(layers: Vec>>, display: ((i32, i32), (usize, usize))) -> Vec { + let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new(display.0, display.1)), layers); + let mut out = Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).unwrap(); + out.into_inner() +} + +/// Where the offset table of a single-part file with `count` chunks starts: the position whose +/// smallest entry is where the table ends. +fn table_at(bytes: &[u8], count: usize) -> usize { + let entry = |p: usize| u64::from_le_bytes(bytes[p..p + 8].try_into().unwrap()) as usize; + (8..bytes.len() - count * 8).find(|p| (0..count).map(|i| entry(p + i * 8)).min() == Some(p + count * 8)).unwrap() +} + +/// Sets the box2i attribute `name` (`dataWindow`, `displayWindow`) of a file to `bounds`. +fn patch_box(bytes: &mut [u8], name: &str, bounds: [i32; 4]) { + let tag = format!("{name}\0box2i\0"); + let at = bytes.windows(tag.len()).position(|w| w == tag.as_bytes()).unwrap() + tag.len() + 4; + for (i, v) in bounds.iter().enumerate() { + bytes[at + i * 4..at + i * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } +} + +/// A tiled 9 × 7 file in 4 × 4 tiles with these levels of one channel `R`. +fn tiled_levels(levels: exr::prelude::Levels) -> Vec { + let encoding = Encoding { compression: Compression::ZIP1, blocks: Blocks::Tiles(Vec2(4, 4)), line_order: LineOrder::Increasing }; + let channels = AnyChannels::sort(vec![AnyChannel::new("R", levels)].into()); + let image = exr::image::Image::from_layers( + ImageAttributes::new(IntegerBounds::new((0, 0), (9, 7))), + vec![Layer::new((9, 7), LayerAttributes::default(), encoding, channels)], + ); + let mut out = Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).unwrap(); + out.into_inner() +} + +#[test] +fn a_channel_requested_twice_is_delivered_in_both_slots() { + for tiles in [false, true] { + let bytes = file(vec![layer(None, (0, 0), (9, 7), &["R", "G"], tiles, Compression::ZIP1)], (9, 7)); + let index = indexed(&bytes); + let whole = oracle(&bytes, 0, 0.0); + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 1), (0, 0), (0, 1)], usize::MAX), &never).unwrap(); + assert_eq!(read.planes, [whole[1].clone(), whole[0].clone(), whole[1].clone()], "tiles {tiles}"); + } +} + +#[test] +fn a_block_is_bounded_by_the_bytes_the_decompressor_allocates_for_it() { + // One row 4 Mi pixels wide of one f32 channel: 16 MiB. PIZ holds 32 rows a block, but a + // one-row part's block is that row; 16 such rows of four channels in one ZIP16 block are 1 GiB. + // Both index; a read refuses the 1 GiB block unless its `max_bytes` allows that much. + // (`cancel` stops each read that passes the check before a chunk is fetched.) + let stop = || true; + for (compression, (w, h), channels, big) in + [(Compression::PIZ, (4 << 20, 1), &["R"][..], false), (Compression::ZIP16, (4 << 20, 16), &["R", "G", "B", "A"][..], true)] + { + let mut bytes = file(vec![layer(None, (0, 0), (1, h), channels, false, compression)], (1, h)); + patch_box(&mut bytes, "dataWindow", [0, 0, w - 1, h as i32 - 1]); + let index = Index::build(&mut Cursor::new(&bytes[..]), &Limits::none(), &never).unwrap(); + let read = |max_bytes| read_bands(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], max_bytes), &stop, &mut |_| {}); + let got = read(256 << 20); + if big { + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("block")), "{compression:?}: {got:?}"); + assert_eq!(read(1 << 30).err(), Some(Error::Cancelled), "{compression:?}: allowed with max_bytes 1 GiB"); + } else { + assert_eq!(got.err(), Some(Error::Cancelled), "{compression:?}"); + } + } +} + +#[test] +fn a_wide_dwab_part_with_half_a_gigabyte_blocks_reads_only_with_a_budget_that_allows_them() { + // 16K wide, 256 lines (one DWAB block), 64 half channels: 128 bytes a pixel, 512 MiB a block. + let mut bytes = many_channels(1, 1, 64, true, Compression::DWAB(None)); + patch_box(&mut bytes, "dataWindow", [0, 0, 16383, 255]); + patch_box(&mut bytes, "displayWindow", [0, 0, 16383, 255]); + let index = Index::build(&mut Cursor::new(&bytes[..]), &Limits::none(), &never).unwrap(); + assert_eq!(index.chunks(0).map(|c| (c.width, c.height)).collect::>(), [(16384, 256)]); + let stop = || true; + let read = |max_bytes| read_bands(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], max_bytes), &stop, &mut |_| {}); + let got = read(256 << 20); + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("block")), "{got:?}"); + assert_eq!(read((512 << 20) - 1).err().map(|e| matches!(e, Error::LimitExceeded(_))), Some(true)); + assert_eq!(read(512 << 20).err(), Some(Error::Cancelled), "a 512 MiB block within max_bytes passes the check"); + assert_eq!(read(1 << 30).err(), Some(Error::Cancelled)); +} + +// (budgets over 4 GiB: a 64-bit usize) +#[cfg(target_pointer_width = "64")] +#[test] +fn a_block_is_held_to_max_block_bytes_whatever_the_total_budget() { + // The same 512 MiB DWAB block, read with a 64 GiB budget: `max_block_bytes` decides. The + // source panics if a chunk is fetched, so a missing check fails at once. + let mut bytes = many_channels(1, 1, 64, true, Compression::DWAB(None)); + patch_box(&mut bytes, "dataWindow", [0, 0, 16383, 255]); + patch_box(&mut bytes, "displayWindow", [0, 0, 16383, 255]); + let index = Index::build(&mut Cursor::new(&bytes[..]), &Limits::none(), &never).unwrap(); + let chunks = index.chunks(0).next().unwrap().offset; + let read = |max_block_bytes, cancel: &dyn Fn() -> bool| { + let request = Request { max_block_bytes, ..Request::new(&[(0, 0)], 64 << 30) }; + read_bands(&mut NoChunks { inner: Cursor::new(&bytes[..]), chunks }, &index, &request, cancel, &mut |_| {}) + }; + let got = read(Some(256 << 20), &never); + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("one block")), "{got:?}"); + // (cancelled right after the check, before a chunk is fetched) + assert_eq!(read(Some(1 << 30), &|| true).err(), Some(Error::Cancelled), "a 1 GiB block limit passes the check"); + // `None`: max(256 MiB, max_bytes), here 64 GiB. + assert_eq!(read(None, &|| true).err(), Some(Error::Cancelled)); +} + +#[test] +fn a_chunk_over_the_in_flight_budget_is_decoded_alone() { + // 64 rows of one f32 channel, 16 wide, one row a chunk: each chunk holds a 64-byte block and + // 64 bytes of bands, 128 bytes in flight; with a budget of 100 no two may be in flight at + // once, however many workers there are. + let bytes = file(vec![layer(None, (0, 0), (16, 64), &["R"], false, Compression::ZIP1)], (16, 64)); + let index = indexed(&bytes); + let whole = oracle(&bytes, 0, 0.0); + for _ in 0..20 { + let mut plane = vec![f32::NAN; 16 * 64]; + let request = Request { workers: Some(8), ..Request::new(&[(0, 0)], usize::MAX) }; + let mut sink = |b: Band| plane[b.y * 16..(b.y + b.height) * 16].copy_from_slice(&b.samples); + let stats = super::seek::read_bands_within(&mut Cursor::new(&bytes[..]), &index, &request, &never, &mut sink, 100).unwrap(); + assert_eq!(stats.in_flight, 128, "one chunk at a time"); + assert_eq!(vec![plane], whole); + } +} + +/// A file of `channels` channels named `c0`, `c1`, … of `w × h` pixels, f32 or half. +fn many_channels(w: usize, h: usize, channels: usize, half: bool, compression: Compression) -> Vec { + use exr::prelude::f16; + let list: Vec> = (0..channels) + .map(|k| { + let samples = (0..w * h).map(|i| ((i * 3 + k * 7) % 50) as f32 / 8.0); + let samples = if half { FlatSamples::F16(samples.map(f16::from_f32).collect()) } else { FlatSamples::F32(samples.collect()) }; + AnyChannel::new(format!("c{k:03}").as_str(), samples) + }) + .collect(); + let encoding = Encoding { compression, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; + file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)) +} + +#[test] +fn wide_dwab_parts_with_many_channels_are_accepted() { + // DWAB holds 256 scan lines a block, and the `exr` crate's bound on a chunk counts all 256 + // even in a part with fewer rows: over 256 MiB for these, though each block is a few MiB. + let dwab = Compression::DWAB(None); + for (w, h, channels, half) in [(65536, 1, 16, false), (4096, 8, 70, false), (8192, 4, 65, true)] { + let mut bytes = many_channels(1, 1, channels, half, dwab); + patch_box(&mut bytes, "dataWindow", [0, 0, w - 1, h - 1]); + let got = Index::build(&mut Cursor::new(&bytes[..]), &Limits::none(), &never); + assert!(got.is_ok(), "{w} × {h}, {channels} channels: {got:?}"); + } + // A real one: one row 4096 wide of 65 f32 channels (the crate's bound: 256 × 1 MiB). + let bytes = many_channels(4096, 1, 65, false, dwab); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&channels, usize::MAX), &never).unwrap(); + assert_eq!(read.planes, oracle(&bytes, 0, 0.0)); +} + +#[test] +fn a_chunk_declaring_more_bytes_than_it_holds_is_refused_before_the_crate_reads_it() { + // A one-pixel-wide part in 4096 × 16 tiles: each chunk holds 16 pixels, but the `exr` crate + // would allocate whatever size up to a whole tile (256 KiB) a chunk declares. + let part = layer(None, (0, 0), (1, 32), &["R"], false, Compression::ZIP1); + let part = + Layer::new((1, 32), LayerAttributes::default(), Encoding { blocks: Blocks::Tiles(Vec2(4096, 16)), ..part.encoding }, part.channel_data); + let good = file(vec![part], (1, 32)); + let table = table_at(&good, 2); + let chunk = u64::from_le_bytes(good[table..table + 8].try_into().unwrap()) as usize; + assert!(indexed(&good).chunks(0).all(|c| (c.width, c.height) == (1, 16))); + for size in [4096 * 16 * 4 - 1, -1i32] { + let mut bytes = good.clone(); + // (tile column, row, level x and y, then the size) + bytes[chunk + 16..chunk + 20].copy_from_slice(&size.to_le_bytes()); + let index = indexed(&bytes); + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &never); + assert!(matches!(&got, Err(Error::Malformed(m)) if m.starts_with("a chunk declaring")), "size {size}: {got:?}"); + } +} + +#[test] +fn a_chunk_naming_another_part_is_refused() { + use super::decode_tests::mixed_file; + // The flat part's first chunk names the deep part. + let (mut bytes, offsets) = mixed_file(false, false); + bytes[offsets[0][0]..offsets[0][0] + 4].copy_from_slice(&1i32.to_le_bytes()); + let index = indexed(&bytes); + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &never); + assert!(matches!(&got, Err(Error::Malformed(m)) if m.contains("another part")), "{got:?}"); +} + +#[test] +fn a_failed_or_cancelled_read_still_reports_how_far_it_got() { + // Row 400's chunk of 600 claims another row (see the damaged-chunk test). + let mut bytes = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let at = bytes.len() - (600 - 400) * 8200; + bytes[at..at + 4].copy_from_slice(&7i32.to_le_bytes()); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let request = Request { workers: Some(4), ..Request::new(&channels, usize::MAX) }; + let mut stats = Stats::default(); + let got = read_bands_with_stats(&mut Cursor::new(&bytes[..]), &index, &request, &never, &mut |_| {}, &mut stats); + assert!(matches!(got, Err(Error::Malformed(_))), "{got:?}"); + assert_eq!(stats.lines, 400, "the lines delivered before the damaged chunk"); + assert!(stats.chunks[0] > 400 && stats.bytes >= 400 * 8200, "{stats:?}"); + // Called off after the first band. + let stop = Cell::new(false); + let got = read_bands_with_stats(&mut Cursor::new(&bytes[..]), &index, &request, &|| stop.get(), &mut |_| stop.set(true), &mut stats); + assert_eq!(got.err(), Some(Error::Cancelled)); + assert!(stats.lines > 0 && stats.lines < 600 && stats.chunks[0] > 0, "{stats:?}"); +} + +#[test] +fn the_index_lists_the_chunks_of_the_full_resolution_level() { + use super::decode_tests::mixed_file; + use exr::math::RoundingMode; + use exr::prelude::Levels; + let sizes: Vec = exr::meta::mip_map_levels(RoundingMode::Down, Vec2(9, 7)).map(|(_, size)| size.area()).collect(); + let bytes = + tiled_levels(Levels::Mip { rounding_mode: RoundingMode::Down, level_data: sizes.iter().map(|n| FlatSamples::F32(vec![1.0; *n])).collect() }); + let index = indexed(&bytes); + let chunks: Vec = index.chunks(0).collect(); + let tiles: Vec<(usize, usize, usize, usize)> = chunks.iter().map(|c| (c.x, c.y, c.width, c.height)).collect(); + assert_eq!(tiles, [(0, 0, 4, 4), (4, 0, 4, 4), (8, 0, 1, 4), (0, 4, 4, 3), (4, 4, 4, 3), (8, 4, 1, 3)]); + assert!(chunks.iter().all(|c| c.len > 0 && c.offset > 0 && c.offset + c.len <= bytes.len() as u64)); + assert_eq!(index.chunks(1).count(), 0, "no such part"); + let (mixed, offsets) = mixed_file(true, false); + let index = indexed(&mixed); + assert_eq!(index.chunks(0).count(), 0, "a deep part"); + assert_eq!(index.chunks(1).map(|c| (c.offset as usize, c.y, c.height)).collect::>(), [(offsets[1][0], 0, 1), (offsets[1][1], 1, 1)]); +} + +#[test] +fn htj2k_compression_is_its_own_error() { + let mut bytes = file(vec![layer(None, (0, 0), (4, 4), &["R"], false, Compression::ZIP1)], (4, 4)); + let tag = b"compression\0compression\0"; + let at = bytes.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len() + 4; + for code in [10u8, 11] { + bytes[at] = code; + let got = Index::build(&mut Cursor::new(&bytes[..]), &Limits::default(), &never); + assert_eq!(got.err(), Some(Error::UnsupportedCompression("HTJ2K".into())), "code {code}"); + } +} + +#[test] +fn the_display_window_may_have_its_own_pixel_limit() { + // A 16 × 16 data window (overscan) over an 8 × 8 display window. + let bytes = file(vec![layer(None, (-4, -4), (16, 16), &["R"], false, Compression::ZIP1)], (8, 8)); + let limits = Limits { max_pixels: 256, ..Limits::default() }; + let build = |display| Index::build_with_display_limit(&mut Cursor::new(&bytes[..]), &limits, display, &never); + assert!(build(64).is_ok()); + assert!(matches!(&build(63), Err(Error::LimitExceeded(m)) if m.contains("display window")), "{:?}", build(63)); + // The data windows stay bound by `max_pixels`. + let tight = Limits { max_pixels: 255, ..Limits::default() }; + let got = Index::build_with_display_limit(&mut Cursor::new(&bytes[..]), &tight, 1 << 20, &never); + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("part 0")), "{got:?}"); + // `build` holds both to `max_pixels`. + assert!(Index::build(&mut Cursor::new(&bytes[..]), &Limits { max_pixels: 63, ..Limits::default() }, &never).is_err()); + assert!(Index::build(&mut Cursor::new(&bytes[..]), &limits, &never).is_ok()); +} + +#[test] +fn rows_and_band_positions_count_from_the_display_window_s_corner() { + // Display window 12 × 9 at (10, 20); the data window 8 × 5 at (11, 22), i.e. (1, 2) inside it. + let bytes = file_at(vec![layer(None, (11, 22), (8, 5), &["Y"], false, Compression::ZIP1)], ((10, 20), (12, 9))); + let index = indexed(&bytes); + assert_eq!((index.display().x, index.display().y), (10, 20)); + let whole = oracle(&bytes, 0, -1.0)[0].clone(); + let request = Request { rows: Some(3..6), fill: &[-1.0], ..Request::new(&[(0, 0)], usize::MAX) }; + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never).unwrap(); + for row in 0..9 { + let got = &read.planes[0][row * 12..row * 12 + 12]; + if (3..6).contains(&row) { + assert_eq!(got, &whole[row * 12..row * 12 + 12], "row {row}"); + assert!(got.iter().any(|v| *v != -1.0), "row {row} has samples"); + } else { + assert_eq!(got, [-1.0; 12], "row {row}"); + } + } + let mut placed = Vec::new(); + read_bands(&mut Cursor::new(&bytes[..]), &index, &request, &never, &mut |b: Band| placed.push((b.x, b.y, b.width, b.height))).unwrap(); + assert_eq!(placed, [(1, 3, 8, 1), (1, 4, 8, 1), (1, 5, 8, 1)]); +} + +#[test] +fn bands_are_bounded_by_the_rows_they_deliver_and_planes_by_the_display_window() { + let bytes = file(vec![layer(None, (0, 0), (16, 16), &["R", "G"], false, Compression::ZIP1)], (16, 16)); + let index = indexed(&bytes); + // Rows 4..8 of two channels: 4 × 16 × 2 f32, 512 bytes; the whole planes are 2048. + let rows = |max_bytes| Request { rows: Some(4..8), ..Request::new(&[(0, 0), (0, 1)], max_bytes) }; + let mut count = 0; + read_bands(&mut Cursor::new(&bytes[..]), &index, &rows(512), &never, &mut |_| count += 1).unwrap(); + assert_eq!(count, 8); + let got = read_bands(&mut Cursor::new(&bytes[..]), &index, &rows(511), &never, &mut |_| {}); + assert!(matches!(got, Err(Error::LimitExceeded(_))), "{got:?}"); + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &rows(512), &never); + assert!(matches!(got, Err(Error::LimitExceeded(_))), "read_planes allocates the whole planes: {got:?}"); + // At level 2 rows 4..8 hold one row on the grid (row 4): 4 × 2 f32. + let reduced = |max_bytes| Request { level: 2, ..rows(max_bytes) }; + read_bands(&mut Cursor::new(&bytes[..]), &index, &reduced(32), &never, &mut |_| {}).unwrap(); + assert!(read_bands(&mut Cursor::new(&bytes[..]), &index, &reduced(31), &never, &mut |_| {}).is_err()); +} + +#[test] +fn a_header_declaring_more_chunks_than_the_bound_is_refused_before_the_tables_are_read() { + // One column of 2^24 + 1 rows, one row a chunk: the file can't hold its table, but the count + // alone is refused first. + let mut bytes = file(vec![layer(None, (0, 0), (1, 1), &["R"], false, Compression::Uncompressed)], (1, 1)); + patch_box(&mut bytes, "dataWindow", [0, 0, 0, 1 << 24]); + patch_box(&mut bytes, "displayWindow", [0, 0, 0, 1 << 24]); + let got = Index::build(&mut Cursor::new(&bytes[..]), &Limits::none(), &never); + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("chunks")), "{got:?}"); +} + +/// A source that fails with `kind` once `after` bytes have been read. +struct Failing<'a> { + inner: Cursor<&'a [u8]>, + after: u64, + kind: std::io::ErrorKind, +} + +impl Read for Failing<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.inner.position() >= self.after { + return Err(std::io::Error::new(self.kind, "the share went away")); + } + let room = (self.after - self.inner.position()) as usize; + let n = buf.len().min(room); + self.inner.read(&mut buf[..n]) + } +} + +impl Seek for Failing<'_> { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } +} + +#[test] +fn a_failing_source_is_an_io_error_and_a_short_file_is_malformed() { + let bytes = file(vec![layer(None, (0, 0), (8, 8), &["R"], false, Compression::ZIP1)], (8, 8)); + for after in [4u64, 40, 200] { + let mut source = Failing { inner: Cursor::new(&bytes[..]), after, kind: std::io::ErrorKind::Other }; + let got = Index::build(&mut source, &Limits::default(), &never); + assert!(matches!(got, Err(Error::Io(_))), "after {after}: {got:?}"); + let got = Index::build(&mut Cursor::new(&bytes[..after as usize]), &Limits::default(), &never); + assert!(matches!(got, Err(Error::Malformed(_))), "cut at {after}: {got:?}"); + } +} + +#[test] +fn a_read_called_off_while_workers_hold_chunks_stops() { + let bytes = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let stop = Cell::new(false); + let mut bands = 0usize; + let request = Request { workers: Some(2), ..Request::new(&channels, usize::MAX) }; + let got = read_bands(&mut Cursor::new(&bytes[..]), &index, &request, &|| stop.get(), &mut |_| { + bands += 1; + stop.set(true); + }); + assert_eq!(got.err(), Some(Error::Cancelled)); + assert!(bands > 0 && bands < 1200, "{bands} bands"); +} + +#[test] +fn a_part_written_bottom_up_arrives_bottom_up() { + let mut part = layer(None, (0, 0), (8, 12), &["Y"], false, Compression::ZIP1); + part.encoding.line_order = LineOrder::Decreasing; + let bytes = file(vec![part], (8, 12)); + let index = indexed(&bytes); + let mut rows = Vec::new(); + let mut plane = vec![f32::NAN; 96]; + read_bands(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &never, &mut |b: Band| { + rows.push(b.y); + plane[b.y * 8..(b.y + b.height) * 8].copy_from_slice(&b.samples); + }) + .unwrap(); + assert_eq!(rows, (0..12).rev().collect::>(), "file order"); + assert_eq!(vec![plane], oracle(&bytes, 0, 0.0)); +} + +#[test] +fn a_tiled_file_with_rip_levels_is_read_from_its_largest_level_only() { + use exr::image::RipMaps; + use exr::math::RoundingMode; + use exr::prelude::Levels; + let (w, h) = (9usize, 7usize); + let sizes: Vec = exr::meta::rip_map_levels(RoundingMode::Down, Vec2(w, h)).map(|(_, size)| size.area()).collect(); + let level_count = Vec2(exr::meta::compute_level_count(RoundingMode::Down, w), exr::meta::compute_level_count(RoundingMode::Down, h)); + assert!(sizes.len() > 1); + let map_data = sizes + .iter() + .enumerate() + .map(|(level, n)| FlatSamples::F32(if level == 0 { (0..*n).map(|i| value(i, 0)).collect() } else { vec![1e9; *n] })) + .collect(); + let bytes = tiled_levels(Levels::Rip { rounding_mode: RoundingMode::Down, level_data: RipMaps { map_data, level_count } }); + let index = indexed(&bytes); + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &never).unwrap(); + assert_eq!(read.planes[0], (0..w * h).map(|i| value(i, 0)).collect::>()); + assert_eq!(read.stats.chunks[0], 6); +} + +#[test] +fn rows_an_odd_data_window_and_a_level_together_on_several_threads() { + // A 37 × 29 data window at (3, 5) in a 50 × 40 display window, one row a chunk. + let bytes = file(vec![layer(None, (3, 5), (37, 29), &["R", "G"], false, Compression::ZIP1)], (50, 40)); + let index = indexed(&bytes); + let whole = oracle(&bytes, 0, 9.0); + for level in [0u32, 1, 2] { + let stride = 1usize << level; + let request = Request { rows: Some(7..33), level, fill: &[9.0, 9.0], workers: Some(4), ..Request::new(&[(0, 1), (0, 0)], usize::MAX) }; + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never).unwrap(); + for (slot, channel) in [(0, 1), (1, 0)] { + let expected: Vec = (0..40) + .step_by(stride) + .flat_map(|y| (0..50).step_by(stride).map(move |x| (y, x))) + .map(|(y, x)| if (7..33).contains(&y) { whole[channel][y * 50 + x] } else { 9.0 }) + .collect(); + assert_eq!(read.planes[slot], expected, "level {level} slot {slot}"); + } + } +} + +#[test] +fn a_damaged_chunk_in_the_middle_ends_the_read_after_the_bands_before_it() { + // 600 uncompressed chunks of 8200 bytes (y, size, 2 × 1024 f32), the last at the file's end: + // row 400's chunk claims another row. The read spans several pieces and threads. + let mut bytes = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let at = bytes.len() - (600 - 400) * 8200; + assert_eq!(&bytes[at..at + 4], &400i32.to_le_bytes()); + bytes[at..at + 4].copy_from_slice(&7i32.to_le_bytes()); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let mut reached = [0usize; 2]; + let request = Request { workers: Some(4), ..Request::new(&channels, usize::MAX) }; + let got = read_bands(&mut Cursor::new(&bytes[..]), &index, &request, &never, &mut |b: Band| { + assert_eq!(b.y, reached[b.slot]); + reached[b.slot] = b.y + b.height; + }); + assert!(matches!(got, Err(Error::Malformed(_))), "{got:?}"); + assert_eq!(reached, [400, 400], "every row before the damaged chunk, nothing after it"); +} + +#[test] +fn a_chunk_that_is_not_the_block_its_table_entry_stands_for_is_refused() { + // Scan lines: the entries of rows 0 and 1 swapped; reading row 0 fetches row 1's chunk. + let mut bytes = file(vec![layer(None, (0, 0), (8, 16), &["Y"], false, Compression::ZIP1)], (8, 16)); + let table = table_at(&bytes, 16); + let (a, b) = (bytes[table..table + 8].to_vec(), bytes[table + 8..table + 16].to_vec()); + bytes[table..table + 8].copy_from_slice(&b); + bytes[table + 8..table + 16].copy_from_slice(&a); + let index = indexed(&bytes); + let request = Request { rows: Some(0..1), ..Request::new(&[(0, 0)], usize::MAX) }; + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never); + assert!(matches!(got, Err(Error::Malformed(_))), "{got:?}"); + // Mip-mapped tiles: the first full-resolution tile's entry points at a smaller level's tile. + use exr::math::RoundingMode; + use exr::prelude::Levels; + let sizes: Vec = exr::meta::mip_map_levels(RoundingMode::Down, Vec2(9, 7)).map(|(_, size)| size.area()).collect(); + let mut mip = + tiled_levels(Levels::Mip { rounding_mode: RoundingMode::Down, level_data: sizes.iter().map(|n| FlatSamples::F32(vec![1.0; *n])).collect() }); + let table = table_at(&mip, 6 + sizes.len() - 1); + let smaller = mip[table + 6 * 8..table + 7 * 8].to_vec(); + mip[table..table + 8].copy_from_slice(&smaller); + let index = indexed(&mip); + let got = read_planes(&mut Cursor::new(&mip[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &never); + assert!(matches!(got, Err(Error::Malformed(_))), "{got:?}"); +} + +#[test] +fn the_decoded_bytes_in_flight_stay_within_the_budget_however_well_the_file_compresses() { + // A flat colour in ZIP1 lines: each 1024-pixel line of two f32 channels compresses to a few + // dozen bytes but decodes to 8 KiB (and 8 KiB of bands), so a 256 KiB piece would hold + // thousands of them. + let (w, h) = (1024usize, 600usize); + let list = vec![AnyChannel::new("R", FlatSamples::F32(vec![0.25; w * h])), AnyChannel::new("G", FlatSamples::F32(vec![0.5; w * h]))]; + let encoding = Encoding { compression: Compression::ZIP1, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; + let bytes = file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let budget = 64 << 10; + let mut rows = 0usize; + let request = Request { workers: Some(4), ..Request::new(&channels, usize::MAX) }; + let mut sink = |b: Band| { + assert!(b.samples.iter().all(|v| *v == 0.25 || *v == 0.5)); + rows += b.height; + }; + let stats = super::seek::read_bands_within(&mut Cursor::new(&bytes[..]), &index, &request, &never, &mut sink, budget).unwrap(); + assert_eq!(rows, 2 * h); + assert!(stats.bytes < 64 << 10, "{} bytes: well compressed", stats.bytes); + assert!(stats.in_flight > 0 && stats.in_flight <= budget, "{} decoded bytes in flight", stats.in_flight); +} + +#[test] +fn cancel_is_polled_before_each_chunk_reaches_the_sink() { + // Decoded on the calling thread, the first piece's ~30 chunks are ready at once; a cancel + // the sink raises after the first chunk's two bands stops the rest. + let bytes = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let stop = Cell::new(false); + let mut bands = 0usize; + let request = Request { workers: Some(0), ..Request::new(&channels, usize::MAX) }; + let got = read_bands(&mut Cursor::new(&bytes[..]), &index, &request, &|| stop.get(), &mut |_| { + bands += 1; + stop.set(true); + }); + assert_eq!(got.err(), Some(Error::Cancelled)); + assert_eq!(bands, 2, "one chunk (both channels), nothing after the cancel"); +} + +#[test] +fn a_chunk_offset_into_the_headers_is_outside_the_chunk_area() { + let mut bytes = file(vec![layer(None, (0, 0), (8, 16), &["Y"], false, Compression::ZIP1)], (8, 16)); + let table = table_at(&bytes, 16); + bytes[table..table + 8].copy_from_slice(&8u64.to_le_bytes()); + let index = indexed(&bytes); + assert_eq!(index.chunks(0).next().map(|c| c.len), Some(0)); + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &never); + assert!(matches!(&got, Err(Error::Malformed(m)) if m.contains("outside the chunk area")), "{got:?}"); +} + +/// A single-part scan-line DWA file of `w × h` with these half channels (a ramp each). +fn dwa_file(compression: Compression, (w, h): (usize, usize), names: &[&str], tiles: bool) -> Vec { + use exr::prelude::f16; + let list: Vec> = names + .iter() + .enumerate() + .map(|(k, n)| AnyChannel::new(*n, FlatSamples::F16((0..w * h).map(|i| f16::from_f32(((i % w) + k) as f32 / 64.0)).collect()))) + .collect(); + let blocks = if tiles { Blocks::Tiles(Vec2(16, 16)) } else { Blocks::ScanLines }; + let encoding = Encoding { compression, blocks, line_order: LineOrder::Increasing }; + file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)) +} + +/// `bytes` with DWA counter `field` (0: version … 9: DC count) of the first chunk set to `value`. +fn with_dwa_counter(bytes: &[u8], field: usize, value: u64) -> Vec { + let index = indexed(bytes); + let chunk = index.chunks(0).next().unwrap(); + let at = chunk.offset as usize; + // (y, then the payload size: compressed, so it's no raw copy of the 64 × 32 half block) + assert_ne!(i32::from_le_bytes(bytes[at + 4..at + 8].try_into().unwrap()), 64 * 32 * 2); + let mut out = bytes.to_vec(); + out[at + 8 + 8 * field..at + 16 + 8 * field].copy_from_slice(&value.to_le_bytes()); + out +} + +/// Every reader of the crate refuses `bytes` as damaged, and none aborts. +fn refused_by_every_reader(bytes: &[u8], what: &str) { + use crate::decode::{Error as DecodeError, decode_display_part, decode_part}; + let index = indexed(bytes); + let got = read_planes(&mut Cursor::new(bytes), &index, &Request::new(&[(0, 0)], usize::MAX), &never); + assert!(matches!(&got, Err(Error::Malformed(m)) if m.contains("DWA")), "seek, {what}: {got:?}"); + let got = decode_display_part(bytes, 0, &|_| true, &|_| 0.0, &Limits::default()).map(|_| ()); + assert!(matches!(&got, Err(DecodeError::Malformed(m)) if m.contains("DWA")), "decode_display_part, {what}: {got:?}"); + let got = decode_part(bytes, 0, &|_| true, &Limits::default()).map(|_| ()); + assert!(matches!(&got, Err(DecodeError::Malformed(m)) if m.contains("DWA")), "decode_part, {what}: {got:?}"); + let got = crate::stream::Decoder::new(Cursor::new(bytes), &never).and_then(|mut d| { + while d.next_band(&never)?.is_some() {} + Ok(()) + }); + assert!(matches!(&got, Err(DecodeError::Malformed(m)) if m.contains("DWA")), "stream, {what}: {got:?}"); +} + +#[test] +fn a_dwa_chunk_declaring_2_to_the_44_dc_values_is_refused_not_an_abort() { + // The case that aborted the process: DWAA 64 × 32, one half channel R, DC count 2^44. + let bytes = with_dwa_counter(&dwa_file(Compression::DWAA(None), (64, 32), &["R"], false), 9, 1 << 44); + refused_by_every_reader(&bytes, "DC count 2^44"); +} + +#[test] +fn a_dwa_chunk_just_above_the_data_window_is_checked_as_the_block_the_decoder_rounds_it_into() { + // The `exr` crate divides a scan line's offset from the data window toward zero, so a chunk + // at y = -1 (DWAA, 32 lines) or -255 (DWAB, 256 lines) becomes block 0 and is decompressed. + use crate::decode::{Error as DecodeError, decode_display_part, decode_part}; + for (compression, y) in [(Compression::DWAA(None), -1i32), (Compression::DWAA(None), -31), (Compression::DWAB(None), -255)] { + let mut bytes = with_dwa_counter(&dwa_file(compression, (64, 32), &["R"], false), 9, 1 << 40); + let at = indexed(&bytes).chunks(0).next().unwrap().offset as usize; + bytes[at..at + 4].copy_from_slice(&y.to_le_bytes()); + let got = decode_part(&bytes, 0, &|_| true, &Limits::default()).map(|_| ()); + assert!(matches!(&got, Err(DecodeError::Malformed(m)) if m.contains("DWA")), "decode_part, {compression:?} y {y}: {got:?}"); + let got = decode_display_part(&bytes, 0, &|_| true, &|_| 0.0, &Limits::default()).map(|_| ()); + assert!(matches!(&got, Err(DecodeError::Malformed(m)) if m.contains("DWA")), "decode_display_part, {compression:?} y {y}: {got:?}"); + } +} + +#[test] +fn a_dwa_chunk_the_scan_cannot_read_is_refused_not_left_to_the_decoder() { + use crate::decode::{Error as DecodeError, decode_part}; + let good = dwa_file(Compression::DWAA(None), (64, 32), &["R"], false); + let table = table_at(&good, 1); + // The entry points past the end of the file, and into the last bytes of it. + for offset in [good.len() as u64 + 100, good.len() as u64 - 6] { + let mut bytes = good.clone(); + bytes[table..table + 8].copy_from_slice(&offset.to_le_bytes()); + let got = decode_part(&bytes, 0, &|_| true, &Limits::default()).map(|_| ()); + assert!(matches!(&got, Err(DecodeError::Malformed(m)) if m.contains("DWA")), "offset {offset}: {got:?}"); + } +} + +#[test] +fn a_chunk_declaring_a_small_payload_before_padding_is_held_to_what_the_payload_can_hold() { + // A 1 × 1 PIZ file patched to 16 Mi pixels wide (a 64 MiB block) with 100 KiB of padding + // after its one chunk: the gap to the file's end could hold the block at 1024 : 1, the few + // dozen bytes the chunk declares can't. + let mut bytes = file(vec![layer(None, (0, 0), (1, 1), &["R"], false, Compression::PIZ)], (1, 1)); + patch_box(&mut bytes, "dataWindow", [0, 0, (16 << 20) - 1, 0]); + bytes.extend(std::iter::repeat_n(0u8, 100 << 10)); + let limits = Limits { max_ratio: 1024, ..Limits::none() }; + let index = Index::build(&mut Cursor::new(&bytes[..]), &limits, &never).unwrap(); + assert_eq!(index.check_blocks(), Ok(()), "the gap is enough"); + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], 1 << 30), &never); + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("can hold")), "{got:?}"); +} + +#[test] +fn every_dwa_counter_the_inflater_sizes_by_is_bounded_by_the_block() { + for compression in [Compression::DWAA(None), Compression::DWAB(None)] { + // (fields: 1 unknown uncompressed size, 6 RLE uncompressed size, 7 RLE raw size, 8 AC + // count, 9 DC count; a value just over each bound, and a huge one) + let good = dwa_file(compression, (64, 32), &["R"], false); + // The block: 64 × 32 half, 4096 bytes; 8 × 4 DCT blocks of one channel. + for (field, over) in [(1, 4097u64), (6, 8193), (7, 4097), (8, 32 * 63 + 1), (9, 33)] { + for value in [over, 1 << 44, i64::MAX as u64] { + refused_by_every_reader(&with_dwa_counter(&good, field, value), &format!("{compression:?} counter {field} = {value}")); + } + } + } +} + +#[test] +fn valid_dwa_files_pass_the_guard() { + // Odd sizes (blocks padded to 8 × 8 for the DCT), lossy and lossless channels, one-row and + // one-column parts, scan lines and tiles. + for compression in [Compression::DWAA(None), Compression::DWAB(None)] { + for (size, names, tiles) in [ + ((1, 1), &["R"][..], false), + ((9, 7), &["B", "G", "R"][..], false), + ((1, 300), &["Y", "A"][..], false), + ((300, 1), &["R", "G", "B", "A", "Z"][..], false), + ((64, 32), &["R"][..], false), + ((37, 41), &["R", "G", "B", "A"][..], true), + ] { + let bytes = dwa_file(compression, size, names, tiles); + let index = indexed(&bytes); + assert_eq!(index.check_blocks(), Ok(())); + let channels = channels_of(&index, 0); + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&channels, usize::MAX), &never); + assert_eq!(read.map(|r| r.planes).ok(), Some(oracle(&bytes, 0, 0.0)), "{compression:?} {size:?} {names:?} tiles {tiles}"); + assert!(crate::decode::decode_part(&bytes, 0, &|_| true, &Limits::default()).is_ok()); + if !tiles { + let mut stream = crate::stream::Decoder::new(Cursor::new(&bytes[..]), &never); + if let Ok(d) = stream.as_mut() { + while d.next_band(&never).unwrap().is_some() {} + } + } + } + } +} + +/// A source that panics when anything at or past `chunks` (where the chunks start) is read: a +/// read that a check should have refused fails fast instead of allocating. +#[cfg(target_pointer_width = "64")] +struct NoChunks<'a> { + inner: Cursor<&'a [u8]>, + chunks: u64, +} + +#[cfg(target_pointer_width = "64")] +impl Read for NoChunks<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + assert!(self.inner.position() < self.chunks, "a chunk was read"); + self.inner.read(buf) + } +} + +#[cfg(target_pointer_width = "64")] +impl Seek for NoChunks<'_> { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } +} + +// (budgets over 4 GiB: a 64-bit usize) +#[cfg(target_pointer_width = "64")] +#[test] +fn a_tiny_chunk_declaring_a_gigabyte_block_is_refused_before_it_is_read() { + // A 1 × 1 file whose data window is patched to 2^30 - 2 pixels wide: one row of one f32 + // channel is a 4 GiB block over a chunk of a few dozen bytes. Within an app's 8 GiB budget + // the block cap allows it; the bytes can't hold it. + let limits = Limits { max_ratio: Limits::default().max_ratio, ..Limits::none() }; + for compression in [Compression::PIZ, Compression::DWAB(None), Compression::ZIP16] { + let mut bytes = file(vec![layer(None, (0, 0), (1, 1), &["R"], false, compression)], (1, 1)); + patch_box(&mut bytes, "dataWindow", [0, 0, (1 << 30) - 3, 0]); + let index = Index::build(&mut Cursor::new(&bytes[..]), &limits, &never).unwrap(); + let chunk = index.chunks(0).next().unwrap(); + assert!(chunk.len < 200 && chunk.width == (1 << 30) - 2, "{chunk:?}"); + let got = index.check_blocks(); + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("can hold")), "{compression:?}: {got:?}"); + let mut source = NoChunks { inner: Cursor::new(&bytes[..]), chunks: chunk.offset }; + let got = read_planes(&mut source, &index, &Request::new(&[(0, 0)], 8 << 30), &never); + assert!(matches!(&got, Err(Error::LimitExceeded(m)) if m.contains("can hold")), "{compression:?}: {got:?}"); + } +} + +#[test] +fn black_frames_that_compress_extremely_well_still_read() { + // 4096 × 256 × 4 half channels of zero in DWAB (one 8 MiB block) and of f32 in ZIP16. + use exr::prelude::f16; + let (w, h) = (4096usize, 256usize); + for (compression, half) in [(Compression::DWAB(None), true), (Compression::ZIP16, false)] { + let list: Vec> = ["R", "G", "B", "A"] + .iter() + .map(|n| AnyChannel::new(*n, if half { FlatSamples::F16(vec![f16::ZERO; w * h]) } else { FlatSamples::F32(vec![0.0; w * h]) })) + .collect(); + let encoding = Encoding { compression, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; + let bytes = file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)); + let index = indexed(&bytes); + let smallest = index.chunks(0).map(|c| c.len).min().unwrap(); + assert_eq!(index.check_blocks(), Ok(()), "{compression:?}, chunks from {smallest} bytes"); + let channels = channels_of(&index, 0); + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&channels, usize::MAX), &never).unwrap(); + assert!(read.planes.iter().all(|p| p.len() == w * h && p.iter().all(|v| *v == 0.0)), "{compression:?}"); + } +} + +#[test] +fn the_ratio_bound_allows_a_mebibyte_more_and_four_times_as_much_for_dwa() { + use exr::prelude::f16; + let build = |bytes: &[u8], max_ratio| Index::build(&mut Cursor::new(bytes), &Limits { max_ratio, ..Limits::default() }, &never).unwrap(); + // A black ZIP16 block of 512 × 16 f32 RGBA is 128 KiB over a few hundred bytes: refused at + // one byte per byte but for the 1 MiB every chunk is allowed besides. + let zip = file(vec![layer(None, (0, 0), (512, 16), &["R", "G", "B", "A"], false, Compression::ZIP16)], (512, 16)); + let list: Vec> = + ["R", "G", "B", "A"].iter().map(|n| AnyChannel::new(*n, FlatSamples::F32(vec![0.0; 512 * 16]))).collect(); + let encoding = Encoding { compression: Compression::ZIP16, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; + let black = file(vec![Layer::new((512, 16), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (512, 16)); + for bytes in [&zip, &black] { + let index = build(bytes, 1); + assert!(index.chunks(0).all(|c| c.len < 128 << 10)); + assert_eq!(index.check_blocks(), Ok(())); + } + // A black DWAB block of 4096 × 256 half RGBA (8 MiB): with a ratio that lets its bytes hold + // between a quarter of the block and the block (less the 1 MiB), only the fourfold DWA + // allowance admits it. + let list: Vec> = + ["R", "G", "B", "A"].iter().map(|n| AnyChannel::new(*n, FlatSamples::F16(vec![f16::ZERO; 4096 * 256]))).collect(); + let encoding = Encoding { compression: Compression::DWAB(None), blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; + let dwab = file(vec![Layer::new((4096, 256), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (4096, 256)); + let len = indexed(&dwab).chunks(0).next().unwrap().len; + let ratio = (5u64 << 20) / len; // len × ratio ≈ 5 MiB: 8 MiB > that + 1 MiB, but ≤ 4 × that + 1 MiB + let index = build(&dwab, ratio); + assert_eq!(index.check_blocks(), Ok(()), "{len}-byte chunk, ratio {ratio}"); + assert!(matches!(build(&dwab, ratio / 8).check_blocks(), Err(Error::LimitExceeded(_)))); +} + +#[cfg(target_pointer_width = "64")] +#[test] +fn memory_the_system_cannot_give_is_out_of_memory_not_a_limit() { + // A display window of (2^30 - 2)^2 pixels: one f32 plane is 4 EiB, which no system maps, so + // the reservation fails at once (nothing is touched). + let mut bytes = file(vec![layer(None, (0, 0), (1, 1), &["R"], false, Compression::ZIP1)], (1, 1)); + patch_box(&mut bytes, "displayWindow", [0, 0, (1 << 30) - 3, (1 << 30) - 3]); + let index = Index::build(&mut Cursor::new(&bytes[..]), &Limits::none(), &never).unwrap(); + let got = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request::new(&[(0, 0)], usize::MAX), &never); + assert!(matches!(got, Err(Error::OutOfMemory(_))), "{got:?}"); +} + +#[test] +#[allow(clippy::reversed_empty_ranges)] // (reversed ranges are what is tested) +fn empty_reversed_and_extreme_row_ranges_read_without_overflow() { + // (alignment to a level's grid near the ends of i64 overflowed before the rows were clamped) + let bytes = file(vec![layer(None, (0, 0), (9, 7), &["R"], false, Compression::ZIP1)], (9, 7)); + let index = indexed(&bytes); + let whole = oracle(&bytes, 0, 0.0)[0].clone(); + for level in 0..=16u32 { + for rows in [i64::MAX..i64::MAX, i64::MIN..i64::MIN, i64::MAX - 1..i64::MAX, 5..2, i64::MAX..i64::MIN, -3..-1, 7..9] { + let request = Request { rows: Some(rows.clone()), level, ..Request::new(&[(0, 0)], usize::MAX) }; + let mut bands = 0; + read_bands(&mut Cursor::new(&bytes[..]), &index, &request, &never, &mut |_| bands += 1).unwrap(); + assert_eq!(bands, 0, "{rows:?} at level {level} holds no row"); + assert_eq!(index.estimate(&request).unwrap().chunks, 0); + } + // Everything, from one end of i64 to the other. + let request = Request { rows: Some(i64::MIN..i64::MAX), level, ..Request::new(&[(0, 0)], usize::MAX) }; + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never).unwrap(); + let stride = 1usize << level; + let expected: Vec = + (0..7).step_by(stride).flat_map(|y| (0..9).step_by(stride).map(move |x| (y, x))).map(|(y, x)| whole[y * 9 + x]).collect(); + assert_eq!(read.planes[0], expected, "level {level}"); + } +} + +#[test] +fn a_sink_can_stop_the_read_with_its_own_error() { + // 600 chunks on 4 threads: the sink refuses its third band. Nothing reaches it after that, the + // read returns (no hang) with the sink's error unchanged, and the counts say how far it got. + let bytes = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let index = indexed(&bytes); + let channels = channels_of(&index, 0); + let request = Request { workers: Some(4), ..Request::new(&channels, usize::MAX) }; + let mut calls = 0usize; + let mut stats = Stats::default(); + let got = read_bands_try( + &mut Cursor::new(&bytes[..]), + &index, + &request, + &never, + &mut |_: Band| { + calls += 1; + if calls >= 3 { Err("the tile store is full") } else { Ok(()) } + }, + &mut stats, + ); + assert_eq!(got, Err(Stop::Sink("the tile store is full"))); + assert_eq!(calls, 3, "no band after the sink's error"); + assert!(stats.lines >= 1 && stats.lines < 600 && stats.bytes > 0, "{stats:?}"); + // A sink that never fails reads everything, as `read_bands` does. + let mut bands = 0usize; + let mut sink = |_: Band| -> std::result::Result<(), ()> { + bands += 1; + Ok(()) + }; + read_bands_try(&mut Cursor::new(&bytes[..]), &index, &request, &never, &mut sink, &mut stats).unwrap(); + assert_eq!((bands, stats.lines), (1200, 600)); + // The read's own errors come back as such. + let mut damaged = bytes.clone(); + let at = damaged.len() - 200 * 8200; + damaged[at..at + 4].copy_from_slice(&7i32.to_le_bytes()); + let index = indexed(&damaged); + let got = read_bands_try(&mut Cursor::new(&damaged[..]), &index, &request, &never, &mut |_| Ok::<(), ()>(()), &mut stats); + assert!(matches!(got, Err(Stop::Read(Error::Malformed(_)))), "{got:?}"); +} + +/// The planes of `bands` (grouped or not) for `slots` slots of `w × h`, de-interleaved. +fn planes_of(bands: &[Band], slots: usize, (w, h): (usize, usize)) -> Vec> { + let mut planes = vec![vec![-1e30; w * h]; slots]; + for b in bands { + assert_eq!(b.samples.len(), b.width * b.height * b.values_per_pixel); + for r in 0..b.height { + for c in 0..b.width { + for k in 0..b.values_per_pixel { + planes[b.slot + k][(b.y + r) * w + b.x + c] = b.samples[(r * b.width + c) * b.values_per_pixel + k]; + } + } + } + } + planes +} + +#[test] +fn grouped_slots_arrive_interleaved_as_one_band_per_block() { + for tiles in [false, true] { + let bytes = file(vec![layer(None, (0, 0), (13, 11), &["R", "G", "B", "A", "Z"], tiles, Compression::ZIP1)], (13, 11)); + let index = indexed(&bytes); + // Stored A B G R Z: ask for R G B A as a group, Z alone, and G again in a group of one. + let names: Vec<&str> = index.parts()[0].channels.iter().map(|c| c.name.as_str()).collect(); + let at = |n: &str| (0, names.iter().position(|m| *m == n).unwrap()); + let channels = [at("R"), at("G"), at("B"), at("A"), at("Z"), at("G")]; + for (rows, level) in [(None, 0u32), (Some(3..9), 0), (None, 1)] { + let base = Request { rows: rows.clone(), level, ..Request::new(&channels, usize::MAX) }; + let mut single = Vec::new(); + read_bands(&mut Cursor::new(&bytes[..]), &index, &base, &never, &mut |b| single.push(b)).unwrap(); + let groups = [0..4, 5..6]; + let mut grouped = Vec::new(); + read_bands(&mut Cursor::new(&bytes[..]), &index, &Request { groups: &groups, ..base.clone() }, &never, &mut |b| grouped.push(b)).unwrap(); + assert!(single.iter().all(|b| b.values_per_pixel == 1)); + assert!(grouped.iter().all(|b| b.values_per_pixel == if b.slot == 0 { 4 } else { 1 }), "{tiles} {rows:?} {level}"); + assert_eq!(grouped.iter().filter(|b| b.slot == 0).count(), single.iter().filter(|b| b.slot == 0).count(), "one band per block"); + let size = level_size((13, 11), level); + assert_eq!(planes_of(&grouped, 6, size), planes_of(&single, 6, size), "tiles {tiles} rows {rows:?} level {level}"); + // `read_planes` ignores groups. + let with = read_planes(&mut Cursor::new(&bytes[..]), &index, &Request { groups: &groups, ..base.clone() }, &never).unwrap(); + assert_eq!(with, read_planes(&mut Cursor::new(&bytes[..]), &index, &base, &never).unwrap()); + } + } +} + +#[test] +fn groups_must_be_slots_of_one_part_each_in_one_group() { + let bytes = file( + vec![ + layer(Some("a"), (0, 0), (8, 8), &["R", "G"], false, Compression::ZIP1), + layer(Some("b"), (0, 0), (8, 8), &["Z"], false, Compression::ZIP1), + ], + (8, 8), + ); + let index = indexed(&bytes); + let channels = [(0, 0), (0, 1), (1, 0)]; + let read = |groups: &[std::ops::Range]| { + read_bands(&mut Cursor::new(&bytes[..]), &index, &Request { groups, ..Request::new(&channels, usize::MAX) }, &never, &mut |_| {}) + }; + assert!(matches!(read(&[1..3]), Err(Error::Unsupported(m)) if m.contains("spans parts"))); + for bad in [&[0..2, 1..2][..], &[2..4], &[1..1]] { + assert!(matches!(read(bad), Err(Error::Malformed(_))), "{bad:?}"); + } + assert!(read(&[0..2]).is_ok()); +} + +#[test] +fn the_estimate_covers_what_the_read_does() { + // A flat colour in ZIP16 (decodes to far more than it reads), lines of a ramp, and tiles. + let (w, h) = (1024usize, 600usize); + let list = vec![AnyChannel::new("R", FlatSamples::F32(vec![0.25; w * h])), AnyChannel::new("G", FlatSamples::F32(vec![0.5; w * h]))]; + let encoding = Encoding { compression: Compression::ZIP16, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; + let flat = file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)); + let ramp = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let tiled = file(vec![layer(None, (0, 0), (300, 200), &["R", "G", "B"], true, Compression::PIZ)], (300, 200)); + for bytes in [&flat, &ramp, &tiled] { + let index = indexed(bytes); + let channels = channels_of(&index, 0); + for (rows, level, workers) in [(None, 0u32, None), (Some(50..120), 0, Some(4)), (None, 1, Some(0))] { + let request = Request { rows: rows.clone(), level, workers, ..Request::new(&channels, usize::MAX) }; + let estimate = index.estimate(&request).unwrap(); + let read = read_planes(&mut Cursor::new(&bytes[..]), &index, &request, &never).unwrap(); + let what = format!("{rows:?} level {level}: {estimate:?} {:?}", read.stats); + assert_eq!(estimate.chunks, read.stats.chunks.iter().sum::(), "{what}"); + assert_eq!(estimate.compressed_bytes, read.stats.bytes, "{what}"); + assert!(estimate.working_bytes >= read.stats.in_flight, "{what}"); + let (ow, oh) = level_size((index.display().width as usize, index.display().height as usize), level); + assert_eq!(estimate.planes_bytes, (ow * oh * 4 * channels.len()) as u64, "{what}"); + // Measured from what is decoded: the largest chunk's block and bands (decoded, and + // as much again for scratch) fit in the working bytes. + let largest = decoded_per_chunk(bytes, &index, &request).into_iter().max().unwrap_or(0); + assert!(estimate.working_bytes >= 2 * largest, "{what}, largest chunk {largest}"); + } + } + // It refuses what the read refuses. + let index = indexed(&ramp); + assert!(matches!(index.estimate(&Request::new(&[(0, 0)], 1024)), Err(Error::LimitExceeded(_)))); + assert!(matches!(index.estimate(&Request::new(&[(0, 9)], usize::MAX)), Err(Error::Malformed(_)))); +} + +/// Per chunk of a read of part 0 of `bytes`: its decompressed block's bytes (all of the part's +/// channels over the chunk's pixels) plus the bytes of the bands it gave, as decoded. +fn decoded_per_chunk(bytes: &[u8], index: &Index, request: &Request) -> Vec { + let pixel_bytes: u64 = index.parts()[0].channels.iter().map(|c| if c.sample == crate::decode::SampleType::F16 { 2 } else { 4 }).sum(); + let mut bands_of: std::collections::BTreeMap = std::collections::BTreeMap::new(); + read_bands(&mut Cursor::new(bytes), index, request, &never, &mut |b: Band| { + assert_eq!(b.samples.len(), b.width * b.height * b.values_per_pixel, "exactly sized"); + assert_eq!(b.samples.capacity(), b.samples.len(), "no slack"); + *bands_of.entry(b.chunk).or_default() += 4 * b.samples.len() as u64; + }) + .unwrap(); + // The chunks a read fetches, in file order, as the bands number them. + let mut chunks: Vec = index.chunks(0).collect(); + chunks.sort_by_key(|c| c.offset); + let estimate = index.estimate(request).unwrap(); + let needed: Vec = chunks + .into_iter() + .filter(|c| { + let rows = request.rows.clone().unwrap_or(0..i64::MAX); + let stride = 1i64 << request.level; + (c.y as i64..(c.y + c.height) as i64).any(|r| rows.contains(&r) && r % stride == 0) + }) + .collect(); + assert_eq!(needed.len(), estimate.chunks); + needed.iter().enumerate().map(|(i, c)| (c.width * c.height) as u64 * pixel_bytes + bands_of.get(&i).copied().unwrap_or(0)).collect() +} + +#[test] +fn a_grouped_read_with_duplicates_keeps_one_chunk_in_flight_at_its_decoded_size() { + // 1024 × 64 RGBA f32 in ZIP16: 16-row blocks of 256 KiB. R, G, B, A and R again as one group: + // each block's band is 16 × 1024 × 5 values (320 KiB), so a chunk is 576 KiB decoded, over + // a 64 KiB budget: one at a time. + let bytes = file(vec![layer(None, (0, 0), (1024, 64), &["R", "G", "B", "A"], false, Compression::ZIP16)], (1024, 64)); + let index = indexed(&bytes); + let names: Vec<&str> = index.parts()[0].channels.iter().map(|c| c.name.as_str()).collect(); + let at = |n: &str| (0, names.iter().position(|m| *m == n).unwrap()); + let channels = [at("R"), at("G"), at("B"), at("A"), at("R")]; + let groups = [0..5]; + let request = Request { groups: &groups, workers: Some(4), ..Request::new(&channels, usize::MAX) }; + let decoded = decoded_per_chunk(&bytes, &index, &request); + assert_eq!(decoded, vec![(256 + 320) << 10; 4], "block and band of each chunk, as decoded"); + let budget = 64 << 10; + let mut bands = Vec::new(); + let stats = super::seek::read_bands_within(&mut Cursor::new(&bytes[..]), &index, &request, &never, &mut |b| bands.push(b), budget).unwrap(); + assert_eq!(stats.in_flight, (256 + 320) << 10, "one chunk at a time, counted at its decoded size"); + let estimate = super::seek::estimate_within(&index, &request, budget).unwrap(); + assert!(estimate.working_bytes >= 2 * ((256 + 320) << 10), "{estimate:?}"); + // The interleaved values, duplicates included, are those of per-channel reads. + let mut single = Vec::new(); + read_bands(&mut Cursor::new(&bytes[..]), &index, &Request::new(&channels, usize::MAX), &never, &mut |b| single.push(b)).unwrap(); + assert_eq!(planes_of(&bands, 5, (1024, 64)), planes_of(&single, 5, (1024, 64))); +} + +#[test] +fn bands_say_which_chunk_they_came_from_for_progress() { + // Tiles of 4 × 4 over 9 × 7 (six chunks), and one-row chunks read at level 2 over some rows. + let tiled = file(vec![layer(None, (0, 0), (9, 7), &["R", "G"], true, Compression::ZIP1)], (9, 7)); + let lines = file(vec![layer(None, (0, 0), (8, 16), &["Y"], false, Compression::ZIP1)], (8, 16)); + for (bytes, request) in [ + (&tiled, Request::new(&[(0, 0), (0, 1)], usize::MAX)), + (&lines, Request { rows: Some(3..14), level: 2, workers: Some(2), ..Request::new(&[(0, 0)], usize::MAX) }), + ] { + let index = indexed(bytes); + let estimate = index.estimate(&request).unwrap(); + let mut seen = Vec::new(); + read_bands(&mut Cursor::new(&bytes[..]), &index, &request, &never, &mut |b| seen.push(b.chunk)).unwrap(); + assert!(seen.windows(2).all(|w| w[0] <= w[1]), "in order: {seen:?}"); + seen.dedup(); + assert_eq!(seen, (0..estimate.chunks).collect::>(), "every chunk, numbered as the estimate counts"); + } +} + +#[test] +fn a_stop_s_source_is_the_read_error() { + use std::error::Error as _; + let read: Stop = Stop::Read(Error::Cancelled); + assert_eq!(read.source().map(|e| e.to_string()), Some(Error::Cancelled.to_string())); + assert!(Stop::Sink("full".to_string()).source().is_none()); +} diff --git a/crates/exr/src/stream.rs b/crates/exr/src/stream.rs index 8e69e534e9..c3d942e947 100644 --- a/crates/exr/src/stream.rs +++ b/crates/exr/src/stream.rs @@ -262,6 +262,9 @@ impl Decoder { } self.source.read_exact(bytes).map_err(invalid)?; } + // (a DWA chunk's counters can make the crate allocate terabytes: see `crate::dwa_guard`) + let lines = self.rows.min((self.info.height as usize).saturating_sub(row as usize)); + crate::dwa_guard::check_payload(header, (self.info.width as usize, lines), &packed).map_err(invalid)?; let chunk = Chunk { layer_index: 0, compressed_block: CompressedBlock::ScanLine(CompressedScanLineBlock { y_coordinate: y, compressed_pixels_le: packed }), diff --git a/crates/exr/src/zlib.rs b/crates/exr/src/zlib.rs new file mode 100644 index 0000000000..a38bd0b466 --- /dev/null +++ b/crates/exr/src/zlib.rs @@ -0,0 +1,795 @@ +//! A small DEFLATE encoder (RFC 1951) in a zlib wrapper (RFC 1950), written from the RFCs for the +//! ZIP-compressed OpenEXR chunks. +//! +//! Greedy LZ77 over a 32 KB window (hash chains of bounded length), then each block of tokens is +//! written as whichever of stored, fixed-Huffman or dynamic-Huffman is smallest. Huffman code +//! lengths are limited (15 bits, 7 for the code-length code) by halving the symbol frequencies +//! until the tree fits. Every code has at least two symbols, so all codes are complete. The +//! output favours simplicity and correctness over ratio; worst-case expansion is the stored-block +//! overhead (5 bytes per 64 KB). + +use std::cmp::Reverse; +use std::collections::BinaryHeap; + +const WINDOW: usize = 32 * 1024; +const MIN_MATCH: usize = 3; +const MAX_MATCH: usize = 258; +/// Hash chain candidates tried per position. +const MAX_CHAIN: usize = 48; +/// Tokens per block (a new set of Huffman codes after this many). +const BLOCK_TOKENS: usize = 1 << 15; +const MAX_STORED: usize = 65_535; + +const LEN_BASE: [u16; 29] = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258]; +const LEN_EXTRA: [u8; 29] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]; +const DIST_BASE: [u16; 30] = + [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577]; +const DIST_EXTRA: [u8; 30] = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]; +/// Order in which the code-length code's lengths are sent. +const CL_ORDER: [usize; 19] = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + +/// `data` compressed as a zlib stream (CMF 0x78: deflate, 32 KB window). `tables` are the match +/// finder's hash tables, kept by the caller across the chunks of a picture; the output does not +/// depend on what they held before. +pub fn zlib(data: &[u8], tables: &mut Tables) -> Vec { + let mut w = Bits { out: Vec::with_capacity(data.len() / 2 + 64), acc: 0, n: 0 }; + w.out.extend_from_slice(&[0x78, 0x9C]); // (0x78 << 8 | 0x9C) % 31 == 0 + deflate(data, &mut w, tables); + w.align(); + w.out.extend_from_slice(&adler32(data).to_be_bytes()); + w.out +} + +/// Adler-32 (RFC 1950 §9); 5552 bytes is the longest run that cannot overflow the sums. +fn adler32(data: &[u8]) -> u32 { + let (mut a, mut b) = (1_u32, 0_u32); + for c in data.chunks(5552) { + for &x in c { + a += u32::from(x); + b += a; + } + a %= 65_521; + b %= 65_521; + } + (b << 16) | a +} + +/// LSB-first bit writer. +struct Bits { + out: Vec, + acc: u64, + n: u32, +} + +impl Bits { + /// The low `n` bits of `v` (n ≤ 32). + fn put(&mut self, v: u32, n: u32) { + let mask = (1_u64 << n) - 1; + self.acc |= (u64::from(v) & mask) << self.n; + self.n += n; + while self.n >= 8 { + self.out.push(self.acc as u8); + self.acc >>= 8; + self.n -= 8; + } + } + + fn align(&mut self) { + if self.n > 0 { + self.out.push(self.acc as u8); + } + self.acc = 0; + self.n = 0; + } +} + +#[derive(Clone, Copy)] +enum Tok { + Lit(u8), + Match { len: u16, dist: u16 }, +} + +/// Index into [`LEN_BASE`] of a match length (3..=258). +fn len_code(len: u16) -> usize { + LEN_BASE.partition_point(|&b| b <= len).saturating_sub(1) +} + +/// Index into [`DIST_BASE`] of a distance (1..=32768). +fn dist_code(dist: u16) -> usize { + DIST_BASE.partition_point(|&b| b <= dist).saturating_sub(1) +} + +/// The match finder's hash heads and chains, reused from one input to the next. +/// +/// A slot holds `base + p + 1` for position `p` of the input that wrote it; anything at or below +/// the current input's `base` was left by an earlier input and reads as empty. So the tables are +/// never cleared between inputs: an OpenEXR ZIPS frame is one input per scan line, and zeroing +/// 256 KiB of tables for each 23 KB UHD line cost more memory traffic than the data itself. +#[derive(Default)] +pub struct Tables { + head: Vec, + prev: Vec, + /// Bytes compressed through these tables since they were last cleared. + base: u32, +} + +/// LZ77 match finder: hash heads and chains over the window. +struct Matcher<'a> { + data: &'a [u8], + head: &'a mut [u32], + prev: &'a mut [u32], + bits: u32, + /// `prev` slots used by this input, minus one (a power of two minus one). + mask: usize, + base: u32, +} + +impl<'a> Matcher<'a> { + /// A matcher over `data` (shorter than `u32::MAX` bytes), or None when it is not. + fn new(data: &'a [u8], t: &'a mut Tables) -> Option { + // hash width and chain span follow the input's size, as they did when every input had + // tables of its own (the output depends on them), so short chunks stay cheap to hash + let span = data.len().clamp(256, WINDOW).next_power_of_two(); + let bits = span.trailing_zeros().clamp(8, 15); + let n = u32::try_from(data.len()).ok().filter(|&n| n < u32::MAX)?; + if t.base.checked_add(n).and_then(|b| b.checked_add(1)).is_none() { + // positions would no longer fit after `base`: start over from empty tables + t.head.fill(0); + t.prev.fill(0); + t.base = 0; + } + // grown slots are 0, which is never above `base`, so they read as empty + if t.head.len() < 1 << bits { + t.head.resize(1 << bits, 0); + } + if t.prev.len() < span { + t.prev.resize(span, 0); + } + let base = t.base; + t.base += n; + let (head, prev) = (t.head.get_mut(..1 << bits)?, t.prev.get_mut(..span)?); + Some(Matcher { data, head, prev, bits, mask: span - 1, base }) + } + + /// Position `p` of this input from a stored slot, or None for an empty or earlier input's slot. + fn pos(&self, slot: u32) -> Option { + slot.checked_sub(self.base)?.checked_sub(1).map(|p| p as usize) + } + + fn hash(&self, p: usize) -> Option { + let b = self.data.get(p..p + MIN_MATCH)?; + let v = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + Some((v.wrapping_mul(0x9E37_79B1) >> (32 - self.bits)) as usize) + } + + /// Record position `p` (stored as `p + 1`; 0 = empty). + fn insert(&mut self, p: usize) { + let Some(h) = self.hash(p) else { return }; + let (Some(head), Ok(p32)) = (self.head.get(h).copied(), u32::try_from(p)) else { return }; + if let Some(slot) = self.prev.get_mut(p & self.mask) { + *slot = head; + } + if let Some(slot) = self.head.get_mut(h) { + // `new` reserved `base + len + 1` within u32 + *slot = self.base + p32 + 1; + } + } + + /// The longest earlier match at `p`: (length, distance), length 0 if none. + fn longest(&self, p: usize) -> (usize, usize) { + let Some(h) = self.hash(p) else { return (0, 0) }; + let max = self.data.len().saturating_sub(p).min(MAX_MATCH); + let Some(here) = self.data.get(p..p + max) else { return (0, 0) }; + let (mut best, mut best_dist) = (0, 0); + let mut cand = self.head.get(h).and_then(|&s| self.pos(s)); + for _ in 0..MAX_CHAIN { + let Some(c) = cand else { break }; + if c >= p || p - c > WINDOW { + break; + } + // a candidate that differs at `best` cannot be longer than `best`: skip comparing it + if best == 0 || self.data.get(c + best) == here.get(best) { + let l = self.data.get(c..).unwrap_or_default().iter().zip(here).take_while(|(a, b)| a == b).count(); + if l > best { + (best, best_dist) = (l, p - c); + if l == max { + break; + } + } + } + let Some(next) = self.prev.get(c & self.mask).and_then(|&s| self.pos(s)) else { break }; + // chains only go back; anything else is a stale slot + if next >= c { + break; + } + cand = Some(next); + } + (best, best_dist) + } +} + +/// The deflate blocks of `data`, the last one final. +fn deflate(data: &[u8], w: &mut Bits, tables: &mut Tables) { + if data.is_empty() { + // a final fixed-Huffman block holding only end-of-block (code 0000000) + w.put(1, 1); + w.put(1, 2); + w.put(0, 7); + return; + } + // positions are kept in u32; longer inputs (never an OpenEXR chunk) go out stored + let mut m = Matcher::new(data, tables); + let mut toks = Vec::with_capacity(BLOCK_TOKENS.min(data.len()) + 1); + let (mut start, mut i) = (0, 0); + while i < data.len() { + let (len, dist) = m.as_ref().map_or((0, 0), |m| m.longest(i)); + let step = if len >= MIN_MATCH { + toks.push(Tok::Match { len: len as u16, dist: dist as u16 }); + len + } else { + toks.push(Tok::Lit(data[i])); + 1 + }; + if let Some(m) = m.as_mut() { + for p in i..i + step { + m.insert(p); + } + } + i += step; + if toks.len() >= BLOCK_TOKENS || i == data.len() { + block(w, &toks, &data[start..i], i == data.len()); + toks.clear(); + start = i; + } + } +} + +/// Bits the tokens take with the given code lengths (EOB included). +fn data_bits(lf: &[u32], df: &[u32], ll: &[u8], dl: &[u8]) -> u64 { + let mut n = 0_u64; + for (s, (&f, &l)) in lf.iter().zip(ll).enumerate() { + let extra = s.checked_sub(257).and_then(|k| LEN_EXTRA.get(k)).copied().unwrap_or(0); + n += u64::from(f) * u64::from(l + extra); + } + for (d, (&f, &l)) in df.iter().zip(dl).enumerate() { + n += u64::from(f) * u64::from(l + DIST_EXTRA.get(d).copied().unwrap_or(0)); + } + n +} + +/// One block (split into several stored blocks when stored is smallest and `raw` is long). +fn block(w: &mut Bits, toks: &[Tok], raw: &[u8], last: bool) { + let mut lf = [0_u32; 286]; + let mut df = [0_u32; 30]; + for t in toks { + match *t { + Tok::Lit(b) => lf[b as usize] += 1, + Tok::Match { len, dist } => { + lf[257 + len_code(len)] += 1; + df[dist_code(dist)] += 1; + } + } + } + lf[256] += 1; + + // dynamic codes and their header + let ll = lengths(&lf, 15); + let dl = lengths(&df, 15); + let hlit = ll.iter().rposition(|&l| l > 0).map_or(257, |p| (p + 1).max(257)); + let hdist = dl.iter().rposition(|&l| l > 0).map_or(1, |p| p + 1); + let seq = rle_lengths(&[&ll[..hlit], &dl[..hdist]].concat()); + let mut cf = [0_u32; 19]; + for &(s, _) in &seq { + cf[s as usize] += 1; + } + let cl = lengths(&cf, 7); + let hclen = CL_ORDER.iter().rposition(|&s| cl[s] > 0).map_or(4, |p| (p + 1).max(4)); + let seq_bits: u64 = + seq.iter().map(|&(s, _)| u64::from(cl[s as usize]) + [2_u64, 3, 7].get((s as usize).wrapping_sub(16)).copied().unwrap_or(0)).sum(); + let dyn_bits = 3 + 14 + 3 * hclen as u64 + seq_bits + data_bits(&lf, &df, &ll, &dl); + + let (fll, fdl) = fixed_lengths(); + let fixed_bits = 3 + data_bits(&lf, &df, &fll, &fdl); + // per stored piece: header, at most 7 padding bits, LEN and NLEN + let pieces = raw.len().div_ceil(MAX_STORED).max(1) as u64; + let stored_bits = pieces * (3 + 7 + 32) + 8 * raw.len() as u64; + + if stored_bits <= fixed_bits.min(dyn_bits) { + let n = raw.chunks(MAX_STORED).count(); + for (k, piece) in raw.chunks(MAX_STORED).enumerate() { + w.put(u32::from(last && k + 1 == n), 1); + w.put(0, 2); + w.align(); + let len = piece.len() as u16; + w.out.extend_from_slice(&len.to_le_bytes()); + w.out.extend_from_slice(&(!len).to_le_bytes()); + w.out.extend_from_slice(piece); + } + return; + } + w.put(u32::from(last), 1); + if fixed_bits <= dyn_bits { + w.put(1, 2); + write_tokens(w, toks, &fll, &fdl); + return; + } + w.put(2, 2); + w.put((hlit - 257) as u32, 5); + w.put((hdist - 1) as u32, 5); + w.put((hclen - 4) as u32, 4); + for &s in &CL_ORDER[..hclen] { + w.put(u32::from(cl[s]), 3); + } + let cc = codes(&cl); + for &(s, x) in &seq { + w.put(u32::from(cc[s as usize]), u32::from(cl[s as usize])); + match s { + 16 => w.put(u32::from(x), 2), + 17 => w.put(u32::from(x), 3), + 18 => w.put(u32::from(x), 7), + _ => {} + } + } + write_tokens(w, toks, &ll, &dl); +} + +/// The fixed Huffman code lengths (RFC 1951 §3.2.6). +fn fixed_lengths() -> ([u8; 288], [u8; 30]) { + let mut ll = [8_u8; 288]; + ll[144..256].fill(9); + ll[256..280].fill(7); + (ll, [5; 30]) +} + +fn write_tokens(w: &mut Bits, toks: &[Tok], ll: &[u8], dl: &[u8]) { + let lc = codes(ll); + let dc = codes(dl); + let sym = |w: &mut Bits, s: usize| w.put(u32::from(lc[s]), u32::from(ll[s])); + for t in toks { + match *t { + Tok::Lit(b) => sym(w, b as usize), + Tok::Match { len, dist } => { + let k = len_code(len); + sym(w, 257 + k); + w.put(u32::from(len - LEN_BASE[k]), u32::from(LEN_EXTRA[k])); + let d = dist_code(dist); + w.put(u32::from(dc[d]), u32::from(dl[d])); + w.put(u32::from(dist - DIST_BASE[d]), u32::from(DIST_EXTRA[d])); + } + } + } + sym(w, 256); +} + +/// Canonical Huffman codes for `lens`, bit-reversed for the LSB-first writer. +fn codes(lens: &[u8]) -> Vec { + let mut count = [0_u32; 16]; + for &l in lens { + if (1..16).contains(&l) { + count[l as usize] += 1; + } + } + let mut next = [0_u32; 16]; + let mut code = 0; + for bits in 1..16 { + code = (code + count[bits - 1]) << 1; + next[bits] = code; + } + lens.iter() + .map(|&l| { + if !(1..16).contains(&l) { + return 0; + } + let c = next[l as usize]; + next[l as usize] += 1; + (c.reverse_bits() >> (32 - u32::from(l))) as u16 + }) + .collect() +} + +/// Code lengths for `freq`, none longer than `limit`; at least two symbols always get a code. +fn lengths(freq: &[u32], limit: u8) -> Vec { + let mut f: Vec = freq.iter().map(|&x| u64::from(x)).collect(); + let mut used = f.iter().filter(|&&x| x > 0).count(); + for x in f.iter_mut() { + if used >= 2 { + break; + } + if *x == 0 { + *x = 1; + used += 1; + } + } + // halving converges: once every used frequency is 1 the tree is balanced (depth ≤ 9 here) + for _ in 0..66 { + let l = huffman(&f); + if l.iter().all(|&d| d <= limit) { + return l; + } + for x in f.iter_mut().filter(|x| **x > 0) { + *x = (*x >> 1).max(1); + } + } + huffman(&f) +} + +/// Huffman tree depths of the symbols with non-zero frequency (0 for the rest). +fn huffman(f: &[u64]) -> Vec { + let n = f.len(); + let mut heap: BinaryHeap> = f.iter().enumerate().filter(|(_, w)| **w > 0).map(|(i, &w)| Reverse((w, i))).collect(); + let mut parent = vec![usize::MAX; 2 * n]; + let mut next = n; + while heap.len() > 1 { + let (Some(Reverse((wa, a))), Some(Reverse((wb, b)))) = (heap.pop(), heap.pop()) else { break }; + parent[a] = next; + parent[b] = next; + heap.push(Reverse((wa + wb, next))); + next += 1; + } + // parents always come after their children, so walk down from the root + let mut depth = vec![0_u32; next]; + for i in (0..next).rev() { + if let Some(&p) = parent.get(i).filter(|&&p| p < next) { + depth[i] = depth[p].saturating_add(1); + } + } + depth[..n].iter().map(|&d| d.min(u32::from(u8::MAX)) as u8).collect() +} + +/// Code lengths run-length coded with the code-length alphabet: (symbol, extra-bits value). +fn rle_lengths(lens: &[u8]) -> Vec<(u8, u8)> { + let mut out = Vec::new(); + let mut i = 0; + while i < lens.len() { + let l = lens[i]; + let run = lens[i..].iter().take_while(|&&x| x == l).count(); + let mut r = run; + if l == 0 { + while r >= 11 { + let k = r.min(138); + out.push((18, (k - 11) as u8)); + r -= k; + } + if r >= 3 { + out.push((17, (r - 3) as u8)); + r = 0; + } + } else { + out.push((l, 0)); + r -= 1; + while r >= 3 { + let k = r.min(6); + out.push((16, (k - 3) as u8)); + r -= k; + } + } + out.extend(std::iter::repeat_n((l, 0), r)); + i += run; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A minimal inflater (RFC 1951), only to check the encoder; returns None on any error. + pub(crate) fn inflate(z: &[u8]) -> Option> { + let (cmf, flg) = (*z.first()?, *z.get(1)?); + if cmf & 0x0F != 8 || (u16::from(cmf) << 8 | u16::from(flg)) % 31 != 0 || flg & 0x20 != 0 { + return None; + } + let mut pos = 16_usize; // bit position + let bit = |pos: &mut usize| -> Option { + let b = (*z.get(*pos / 8)? >> (*pos % 8)) & 1; + *pos += 1; + Some(u32::from(b)) + }; + let bits = |pos: &mut usize, n: u32| -> Option { + let mut v = 0; + for k in 0..n { + v |= bit(pos)? << k; + } + Some(v) + }; + // decode one symbol with canonical lengths (slow but simple) + let decode = |pos: &mut usize, lens: &[u8]| -> Option { + let (mut code, mut first, mut index) = (0_i32, 0_i32, 0_i32); + let mut count = [0_i32; 16]; + for &l in lens { + count[l as usize] += 1; + } + let mut sorted: Vec = (0..lens.len()).filter(|&s| lens[s] > 0).collect(); + sorted.sort_by_key(|&s| (lens[s], s)); + for &c in count.iter().skip(1) { + code |= bit(pos)? as i32; + if code - c < first { + return sorted.get((index + code - first) as usize).copied(); + } + index += c; + first = (first + c) << 1; + code <<= 1; + } + None + }; + let mut out = Vec::new(); + loop { + let last = bit(&mut pos)?; + match bits(&mut pos, 2)? { + 0 => { + pos = pos.div_ceil(8) * 8; + let at = pos / 8; + let len = u16::from_le_bytes([*z.get(at)?, *z.get(at + 1)?]); + let nlen = u16::from_le_bytes([*z.get(at + 2)?, *z.get(at + 3)?]); + if len != !nlen { + return None; + } + out.extend_from_slice(z.get(at + 4..at + 4 + len as usize)?); + pos = (at + 4 + len as usize) * 8; + } + t @ (1 | 2) => { + let (ll, dl) = if t == 1 { + let (a, b) = fixed_lengths(); + (a.to_vec(), b.to_vec()) + } else { + let hlit = bits(&mut pos, 5)? as usize + 257; + let hdist = bits(&mut pos, 5)? as usize + 1; + let hclen = bits(&mut pos, 4)? as usize + 4; + let mut cl = [0_u8; 19]; + for &s in &CL_ORDER[..hclen] { + cl[s] = bits(&mut pos, 3)? as u8; + } + let mut lens = Vec::new(); + while lens.len() < hlit + hdist { + match decode(&mut pos, &cl)? { + s @ 0..=15 => lens.push(s as u8), + 16 => { + let p = *lens.last()?; + lens.extend(std::iter::repeat_n(p, 3 + bits(&mut pos, 2)? as usize)); + } + 17 => lens.extend(std::iter::repeat_n(0, 3 + bits(&mut pos, 3)? as usize)), + _ => lens.extend(std::iter::repeat_n(0, 11 + bits(&mut pos, 7)? as usize)), + } + } + if lens.len() != hlit + hdist { + return None; + } + (lens[..hlit].to_vec(), lens[hlit..].to_vec()) + }; + loop { + let s = decode(&mut pos, &ll)?; + if s < 256 { + out.push(s as u8); + } else if s == 256 { + break; + } else { + let k = s - 257; + let len = *LEN_BASE.get(k)? as usize + bits(&mut pos, u32::from(LEN_EXTRA[k]))? as usize; + let d = decode(&mut pos, &dl)?; + let dist = *DIST_BASE.get(d)? as usize + bits(&mut pos, u32::from(DIST_EXTRA[d]))? as usize; + let from = out.len().checked_sub(dist)?; + for j in 0..len { + out.push(out[from + j]); + } + } + } + } + _ => return None, + } + if last == 1 { + break; + } + } + let at = pos.div_ceil(8); + let sum = u32::from_be_bytes(z.get(at..at + 4)?.try_into().ok()?); + (sum == adler32(&out) && at + 4 == z.len()).then_some(out) + } + + /// A deterministic pseudo-random byte stream. + fn noise(n: usize, seed: u32) -> Vec { + let mut s = seed | 1; + (0..n) + .map(|_| { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + s as u8 + }) + .collect() + } + + #[test] + fn round_trips() { + let mut cases: Vec> = vec![vec![], vec![7], vec![1, 2], vec![0; 1], vec![0; 300_000], b"abcabcabcabcabcabd".to_vec()]; + cases.push(noise(100_000, 9)); // incompressible: stored blocks + cases.push(noise(70_000, 3).iter().map(|b| b % 4).collect()); // few symbols: dynamic + cases.push((0..200_000_u32).map(|i| ((i / 7) % 251) as u8).collect()); // long repeats + // text-like: a small vocabulary repeated at varying distances + let words: [&[u8]; 6] = [b"red ", b"green ", b"blue ", b"alpha ", b"half ", b"linear "]; + cases.push(noise(40_000, 5).iter().flat_map(|b| words[*b as usize % 6].iter().copied()).collect()); + // skewed frequencies: Huffman lengths beyond 15 before limiting + let mut fib = Vec::new(); + let (mut a, mut b) = (1_usize, 1_usize); + for s in 0..25_u8 { + fib.extend(std::iter::repeat_n(s.wrapping_mul(37), a.min(200_000))); + (a, b) = (b, a + b); + } + let r = noise(fib.len() * 4, 11); + for i in (1..fib.len()).rev() { + let j = u32::from_le_bytes(r[i * 4..i * 4 + 4].try_into().unwrap()) as usize % (i + 1); + fib.swap(i, j); + } + cases.push(fib); + for (k, data) in cases.iter().enumerate() { + let z = zlib(data, &mut Tables::default()); + assert_eq!(inflate(&z).as_deref(), Some(data.as_slice()), "case {k}"); + // worst case: stored overhead only + assert!(z.len() <= data.len() + (data.len().div_ceil(BLOCK_TOKENS) + 1) * 5 + 6, "case {k}: {} > {}", z.len(), data.len()); + } + // repetitive data actually compresses + assert!(zlib(&cases[4], &mut Tables::default()).len() < 2_000); + assert!(zlib(&cases[8], &mut Tables::default()).len() < 20_000); + } + + #[test] + fn length_limits_hold() { + // Fibonacci frequencies give the deepest possible Huffman tree + let mut f = vec![0_u32; 286]; + let (mut a, mut b) = (1_u32, 1_u32); + for x in f.iter_mut().take(30) { + *x = a; + (a, b) = (b, a.saturating_add(b)); + } + let l = lengths(&f, 15); + assert!(l.iter().all(|&d| d <= 15)); + // a complete code: Kraft sum exactly 1 + let kraft: f64 = l.iter().filter(|&&d| d > 0).map(|&d| 0.5_f64.powi(i32::from(d))).sum(); + assert!((kraft - 1.0).abs() < 1e-12); + // one used symbol still gets a two-symbol code + let l = lengths(&[0, 5, 0], 7); + assert_eq!(l.iter().filter(|&&d| d == 1).count(), 2); + } + + #[test] + fn adler_matches_rfc_example() { + // the classic test vector for "Wikipedia" + assert_eq!(adler32(b"Wikipedia"), 0x11E6_0398); + assert_eq!(adler32(&[]), 1); + } + + /// The match finder before #4659: tables of its own per input, every chain candidate compared + /// from its first byte. + struct OldMatcher<'a> { + data: &'a [u8], + head: Vec, + prev: Vec, + bits: u32, + } + + impl<'a> OldMatcher<'a> { + /// Tables of its own, sized to `data`. + fn new(data: &'a [u8]) -> Self { + let span = data.len().clamp(256, WINDOW).next_power_of_two(); + let bits = span.trailing_zeros().clamp(8, 15); + OldMatcher { data, head: vec![0; 1 << bits], prev: vec![0; span], bits } + } + + /// The hash of the three bytes at `p`, None near the end. + fn hash(&self, p: usize) -> Option { + let b = self.data.get(p..p + MIN_MATCH)?; + let v = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + Some((v.wrapping_mul(0x9E37_79B1) >> (32 - self.bits)) as usize) + } + + /// Record position `p` (stored as `p + 1`; 0 = empty). + fn insert(&mut self, p: usize) { + let Some(h) = self.hash(p) else { return }; + let mask = self.prev.len() - 1; + self.prev[p & mask] = self.head[h]; + self.head[h] = p as u32 + 1; + } + + /// The longest earlier match at `p`: (length, distance), length 0 if none. + fn longest(&self, p: usize) -> (usize, usize) { + let Some(h) = self.hash(p) else { return (0, 0) }; + let max = (self.data.len() - p).min(MAX_MATCH); + let here = &self.data[p..p + max]; + let mask = self.prev.len() - 1; + let (mut best, mut best_dist) = (0, 0); + let mut cand = self.head[h] as usize; + for _ in 0..MAX_CHAIN { + let Some(c) = cand.checked_sub(1) else { break }; + if c >= p || p - c > WINDOW { + break; + } + let l = self.data[c..].iter().zip(here).take_while(|(a, b)| a == b).count(); + if l > best { + (best, best_dist) = (l, p - c); + if l == max { + break; + } + } + let next = self.prev[c & mask] as usize; + if next == 0 || next > c { + break; + } + cand = next; + } + (best, best_dist) + } + } + + /// Inputs shaped like OpenEXR chunks (predicted half-float scan lines, single and 16-line) + /// and the awkward cases: empty, tiny, incompressible, long runs, few symbols. + fn chunk_cases() -> Vec> { + let line: Vec = (0..23_040_u32).map(|i| (128 + ((i / 3) % 7) as i32 - 3 + (i % 5 == 0) as i32) as u8).collect(); + let mut cases = vec![line.clone(), line.iter().rev().copied().collect(), vec![], vec![9], b"abcabcabcabd".to_vec()]; + cases.push(line.iter().cycle().take(16 * 23_040).copied().collect()); // ZIP: 16 lines, longer than the window + cases.push(noise(23_040, 4)); + cases.push(noise(70_000, 3).iter().map(|b| b % 4).collect()); + cases.push(vec![0; 300_000]); + cases.push(line.clone()); + cases.push(noise(300, 7)); + cases + } + + /// The matcher's greedy parse of `data`: what `deflate` codes. + fn parse (usize, usize), G: FnMut(usize)>(data: &[u8], mut longest: F, mut insert: G) -> Vec<(usize, usize)> { + let (mut out, mut i) = (Vec::new(), 0); + while i < data.len() { + let (len, dist) = longest(i); + let step = if len >= MIN_MATCH { len } else { 1 }; + out.push(if len >= MIN_MATCH { (len, dist) } else { (0, 0) }); + for p in i..i + step { + insert(p); + } + i += step; + } + out + } + + /// Shared tables and the candidate skip find exactly the matches the previous matcher found. + #[test] + fn shared_tables_find_the_matches_the_old_per_chunk_tables_found() { + let mut tables = Tables::default(); + for (k, data) in chunk_cases().iter().enumerate() { + let old = std::cell::RefCell::new(OldMatcher::new(data)); + let want = parse(data, |p| old.borrow().longest(p), |p| old.borrow_mut().insert(p)); + let new = std::cell::RefCell::new(Matcher::new(data, &mut tables).expect("fits")); + let got = parse(data, |p| new.borrow().longest(p), |p| new.borrow_mut().insert(p)); + assert!(got == want, "chunk {k}: the parse differs"); + } + } + + /// Shared tables compress to the bytes fresh ones give, also when positions run out and they start over. + #[test] + fn shared_tables_give_the_bytes_of_fresh_ones() { + let mut shared = Tables::default(); + for (k, data) in chunk_cases().iter().enumerate() { + let z = zlib(data, &mut shared); + assert!(z == zlib(data, &mut Tables::default()), "chunk {k}"); + assert_eq!(inflate(&z).as_deref(), Some(data.as_slice()), "chunk {k}"); + } + // positions about to run past u32: the tables start over and the bytes stay the same + for gap in [0_u32, 1, 2, 23_040, 23_041, 1 << 20] { + shared.base = u32::MAX - gap; + for (k, data) in chunk_cases().iter().enumerate() { + assert!(zlib(data, &mut shared) == zlib(data, &mut Tables::default()), "gap {gap}, chunk {k}"); + } + } + } + + /// Later chunks use the same tables instead of allocating new ones. + #[test] + fn the_tables_are_reused_across_chunks() { + let mut tables = Tables::default(); + let line = &chunk_cases()[0]; + zlib(line, &mut tables); + let (head, prev) = (tables.head.as_ptr(), tables.prev.as_ptr()); + for _ in 0..4 { + zlib(line, &mut tables); + assert!(tables.head.as_ptr() == head && tables.prev.as_ptr() == prev, "a chunk allocated new tables"); + } + assert_eq!(tables.base as usize, 5 * line.len()); + } +} diff --git a/crates/fcproj-format/Cargo.toml b/crates/fcproj-format/Cargo.toml new file mode 100644 index 0000000000..aa210187d9 --- /dev/null +++ b/crates/fcproj-format/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "craft-fcproj-format" +description = "FilmCraft project envelope and schema migrations" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/fcproj-format/src/lib.rs b/crates/fcproj-format/src/lib.rs new file mode 100644 index 0000000000..4ac1b72439 --- /dev/null +++ b/crates/fcproj-format/src/lib.rs @@ -0,0 +1,322 @@ +//! FilmCraft `.fcproj` JSON envelope, version detection and historical migrations. +//! Project and editor-view types are supplied by the caller. +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] +use serde::{Deserialize, Serialize}; +use serde_json::Value; +/// The `format` tag written in every envelope. +pub const FORMAT_ID: &str = "filmcraft.project"; + +/// A migration upgrades a whole document from schema `n` to `n + 1`. +pub type Migration = fn(Value) -> Result; + +/// `MIGRATIONS[i]` upgrades schema `i + 1` to `i + 2`. Append one function per schema bump; never +/// edit a shipped one. +pub const MIGRATIONS: &[Migration] = &[ + v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9, v9_to_v10, v10_to_v11, v11_to_v12, v12_to_v13, v13_to_v14, + v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, +]; + +/// The schema version this build writes (and the newest it reads). +pub const SCHEMA_VERSION: u32 = MIGRATIONS.len() as u32 + 1; + +/// Oldest schema this build can still upgrade. +pub const OLDEST_SCHEMA: u32 = 1; + +#[derive(Debug, thiserror::Error)] +pub enum FormatError { + #[error("not a FilmCraft project: {0}")] + NotAProject(String), + #[error( + "this project was saved by a newer version of FilmCraft (project schema v{found}); this build reads up to v{supported}. Update FilmCraft to open it." + )] + TooNew { found: u32, supported: u32 }, + #[error("project schema v{found} is too old for this build (oldest supported: v{oldest})")] + TooOld { found: u32, oldest: u32 }, + #[error("upgrading project from schema v{from} to v{}: {msg}", from + 1)] + Migration { from: u32, msg: String }, + #[error("project file is damaged: {0}")] + Corrupt(String), +} + +/// Serialized current-schema envelope. +#[derive(Serialize)] +pub struct EnvelopeOut<'a, P, V> { + pub format: &'static str, + pub schema_version: u32, + pub generator: String, + pub project: &'a P, + #[serde(skip_serializing_if = "Option::is_none")] + pub view: Option<&'a V>, +} +/// Parsed envelope. View parsing remains optional to preserve forward compatibility. +#[derive(Deserialize)] +pub struct EnvelopeIn

{ + #[serde(default)] + pub generator: Option, + pub project: P, + #[serde(default)] + pub view: Option, +} +/// Serialize the current envelope, with optional editor view and caller-provided generator. +pub fn encode(project: &P, view: Option<&V>, generator: String, pretty: bool) -> Vec { + let envelope = EnvelopeOut { format: FORMAT_ID, schema_version: SCHEMA_VERSION, generator, project, view }; + let result = if pretty { serde_json::to_vec_pretty(&envelope) } else { serde_json::to_vec(&envelope) }; + result.unwrap_or_default() +} + +/// Decode an envelope, migrating older documents while retaining the current-version fast path. +pub fn decode(bytes: &[u8]) -> Result<(EnvelopeIn

, u32), FormatError> { + let found = detect_bytes(bytes)?; + if found == SCHEMA_VERSION { + let env = serde_json::from_slice(bytes).map_err(|e| FormatError::Corrupt(e.to_string()))?; + return Ok((env, found)); + } + let doc: Value = serde_json::from_slice(bytes).map_err(|e| FormatError::Corrupt(e.to_string()))?; + let doc = migrate_with(MIGRATIONS, doc, found)?; + let env = serde_json::from_value(doc).map_err(|e| FormatError::Corrupt(format!("after upgrading from schema v{found}: {e}")))?; + Ok((env, found)) +} + +/// Probe and validate the schema directly from bytes without building a JSON tree. +pub fn detect_bytes(bytes: &[u8]) -> Result { + let probe: Probe = serde_json::from_slice(bytes) + .map_err(|e| if e.is_syntax() || e.is_eof() { FormatError::Corrupt(e.to_string()) } else { FormatError::NotAProject(e.to_string()) })?; + let found = probe_version(&probe)?; + check_supported(found)?; + Ok(found) +} +/// Just enough of a document to know which schema it is. +#[derive(Deserialize)] +struct Probe { + #[serde(default)] + format: Option, + #[serde(default)] + schema_version: Option, + /// Bare (pre-envelope) project: its `version` field. + #[serde(default)] + version: Option, + #[serde(default)] + items: Option, + #[serde(default)] + root: Option, +} + +/// Detect the schema version of a parsed document. +pub fn detect_version(doc: &Value) -> Result { + let probe: Probe = serde_json::from_value(doc.clone()).map_err(|e| FormatError::NotAProject(e.to_string()))?; + probe_version(&probe) +} + +fn probe_version(p: &Probe) -> Result { + if let Some(v) = p.schema_version { + if let Some(f) = &p.format + && f != FORMAT_ID + { + return Err(FormatError::NotAProject(format!("format is `{f}`, expected `{FORMAT_ID}`"))); + } + return Ok(v); + } + // Before the envelope (v1) a file was the bare Project object with `version`. + // Its `version` was 1, or 2 on builds that briefly bumped it when caption tracks were added + // (same shape; the new field loads with its default). Anything higher is from the future. + if p.items.is_some() && p.root.is_some() { + return Ok(match p.version.unwrap_or(1) { + 0..=2 => 1, + v => v, + }); + } + Err(FormatError::NotAProject("no `schema_version` and not a legacy project".into())) +} + +pub fn check_supported(found: u32) -> Result<(), FormatError> { + if found > SCHEMA_VERSION { + return Err(FormatError::TooNew { found, supported: SCHEMA_VERSION }); + } + if found < OLDEST_SCHEMA { + return Err(FormatError::TooOld { found, oldest: OLDEST_SCHEMA }); + } + Ok(()) +} + +/// Run `table` from schema `from` up to `table.len() + 1`, stamping `schema_version` after each step. +pub fn migrate_with(table: &[Migration], mut doc: Value, from: u32) -> Result { + let target = table.len() as u32 + 1; + if from > target { + return Err(FormatError::TooNew { found: from, supported: target }); + } + if from == 0 { + return Err(FormatError::TooOld { found: 0, oldest: 1 }); + } + for v in from..target { + let step = table[(v - 1) as usize]; + doc = step(doc).map_err(|msg| FormatError::Migration { from: v, msg })?; + match doc.as_object_mut() { + Some(o) => { + o.insert("schema_version".into(), Value::from(v + 1)); + } + None => return Err(FormatError::Migration { from: v, msg: "migration produced a non-object document".into() }), + } + } + Ok(doc) +} + +/// v1 → v2: wrap the bare project in the envelope and drop the per-project `version` field. +fn v1_to_v2(doc: Value) -> Result { + let Value::Object(mut project) = doc else { return Err("expected a JSON object".into()) }; + project.remove("version"); + Ok(serde_json::json!({ + "format": FORMAT_ID, + "schema_version": 2, + "generator": "FilmCraft (schema v1)", + "project": Value::Object(project), + })) +} + +/// v2 → v3: graphic clips added; existing data needs no change. +fn v2_to_v3(doc: Value) -> Result { + Ok(doc) +} + +/// v3 → v4: Essential Sound fields added; existing data needs no change. +fn v3_to_v4(doc: Value) -> Result { + Ok(doc) +} + +/// v4 → v5: colour-management fields added; existing data needs no change. +fn v4_to_v5(doc: Value) -> Result { + Ok(doc) +} + +/// v5 → v6: media identity and ingest settings added; existing data needs no change. +fn v5_to_v6(doc: Value) -> Result { + Ok(doc) +} + +/// v6 → v7: effect masks (Bézier mask paths as keyframable parameters); existing data needs no change. +fn v6_to_v7(doc: Value) -> Result { + Ok(doc) +} + +/// v7 → v8: multi-camera source sequences / clips and merged clips added; existing data needs no +/// change. +fn v7_to_v8(doc: Value) -> Result { + Ok(doc) +} + +/// v8 → v9: per-media-item transcripts (`project.transcripts`) added; existing data needs no change. +fn v8_to_v9(doc: Value) -> Result { + Ok(doc) +} + +/// v9 → v10: clip time interpolation, Hold Filters, Field Options and audio source channels; the +/// Modify ▸ Audio Channels map; subclips' Restrict Trims flag. Existing data needs no change. +fn v9_to_v10(doc: Value) -> Result { + Ok(doc) +} + +/// v10 → v11: search bins (`project.search_bins`), Flash Cue markers, Project Settings safe areas, +/// capture format and scratch disks. Existing data needs no change. +fn v10_to_v11(doc: Value) -> Result { + Ok(doc) +} + +/// v11 → v12: graphics templates, rolls / crawls, responsive design and per-character text styles +/// on graphic clips, and source graphics. Existing data needs no change. +fn v11_to_v12(doc: Value) -> Result { + Ok(doc) +} + +/// v12 → v13: container audio streams and per-clip stream selection. `MediaInfo` reads the old +/// `audio` field as stream zero; `TrackItem::audio_stream` defaults to zero. +fn v12_to_v13(doc: Value) -> Result { + Ok(doc) +} + +/// v13 → v14: narrations (Text to Speech). Existing data needs no change. +fn v13_to_v14(doc: Value) -> Result { + Ok(doc) +} + +/// v14 → v15: project notes. Existing data needs no change. +fn v14_to_v15(doc: Value) -> Result { + Ok(doc) +} + +/// v15 → v16: existing colors remain presets; authors and the named custom palette default empty. +fn v15_to_v16(doc: Value) -> Result { + Ok(doc) +} + +/// v16 → v17: marker URLs default empty. Older builds must not silently drop saved URLs. +fn v16_to_v17(doc: Value) -> Result { + Ok(doc) +} + +/// v17 → v18: camera raw Source Settings on media items (`Interpretation::raw`: white balance, +/// exposure, highlights, demosaic quality and output colour space of DNG / CinemaDNG footage; +/// absent = as the file says). Existing data needs no change; older builds must refuse such +/// projects instead of silently dropping the settings when saving. +fn v17_to_v18(doc: Value) -> Result { + Ok(doc) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn legacy_and_current_envelopes_preserve_values() { + let bare = json!({"version": 2, "items": {}, "root": {}, "extra": [1, 2]}); + assert_eq!(detect_version(&bare).unwrap(), 1); + let migrated = migrate_with(MIGRATIONS, bare, 1).unwrap(); + assert_eq!(migrated["schema_version"], 18); + assert_eq!(migrated["project"]["extra"], json!([1, 2])); + assert_eq!(migrated["generator"], "FilmCraft (schema v1)"); + assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), 18); + let parsed: EnvelopeIn = serde_json::from_value(migrated).unwrap(); + assert!(parsed.view.is_none()); + assert_eq!(parsed.project["extra"], json!([1, 2])); + } + #[test] + fn typed_encode_and_decode_current_and_legacy() { + let project = json!({"items": {}, "root": {}, "name": "Cut"}); + let view = json!({"active": 3}); + for pretty in [false, true] { + let bytes = encode(&project, Some(&view), "FilmCraft test".into(), pretty); + let (file, version): (EnvelopeIn, _) = decode(&bytes).unwrap(); + assert_eq!(version, SCHEMA_VERSION); + assert_eq!(file.project, project); + assert_eq!(file.view, Some(view.clone())); + } + let old = br#"{"version":1,"items":{},"root":{},"name":"Cut"}"#; + let (file, version): (EnvelopeIn, _) = decode(old).unwrap(); + assert_eq!(version, 1); + assert_eq!(file.project["name"], "Cut"); + } + /// Schema 18 (camera raw Source Settings): a v17 project upgrades with its data untouched, and a + /// v18 project with `interpret.raw` settings is read rather than refused as too new. + #[test] + fn v17_upgrades_and_v18_raw_settings_are_read() { + let item = json!({"Media": {"interpret": {"par": [1, 1]}}}); + let v17 = json!({"format": FORMAT_ID, "schema_version": 17, "project": {"items": {"1": {"kind": item}}, "root": {}}}); + let up = migrate_with(MIGRATIONS, v17.clone(), 17).unwrap(); + assert_eq!(up["schema_version"], 18); + assert_eq!(up["project"], v17["project"]); + let raw = json!({"white_balance": {"Custom": {"temperature": 3200.0, "tint": 12.5}}, "exposure": -0.75}); + let mut v18 = up; + v18["project"]["items"]["1"]["kind"]["Media"]["interpret"]["raw"] = raw.clone(); + let bytes = serde_json::to_vec(&v18).unwrap(); + let (file, version): (EnvelopeIn, _) = decode(&bytes).unwrap(); + assert_eq!(version, 18); + assert_eq!(file.project["items"]["1"]["kind"]["Media"]["interpret"]["raw"], raw); + } + #[test] + fn rejects_wrong_future_and_damaged_envelopes() { + assert!(matches!(detect_bytes(br#"{"format":"other","schema_version":1}"#), Err(FormatError::NotAProject(_)))); + assert!(matches!(detect_bytes(br#"{"schema_version":19}"#), Err(FormatError::TooNew { found: 19, supported: 18 }))); + assert!(matches!(detect_bytes(br#"{"schema_version":0}"#), Err(FormatError::TooOld { found: 0, oldest: 1 }))); + assert!(matches!(detect_bytes(b"{"), Err(FormatError::Corrupt(_)))); + assert!(matches!(migrate_with(MIGRATIONS, json!([]), 1), Err(FormatError::Migration { from: 1, .. }))); + } +} diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 341ded449f..d85953a0a2 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -342,6 +342,20 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op }) } +/// The freeform a `w` × `h` frame shape with border `corner` (see +/// [`craft_wordmodel::connector::frame_width`]) draws: its outline clockwise and its hole the +/// other way, so the hole stays empty under either fill rule. +fn frame_freeform(corner: Option, w: f32, h: f32) -> craft_wordmodel::freeform::Freeform { + use craft_wordmodel::freeform::{FreePath, Freeform}; + let (w, h) = (craft_wordmodel::geom::finite(w).max(0.0), craft_wordmodel::geom::finite(h).max(0.0)); + let t = craft_wordmodel::connector::frame_width(corner, w, h); + let mut paths = vec![FreePath { pts: vec![[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], closed: true }]; + if w - 2.0 * t > 0.0 && h - 2.0 * t > 0.0 { + paths.push(FreePath { pts: vec![[t, t], [t, h - t], [w - t, h - t], [w - t, t]], closed: true }); + } + Freeform { w, h, paths, ..Default::default() } +} + /// Comment `c` (a reply to `parent`) of `doc` as a flow comment: its text holds no comments or /// notes of its own. /// The flow inline for picture, shape or group `o` of `doc` (a member of groups `depth` deep), @@ -358,8 +372,12 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize { // A connector stays one in formats that glue them (ODT, with boxes); elsewhere it is a // straight line. + // A frame (a border with a hole), which the other formats have no shape for, is the + // freeform it draws: its outline and, wound the other way, its hole. + let frame = (*kind == ShapeKind::Frame).then(|| std::sync::Arc::new(frame_freeform(extra.corner, *w, *h))); let kind = match kind { ShapeKind::StraightConnector | ShapeKind::ElbowConnector | ShapeKind::CurvedConnector if !opts.boxes => ShapeKind::Line, + ShapeKind::Frame => ShapeKind::Freeform, k => *k, }; let inner = FlowOpts { notes: false, comments: false, boxes: false, ..opts }; @@ -383,7 +401,7 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize Box::new(crate::Chain { name: format!("Frame{id}"), next }) }), }; - let path = freeform.clone().filter(|_| kind == ShapeKind::Freeform); + let path = frame.or_else(|| freeform.clone()).filter(|_| kind == ShapeKind::Freeform); Some(Inline::Shape { kind, w: w * sx, h: h * sy, float: kept_float(float), blocks, look, path }) } InlineObject::Image { media, w, h, alt, float, ole, crop, .. } => { @@ -493,6 +511,8 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { kind, list, align: p.props.align, + // Direction can come from the paragraph's style (`w:bidi` in the style's pPr). + rtl: doc.styles.resolve_para(&p.props).bidi, page_break: p.props.page_break_before.unwrap_or(false), keep_next: p.props.keep_next.unwrap_or(false), inlines: Vec::new(), @@ -536,6 +556,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { kind, list: None, align: p.props.align, + rtl: out.rtl, page_break: true, keep_next: p.props.keep_next.unwrap_or(false), inlines: Vec::new(), @@ -658,7 +679,10 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { { (li.list, li.label) = (0, None); } - let old = Para { kind, list, align: c.old.align, page_break: c.old.page_break_before.unwrap_or(false), ..Default::default() }; + // Direction resolved like the current paragraph's: the old properties' own `w:bidi`, else + // the style's. + let rtl = doc.styles.resolve_para(&c.old).bidi; + let old = Para { kind, list, align: c.old.align, rtl, page_break: c.old.page_break_before.unwrap_or(false), ..Default::default() }; Box::new(FmtChange { mark: rev_mark(doc, c.rev), old }) }); } @@ -749,7 +773,7 @@ fn graphic_group( let inline = Inline::Shape { kind: *kind, w: rect[2] * sx, h: rect[3] * sy, float: None, blocks: Vec::new(), look, path: None }; Some(Member { x: rect[0] * sx, y: rect[1] * sy, inline }) } - GraphicItem::Text { rect, text, size, color, bold, align, font } if finite(rect) && !text.trim().is_empty() => { + GraphicItem::Text { rect, text, size, color, bold, align, font, .. } if finite(rect) && !text.trim().is_empty() => { let size = if size.is_finite() { size.clamp(1.0, 400.0) } else { 11.0 }; // One line, centred vertically in its place as the graphic draws it. let line = size * 1.2; @@ -1077,7 +1101,10 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa let ncols = t.rows.iter().map(|r| r.first_grid() + r.cells.iter().map(|c| c.span()).sum::() + r.grid_after()).max().unwrap_or(0).max(t.grid.len()); for (ri, r) in t.rows.iter().enumerate() { - let header = r.props.header || (ri == 0 && t.props.look.header_row && t.rows.len() > 1); + // The look's header row is an option of the table's style (`w:tblLook/@w:firstRow`): with + // no table style there is nothing to apply, so the first row stays an ordinary row, as in + // Word. Only Repeat as header row makes it one then. + let header = r.props.header || (ri == 0 && style.is_some() && t.props.look.header_row && t.rows.len() > 1); let mut cells = Vec::new(); for (ci, c) in r.cells.iter().enumerate() { let styled = if bake { styled_cell(t, style.as_ref(), (ri, ci), ncols) } else { None }; diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 774b5ffd17..7dc83c99d8 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -80,6 +80,32 @@ mod tests { assert!(kept); } + /// The default look's header row is an option of the table style: a table with no style (or a + /// style the document doesn't have) has an ordinary first row, so RTF doesn't bold it or + /// repeat it on each page, and HTML doesn't make it `th`. Repeat as header row still does. + #[test] + fn look_header_row_needs_a_table_style() { + use craft_wordmodel::{Block, Document, table::Table}; + let first_row_header = |style: Option<&str>, repeat: bool| { + let mut t = Table::new(2, 2, 200.0); + t.props.style = style.map(str::to_string); + assert!(t.props.look.header_row, "the default look has a header row"); + if let Some(r) = t.rows.first_mut() { + r.props.header = repeat; + } + let mut doc = Document::new(); + doc.body = vec![std::sync::Arc::new(Block::Table(t))]; + let flow = from_doc(&doc); + let Some(FBlock::Table(ft)) = flow.blocks.iter().find(|b| matches!(b, FBlock::Table(_))) else { panic!("no table in {:?}", flow.blocks) }; + assert!(ft.rows.get(1).is_some_and(|r| r.iter().all(|c| !c.header)), "the second row is never a header"); + ft.rows.first().is_some_and(|r| r.iter().all(|c| c.header)) + }; + assert!(first_row_header(Some("TableGrid"), false), "a table style applies the look's header row"); + assert!(!first_row_header(None, false), "no style, no header row"); + assert!(!first_row_header(Some("NoSuchStyle"), false), "a missing style applies nothing"); + assert!(first_row_header(None, true), "Repeat as header row"); + } + #[test] fn percent_decode_requires_hex_digits() { assert_eq!(percent_decode("%+A"), b"%+A".to_vec()); diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index c10be85c27..0375c448c2 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -159,6 +159,9 @@ fn para_props(p: &Para, list_num: Option) -> ParaProps { out.numbering = Some(NumRef { num, level: li.level.min(8) }); } out.align = p.align; + if p.rtl { + out.bidi = Some(true); + } let sp = p.spacing; out.space_before = sp.before; out.space_after = sp.after; @@ -838,7 +841,8 @@ impl<'a> Builder<'a> { tb.props.style = None; } if t.widths.len() == cols && t.widths.iter().all(|w| w.is_finite() && *w > 1.0) { - tb.grid = t.widths.iter().map(|w| w.clamp(6.0, 1584.0)).collect(); + // Narrow columns stay as they are: raising them would widen the table past its source. + tb.grid = t.widths.iter().map(|w| w.min(1584.0)).collect(); } tb.rows.clear(); if let Some(x) = &t.extra { diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index e897778f9c..f1c281c62e 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -676,6 +676,8 @@ pub struct Para { pub kind: Kind, pub list: Option, pub align: Option, + /// The paragraph reads right to left (OOXML `w:bidi`, RTF `\rtlpar`). + pub rtl: bool, pub page_break: bool, /// Keep the paragraph on the same page as the next one (ODT `fo:keep-with-next`). pub keep_next: bool, diff --git a/crates/font-catalog/Cargo.toml b/crates/font-catalog/Cargo.toml index a95e1c28f3..d4620862be 100644 --- a/crates/font-catalog/Cargo.toml +++ b/crates/font-catalog/Cargo.toml @@ -15,8 +15,12 @@ default = ["system"] system = ["dep:fontique"] [dependencies] +harfrust = "0.13" +kurbo = { workspace = true } skrifa = { version = "0.47", default-features = false, features = ["std"] } thiserror = { workspace = true } +unicode-bidi = "0.3.18" +unicode-segmentation = "1.13" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] fontique = { version = "0.11.1", default-features = false, features = ["system", "fontconfig-dlopen"], optional = true } diff --git a/crates/font-catalog/src/embedding.rs b/crates/font-catalog/src/embedding.rs new file mode 100644 index 0000000000..42321824e1 --- /dev/null +++ b/crates/font-catalog/src/embedding.rs @@ -0,0 +1,85 @@ +//! Permission to embed TrueType outline subsets based on the face's OS/2 `fsType`. + +use skrifa::{FontRef, Tag}; + +/// Whether a face can be embedded as a TrueType subset. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SubsetEmbedding { + /// Installable, editable, or preview-and-print embedding, or no readable `fsType`. + Allowed, + /// Restricted licence embedding. + Restricted, + /// Embedding is allowed only without subsetting. + NoSubsetting, + /// Only bitmap embedding is allowed. + BitmapOnly, + /// The face is invalid or lacks a TrueType outline table. + NotTrueType, +} + +/// Classify a face's TrueType subset embedding permissions. Missing or truncated OS/2 +/// data permits embedding; bitmap-only takes precedence over restricted and no-subsetting. +pub fn subset_embedding(bytes: &[u8], index: u32) -> SubsetEmbedding { + let Ok(face) = FontRef::from_index(bytes, index) else { return SubsetEmbedding::NotTrueType }; + if [b"glyf", b"loca", b"head"].iter().any(|tag| face.table_data(Tag::new(tag)).is_none()) { + return SubsetEmbedding::NotTrueType; + } + let fs_type = face.table_data(Tag::new(b"OS/2")).and_then(|table| { + let data = table.as_bytes(); + Some(u16::from_be_bytes([*data.get(8)?, *data.get(9)?])) + }); + let Some(fs_type) = fs_type else { return SubsetEmbedding::Allowed }; + if fs_type & 0x0200 != 0 { + SubsetEmbedding::BitmapOnly + } else if fs_type & 0x000f == 0x0002 { + SubsetEmbedding::Restricted + } else if fs_type & 0x0100 != 0 { + SubsetEmbedding::NoSubsetting + } else { + SubsetEmbedding::Allowed + } +} + +#[cfg(test)] +mod tests { + use super::*; + use write_fonts::{FontBuilder, types::Tag}; + + fn font(fs_type: Option<&[u8]>, missing: Option<&[u8; 4]>) -> Vec { + let mut builder = FontBuilder::new(); + for tag in [b"glyf", b"loca", b"head"] { + if Some(tag) != missing { + builder.add_raw(Tag::new(tag), vec![0; 4]); + } + } + if let Some(data) = fs_type { + builder.add_raw(Tag::new(b"OS/2"), data.to_vec()); + } + builder.build() + } + + #[test] + fn subset_permissions_and_precedence() { + assert_eq!(subset_embedding(b"junk", 0), SubsetEmbedding::NotTrueType); + for tag in [b"glyf", b"loca", b"head"] { + assert_eq!(subset_embedding(&font(None, Some(tag)), 0), SubsetEmbedding::NotTrueType); + } + assert_eq!(subset_embedding(&font(None, None), 1), SubsetEmbedding::NotTrueType); + assert_eq!(subset_embedding(&font(Some(&[0; 9]), None), 0), SubsetEmbedding::Allowed); + for (bits, expected) in [ + (0x0000u16, SubsetEmbedding::Allowed), + (0x0004, SubsetEmbedding::Allowed), + (0x0008, SubsetEmbedding::Allowed), + (0x0006, SubsetEmbedding::Allowed), + (0x0002, SubsetEmbedding::Restricted), + (0x0100, SubsetEmbedding::NoSubsetting), + (0x0102, SubsetEmbedding::Restricted), + (0x0302, SubsetEmbedding::BitmapOnly), + ] { + let mut os2 = [0; 10]; + os2[8..10].copy_from_slice(&bits.to_be_bytes()); + assert_eq!(subset_embedding(&font(Some(&os2), None), 0), expected, "fsType {bits:#06x}"); + } + assert_eq!(subset_embedding(&font(None, None), 0), SubsetEmbedding::Allowed); + } +} diff --git a/crates/font-catalog/src/face_data.rs b/crates/font-catalog/src/face_data.rs new file mode 100644 index 0000000000..655c2f4084 --- /dev/null +++ b/crates/font-catalog/src/face_data.rs @@ -0,0 +1,89 @@ +//! Shared ownership of a font file and a face within it. + +use std::sync::Arc; + +/// Font file bytes and the index of a face in that file. +/// +/// Clones share owned bytes, so collection faces and variable instances do not copy the file. +/// Static bytes let applications use embedded fonts without allocating a copy. +#[derive(Clone, Debug)] +pub struct FaceData { + bytes: Bytes, + index: u32, +} + +#[derive(Clone, Debug)] +enum Bytes { + Static(&'static [u8]), + Owned(Arc>), + Shared(Arc<[u8]>), +} + +impl FaceData { + /// A face in statically embedded font bytes. + pub fn from_static(bytes: &'static [u8], index: u32) -> Self { + Self { bytes: Bytes::Static(bytes), index } + } + + /// A face in a shared vector, without copying its allocation. + pub fn from_owned(bytes: Arc>, index: u32) -> Self { + Self { bytes: Bytes::Owned(bytes), index } + } + + /// A face in bytes shared by a catalog. + pub fn from_shared(bytes: Arc<[u8]>, index: u32) -> Self { + Self { bytes: Bytes::Shared(bytes), index } + } + + /// The entire font file. + pub fn bytes(&self) -> &[u8] { + match &self.bytes { + Bytes::Static(bytes) => bytes, + Bytes::Owned(bytes) => bytes.as_slice(), + Bytes::Shared(bytes) => bytes, + } + } + + /// The index of this face in the file. + pub fn index(&self) -> u32 { + self.index + } + + /// Parse this face for font metadata and outlines. + pub fn skrifa(&self) -> Option> { + skrifa::FontRef::from_index(self.bytes(), self.index).ok() + } + + /// Parse this face for shaping. + pub fn harfrust(&self) -> Option> { + harfrust::FontRef::from_index(self.bytes(), self.index).ok() + } +} + +impl From for FaceData { + fn from(data: crate::FontData) -> Self { + Self::from_shared(data.bytes, data.index) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sources_keep_bytes_and_face_index_without_copying() { + static DATA: &[u8] = b"not a font"; + let owned = Arc::new(DATA.to_vec()); + let shared: Arc<[u8]> = Arc::from(DATA); + for data in [FaceData::from_static(DATA, 2), FaceData::from_owned(owned.clone(), 2), FaceData::from_shared(shared.clone(), 2)] { + let clone = data.clone(); + assert_eq!(clone.bytes(), DATA); + assert_eq!(clone.bytes().as_ptr(), data.bytes().as_ptr()); + assert_eq!(clone.index(), 2); + assert!(clone.skrifa().is_none()); + assert!(clone.harfrust().is_none()); + } + assert_eq!(Arc::strong_count(&owned), 1); + assert_eq!(Arc::strong_count(&shared), 1); + } +} diff --git a/crates/font-catalog/src/fallback.rs b/crates/font-catalog/src/fallback.rs new file mode 100644 index 0000000000..2b0d181d00 --- /dev/null +++ b/crates/font-catalog/src/fallback.rs @@ -0,0 +1,62 @@ +//! Face choice for a grapheme cluster. + +/// Characters requiring their own glyph, after numeral or other caller-supplied mapping. +/// Controls, joiners and variation selectors affect shaping but do not need a separate glyph. +pub fn drawable_characters<'a>(cluster: &'a str, map: impl Fn(char) -> char + Copy + 'a) -> impl Iterator + 'a { + cluster + .chars() + .map(map) + .filter(|&c| !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}'))) +} + +/// Select one face for a cluster: prefer the primary if it covers every drawable character; +/// otherwise try each character's fallback until a face covers the whole cluster. If none does, +/// use the first character's fallback when the primary lacks it, or keep the primary. +/// The caller controls the font catalog, ordering and style matching. +pub fn cluster_face( + cluster: &str, + primary: &F, + map: impl Fn(char) -> char + Copy, + primary_covers: impl Fn(char) -> bool, + mut fallback: impl FnMut(char) -> Option, + covers: impl Fn(&F, char) -> bool, +) -> F { + let characters = || drawable_characters(cluster, map); + if characters().all(&primary_covers) { + return primary.clone(); + } + for c in characters() { + if let Some(face) = fallback(c) + && characters().all(|ch| covers(&face, ch)) + { + return face; + } + } + if let Some(c) = characters().next() + && !primary_covers(c) + && let Some(face) = fallback(c) + { + return face; + } + primary.clone() +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn chooses_one_face_for_a_base_and_mark() { + let fallback = |c| match c { + 'a' => Some(1), + '\u{301}' => Some(2), + _ => None, + }; + let covers = |face: &u8, c| *face == 2 || (*face == 1 && c == 'a'); + assert_eq!(cluster_face("a\u{301}\u{200d}", &0, |c| c, |_| false, fallback, covers), 2); + assert_eq!(drawable_characters("a\u{200d}\u{fe0f}", |c| c).collect::(), "a"); + } + #[test] + fn uses_first_character_fallback_when_no_face_covers_cluster() { + assert_eq!(cluster_face("ab", &0, |c| c, |_| false, |c| if c == 'a' { Some(1) } else { Some(2) }, |face, c| (*face, c) == (1, 'a')), 1); + } +} diff --git a/crates/font-catalog/src/lib.rs b/crates/font-catalog/src/lib.rs index c787d3ece1..70aaa19b1f 100644 --- a/crates/font-catalog/src/lib.rs +++ b/crates/font-catalog/src/lib.rs @@ -21,17 +21,39 @@ //! ``` mod catalog; +mod embedding; mod env; +mod face_data; +mod fallback; mod fontconfig; +mod ligature; +mod line_break; +mod outline; +mod plan_cache; mod registry; mod scan; +mod segments; +/// Bounded SFNT face metadata discovery over caller-provided random-access readers. +pub mod sfnt; +mod shape; mod suitcase; pub mod system; +mod visual_order; pub use catalog::{Catalog, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch}; +pub use embedding::{SubsetEmbedding, subset_embedding}; pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs}; +pub use face_data::FaceData; +pub use fallback::{cluster_face, drawable_characters}; pub use fontconfig::fontconfig_dirs; +pub use ligature::ligature_caret_stops; +pub use line_break::settle_line_break; +pub use outline::{FontOutline, GlyphPen, OutlineError}; +pub use plan_cache::ShapePlanCache; pub use scan::{FaceInfo, LocalizedName, Source, is_font_file, style_italic, style_weight, style_width}; +pub use segments::SegmentBoundary; +pub use shape::{RunGlyph, RunInput, ShapeRunError, shape_run}; +pub use visual_order::{VisualGlyph, visual_order}; #[cfg(test)] mod tests; diff --git a/crates/font-catalog/src/ligature.rs b/crates/font-catalog/src/ligature.rs new file mode 100644 index 0000000000..fa9efe5dac --- /dev/null +++ b/crates/font-catalog/src/ligature.rs @@ -0,0 +1,33 @@ +//! Map ligature caret fractions to grapheme boundaries. +use unicode_segmentation::UnicodeSegmentation; + +/// Return logical source-byte caret stops inside a shaped cluster. `font_carets` receives the +/// number of stops and may return their normalized positions along the glyph's logical width. +/// Missing or incorrectly sized font data falls back to equal divisions of the width. +pub fn ligature_caret_stops(text: &str, byte: usize, len: usize, font_carets: impl FnOnce(usize) -> Option>) -> Vec<(usize, f64)> { + let Some(s) = byte.checked_add(len).and_then(|end| text.get(byte..end)).filter(|_| len > 1) else { return Vec::new() }; + let starts: Vec = s.grapheme_indices(true).skip(1).map(|(i, _)| byte + i).collect(); + if starts.is_empty() { + return Vec::new(); + } + let parts = starts.len() + 1; + let mut at = + font_carets(starts.len()).filter(|c| c.len() == starts.len()).unwrap_or_else(|| (1..parts).map(|j| j as f64 / parts as f64).collect()); + at.sort_by(f64::total_cmp); + starts.into_iter().zip(at).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn maps_graphemes_and_sorts_font_positions() { + assert_eq!(ligature_caret_stops("a�bc", 0, 5, |_| Some(vec![0.8, 0.3])), vec![(3, 0.3), (4, 0.8)]); + } + #[test] + fn falls_back_and_rejects_invalid_ranges() { + assert_eq!(ligature_caret_stops("abc", 0, 3, |_| Some(vec![0.5])), vec![(1, 1.0 / 3.0), (2, 2.0 / 3.0)]); + assert!(ligature_caret_stops("abc", usize::MAX, 2, |_| None).is_empty()); + assert!(ligature_caret_stops("é", 1, 1, |_| None).is_empty()); + } +} diff --git a/crates/font-catalog/src/line_break.rs b/crates/font-catalog/src/line_break.rs new file mode 100644 index 0000000000..10983d7170 --- /dev/null +++ b/crates/font-catalog/src/line_break.rs @@ -0,0 +1,49 @@ +//! Choose a line break after measuring candidate lines as drawn. + +/// Choose the latest candidate that fits when a tab changes the line's drawn width. +/// +/// `breaks` must be sorted by glyph index and the boolean marks hyphenated breaks. +/// `checks` limits the candidates measured individually from the end; older non-hyphenated +/// candidates are bisected, assuming their drawn widths are nondecreasing. If none fits, +/// the earliest eligible break is returned. Without a tab or a measurement callback the +/// original `chosen` break is returned. +pub fn settle_line_break( + tabbed: bool, + checks: usize, + start: usize, + chosen: (usize, bool), + breaks: &[(usize, bool)], + fits: Option<&dyn Fn(usize, bool) -> bool>, +) -> (usize, bool) { + let Some(fits) = fits.filter(|_| tabbed) else { return chosen }; + if fits(chosen.0, chosen.1) { + return chosen; + } + let earlier = breaks.get(breaks.partition_point(|b| b.0 <= start)..breaks.partition_point(|b| b.0 < chosen.0)).unwrap_or_default(); + if let Some(&b) = earlier.iter().rev().take(checks).find(|b| fits(b.0, b.1)) { + return b; + } + let rest = earlier.get(..earlier.len().saturating_sub(checks)).unwrap_or_default(); + let plain: Vec<&(usize, bool)> = rest.iter().filter(|b| !b.1).collect(); + let fitting = plain.partition_point(|b| fits(b.0, b.1)); + fitting.checked_sub(1).and_then(|k| plain.get(k).copied()).or(earlier.first()).copied().unwrap_or(chosen) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn measures_latest_candidates_and_preserves_hyphenation() { + let breaks = [(1, false), (2, false), (3, true), (4, false)]; + let fits = |i, hyphen| i <= 2 || (i == 3 && hyphen); + assert_eq!(settle_line_break(true, 2, 0, (4, false), &breaks, Some(&fits)), (3, true)); + assert_eq!(settle_line_break(false, 2, 0, (4, false), &breaks, Some(&fits)), (4, false)); + } + #[test] + fn bisects_older_plain_breaks_and_falls_back_to_first_eligible() { + let breaks = [(1, false), (2, true), (3, false), (4, false), (5, false)]; + assert_eq!(settle_line_break(true, 1, 0, (5, false), &breaks, Some(&|i, _| i <= 3)), (3, false)); + assert_eq!(settle_line_break(true, 1, 1, (5, false), &breaks, Some(&|_, _| false)), (2, true)); + assert_eq!(settle_line_break(true, 1, 5, (5, false), &breaks, Some(&|_, _| false)), (5, false)); + } +} diff --git a/crates/font-catalog/src/outline.rs b/crates/font-catalog/src/outline.rs new file mode 100644 index 0000000000..f48b61e4f2 --- /dev/null +++ b/crates/font-catalog/src/outline.rs @@ -0,0 +1,399 @@ +//! Unhinted glyph outlines and metrics for catalog faces. + +use kurbo::BezPath; +use skrifa::instance::{Location, Size}; +use skrifa::outline::{DrawSettings, OutlinePen}; +use skrifa::{FontRef, GlyphId, MetadataProvider, Tag}; + +use crate::{FontData, LoadedFace}; + +/// A parsed face and its variation location. Coordinates use font design units, with y up. +/// The bytes can come from a catalog or any other source, including a collection face. +pub struct FontOutline<'a> { + font: FontRef<'a>, + location: Location, +} + +/// Receives unhinted glyph commands in design units (y up). Implementations own their +/// storage and resource policy; drawing writes directly to the sink without an intermediate path. +pub trait GlyphPen { + /// Start a contour. + fn move_to(&mut self, x: f32, y: f32); + /// Add a straight segment. + fn line_to(&mut self, x: f32, y: f32); + /// Add a quadratic segment. + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32); + /// Add a cubic segment. + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32); + /// Close the current contour. + fn close(&mut self); +} + +struct Sink<'a>(&'a mut dyn GlyphPen); +impl OutlinePen for Sink<'_> { + fn move_to(&mut self, x: f32, y: f32) { + self.0.move_to(x, y); + } + fn line_to(&mut self, x: f32, y: f32) { + self.0.line_to(x, y); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + self.0.quad_to(x1, y1, x, y); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + self.0.curve_to(x1, y1, x2, y2, x, y); + } + fn close(&mut self) { + self.0.close(); + } +} + +/// Why a font or glyph outline could not be read. +#[derive(Debug, thiserror::Error)] +pub enum OutlineError { + /// The face index or font data is invalid. + #[error("invalid font face")] + InvalidFace, + /// The glyph has no outline in this face. + #[error("glyph has no outline")] + MissingGlyph, + /// The glyph's outline is malformed. + #[error("cannot draw glyph outline: {0}")] + Draw(#[from] skrifa::outline::DrawError), + /// The glyph emitted more path elements than the safety limit. + #[error("glyph outline exceeds the element limit")] + TooComplex, + /// The outline starts without a move command. + #[error("glyph outline has no initial move")] + InvalidPath, +} + +impl<'a> FontOutline<'a> { + /// Parse the given face and select axis values in user units. Unknown axes are ignored and + /// values are clamped to their axis ranges by the font parser. + pub fn new(data: &'a FontData, variations: &[([u8; 4], f32)]) -> Result { + Self::from_bytes(&data.bytes, data.index, variations) + } + + /// Parse borrowed bytes and a collection face index without copying the font. + pub fn from_bytes(bytes: &'a [u8], index: u32, variations: &[([u8; 4], f32)]) -> Result { + let font = FontRef::from_index(bytes, index).map_err(|_| OutlineError::InvalidFace)?; + let location = font.axes().location(variations.iter().map(|(tag, value)| (Tag::new(tag), *value))); + Ok(Self { font, location }) + } + + /// Parse a catalog face, retaining the axis settings of a named instance. + pub fn from_loaded(face: &'a LoadedFace) -> Result { + Self::new(&face.data, &face.info.variations) + } + + /// Font-wide metrics in unscaled design units at this variation location. + pub fn metrics(&self) -> skrifa::metrics::Metrics { + self.font.metrics(Size::unscaled(), &self.location) + } + + /// Resolve a Unicode scalar to a glyph identifier. + pub fn glyph_for(&self, character: char) -> Option { + self.font.charmap().map(character).map(|id| id.to_u32()) + } + + /// Stream an unhinted glyph into the caller's sink. On an error, commands already sent + /// remain in the sink. The sink owns any allocation and enforces its own resource limit. + pub fn draw_to(&self, glyph: u32, pen: &mut dyn GlyphPen) -> Result<(), OutlineError> { + let outline = self.font.outline_glyphs().get(GlyphId::new(glyph)).ok_or(OutlineError::MissingGlyph)?; + outline.draw(DrawSettings::unhinted(Size::unscaled(), &self.location), &mut Sink(pen))?; + Ok(()) + } + + /// Draw a glyph in design units. Empty glyphs such as spaces can produce an empty path. + /// A malformed or excessively complex glyph returns an error instead of partial geometry. + pub fn outline(&self, glyph: u32) -> Result { + let (path, status) = self.outline_recovering(glyph)?; + status.map(|()| path) + } + + /// Draw a glyph while retaining the bounded prefix produced before a draw error. This is + /// useful for consumers preserving existing rendering of damaged fonts. The inner result + /// reports whether the returned path is complete; the outer error means no glyph was found. + /// Paths stop growing at 100,000 elements, even when the font is untrusted. + pub fn outline_recovering(&self, glyph: u32) -> Result<(BezPath, Result<(), OutlineError>), OutlineError> { + let outline = self.font.outline_glyphs().get(GlyphId::new(glyph)).ok_or(OutlineError::MissingGlyph)?; + let mut pen = PathPen::new(); + let result = outline.draw(DrawSettings::unhinted(Size::unscaled(), &self.location), &mut pen); + let status = if pen.invalid { + Err(OutlineError::InvalidPath) + } else if pen.truncated { + Err(OutlineError::TooComplex) + } else { + result.map(|_| ()).map_err(OutlineError::Draw) + }; + Ok((pen.path, status)) + } +} + +const MAX_OUTLINE_ELEMENTS: usize = 100_000; +struct PathPen { + path: BezPath, + truncated: bool, + invalid: bool, +} +impl PathPen { + fn new() -> Self { + Self { path: BezPath::new(), truncated: false, invalid: false } + } + fn has_start(&mut self) -> bool { + if self.path.elements().is_empty() { + self.invalid = true; + false + } else { + true + } + } + fn room(&mut self) -> bool { + if self.path.elements().len() >= MAX_OUTLINE_ELEMENTS { + self.truncated = true; + false + } else { + true + } + } +} +impl OutlinePen for PathPen { + fn move_to(&mut self, x: f32, y: f32) { + if self.room() { + self.path.move_to((f64::from(x), f64::from(y))); + } + } + fn line_to(&mut self, x: f32, y: f32) { + if self.has_start() && self.room() { + self.path.line_to((f64::from(x), f64::from(y))); + } + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + if self.has_start() && self.room() { + self.path.quad_to((f64::from(x1), f64::from(y1)), (f64::from(x), f64::from(y))); + } + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + if self.has_start() && self.room() { + self.path.curve_to((f64::from(x1), f64::from(y1)), (f64::from(x2), f64::from(y2)), (f64::from(x), f64::from(y))); + } + } + fn close(&mut self) { + if self.has_start() && self.room() { + self.path.close_path(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::PathEl; + use std::sync::Arc; + + impl GlyphPen for PathPen { + fn move_to(&mut self, x: f32, y: f32) { + OutlinePen::move_to(self, x, y); + } + fn line_to(&mut self, x: f32, y: f32) { + OutlinePen::line_to(self, x, y); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + OutlinePen::quad_to(self, x1, y1, x, y); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + OutlinePen::curve_to(self, x1, y1, x2, y2, x, y); + } + fn close(&mut self) { + OutlinePen::close(self); + } + } + + #[test] + fn rejects_invalid_face_and_collection_index() { + let data = FontData { bytes: Arc::from(&b"not a font"[..]), index: 0 }; + assert!(matches!(FontOutline::new(&data, &[]), Err(OutlineError::InvalidFace))); + } + + #[test] + fn pen_preserves_geometry_and_upward_y() { + let mut pen = PathPen::new(); + OutlinePen::move_to(&mut pen, 1.0, 2.0); + OutlinePen::line_to(&mut pen, 3.0, 4.0); + OutlinePen::quad_to(&mut pen, 5.0, 6.0, 7.0, 8.0); + OutlinePen::curve_to(&mut pen, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0); + OutlinePen::close(&mut pen); + assert_eq!( + pen.path.elements(), + &[ + PathEl::MoveTo((1.0, 2.0).into()), + PathEl::LineTo((3.0, 4.0).into()), + PathEl::QuadTo((5.0, 6.0).into(), (7.0, 8.0).into()), + PathEl::CurveTo((9.0, 10.0).into(), (11.0, 12.0).into(), (13.0, 14.0).into()), + PathEl::ClosePath, + ] + ); + } + + #[test] + fn streaming_adapter_forwards_each_command_and_rejects_an_invalid_prefix() { + let mut pen = PathPen::new(); + { + let mut sink = Sink(&mut pen); + OutlinePen::move_to(&mut sink, 1.0, 2.0); + OutlinePen::line_to(&mut sink, 3.0, 4.0); + OutlinePen::quad_to(&mut sink, 5.0, 6.0, 7.0, 8.0); + OutlinePen::curve_to(&mut sink, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0); + OutlinePen::close(&mut sink); + } + assert_eq!(pen.path.elements().len(), 5); + assert_eq!(pen.path.elements()[2], PathEl::QuadTo((5.0, 6.0).into(), (7.0, 8.0).into())); + let mut invalid = PathPen::new(); + OutlinePen::line_to(&mut invalid, 1.0, 2.0); + assert!(invalid.invalid); + assert!(invalid.path.elements().is_empty()); + } + + #[test] + fn pen_caps_path_growth() { + let mut pen = PathPen::new(); + OutlinePen::move_to(&mut pen, 0.0, 0.0); + for _ in 0..MAX_OUTLINE_ELEMENTS { + OutlinePen::line_to(&mut pen, 1.0, 2.0); + } + assert_eq!(pen.path.elements().len(), MAX_OUTLINE_ELEMENTS); + assert!(pen.truncated); + } + + #[test] + fn reads_craft_font_when_available() { + let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return }; + let bytes = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-hebrew/NotoSansHebrew-Regular.ttf")).unwrap(); + let data = FontData { bytes: bytes.into(), index: 0 }; + let face = FontOutline::new(&data, &[]).unwrap(); + assert!(face.metrics().units_per_em > 0); + let glyph = face.glyph_for('�').unwrap(); + assert!(!face.outline(glyph).unwrap().elements().is_empty()); + assert!(matches!(face.outline(u32::MAX), Err(OutlineError::MissingGlyph))); + let invalid_index = FontData { bytes: data.bytes.clone(), index: u32::MAX }; + assert!(matches!(FontOutline::new(&invalid_index, &[]), Err(OutlineError::InvalidFace))); + } + + #[test] + fn variation_changes_glyph_geometry() { + let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return }; + let bytes = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-arabic/NotoSansArabic.ttf")).unwrap(); + let data = FontData { bytes: bytes.into(), index: 0 }; + let light = FontOutline::new(&data, &[(*b"wght", 100.0)]).unwrap(); + let bold = FontOutline::new(&data, &[(*b"wght", 900.0)]).unwrap(); + let glyph = light.glyph_for('ب').unwrap(); + let light_path = light.outline(glyph).unwrap(); + let bold_path = bold.outline(glyph).unwrap(); + assert!(!light_path.elements().is_empty()); + assert_ne!(light_path, bold_path); + } + + // Construct a minimal CFF font so CI can exercise the public API without installed fonts. + fn cff_font(program: &[u8]) -> Vec { + let mut cff = vec![1, 0, 4, 4, 0, 1, 1, 1, 2, b'X', 0, 1, 1, 1, 7, 29, 0, 0, 0, 25, 17, 0, 0, 0, 0]; + cff.extend_from_slice(&[0, 1, 4]); + cff.extend_from_slice(&1u32.to_be_bytes()); + cff.extend_from_slice(&((program.len() as u32) + 1).to_be_bytes()); + cff.extend_from_slice(program); + let mut builder = write_fonts::FontBuilder::new(); + let mut head = vec![0; 54]; + head[18..20].copy_from_slice(&1000u16.to_be_bytes()); + let mut hhea = vec![0; 36]; + hhea[34..36].copy_from_slice(&1u16.to_be_bytes()); + builder.add_raw(write_fonts::types::Tag::new(b"head"), head); + builder.add_raw(write_fonts::types::Tag::new(b"hhea"), hhea); + builder.add_raw(write_fonts::types::Tag::new(b"hmtx"), vec![0, 100, 0, 0]); + builder.add_raw(write_fonts::types::Tag::new(b"maxp"), vec![0, 0, 0x50, 0, 0, 1]); + builder.add_raw(write_fonts::types::Tag::new(b"CFF "), cff); + builder.build() + } + + #[test] + fn malformed_cff_recovers_the_same_prefix_as_direct_drawing() { + // Move and line, then callsubr without an operand: a prefix is emitted before failure. + let bytes = cff_font(&[139, 139, 21, 239, 139, 5, 10, 14]); + let gid = 0; + let f = FontRef::new(&bytes).unwrap(); + let mut old = PathPen::new(); + let result = + f.outline_glyphs().get(GlyphId::new(gid)).unwrap().draw(DrawSettings::unhinted(Size::unscaled(), &Location::default()), &mut old); + assert!(result.is_err()); + assert!(!old.path.elements().is_empty()); + let shared = FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); + assert_eq!(shared.metrics().units_per_em, 1000); + assert_eq!(shared.glyph_for('A'), None); + let (prefix, status) = shared.outline_recovering(gid).unwrap(); + assert!(matches!(status, Err(OutlineError::Draw(_)))); + assert_eq!(prefix, old.path); + let mut streamed = PathPen::new(); + assert!(matches!(shared.draw_to(gid, &mut streamed), Err(OutlineError::Draw(_)))); + assert_eq!(streamed.path, old.path); + assert!(matches!(shared.outline(gid), Err(OutlineError::Draw(_)))); + } + + #[test] + fn streaming_preserves_a_large_valid_cff_outline() { + // Minimal CFF with more than 100,000 line segments. + let mut program = vec![139, 139, 21]; + for _ in 0..100_001 { + program.extend_from_slice(&[140, 6]); + } + program.push(14); + let bytes = cff_font(&program); + let shared = FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); + struct Count(usize); + impl GlyphPen for Count { + fn move_to(&mut self, _: f32, _: f32) { + self.0 += 1; + } + fn line_to(&mut self, _: f32, _: f32) { + self.0 += 1; + } + fn quad_to(&mut self, _: f32, _: f32, _: f32, _: f32) { + self.0 += 1; + } + fn curve_to(&mut self, _: f32, _: f32, _: f32, _: f32, _: f32, _: f32) { + self.0 += 1; + } + fn close(&mut self) { + self.0 += 1; + } + } + impl OutlinePen for Count { + fn move_to(&mut self, x: f32, y: f32) { + GlyphPen::move_to(self, x, y); + } + fn line_to(&mut self, x: f32, y: f32) { + GlyphPen::line_to(self, x, y); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + GlyphPen::quad_to(self, x1, y1, x, y); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + GlyphPen::curve_to(self, x1, y1, x2, y2, x, y); + } + fn close(&mut self) { + GlyphPen::close(self); + } + } + let mut old = Count(0); + FontRef::new(&bytes) + .unwrap() + .outline_glyphs() + .get(GlyphId::new(0)) + .unwrap() + .draw(DrawSettings::unhinted(Size::unscaled(), &Location::default()), &mut old) + .unwrap(); + let mut count = Count(0); + shared.draw_to(0, &mut count).unwrap(); + assert_eq!(count.0, old.0); + assert!(count.0 > MAX_OUTLINE_ELEMENTS); + assert!(matches!(shared.outline(0), Err(OutlineError::TooComplex))); + } +} diff --git a/crates/font-catalog/src/plan_cache.rs b/crates/font-catalog/src/plan_cache.rs new file mode 100644 index 0000000000..d428de4cd7 --- /dev/null +++ b/crates/font-catalog/src/plan_cache.rs @@ -0,0 +1,52 @@ +//! Per-face bounded shaping plan reuse. + +use std::sync::{Arc, Mutex}; + +/// A cache for one font face and variation instance. Do not share it across faces or instances. +/// Plans are created outside the lock, then checked again to avoid retaining duplicates. +#[derive(Default)] +pub struct ShapePlanCache { + plans: Mutex>>, +} + +impl ShapePlanCache { + /// Maximum number of plans retained; the oldest is evicted when this is reached. + pub const CAPACITY: usize = 32; + + /// Returns a matching plan or builds and retains one for this face. + pub fn get_or_create( + &self, + shaper: &harfrust::Shaper<'_>, + instance: Option<&harfrust::ShaperInstance>, + direction: harfrust::Direction, + script: Option, + language: Option<&harfrust::Language>, + features: &[harfrust::Feature], + ) -> Arc { + let key = harfrust::ShapePlanKey::new(script, direction).language(language).instance(instance).features(features); + let kept = |plans: &[Arc]| plans.iter().rev().find(|p| key.matches(p)).cloned(); + if let Some(plan) = kept(&self.plans.lock().unwrap_or_else(|e| e.into_inner())) { + return plan; + } + let plan = Arc::new(harfrust::ShapePlan::new(shaper, direction, script, language, features)); + let mut plans = self.plans.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(made) = kept(&plans) { + return made; + } + if plans.len() >= Self::CAPACITY { + plans.remove(0); + } + plans.push(plan.clone()); + plan + } + + /// Number of retained plans. + pub fn len(&self) -> usize { + self.plans.lock().unwrap_or_else(|e| e.into_inner()).len() + } + + /// Whether this cache contains no plans. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} diff --git a/crates/font-catalog/src/segments.rs b/crates/font-catalog/src/segments.rs new file mode 100644 index 0000000000..e36a051446 --- /dev/null +++ b/crates/font-catalog/src/segments.rs @@ -0,0 +1,55 @@ +//! Boundaries between runs that need separate shaping. + +/// Tracks the properties of the current shaping segment while walking grapheme clusters. +/// The caller resolves font faces, bidi levels and script classification; marks stay with the +/// preceding segment even when their face, level or case differs. +pub struct SegmentBoundary { + face: F, + level: L, + small_caps: bool, + strong_script: Option, +} + +impl SegmentBoundary { + /// Begin at the first segment's face and bidi level. + pub fn new(face: F, level: L) -> Self { + Self { face, level, small_caps: false, strong_script: None } + } + + /// Observe a cluster and return whether it begins a new shaping segment. Pass `None` for + /// common or inherited script and `true` for marks, joiners and variation selectors. + pub fn advance(&mut self, face: F, level: L, small_caps: bool, strong_script: Option, mark: bool) -> bool { + let script_change = matches!((self.strong_script, strong_script), (Some(a), Some(b)) if a != b); + let split = (self.face != face || self.level != level || self.small_caps != small_caps || script_change) && !mark; + if split { + self.face = face; + self.level = level; + self.small_caps = small_caps; + } + if let Some(script) = strong_script { + self.strong_script = Some(script); + } + split + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn preserves_marks_and_splits_on_face_direction_case_and_script() { + let mut state = SegmentBoundary::::new(1, 0); + assert!(!state.advance(1, 0, false, Some(1), false)); + assert!(!state.advance(2, 1, true, None, true)); + assert!(state.advance(2, 1, true, Some(2), false)); + assert!(!state.advance(2, 1, true, None, false)); + assert!(state.advance(2, 1, true, Some(1), false)); + } + #[test] + fn strong_script_on_a_mark_updates_the_following_boundary() { + let mut state = SegmentBoundary::::new(1, 0); + assert!(!state.advance(1, 0, false, Some(1), false)); + assert!(!state.advance(1, 0, false, Some(2), true)); + assert!(!state.advance(1, 0, false, Some(2), false)); + } +} diff --git a/crates/font-catalog/src/sfnt.rs b/crates/font-catalog/src/sfnt.rs new file mode 100644 index 0000000000..83efa64ddb --- /dev/null +++ b/crates/font-catalog/src/sfnt.rs @@ -0,0 +1,178 @@ +//! Minimal SFNT (TrueType / OpenType / collection) header reader for font discovery: reads only +//! the table directory, `name` and `OS/2` of each face, so scanning a system font folder does not +//! load whole files. + +use std::io::{Read, Seek, SeekFrom}; + +/// The tables skrifa reads glyph outlines from: TrueType, CFF, CFF2 and VARC. The renderer draws +/// no glyph of a face that has none of them, such as a face with bitmaps only or with its outlines +/// in Apple's `hvgl` table. +const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"]; + +/// Names and style attributes of one face in a font file. +#[derive(Clone, Debug, PartialEq)] +pub struct FaceNames { + pub index: u32, + pub family: String, + pub style: String, + pub full_name: String, + pub weight: u16, + pub italic: bool, +} + +fn be16(b: &[u8], o: usize) -> Option { + Some(u16::from_be_bytes([*b.get(o)?, *b.get(o + 1)?])) +} +fn be32(b: &[u8], o: usize) -> Option { + Some(u32::from_be_bytes([*b.get(o)?, *b.get(o + 1)?, *b.get(o + 2)?, *b.get(o + 3)?])) +} + +fn read_at(r: &mut R, off: u64, len: usize) -> Option> { + if len > 4 << 20 { + return None; + } + r.seek(SeekFrom::Start(off)).ok()?; + let mut v = vec![0u8; len]; + r.read_exact(&mut v).ok()?; + Some(v) +} + +/// Read the names of every face in a font file (a single font or a collection). Faces with none +/// of the `OUTLINE_TABLES` are left out. +pub fn read_faces(r: &mut R) -> Vec { + let Some(head) = read_at(r, 0, 12) else { return Vec::new() }; + let offsets: Vec = if &head[0..4] == b"ttcf" { + let n = be32(&head, 8).unwrap_or(0).min(256) as usize; + let Some(t) = read_at(r, 12, n * 4) else { return Vec::new() }; + (0..n).filter_map(|i| be32(&t, i * 4)).collect() + } else { + vec![0] + }; + offsets.iter().enumerate().filter_map(|(i, &o)| read_face(r, o as u64, i as u32)).collect() +} + +/// Names from in-memory font data. +pub fn read_faces_bytes(data: &[u8]) -> Vec { + read_faces(&mut std::io::Cursor::new(data)) +} + +fn read_face(r: &mut R, off: u64, index: u32) -> Option { + let h = read_at(r, off, 12)?; + let tag = &h[0..4]; + if tag != [0, 1, 0, 0] && tag != b"OTTO" && tag != b"true" { + return None; + } + let n = be16(&h, 4)? as usize; + let dir = read_at(r, off + 12, n * 16)?; + if !dir.as_chunks::<16>().0.iter().any(|rec| OUTLINE_TABLES.iter().any(|t| rec.starts_with(*t))) { + return None; + } + let mut name = None; + let mut os2 = None; + for i in 0..n { + let rec = &dir[i * 16..i * 16 + 16]; + let (o, l) = (be32(rec, 8)? as u64, be32(rec, 12)? as usize); + match &rec[0..4] { + b"name" => name = Some((o, l)), + b"OS/2" => os2 = Some((o, l)), + _ => {} + } + } + let (no, nl) = name?; + let nb = read_at(r, no, nl)?; + let get = |id: u16| name_string(&nb, id); + let family = get(16).or_else(|| get(1))?; + let style = get(17).or_else(|| get(2)).unwrap_or_else(|| "Regular".into()); + let full_name = get(4).unwrap_or_else(|| format!("{family} {style}")); + let (mut weight, mut italic) = (400u16, false); + if let Some((oo, ol)) = os2 + && let Some(ob) = read_at(r, oo, ol.min(78)) + { + weight = be16(&ob, 4).unwrap_or(400); + italic = be16(&ob, 62).is_some_and(|fs| fs & 1 != 0); + } + let sl = style.to_ascii_lowercase(); + italic |= sl.contains("italic") || sl.contains("oblique"); + Some(FaceNames { index, family, style, full_name, weight, italic }) +} + +/// A name-table string by id, preferring Windows Unicode English, then any Unicode, then Mac Roman. +fn name_string(b: &[u8], id: u16) -> Option { + let count = be16(b, 2)? as usize; + let storage = be16(b, 4)? as usize; + let mut best: Option<(u8, String)> = None; + for i in 0..count { + let r = 6 + i * 12; + let (plat, enc, lang, nid, len, off) = + (be16(b, r)?, be16(b, r + 2)?, be16(b, r + 4)?, be16(b, r + 6)?, be16(b, r + 8)? as usize, be16(b, r + 10)? as usize); + if nid != id { + continue; + } + let rank = match plat { + 3 if enc == 1 || enc == 10 => { + if best.as_ref().is_some_and(|(current, _)| *current <= if lang == 0x409 { 0 } else { 1 }) { + continue; + } + if lang == 0x409 { 0 } else { 1 } + } + 0 => { + if best.as_ref().is_some_and(|(current, _)| *current <= 2) { + continue; + } + 2 + } + 1 if enc == 0 => { + if best.as_ref().is_some_and(|(current, _)| *current <= 3) { + continue; + } + 3 + } + _ => continue, + }; + // Only decode a record that can improve the selected name. A hostile name table may + // point thousands of records at the same huge string. + let raw = b.get(storage + off..storage + off + len)?; + let s = match plat { + 3 => { + let u: Vec = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); + String::from_utf16_lossy(&u) + } + 0 => { + let u: Vec = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); + String::from_utf16_lossy(&u) + } + 1 => raw.iter().map(|&c| if c < 128 { c as char } else { '?' }).collect(), + _ => return None, + }; + best = Some((rank, s)); + } + best.map(|(_, s)| s).filter(|s| !s.trim().is_empty()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn later_non_improving_name_records_are_not_decoded() { + // The first record is the preferred Windows-English value. The second names an invalid + // range: it must be ignored instead of making the whole name lookup fail. + let mut table = vec![0; 30]; + table[2..4].copy_from_slice(&2u16.to_be_bytes()); + table[4..6].copy_from_slice(&30u16.to_be_bytes()); + let first = 6usize; + table[first..first + 2].copy_from_slice(&3u16.to_be_bytes()); + table[first + 2..first + 4].copy_from_slice(&1u16.to_be_bytes()); + table[first + 4..first + 6].copy_from_slice(&0x409u16.to_be_bytes()); + table[first + 6..first + 8].copy_from_slice(&1u16.to_be_bytes()); + table[first + 8..first + 10].copy_from_slice(&4u16.to_be_bytes()); + let second = first + 12; + table[second..second + 2].copy_from_slice(&3u16.to_be_bytes()); + table[second + 2..second + 4].copy_from_slice(&1u16.to_be_bytes()); + table[second + 4..second + 6].copy_from_slice(&0x409u16.to_be_bytes()); + table[second + 6..second + 8].copy_from_slice(&1u16.to_be_bytes()); + table[second + 8..second + 10].copy_from_slice(&u16::MAX.to_be_bytes()); + table.extend_from_slice(&[0, b'A', 0, b'B']); + assert_eq!(name_string(&table, 1).as_deref(), Some("AB")); + } +} diff --git a/crates/font-catalog/src/shape.rs b/crates/font-catalog/src/shape.rs new file mode 100644 index 0000000000..966597d3b5 --- /dev/null +++ b/crates/font-catalog/src/shape.rs @@ -0,0 +1,181 @@ +//! Shape a run with its source clusters and surrounding text context. + +use std::sync::Arc; + +use harfrust::{BufferClusterLevel, Direction, Feature, Language, Script, ShapeOptions, ShapePlan, Shaper, UnicodeBuffer}; + +/// Parameters for a single directional run. Text is in logical order and `source_start` is its +/// byte offset in the complete source. Context influences joining but emits no glyphs. +pub struct RunInput<'a> { + /// Text in this run. + pub text: &'a str, + /// Its byte offset in the complete source. + pub source_start: usize, + /// Text before the run, within the same shaping context. + pub pre_context: &'a str, + /// Text after the run, within the same shaping context. + pub post_context: &'a str, + /// Direction of shaping. + pub direction: Direction, + /// Language used for language-specific forms. + pub language: Option<&'a Language>, + /// OpenType features with ranges in source byte coordinates. + pub features: &'a [Feature], + /// Use character-level instead of monotone grapheme clusters. + pub character_clusters: bool, + /// Uppercase each mapped character without losing its source cluster. + pub uppercase: bool, +} + +/// A glyph in design units, with its source-byte cluster and directional advances and offsets. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RunGlyph { + pub glyph_id: u32, + pub cluster: u32, + pub x_advance: i32, + pub y_advance: i32, + pub x_offset: i32, + pub y_offset: i32, +} + +/// A run's source offsets cannot fit HarfRust's 32-bit clusters. +#[derive(Debug, thiserror::Error)] +#[error("shaping cluster exceeds the 32-bit source offset range")] +pub struct ShapeRunError; + +/// Shape a run using a caller's face-specific plan cache. `map_character` applies digit or other +/// character mapping before case conversion; expansions retain the original byte cluster. +/// The plan callback receives the guessed script, direction, language and feature set so it can +/// reuse plans for the particular shaper and its variable-font instance. +pub fn shape_run( + shaper: &Shaper<'_>, + input: &RunInput<'_>, + mut map_character: impl FnMut(char) -> char, + plan: impl FnOnce(&Shaper<'_>, Direction, Option + + "##; + let checked = crate::tree::preflight(svg, &Limits::default()).unwrap(); + assert_eq!( + checked.unsupported_elements(), + vec![("animate", 2), ("animateTransform", 1), ("foreignObject", 1), ("script", 1), ("set", 1)], + "the XHTML div is not an SVG element" + ); + // The same checked XML still parses. + assert!(checked.parse(&usvg::Options::default()).is_ok()); + let plain = crate::tree::preflight(r#""#, &Limits::default()).unwrap(); + assert!(plain.unsupported_elements().is_empty()); +} + +#[cfg(feature = "tree-text")] +#[test] +fn local_text_is_placed_and_bounded_in_its_parents_frame() { + let mut options = usvg::Options::default(); + let fonts = options.fontdb_mut(); + fonts.load_font_data(include_bytes!("../../../ui/tests/fonts/NotoSans-test.ttf").to_vec()); + let family = fonts.faces().next().unwrap().families[0].0.clone(); + let svg = format!( + r#"Hi"# + ); + let tree = parse(svg.as_bytes(), &Limits::default(), &options).unwrap(); + let local = Document::from_tree_local(&tree, 64); + let absolute = Document::from_tree(&tree, 64); + + let groups = group_ids(&local.nodes); + let text = groups.iter().find(|(id, _)| id == "t").unwrap(); + assert!(close([text.1[0], text.1[3]], [1.0, 1.0]) && close([text.1[4], text.1[5]], [0.0, 0.0]), "text sits in its group's frame: {text:?}"); + + let bounds = |nodes: &[Node]| -> [f64; 4] { + let Node::Group { children, .. } = &nodes[0] else { panic!() }; + let Node::Group { bounds, .. } = &children[0] else { panic!() }; + *bounds + }; + let (l, a) = (bounds(&local.nodes), bounds(&absolute.nodes)); + assert!(close([l[0] + 50.0, l[1]], [a[0], a[1]]) && close([l[2], l[3]], [a[2], a[3]]), "local {l:?} vs absolute {a:?}"); + assert!(l[0] > 0.0 && l[0] < 10.0, "near x=5 in the group's frame: {l:?}"); + + let (mut lp, mut ap) = (Vec::new(), Vec::new()); + document_points(&local.nodes, IDENTITY, true, &mut lp); + document_points(&absolute.nodes, IDENTITY, false, &mut ap); + assert!(!lp.is_empty() && lp.len() == ap.len()); + assert!(lp.iter().zip(&ap).all(|(l, a)| close(*l, *a))); +} diff --git a/crates/svg/src/tree/primitive.rs b/crates/svg/src/tree/primitive.rs new file mode 100644 index 0000000000..a43933ec3c --- /dev/null +++ b/crates/svg/src/tree/primitive.rs @@ -0,0 +1,164 @@ +//! Basic shapes recovered from a scene path. usvg turns `rect`, `circle` and `ellipse` into +//! paths; an app that edits them as shapes (a rectangle with corner radii, an ellipse) gets them +//! back here from the segments alone. +//! +//! A path is a primitive when it is one closed contour whose points all lie on the outline of +//! an axis-aligned (rounded) rectangle or ellipse and that encloses its area. The check works on +//! the segments as given, so use it on a [`Coordinates::Local`](super::document::Coordinates) +//! scene, where a rotated or skewed shape keeps its own axes. + +use super::document::Segment; + +/// An axis-aligned basic shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Primitive { + /// A rectangle, with elliptical corners of radii `rx`, `ry` (both 0 for square corners). + Rect { x: f64, y: f64, width: f64, height: f64, rx: f64, ry: f64 }, + /// An ellipse (a circle when `rx == ry`). + Ellipse { cx: f64, cy: f64, rx: f64, ry: f64 }, +} + +/// Most segments a primitive's contour has: usvg writes a rounded rectangle as 4 lines and up to +/// 4 curves per corner. +const MAX_SEGMENTS: usize = 32; +/// Points sampled on each curve, besides its ends: enough that the polygon through them +/// encloses a curved outline's area to well within the area check's 1%. +const SAMPLES: usize = 31; + +/// The curve parameters sampled between a curve's ends. +fn samples() -> impl Iterator { + (1..=SAMPLES).map(|i| i as f64 / (SAMPLES + 1) as f64) +} + +/// The basic shape `segments` draw, if they draw one. +pub fn recognize(segments: &[Segment]) -> Option { + let (ends, points) = contour(segments)?; + let (mut min, mut max) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for p in &points { + for axis in 0..2 { + min[axis] = min[axis].min(p[axis]); + max[axis] = max[axis].max(p[axis]); + } + } + let (width, height) = (max[0] - min[0], max[1] - min[1]); + if !(width.is_finite() && height.is_finite()) || width <= 0.0 || height <= 0.0 { + return None; + } + let tol = 1e-3 * width.max(height); + // The straight part of the top edge starts `rx` in; of the left edge, `ry` down. + let rx = ends.iter().filter(|p| (p[1] - min[1]).abs() <= tol).map(|p| p[0] - min[0]).fold(f64::INFINITY, f64::min); + let ry = ends.iter().filter(|p| (p[0] - min[0]).abs() <= tol).map(|p| p[1] - min[1]).fold(f64::INFINITY, f64::min); + let rx = snap(rx, width / 2.0, tol)?; + let ry = snap(ry, height / 2.0, tol)?; + if (rx == 0.0) != (ry == 0.0) { + return None; + } + let inner = ([min[0] + rx, min[1] + ry], [max[0] - rx, max[1] - ry]); + let on_outline = |p: &[f64; 2]| { + let q = [p[0].clamp(inner.0[0], inner.1[0]), p[1].clamp(inner.0[1], inner.1[1])]; + let d = [p[0] - q[0], p[1] - q[1]]; + if rx == 0.0 { + // Square corners: on an edge of the box. + (p[0] - min[0]).abs() <= tol || (p[0] - max[0]).abs() <= tol || (p[1] - min[1]).abs() <= tol || (p[1] - max[1]).abs() <= tol + } else if d == [0.0, 0.0] { + false + } else { + let e = (d[0] / rx).hypot(d[1] / ry); + (e - 1.0).abs() * rx.min(ry) <= tol || (d[0] == 0.0 && (d[1].abs() - ry).abs() <= tol) || (d[1] == 0.0 && (d[0].abs() - rx).abs() <= tol) + } + }; + if !points.iter().all(on_outline) { + return None; + } + // Every point is on the outline; it also has to go all the way round once. + let expected = width * height - (4.0 - std::f64::consts::PI) * rx * ry; + if (area(&points).abs() - expected).abs() > 0.01 * expected { + return None; + } + if (rx - width / 2.0).abs() <= tol && (ry - height / 2.0).abs() <= tol { + return Some(Primitive::Ellipse { cx: min[0] + width / 2.0, cy: min[1] + height / 2.0, rx: width / 2.0, ry: height / 2.0 }); + } + Some(Primitive::Rect { x: min[0], y: min[1], width, height, rx, ry }) +} + +/// `value` within `tol` of 0 or `half` is snapped there; past `half` it isn't a corner radius. +fn snap(value: f64, half: f64, tol: f64) -> Option { + if !value.is_finite() || value < -tol || value > half + tol { + return None; + } + Some(if value <= tol { + 0.0 + } else if (value - half).abs() <= tol { + half + } else { + value + }) +} + +/// Points of a contour. +type Points = Vec<[f64; 2]>; + +/// The segment ends of one closed contour, and all its points (ends and curve samples), or +/// `None` for anything else: several contours, an open one, or too many segments. +fn contour(segments: &[Segment]) -> Option<(Points, Points)> { + if segments.len() > MAX_SEGMENTS + 2 { + return None; + } + let (first, rest) = segments.split_first()?; + let Segment::MoveTo(start) = *first else { return None }; + let mut points = vec![start]; + let mut ends = vec![start]; + let mut at = start; + let mut closed = false; + for segment in rest { + if closed { + return None; + } + match *segment { + Segment::MoveTo(_) => return None, + Segment::LineTo(p) => { + points.push(p); + ends.push(p); + at = p; + } + Segment::QuadTo(c, p) => { + for t in samples() { + let u = 1.0 - t; + points.push([u * u * at[0] + 2.0 * u * t * c[0] + t * t * p[0], u * u * at[1] + 2.0 * u * t * c[1] + t * t * p[1]]); + } + points.push(p); + ends.push(p); + at = p; + } + Segment::CubicTo(c1, c2, p) => { + for t in samples() { + let u = 1.0 - t; + let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + points.push([a * at[0] + b * c1[0] + c * c2[0] + d * p[0], a * at[1] + b * c1[1] + c * c2[1] + d * p[1]]); + } + points.push(p); + ends.push(p); + at = p; + } + Segment::Close => closed = true, + } + } + let ends_at_start = (at[0] - start[0]).abs() < 1e-9 && (at[1] - start[1]).abs() < 1e-9; + (closed || ends_at_start).then_some((ends, points)) +} + +/// The signed area of the polygon through `points`. +fn area(points: &[[f64; 2]]) -> f64 { + let n = points.len(); + (0..n) + .map(|i| { + let (a, b) = (points[i], points[(i + 1) % n]); + a[0] * b[1] - b[0] * a[1] + }) + .sum::() + / 2.0 +} + +#[cfg(test)] +#[path = "primitive_tests.rs"] +mod tests; diff --git a/crates/svg/src/tree/primitive_tests.rs b/crates/svg/src/tree/primitive_tests.rs new file mode 100644 index 0000000000..ac417eb6ca --- /dev/null +++ b/crates/svg/src/tree/primitive_tests.rs @@ -0,0 +1,119 @@ +#![allow(clippy::unwrap_used, clippy::panic, clippy::indexing_slicing, clippy::float_cmp)] + +use super::*; +use crate::tree::document::{Document, Node}; +use crate::tree::{Limits, parse, usvg}; + +/// The segments usvg makes of `element`, the only shape in a document. +fn segments(element: &str) -> Vec { + let svg = format!(r#"{element}"#); + let tree = parse(svg.as_bytes(), &Limits::default(), &usvg::Options::default()).unwrap(); + let document = Document::from_tree(&tree, 16); + fn first(nodes: &[Node]) -> Option> { + nodes.iter().find_map(|n| match n { + Node::Path(p) => Some(p.segments.clone()), + Node::Group { children, .. } => first(children), + Node::Image(_) => None, + }) + } + first(&document.nodes).unwrap() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-3 +} + +#[test] +fn a_rect_is_a_rect() { + let Some(Primitive::Rect { x, y, width, height, rx, ry }) = recognize(&segments(r#""#)) else { + panic!() + }; + assert_eq!((x, y, width, height, rx, ry), (10.0, 20.0, 30.0, 40.0, 0.0, 0.0)); +} + +#[test] +fn a_rounded_rect_keeps_its_radii() { + for (attrs, want) in [(r#"rx="5""#, (5.0, 5.0)), (r#"rx="6" ry="3""#, (6.0, 3.0)), (r#"ry="4""#, (4.0, 4.0))] { + let element = format!(r#""#); + let Some(Primitive::Rect { x, y, width, height, rx, ry }) = recognize(&segments(&element)) else { panic!("{element}") }; + assert!(near(x, 10.0) && near(y, 20.0) && near(width, 30.0) && near(height, 40.0), "{element}"); + assert!(near(rx, want.0) && near(ry, want.1), "{element}: {rx} {ry}"); + } +} + +#[test] +fn circles_and_ellipses_are_ellipses() { + for (element, want) in [ + (r#""#, (50.0, 60.0, 25.0, 25.0)), + (r#""#, (50.0, 60.0, 40.0, 10.0)), + // A rectangle whose corners meet in the middle is an ellipse too. + (r#""#, (10.0, 5.0, 10.0, 5.0)), + ] { + let Some(Primitive::Ellipse { cx, cy, rx, ry }) = recognize(&segments(element)) else { panic!("{element}") }; + assert!(near(cx, want.0) && near(cy, want.1) && near(rx, want.2) && near(ry, want.3), "{element}: {cx} {cy} {rx} {ry}"); + } +} + +#[test] +fn other_paths_are_not_primitives() { + for element in [ + // A triangle on the edges of its box encloses half of it. + r#""#, + // Open, or two contours. + r#""#, + r#""#, + // A rectangle drawn twice, a diamond, a star. + r#""#, + r#""#, + r#""#, + // A curve that bulges past a circle's outline. + r#""#, + ] { + assert_eq!(recognize(&segments(element)), None, "{element}"); + } +} + +#[test] +fn degenerate_and_oversized_input_is_refused() { + assert_eq!(recognize(&[]), None); + assert_eq!(recognize(&[Segment::LineTo([1.0, 1.0])]), None); + assert_eq!(recognize(&[Segment::MoveTo([0.0, 0.0]), Segment::LineTo([10.0, 0.0]), Segment::Close]), None, "no height"); + let nan = [Segment::MoveTo([f64::NAN, 0.0]), Segment::LineTo([1.0, 0.0]), Segment::LineTo([1.0, 1.0]), Segment::Close]; + assert_eq!(recognize(&nan), None); + let mut long = vec![Segment::MoveTo([0.0, 0.0])]; + long.extend((0..100).map(|i| Segment::LineTo([f64::from(i % 2) * 10.0, 0.0]))); + long.push(Segment::Close); + assert_eq!(recognize(&long), None); +} + +#[test] +fn hand_written_segments_are_recognised_too() { + // Square corners written clockwise from the bottom left, closed by returning to the start. + let square = [ + Segment::MoveTo([0.0, 10.0]), + Segment::LineTo([0.0, 0.0]), + Segment::LineTo([10.0, 0.0]), + Segment::LineTo([10.0, 10.0]), + Segment::LineTo([0.0, 10.0]), + ]; + assert_eq!(recognize(&square), Some(Primitive::Rect { x: 0.0, y: 0.0, width: 10.0, height: 10.0, rx: 0.0, ry: 0.0 })); + // A circle from four cubic quarters, through Path::primitive. + let k = 0.552_284_749_830_793_6 * 5.0; + let path = crate::tree::document::Path { + segments: vec![ + Segment::MoveTo([10.0, 5.0]), + Segment::CubicTo([10.0, 5.0 + k], [5.0 + k, 10.0], [5.0, 10.0]), + Segment::CubicTo([5.0 - k, 10.0], [0.0, 5.0 + k], [0.0, 5.0]), + Segment::CubicTo([0.0, 5.0 - k], [5.0 - k, 0.0], [5.0, 0.0]), + Segment::CubicTo([5.0 + k, 0.0], [10.0, 5.0 - k], [10.0, 5.0]), + Segment::Close, + ], + fill: None, + fill_rule: crate::tree::document::FillRule::NonZero, + stroke: None, + source_path: crate::tree::document::NodePath::default(), + id: String::new(), + transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + }; + assert_eq!(path.primitive(), Some(Primitive::Ellipse { cx: 5.0, cy: 5.0, rx: 5.0, ry: 5.0 })); +} diff --git a/crates/svg/src/tree/tests.rs b/crates/svg/src/tree/tests.rs index 59b42dacc0..abdf0f7723 100644 --- a/crates/svg/src/tree/tests.rs +++ b/crates/svg/src/tree/tests.rs @@ -92,6 +92,10 @@ fn every_limit_refuses_the_file_past_it() { 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()); + // A comment marker in an earlier entity's value hides no declaration. + let bait = bomb.replacen("".repeat(100)), &Limits { xml_nodes: 50, ..shallow() }), Err(Error::Xml(_)))); // Not XML, and XML that is not an SVG. @@ -245,6 +249,195 @@ fn embedded_svgs_are_read_within_their_budgets() { assert_eq!(found(&svg(r#""#), shallow()), [false; 0]); } +mod resource_limit_usage { + use super::*; + + fn data_image(bytes: &[u8]) -> String { + let encoded: String = bytes.iter().map(|byte| format!("%{byte:02X}")).collect(); + format!(r#""#) + } + + fn packed(text: &str, gzip: bool) -> Vec { + if gzip { svgz::compress(text.as_bytes()) } else { text.as_bytes().to_vec() } + } + + /// The outer document has its own generous text allowance, so tiny resolver limits + /// test the public embedded admission contract rather than rejecting the outer XML. + fn resolved(text: &str, limits: Limits, outer_depth: usize) -> (Vec, ImageUsage) { + let resolver = ImageResolver::new(limits); + resolver.set_document_depth(outer_depth); + let options = usvg::Options { image_href_resolver: resolver.resolver(), ..Default::default() }; + let tree = parse(text.as_bytes(), &shallow(), &options).unwrap(); + let mut found = Vec::new(); + images(tree.root(), &mut found); + (found, resolver.usage()) + } + + fn expanding_encoded_children() -> Vec<(&'static str, Vec)> { + let latin = + format!("{}", svg(&format!("{}", "é".repeat(100)))); + let latin = latin.chars().map(|c| u8::try_from(u32::from(c)).unwrap()).collect(); + let wide = svg(&format!("{}", "ࠀ".repeat(400))); + let mut little = vec![0xff, 0xfe]; + little.extend(wide.encode_utf16().flat_map(u16::to_le_bytes)); + let mut big = vec![0xfe, 0xff]; + big.extend(wide.encode_utf16().flat_map(u16::to_be_bytes)); + vec![("Latin-1", latin), ("UTF-16LE", little), ("UTF-16BE", big)] + } + + #[test] + fn decoded_text_expansion_is_a_resource_refusal_for_plain_and_gzip_children() { + for (encoding, raw) in expanding_encoded_children() { + let decoded = svgz::decode(&raw).unwrap(); + let cap = raw.len(); + assert!(decoded.len() > cap, "{encoding} fixture must expand after inflation"); + for gzip in [false, true] { + let data = if gzip { svgz::compress(&raw) } else { raw.clone() }; + assert_eq!(svgz::inflate(&data, cap).unwrap().len(), cap, "raw bytes fit exactly"); + assert_eq!(svgz::text(&data, cap).unwrap().len(), decoded.len(), "decoding itself succeeds"); + let limits = Limits { bytes: cap, embedded_bytes: decoded.len(), ..shallow() }; + assert!(matches!(preflight(&decoded, &limits), Err(Error::Text(svgz::Error::TooLarge(n))) if n == cap)); + let image = data_image(&data); + let (found, usage) = resolved(&svg(&image), limits, 1); + assert!(found.is_empty(), "{encoding}, gzip {gzip}"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (1, 1, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len(), "spent decoded work remains charged"); + let (found, usage) = resolved(&svg(&format!("{image}{image}")), limits, 1); + assert!(found.is_empty()); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (2, 2, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len(), "a refused sibling cannot repeat exhausted work"); + } + } + } + + #[test] + fn decoded_text_expansion_respects_aggregate_bytes_even_when_each_child_fits() { + for (encoding, raw) in expanding_encoded_children() { + let decoded = svgz::decode(&raw).unwrap(); + let limits = Limits { bytes: decoded.len(), embedded_bytes: raw.len(), ..shallow() }; + assert!(decoded.len() > limits.embedded_bytes); + preflight(&decoded, &limits).unwrap(); // The independent per-image cap allows this complete XML. + for gzip in [false, true] { + let data = if gzip { svgz::compress(&raw) } else { raw.clone() }; + assert_eq!(svgz::inflate(&data, limits.embedded_bytes).unwrap().len(), raw.len()); + let image = data_image(&data); + let (found, usage) = resolved(&svg(&image), limits, 1); + assert!(found.is_empty(), "{encoding}, gzip {gzip}"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (1, 1, 0)); + assert_eq!(usage.embedded_svg_bytes, limits.embedded_bytes, "refusal consumes exactly the remaining allowance"); + let (found, usage) = resolved(&svg(&format!("{image}{image}")), limits, 1); + assert!(found.is_empty()); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (2, 2, 0)); + assert_eq!(usage.embedded_svg_bytes, limits.embedded_bytes, "a later child cannot repeat exhausted work"); + let (found, usage) = resolved(&svg(&image), Limits { embedded_bytes: decoded.len(), ..limits }, 1); + assert_eq!(found, [true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (0, 0, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len()); + } + } + } + + #[test] + fn decoded_text_expansion_at_the_cap_is_valid_and_malformed_xml_stays_invalid() { + for (encoding, raw) in expanding_encoded_children() { + let decoded = svgz::decode(&raw).unwrap(); + for gzip in [false, true] { + let data = if gzip { svgz::compress(&raw) } else { raw.clone() }; + let limits = Limits { bytes: decoded.len(), embedded_bytes: decoded.len(), ..shallow() }; + let (found, usage) = resolved(&svg(&data_image(&data)), limits, 1); + assert_eq!(found, [true], "{encoding}, gzip {gzip}"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (0, 0, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len()); + // Preserve the declared/BOM encoding when making the XML malformed; + // re-encoding Latin-1 text as UTF-8 would test a second expansion instead. + let closing_bytes = if encoding == "Latin-1" { 6 } else { 12 }; + let malformed = &raw[..raw.len() - closing_bytes]; + let data = if gzip { svgz::compress(malformed) } else { malformed.to_vec() }; + let (found, usage) = resolved(&svg(&data_image(&data)), limits, 1); + assert!(found.is_empty()); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (0, 0, 1)); + } + } + } + + #[test] + fn embedded_chain_caps_are_explicit_resource_refusals_for_plain_and_gzip_children() { + for gzip in [false, true] { + let inner = svg(""); + let middle = svg(&data_image(&packed(&inner, gzip))); + let outer = svg(&data_image(&packed(&middle, gzip))); + let (found, usage) = resolved(&outer, Limits { embedded_depth: 1, ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!(usage.embedded_svg_depth, 1); + assert_eq!(usage.svg_limit_images, 1, "strict consumers still see the existing limit flag"); + assert_eq!(usage.svg_resource_limit_images, 1, "a chain cap must not become a successful partial bounded preview"); + let (found, usage) = resolved(&outer, Limits { embedded_depth: 2, ..shallow() }, 1); + assert_eq!(found, [true, true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn embedded_per_image_byte_caps_are_resource_refusals_for_plain_and_gzip_children() { + let inner = svg(""); + for gzip in [false, true] { + let outer = svg(&data_image(&packed(&inner, gzip))); + let (_, usage) = resolved(&outer, Limits { bytes: inner.len() - 1, embedded_bytes: inner.len() * 3, ..shallow() }, 1); + assert_eq!(usage.embedded_svg_count, 0); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (1, 1)); + let (found, usage) = resolved(&outer, Limits { bytes: inner.len(), ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn aggregate_embedded_bytes_are_resource_refusals_even_when_each_child_fits() { + let inner = svg(""); + for gzip in [false, true] { + let image = data_image(&packed(&inner, gzip)); + let outer = svg(&format!("{image}{image}")); + let cap = inner.len() * 2 - 1; + let (found, usage) = resolved(&outer, Limits { embedded_bytes: cap, ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!(usage.embedded_svg_bytes, cap, "a refused child still spends the remaining work allowance"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (1, 1)); + let (found, usage) = resolved(&outer, Limits { embedded_bytes: inner.len() * 2, ..shallow() }, 1); + assert_eq!(found, [true, true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn combined_xml_depth_omissions_remain_distinct_from_resource_refusals() { + let inner = svg(""); + for gzip in [false, true] { + let image = data_image(&packed(&inner, gzip)); + let outer = svg(&format!("{}{}{}", "".repeat(4), image, "".repeat(4))); + let (found, usage) = resolved(&outer, Limits { tree_depth: 6, ..shallow() }, 5); + assert!(found.is_empty()); + assert_eq!(usage.svg_limit_images, 1, "strict consumers must continue to reject this omission"); + assert_eq!(usage.svg_resource_limit_images, 0, "non-strict consumers may omit this child without disguising a byte/chain overrun"); + let (found, usage) = resolved(&svg(&image), Limits { tree_depth: 6, ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn invalid_and_corrupt_children_do_not_claim_a_resource_limit() { + let mut corrupt = svgz::compress(svg("").as_bytes()); + let crc = corrupt.len() - 8; + corrupt[crc] ^= 1; + for data in [b"not XML".to_vec(), corrupt] { + let (found, usage) = resolved(&svg(&data_image(&data)), shallow(), 1); + assert!(found.is_empty()); + assert!(usage.invalid_svg_images > 0 || usage.svg_limit_images > 0, "strict consumers still observe unreadable content"); + assert_eq!(usage.svg_resource_limit_images, 0); + } + } +} + mod draw_checks { use super::*; @@ -303,3 +496,196 @@ mod draw_checks { assert!(!refusal.memory && refusal.message.contains("clip-paths"), "{refusal:?}"); } } + +mod invalid_image_accounting { + use super::*; + + fn usage(body: &str, limits: Limits) -> (Vec, ImageUsage) { + let text = svg(body); + let resolver = ImageResolver::new(limits); + resolver.check_document(&text).unwrap(); + let options = usvg::Options { image_href_resolver: resolver.resolver(), ..Default::default() }; + let tree = parse_text(&text, &limits, &options).unwrap(); + let mut found = Vec::new(); + images(tree.root(), &mut found); + (found, resolver.usage()) + } + + fn png() -> Vec { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType, encode}; + let image = Image::new(1, 1, ChannelLayout::Rgba, SampleType::U8).unwrap(); + encode(&image, Format::Png, &EncodeOptions::default()).unwrap() + } + + fn image(data: &[u8]) -> String { + let encoded: String = data.iter().map(|b| format!("%{b:02X}")).collect(); + format!(r#""#) + } + + #[test] + fn malformed_base64_is_counted_before_usvg_discards_it() { + let bad = r#""#; + let (found, report) = usage(bad, shallow()); + assert!(found.is_empty()); + assert_eq!(report.invalid_raster_images, 1); + let (found, report) = usage(&embed(&svg(bad)), shallow()); + assert_eq!(found, [true]); + assert_eq!(report.invalid_raster_images, 1); + } + + #[test] + fn malformed_data_url_without_comma_is_counted() { + for href in ["data:image/png;base64", " data:image/png;base64", "da ta:image/png;base64", "da ta:image/png;base64"] { + let bad = format!(r#""#); + let (found, report) = usage(&bad, shallow()); + assert!(found.is_empty(), "{href}"); + assert_eq!(report.invalid_raster_images, 1, "{href}"); + let (found, report) = usage(&embed(&svg(&bad)), shallow()); + assert_eq!(found, [true], "{href}"); + assert_eq!(report.invalid_raster_images, 1, "{href}"); + } + } + + #[test] + fn failed_decode_forgets_address_but_preserves_spent_budget() { + let valid = png(); + let idat = valid.windows(4).position(|b| b == b"IDAT").unwrap(); + let invalid = Arc::new(valid[..idat + 4].to_vec()); + let pointer = Arc::as_ptr(&invalid) as usize; + let limits = Limits { embedded_raster_pixels: 3, ..shallow() }; + let resolver = ImageResolver::new(limits); + let used = &resolver.used; + let format = craft_image_codecs::Format::Png; + assert!(raster_image(used, &limits, invalid, format).is_none()); + assert!(!used.raster_data.lock().unwrap().contains(&pointer)); + assert_eq!(resolver.usage().raster_pixels, 1); + let first_data = Arc::new(valid.clone()); + let first = raster_image(used, &limits, first_data.clone(), format).unwrap(); + assert_eq!(resolver.usage().raster_pixels, 2); + let repeated = raster_image(used, &limits, first_data, format).unwrap(); + assert_eq!(resolver.usage().raster_pixels, 2); + let second = raster_image(used, &limits, Arc::new(valid.clone()), format).unwrap(); + assert_eq!(resolver.usage().raster_pixels, 3); + assert!(raster_image(used, &limits, Arc::new(valid), format).is_none()); + assert_eq!(resolver.usage().raster_limit_images, 1); + drop((first, repeated, second)); + } + + #[test] + fn corrupt_pixels_do_not_pass_a_valid_header_probe() { + let valid = png(); + let (found, report) = usage(&image(&valid), shallow()); + assert_eq!(found, [false]); + assert_eq!(report.invalid_raster_images, 0); + let idat = valid.windows(4).position(|b| b == b"IDAT").unwrap(); + let corrupt = &valid[..idat + 4]; + assert_eq!(craft_image_codecs::probe_allocation_size(corrupt).unwrap(), (1, 1)); + let (found, report) = usage(&image(corrupt), shallow()); + assert!(found.is_empty()); + assert_eq!(report.invalid_raster_images, 1); + let (found, report) = usage(&image(&valid), Limits { embedded_raster_pixels: 0, ..shallow() }); + assert!(found.is_empty()); + assert_eq!(report.raster_limit_images, 1); + } +} + +#[test] +fn preflight_keeps_source_depth_and_parses_the_checked_tree() { + let text = svg(""); + let checked = preflight(&text, &Limits::default()).unwrap(); + // svg and g are open; the self-closing rect opens no level. + assert_eq!(checked.depth(), 2); + let tree = checked.parse(&options()).unwrap(); + assert_eq!(tree.size().width(), 10.0); + assert!(matches!(preflight(&svg(&groups(30)), &shallow()), Err(Error::TooDeep(24)))); +} + +#[test] +fn preflight_matches_parse_text_refusals() { + for text in [""] { + assert!(matches!(preflight(text, &Limits::default()), Err(Error::Xml(_)))); + assert!(matches!(parse_text(text, &Limits::default(), &options()), Err(Error::Xml(_)))); + } +} + +#[test] +fn rewrite_root_viewport_wraps_the_root_and_keeps_the_preamble() { + let source = concat!( + "\n]>\n", + "", + "" + ); + let out = rewrite_root_viewport(source, Viewport { width: 40.0, height: 30.0 }, &Limits::default(), 4096).unwrap(); + assert!(out.starts_with("\n]>\n")); + let tree = parse_text(&out, &Limits::default(), &options()).unwrap(); + assert_eq!((tree.size().width(), tree.size().height()), (40.0, 30.0)); +} + +#[test] +fn rewrite_root_viewport_reads_points_and_pixels() { + let points = rewrite_root_viewport( + "", + Viewport { width: 1.0, height: 1.0 }, + &Limits::default(), + 4096, + ) + .unwrap(); + assert!(points.contains("viewBox=\"0 0 96 48\"")); + let pixels = rewrite_root_viewport( + "", + Viewport { width: 1.0, height: 1.0 }, + &Limits::default(), + 4096, + ) + .unwrap(); + assert!(pixels.contains("viewBox=\"0 0 12 8\"")); +} + +#[test] +fn rewrite_root_viewport_refusals() { + let limits = Limits::default(); + let one = Viewport { width: 1.0, height: 1.0 }; + let sized = ""; + for target in [ + Viewport { width: f64::NAN, height: 1.0 }, + Viewport { width: 1.0, height: f64::INFINITY }, + Viewport { width: 0.0, height: 1.0 }, + Viewport { width: 1.0, height: -2.0 }, + ] { + assert!(matches!(rewrite_root_viewport(sized, target, &limits, 4096), Err(Error::Viewport(_)))); + } + assert!(matches!(rewrite_root_viewport("", one, &limits, 4096), Err(Error::Viewport(_)))); + for source in [ + "", + "", + "", + "", + "", + ] { + assert!(matches!(rewrite_root_viewport(source, one, &limits, 4096), Err(Error::Viewport(_))), "{source}"); + } + assert!(matches!(rewrite_root_viewport(" assert!(parse_text(&out, &limits, &options()).is_ok(), "{n} groups"), + Err(Error::TooDeep(_)) => refused_at_the_limit = true, + Err(e) => panic!("{n} groups: {e:?}"), + } + } + assert!(refused_at_the_limit, "a source at the depth limit is refused, not wrapped past it"); +} diff --git a/crates/svg/src/write.rs b/crates/svg/src/write.rs index 469a4f8fa4..af3eec992b 100644 --- a/crates/svg/src/write.rs +++ b/crates/svg/src/write.rs @@ -86,18 +86,36 @@ impl Attribute { pub fn translate_scale(x: f64, y: f64, scale_x: f64, scale_y: f64) -> Self { Self { name: "transform".into(), value: Value::TranslateScale { x, y, scale_x, scale_y } } } + /// A translate/scale transform with three decimal places for positions and four for scales. + pub fn translate_scale_fixed(x: f64, y: f64, scale_x: f64, scale_y: f64) -> Self { + Self::text("transform", format!("translate({} {}) scale({} {})", num(x, 3), num(y, 3), num(scale_x, 4), num(scale_y, 4))) + } } impl Scene { /// Serialize the scene as an SVG 1.1 document. pub fn write(&self) -> String { + self.write_impl(false) + } + + /// Serialize the root viewBox with three decimal places for stable fixed-width output. + pub fn write_fixed_view_box(&self) -> String { + self.write_impl(true) + } + + fn write_impl(&self, fixed: bool) -> String { let mut writer = SvgWriter::new(); + let view_box = if fixed { + format!("{} {} {} {}", num(self.view_box[0], 3), num(self.view_box[1], 3), num(self.view_box[2], 3), num(self.view_box[3], 3)) + } else { + view_box_data(self.view_box) + }; writer .root() .attr("version", "1.1") .attr("width", format!("{}mm", num(self.width_mm, 3))) .attr("height", format!("{}mm", num(self.height_mm, 3))) - .attr("viewBox", view_box_data(self.view_box)) + .attr("viewBox", view_box) .open(); write_elements(&mut writer, &self.elements, 1); writer.line(0); @@ -240,6 +258,42 @@ pub fn path_data_fixed(path: &BezPath, decimals: usize) -> String { #[derive(Clone, Debug, Default)] pub struct SvgWriter(craft_xml::Writer); +// A subset ends with `] S? >`; quoted entity values, comments and PIs may contain that text. +// Scan once without allocations; malformed unterminated constructs remain the caller's error. +fn closes_internal_subset(internal: &str) -> bool { + let bytes = internal.as_bytes(); + let mut i = 0; + while i < bytes.len() { + if bytes[i..].starts_with(b"") } else { (2, b"?>") }; + let Some(offset) = bytes[i + start..].windows(end.len()).position(|part| part == end) else { + return false; + }; + i += start + offset + end.len(); + } else if matches!(bytes[i], b'\'' | b'"') { + let quote = bytes[i]; + i += 1; + while i < bytes.len() && bytes[i] != quote { + i += 1; + } + if i < bytes.len() { + i += 1; + } + } else if bytes[i] == b']' { + i += 1; + while i < bytes.len() && matches!(bytes[i], b' ' | b'\t' | b'\r' | b'\n') { + i += 1; + } + if bytes.get(i) == Some(&b'>') { + return true; + } + } else { + i += 1; + } + } + false +} + impl SvgWriter { /// A document: starts with the XML declaration. pub fn new() -> SvgWriter { @@ -251,6 +305,41 @@ impl SvgWriter { pub fn fragment() -> SvgWriter { SvgWriter::default() } + /// A document that starts with an XML declaration naming `encoding` (for example `UTF-8` or + /// `ISO-8859-1`) and a newline. Nothing is written for an invalid XML encoding name. + pub fn with_encoding(encoding: &str) -> SvgWriter { + let mut w = SvgWriter::fragment(); + w.decl(encoding, "\n"); + w + } + /// Writes `` followed by `newline`. Nothing is + /// written unless `encoding` starts with an ASCII letter and continues with ASCII letters, + /// digits, `.`, `_`, or `-` (XML EncName). + pub fn decl(&mut self, encoding: &str, newline: &str) { + let mut bytes = encoding.bytes(); + if bytes.next().is_some_and(|b| b.is_ascii_alphabetic()) && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) { + self.0.raw(&format!("{newline}")); + } + } + /// Writes `` + `newline`. When + /// `internal` is empty, the inner newline is omitted, so a minified document can be + /// `` with no extra breaks. Nothing is written if `name` is not an XML name + /// or `internal` closes the subset outside a quoted value, comment or processing instruction. + /// The caller still supplies valid DTD declarations; this is not a DTD validator. + pub fn doctype_internal(&mut self, name: &str, internal: &str, newline: &str) { + if !craft_xml::is_name(name) || closes_internal_subset(internal) { + return; + } + let mut out = format!(""); + out.push_str(newline); + self.0.raw(&out); + } /// Starts the root tag, ` Tag<'_> { @@ -277,9 +366,13 @@ impl SvgWriter { pub fn raw(&mut self, svg: &str) { self.0.raw(svg); } + /// What has been written so far, including any element that is still open. + pub fn as_str(&self) -> &str { + self.0.as_str() + } /// How many bytes have been written so far. pub fn len(&self) -> usize { - self.0.as_str().len() + self.as_str().len() } /// Has nothing been written yet? pub fn is_empty(&self) -> bool { @@ -307,6 +400,14 @@ mod tests { p } + #[test] + fn scene_can_keep_fixed_view_box_without_changing_default_output() { + let scene = Scene { width_mm: 100.0, height_mm: 150.0, view_box: [0.0, 0.0, 100.0, 150.0], elements: vec![] }; + assert!(scene.write().contains("viewBox=\"0 0 100 150\"")); + assert!(scene.write_fixed_view_box().contains("viewBox=\"0.000 0.000 100.000 150.000\"")); + assert_eq!(Attribute::translate_scale_fixed(6.0, 46.0, 0.5, -0.5).value, Value::Text("translate(6.000 46.000) scale(0.5000 -0.5000)".into())); + } + #[test] fn numbers_have_fixed_decimals_and_are_never_non_finite() { assert_eq!(num(1.5, 3).to_string(), "1.500"); @@ -336,6 +437,7 @@ mod tests { } #[test] + #[cfg(feature = "paths")] fn writes_a_document_the_reader_reads() { let mut w = SvgWriter::new(); assert!(!w.is_empty()); @@ -386,4 +488,58 @@ mod tests { assert_eq!(w.len(), before + inner.len()); assert_eq!(w.finish(), ""); } + + #[test] + fn declaration_names_the_encoding_and_rejects_a_bad_name() { + assert_eq!(SvgWriter::with_encoding("UTF-8").finish(), "\n"); + assert_eq!(SvgWriter::with_encoding("ISO-8859-1").finish(), "\n"); + assert!(SvgWriter::with_encoding("UTF-8\"").is_empty()); + assert!(SvgWriter::with_encoding("").is_empty()); + for valid in ["A", "a0._-"] { + assert_eq!(SvgWriter::with_encoding(valid).finish(), format!("\n")); + } + for invalid in [":UTF-8", "_UTF8", "1UTF8", "é", "UTF:8", "UTFé", "UTF 8"] { + assert!(SvgWriter::with_encoding(invalid).is_empty(), "{invalid}"); + } + let mut compact = SvgWriter::fragment(); + compact.decl("ISO-8859-1", ""); + compact.root().open(); + assert_eq!(compact.as_str(), ""); + compact.close(); + assert_eq!(compact.finish(), ""); + } + + #[test] + fn doctype_internal_subset_keeps_caller_newlines() { + let mut pretty = SvgWriter::fragment(); + pretty.doctype_internal("svg", " ", "\n"); + pretty.root().open(); + pretty.close(); + assert_eq!(pretty.finish(), "\n]>\n"); + let mut compact = SvgWriter::fragment(); + compact.doctype_internal("svg", "", ""); + assert_eq!(compact.finish(), "]>"); + let mut empty = SvgWriter::fragment(); + empty.doctype_internal("svg", "", "\n"); + assert_eq!(empty.finish(), "\n"); + let mut refused = SvgWriter::fragment(); + refused.doctype_internal("svg", "]]>", "\n"); + refused.doctype_internal("svg", "]>", "?>"] { + let mut writer = SvgWriter::fragment(); + writer.doctype_internal("svg", internal, ""); + assert_eq!(writer.finish(), format!("")); + } + for internal in ["]>", "] >", "]>"] { + let mut writer = SvgWriter::fragment(); + writer.doctype_internal("svg", internal, ""); + assert!(writer.is_empty()); + } + } } diff --git a/crates/tar/Cargo.toml b/crates/tar/Cargo.toml new file mode 100644 index 0000000000..e0628a35a7 --- /dev/null +++ b/crates/tar/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "craft-tar" +description = "TAR (v7, ustar, GNU long names and base-256 sizes, pax overrides) and cpio (newc, crc, odc) member walkers for hostile input: list members and where their data lies, without extracting. From Craft Anything." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +# `serde`: `Serialize` on the listing types, for apps that report listings as JSON. +serde = { workspace = true, optional = true } + +[features] +serde = ["dep:serde"] diff --git a/crates/tar/src/lib.rs b/crates/tar/src/lib.rs new file mode 100644 index 0000000000..7712fc2aa2 --- /dev/null +++ b/crates/tar/src/lib.rs @@ -0,0 +1,911 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Member walkers for Unix archives: tar (v7, ustar, GNU long names and base-256 sizes, pax path +//! local/global overrides) and cpio (newc, crc and portable odc). They list members and where their data +//! lies; nothing is extracted here, and no input can make them panic or loop forever. + +use std::collections::BTreeSet; + +/// Bounds-checked reads from the archive bytes. +struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + /// `len` bytes at `off`, or `None` when they don't all lie inside the data. + fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + self.data.get(off..off.checked_add(len)?) + } +} + +/// What a member is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +pub enum MemberKind { + File, + Dir, + Symlink, + Hardlink, + Device, + Fifo, + Other, +} + +/// One archive member. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct Member { + pub name: String, + pub kind: MemberKind, + pub size: u64, + /// Where the member's data starts, relative to the archive start. + pub data_offset: u64, + #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))] + pub link_target: Option, + pub mode: u32, +} + +/// Why tar name metadata stopped a walk that still retains earlier members. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +pub enum StopReason { + GnuMetadataTooLong, + GnuMetadataTruncated, + GlobalNameBudget, +} + +/// The members of an archive. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct Listing { + /// `tar`, `cpio-newc`, `cpio-crc` or `cpio-odc`. + pub format: &'static str, + pub members: Vec, + /// Bytes from the archive start to the end of its last structure (end marker included). + pub length: u64, + /// True when the end-of-archive marker was reached. + pub complete: bool, + /// True when `max_members` stopped the walk. + pub truncated: bool, + /// Name metadata that prevented reading the remaining member identities. + #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))] + pub stop_reason: Option, + pub warnings: Vec, +} + +const BLOCK: usize = 512; +const MAX_NAME: usize = 4096; +const MAX_GLOBAL_NAME_COPIES: usize = 64 << 20; + +fn trim_field(f: &[u8]) -> &[u8] { + let end = f.iter().position(|&b| b == 0).unwrap_or(f.len()); + f.get(..end).unwrap_or(&[]) +} + +fn text(f: &[u8]) -> String { + String::from_utf8_lossy(trim_field(f)).into_owned() +} + +/// An octal number field (spaces and NULs around it are ignored); GNU base-256 when the high bit +/// of the first byte is set. +fn octal(f: &[u8]) -> Option { + if let Some((&first, rest)) = f.split_first() + && first & 0x80 != 0 + { + if first & 0x40 != 0 { + return None; // This field holds an unsigned value. + } + let mut v = u64::from(first & 0x7f); + for &b in rest { + v = v.checked_mul(256)?.checked_add(u64::from(b))?; + } + return Some(v); + } + let padding = |&b: &u8| b == 0 || b == b' '; + let mut digits = f.iter().copied().skip_while(padding).peekable(); + let mut v = 0u64; + while let Some(b) = digits.next_if(|b| !padding(b)) { + if !(b'0'..=b'7').contains(&b) { + return None; + } + v = v.checked_mul(8)?.checked_add(u64::from(b - b'0'))?; + } + digits.all(|b| padding(&b)).then_some(v) +} + +/// True when a 512-byte block is a tar header with a correct checksum. +pub fn tar_header_ok(h: &[u8]) -> bool { + let Some(h) = h.get(..BLOCK) else { return false }; + let Some(stored) = h.get(148..156).and_then(octal) else { return false }; + let mut unsigned = 0u64; + let mut signed = 0i64; + for (i, &b) in h.iter().enumerate() { + let v = if (148..156).contains(&i) { b' ' } else { b }; + unsigned += u64::from(v); + signed += i64::from(v as i8); + } + // An all-zero block sums to 256 (the blank checksum field) and is the end marker, not a header. + unsigned != 256 && (stored == unsigned || i64::try_from(stored).is_ok_and(|s| s == signed)) +} + +fn round_up(v: u64, to: u64) -> Option { + let r = v % to; + if r == 0 { Some(v) } else { v.checked_add(to - r) } +} + +/// Walk a tar archive. `None` when the first block is not a valid header. +pub fn tar(data: &[u8], max_members: usize) -> Option

{ + tar_with_name_copy_limit(data, max_members, MAX_GLOBAL_NAME_COPIES) +} + +fn tar_with_name_copy_limit(data: &[u8], max_members: usize, mut name_bytes_left: usize) -> Option { + let r = Reader::new(data); + if !tar_header_ok(r.slice(0, BLOCK)?) { + return None; + } + let mut out = Listing { format: "tar", ..Listing::default() }; + let mut pos = 0usize; + let mut long_name: Option = None; + let mut long_link: Option = None; + let mut pax = PaxOverrides::default(); + // Every iteration advances by at least one block, so the walk is bounded by the input size. + 'headers: loop { + let Some(h) = r.slice(pos, BLOCK) else { + out.warnings.push(format!("archive ends inside a header at {pos:#x}")); + out.length = data.len() as u64; + break; + }; + if h.iter().all(|&b| b == 0) { + // End of archive: one or two zero blocks. + let second = r.slice(pos + BLOCK, BLOCK).is_some_and(|b| b.iter().all(|&x| x == 0)); + out.length = (pos + if second { 2 * BLOCK } else { BLOCK }) as u64; + out.complete = true; + break; + } + if !tar_header_ok(h) { + out.warnings.push(format!("invalid header checksum at {pos:#x}; stopping")); + out.length = pos as u64; + break; + } + let typeflag = h.get(156).copied().unwrap_or(0); + let Some(mut size) = h.get(124..136).and_then(octal) else { + out.warnings.push(format!("unreadable size at {pos:#x}")); + out.length = pos as u64; + break; + }; + if !matches!(typeflag, b'x' | b'g' | b'L' | b'K') + && let Some(s) = pax.size.take().or(pax.global_size) + { + size = s; + } + let data_off = pos + BLOCK; + let Some(next) = + round_up(size, BLOCK as u64).and_then(|s| u64::try_from(data_off).ok()?.checked_add(s)).and_then(|n| usize::try_from(n).ok()) + else { + if matches!(typeflag, b'L' | b'K') { + out.stop_reason = Some(StopReason::GnuMetadataTruncated); + } + out.warnings.push(format!("size overflows at {pos:#x}")); + out.length = pos as u64; + break; + }; + let body = r.slice(data_off, usize::try_from(size).unwrap_or(usize::MAX)); + match typeflag { + b'L' | b'K' => { + let Some(body) = body.filter(|_| next <= data.len()) else { + out.stop_reason = Some(StopReason::GnuMetadataTruncated); + out.warnings.push(format!("GNU long-name record ends early at {pos:#x}")); + out.length = data.len() as u64; + break; + }; + let end = body.iter().take(MAX_NAME + 1).position(|&byte| byte == 0).unwrap_or(body.len()); + if end > MAX_NAME { + out.stop_reason = Some(StopReason::GnuMetadataTooLong); + out.warnings.push(format!("GNU long name or link exceeds {MAX_NAME} bytes at {pos:#x}")); + out.length = pos as u64; + break; + } + let value = Some(String::from_utf8_lossy(&body[..end]).into_owned()); + if typeflag == b'L' { + long_name = value; + } else { + long_link = value; + } + } + b'x' | b'g' => { + if let Some(records) = body + && let Err(warning) = pax.apply(records, typeflag == b'g', pos) + { + out.warnings.push(warning); + out.length = pos as u64; + break 'headers; + } + } + _ => { + if out.members.len() >= max_members { + out.truncated = true; + out.length = pos as u64; + break; + } + let linked = matches!(typeflag, b'1' | b'2'); + let copied_path = if pax.path.is_none() { pax.global_path.as_ref().map_or(0, String::len) } else { 0 }; + let copied_link = if linked && pax.link.is_none() { pax.global_link.as_ref().map_or(0, String::len) } else { 0 }; + let Some(remaining) = name_bytes_left.checked_sub(copied_path.saturating_add(copied_link)) else { + out.stop_reason = Some(StopReason::GlobalNameBudget); + out.warnings.push("the retained global pax name-byte budget was reached; later members were omitted".into()); + out.length = pos as u64; + break; + }; + name_bytes_left = remaining; + // Old GNU headers use these bytes for timestamps and sparse-file metadata. + let ustar = h.get(257..263) == Some(b"ustar\0"); + let base = text(h.get(0..100).unwrap_or(&[])); + let prefix = if ustar { text(h.get(345..500).unwrap_or(&[])) } else { String::new() }; + let joined = if prefix.is_empty() { base } else { format!("{prefix}/{base}") }; + // PAX values override header names, including GNU's long-name replacement. + // Consume the one-member GNU records even when a PAX value takes precedence. + let gnu_name = long_name.take(); + let gnu_link = long_link.take(); + let name = pax.path.take().or_else(|| pax.global_path.clone()).or(gnu_name).unwrap_or(joined); + let link = pax + .link + .take() + .or_else(|| if linked { pax.global_link.clone() } else { None }) + .or(gnu_link) + .or_else(|| Some(text(h.get(157..257).unwrap_or(&[])))) + .filter(|l| !l.is_empty()); + let mut kind = tar_kind(typeflag, &name); + if std::mem::take(&mut pax.sparse) || !pax.global_sparse.is_empty() { + kind = MemberKind::Other; + out.warnings.push(format!("{name}: GNU sparse reconstruction is unsupported; stored extents are not the complete file")); + } + let mode = h.get(100..108).and_then(octal).and_then(|m| u32::try_from(m).ok()).unwrap_or(0); + if body.is_none() && kind == MemberKind::File { + out.warnings.push(format!("{name}: data runs past the end of the input")); + } + out.members.push(Member { + name, + kind, + size, + data_offset: data_off as u64, + link_target: if matches!(kind, MemberKind::Symlink | MemberKind::Hardlink) { link } else { None }, + mode, + }); + } + } + if next > data.len() { + out.length = data.len() as u64; + out.warnings.push("archive ends early (no end-of-archive marker)".into()); + break; + } + pos = next; + } + Some(out) +} + +/// What a tar header's typeflag says the member is. +fn tar_kind(typeflag: u8, name: &str) -> MemberKind { + match typeflag { + b'0' | 0 | b'7' => { + if name.ends_with('/') { + MemberKind::Dir + } else { + MemberKind::File + } + } + b'1' => MemberKind::Hardlink, + b'2' => MemberKind::Symlink, + b'3' | b'4' => MemberKind::Device, + b'5' => MemberKind::Dir, + b'6' => MemberKind::Fifo, + _ => MemberKind::Other, + } +} + +/// The pax values that override the next member (local) or every later one (global). +#[derive(Default)] +struct PaxOverrides<'a> { + path: Option, + link: Option, + size: Option, + sparse: bool, + global_path: Option, + global_link: Option, + global_size: Option, + /// Borrow keys from the input: global sparse attributes persist until their own deletion. + global_sparse: BTreeSet<&'a [u8]>, +} + +impl<'a> PaxOverrides<'a> { + /// Apply one extended header's records. `Err` is the warning that stops the walk. + fn apply(&mut self, mut remaining: &'a [u8], global: bool, pos: usize) -> Result<(), String> { + for _ in 0..256 { + if remaining.is_empty() { + break; + } + let Some((key, value, rest)) = pax_record(remaining) else { + return Err(format!("invalid pax record at {pos:#x}")); + }; + if key.starts_with(b"GNU.sparse.") { + if !global { + self.sparse = true; + } else if value.is_empty() { + self.global_sparse.remove(key); + } else { + self.global_sparse.insert(key); + } + } + match key { + b"path" | b"linkpath" | b"GNU.sparse.name" => self.set_name(key, value, global, pos)?, + b"size" => self.set_size(value, global, pos)?, + _ => {} + } + remaining = rest; + } + if remaining.is_empty() { Ok(()) } else { Err(format!("pax record limit reached at {pos:#x}")) } + } + + fn set_name(&mut self, key: &[u8], value: &[u8], global: bool, pos: usize) -> Result<(), String> { + if value.len() > MAX_NAME { + return Err(format!("pax name exceeds {MAX_NAME} bytes at {pos:#x}")); + } + let slot = match (global, key == b"linkpath") { + (true, true) => &mut self.global_link, + (true, false) => &mut self.global_path, + (false, true) => &mut self.link, + (false, false) => &mut self.path, + }; + *slot = if global && value.is_empty() { None } else { Some(String::from_utf8_lossy(value).into_owned()) }; + Ok(()) + } + + fn set_size(&mut self, value: &[u8], global: bool, pos: usize) -> Result<(), String> { + let size = std::str::from_utf8(value).ok().and_then(|s| s.parse().ok()); + if !value.is_empty() && (size.is_none() || !value.iter().all(u8::is_ascii_digit)) { + let scope = if global { "global" } else { "local" }; + return Err(format!("invalid {scope} pax size at {pos:#x}")); + } + if global { + self.global_size = size; + } else { + self.size = size; + } + Ok(()) + } +} + +/// Read one length-prefixed pax record, borrowing even unknown keys and values from the header. +fn pax_record(data: &[u8]) -> Option<(&[u8], &[u8], &[u8])> { + let sp = data.iter().position(|&byte| byte == b' ')?; + let digits = data.get(..sp)?; + if !digits.iter().all(u8::is_ascii_digit) { + return None; + } + let len: usize = std::str::from_utf8(digits).ok()?.parse().ok()?; + let field = data.get(sp + 1..len)?.strip_suffix(b"\n")?; + let eq = field.iter().position(|&byte| byte == b'=')?; + if eq == 0 { + return None; + } + Some((field.get(..eq)?, field.get(eq + 1..)?, data.get(len..)?)) +} + +fn hex_field(f: &[u8]) -> Option { + if !f.iter().all(u8::is_ascii_hexdigit) { + return None; + } + let s = std::str::from_utf8(f).ok()?; + u64::from_str_radix(s, 16).ok() +} + +fn oct_field(f: &[u8]) -> Option { + if !f.iter().all(|b| (b'0'..=b'7').contains(b)) { + return None; + } + let s = std::str::from_utf8(f).ok()?; + u64::from_str_radix(s, 8).ok() +} + +fn mode_kind(mode: u32) -> MemberKind { + match mode & 0o170_000 { + 0o100_000 => MemberKind::File, + 0o040_000 => MemberKind::Dir, + 0o120_000 => MemberKind::Symlink, + 0o020_000 | 0o060_000 => MemberKind::Device, + 0o010_000 => MemberKind::Fifo, + _ => MemberKind::Other, + } +} + +/// Walk a cpio archive (newc `070701`, crc `070702`, odc `070707`). `None` when the first header +/// is not one of these. +pub fn cpio(data: &[u8], max_members: usize) -> Option { + cpio_with_checksum(data, max_members, &mut |body| CpioChecksum::Value(body.iter().fold(0u32, |sum, &byte| sum.wrapping_add(u32::from(byte))))) +} + +/// A checksum sum, or the reason a caller stopped verification before completing it. +#[derive(Clone, Copy)] +pub enum CpioChecksum { + Value(u32), + Skipped, + Cancelled, +} + +/// Let a scanner share its checksum work allowance and cancellation across overlapping probes. +pub fn cpio_with_checksum(data: &[u8], max_members: usize, checksum: &mut dyn FnMut(&[u8]) -> CpioChecksum) -> Option { + let r = Reader::new(data); + let format = match r.slice(0, 6)? { + b"070701" => "cpio-newc", + b"070702" => "cpio-crc", + b"070707" => "cpio-odc", + _ => return None, + }; + let odc = format == "cpio-odc"; + let mut hard_links = std::collections::HashMap::<(u64, u64, u64), Vec>::new(); + let mut out = Listing { format, ..Listing::default() }; + let mut pos = 0usize; + let align = |v: usize| if odc { Some(v) } else { v.checked_add(3).map(|x| x & !3) }; + loop { + let hdr_len = if odc { 76 } else { 110 }; + let Some(h) = r.slice(pos, hdr_len) else { + out.warnings.push(format!("archive ends inside a header at {pos:#x}")); + out.length = data.len() as u64; + break; + }; + if h.get(..6) != r.slice(0, 6) { + out.warnings.push(format!("bad header magic at {pos:#x}; stopping")); + out.length = pos as u64; + break; + } + let fields = if odc { + (h.get(18..24).and_then(oct_field), h.get(59..65).and_then(oct_field), h.get(65..76).and_then(oct_field)) + } else { + (h.get(14..22).and_then(hex_field), h.get(94..102).and_then(hex_field), h.get(54..62).and_then(hex_field)) + }; + let (Some(mode), Some(namesize), Some(filesize)) = fields else { + out.warnings.push(format!("unreadable header fields at {pos:#x}")); + out.length = pos as u64; + break; + }; + let namesize = usize::try_from(namesize).unwrap_or(usize::MAX); + if namesize == 0 || namesize > MAX_NAME { + out.warnings.push(format!("implausible name size at {pos:#x}")); + out.length = pos as u64; + break; + } + let Some(name_bytes) = r.slice(pos + hdr_len, namesize) else { + out.warnings.push(format!("name runs past the end at {pos:#x}")); + out.length = data.len() as u64; + break; + }; + // newc permits extra trailing NULs in namesize for alignment. + let Some(end) = name_bytes.iter().position(|&b| b == 0) else { + out.warnings.push(format!("unterminated member name at {pos:#x}")); + out.length = pos as u64; + break; + }; + if end == 0 || name_bytes.get(end..).is_some_and(|pad| pad.iter().any(|&b| b != 0)) { + out.warnings.push(format!("invalid member name at {pos:#x}")); + out.length = pos as u64; + break; + } + let name = text(name_bytes); + let Some(data_off) = (pos + hdr_len).checked_add(namesize).and_then(align) else { break }; + let size = usize::try_from(filesize).unwrap_or(usize::MAX); + let Some(next) = data_off.checked_add(size).and_then(align) else { + out.warnings.push(format!("size overflows at {pos:#x}")); + out.length = pos as u64; + break; + }; + if name == "TRAILER!!!" { + out.length = next.min(data.len()) as u64; + if size == 0 && next <= data.len() { + out.complete = true; + } else { + out.warnings.push(format!("invalid or truncated trailer at {pos:#x}")); + } + break; + } + let mode = u32::try_from(mode).unwrap_or(0); + let kind = mode_kind(mode); + let link_target = if kind == MemberKind::Symlink { r.slice(data_off, size.min(MAX_NAME)).map(text) } else { None }; + if out.members.len() >= max_members { + out.truncated = true; + out.length = pos as u64; + break; + } + if format == "cpio-crc" { + match h.get(102..110).filter(|field| field.iter().all(u8::is_ascii_hexdigit)).and_then(hex_field).and_then(|n| u32::try_from(n).ok()) { + Some(expected) => { + if let Some(body) = r.slice(data_off, size) { + match checksum(body) { + CpioChecksum::Value(actual) => { + if actual != expected { + out.warnings.push(format!("{name}: data checksum mismatch (stored {expected:08x}, computed {actual:08x})")); + } + } + CpioChecksum::Skipped => out.warnings.push(format!("{name}: data checksum not verified (scan byte budget exhausted)")), + CpioChecksum::Cancelled => return None, + } + } + } + None => out.warnings.push(format!("{name}: unreadable data checksum")), + } + } + // newc stores hard-linked files by device and inode. GNU cpio may put the + // payload on the last name, so identify aliases after scanning the group. + if !odc + && kind == MemberKind::File + && h.get(38..46).and_then(hex_field).is_some_and(|n| n > 1) + && let (Some(ino), Some(major), Some(minor)) = + (h.get(6..14).and_then(hex_field), h.get(62..70).and_then(hex_field), h.get(70..78).and_then(hex_field)) + { + hard_links.entry((major, minor, ino)).or_default().push(out.members.len()); + } + out.members.push(Member { name, kind, size: filesize, data_offset: data_off as u64, link_target, mode }); + if next > data.len() { + out.warnings.push("archive ends early (no trailer)".into()); + out.length = data.len() as u64; + break; + } + pos = next; + } + for group in hard_links.values().filter(|group| group.len() > 1) { + let source = group.iter().rev().copied().find(|&i| out.members.get(i).is_some_and(|m| m.size > 0)).or_else(|| group.first().copied()); + let Some(source) = source else { continue }; + let Some(name) = out.members.get(source).map(|m| m.name.clone()) else { continue }; + for &index in group { + if index != source + && let Some(alias) = out.members.get_mut(index) + && alias.size == 0 + { + alias.kind = MemberKind::Hardlink; + alias.link_target = Some(name.clone()); + } + } + } + Some(out) +} + +/// The data of a member, when it lies inside `data`. +pub fn member_data<'a>(data: &'a [u8], m: &Member) -> Option<&'a [u8]> { + Reader::new(data).slice(usize::try_from(m.data_offset).ok()?, usize::try_from(m.size).ok()?) +} + +#[cfg(test)] +mod tar_tests; +#[cfg(test)] +mod testkit; + +#[cfg(test)] +mod tests { + use super::*; + use crate::testkit as fx; + + #[test] + fn plus_sign_in_cpio_fields_is_rejected() { + assert_eq!(hex_field(b"+000000A"), None); + assert_eq!(oct_field(b"+00012"), None); + assert_eq!(hex_field(b"0000000A"), Some(10)); + assert_eq!(oct_field(b"00012"), Some(10)); + } + + fn global_record(key: &str, value: &str) -> String { + let tail = format!(" {key}={value}\n"); + let mut len = tail.len() + 1; + loop { + let record = format!("{len}{tail}"); + if record.len() == len { + return record; + } + len = record.len(); + } + } + + #[test] + fn global_name_copies_stop_before_spending_the_budget() { + let global = global_record("path", "shared"); + let data = + fx::tar_entries(&[("global", b'g', global.as_bytes(), ""), ("one", b'0', b"", ""), ("two", b'0', b"", ""), ("three", b'0', b"", "")]); + let listing = tar_with_name_copy_limit(&data, 10, 12).unwrap(); + assert_eq!(listing.members.len(), 2); + assert!(listing.members.iter().all(|m| m.name == "shared")); + assert_eq!(listing.stop_reason, Some(StopReason::GlobalNameBudget)); + assert!(!listing.complete && !listing.truncated); + assert!(listing.warnings.iter().any(|w| w.contains("name-byte budget"))); + assert_eq!(listing.length, 2048); + assert!(tar_with_name_copy_limit(&data, 10, 18).unwrap().complete); + } + + #[test] + fn local_names_and_unused_global_links_do_not_spend_copy_bytes() { + let global = global_record("path", "name") + &global_record("linkpath", "unused-link"); + let local = global_record("path", "local-name"); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("local", b'x', local.as_bytes(), ""), + ("one", b'0', b"", ""), + ("two", b'0', b"", ""), + ]); + let listing = tar_with_name_copy_limit(&data, 10, 4).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members.iter().map(|m| m.name.as_str()).collect::>(), ["local-name", "name"]); + assert!(listing.members.iter().all(|m| m.link_target.is_none())); + } + + #[test] + fn global_names_and_links_share_the_decoded_byte_budget() { + let global = global_record("path", "é") + &global_record("linkpath", "中"); + let data = fx::tar_entries(&[("global", b'g', global.as_bytes(), ""), ("one", b'2', b"", "fallback"), ("two", b'1', b"", "fallback")]); + let listing = tar_with_name_copy_limit(&data, 10, 5).unwrap(); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].link_target.as_deref(), Some("中")); + assert_eq!(listing.stop_reason, Some(StopReason::GlobalNameBudget)); + assert!(tar_with_name_copy_limit(&data, 10, 10).unwrap().complete); + } + + #[test] + fn oversized_gnu_names_do_not_alias_their_truncated_prefix() { + for kind in *b"LK" { + let mut long = vec![b'n'; MAX_NAME + 1]; + long.push(0); + let data = fx::tar_entries(&[ + ("before", b'0', b"kept", ""), + ("././@LongLink", kind, &long, ""), + ("short", if kind == b'K' { b'2' } else { b'0' }, b"", "fallback"), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.stop_reason, Some(StopReason::GnuMetadataTooLong)); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].name, "before"); + assert_eq!(member_data(&data, &listing.members[0]).unwrap(), b"kept"); + assert!(listing.warnings.iter().any(|warning| warning.contains("GNU long name or link exceeds"))); + } + } + + #[test] + fn gnu_long_names_keep_exact_limits_and_short_terminated_values() { + for kind in *b"LK" { + for terminated in [false, true] { + let mut long = vec![b'n'; MAX_NAME]; + if terminated { + long.push(0); + } + let data = fx::tar_entries(&[("././@LongLink", kind, &long, ""), ("short", if kind == b'K' { b'2' } else { b'0' }, b"", "fallback")]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete, "{:?}", listing.warnings); + let member = &listing.members[0]; + let name = if kind == b'L' { member.name.as_str() } else { member.link_target.as_deref().unwrap() }; + assert_eq!(name, "n".repeat(MAX_NAME)); + } + } + let mut padded = b"short\0".to_vec(); + padded.resize(MAX_NAME + 100, 0); + let data = fx::tar_entries(&[("././@LongLink", b'L', &padded, ""), ("fallback", b'0', b"payload", "")]); + assert_eq!(tar(&data, 10).unwrap().members[0].name, "short"); + } + + fn sparse_pax_record(key: &str, value: &str) -> Vec { + let field = format!(" {key}={value}\n"); + let mut length = field.len() + 1; + loop { + let actual = field.len() + length.to_string().len(); + if actual == length { + return format!("{length}{field}").into_bytes(); + } + length = actual; + } + } + + #[test] + fn gnu_sparse_pax_members_are_not_regular_file_bytes() { + for fields in [ + vec![("GNU.sparse.size", "100"), ("GNU.sparse.numblocks", "1"), ("GNU.sparse.offset", "50"), ("GNU.sparse.numbytes", "3")], + vec![("GNU.sparse.size", "100"), ("GNU.sparse.map", "50,3"), ("GNU.sparse.name", "original.bin")], + vec![("GNU.sparse.major", "1"), ("GNU.sparse.minor", "0"), ("GNU.sparse.realsize", "100"), ("GNU.sparse.name", "original.bin")], + ] { + let metadata: Vec = fields.iter().flat_map(|(key, value)| sparse_pax_record(key, value)).collect(); + let version_one = fields.iter().any(|(key, _)| *key == "GNU.sparse.major"); + let mut sparse_body = if version_one { b"1\n50\n3\n".to_vec() } else { Vec::new() }; + if version_one { + sparse_body.resize(512, 0); + } + sparse_body.extend_from_slice(b"abc"); + let data = + fx::tar_entries(&[("metadata", b'x', &metadata, ""), ("stored-name", b'0', &sparse_body, ""), ("normal", b'0', b"ordinary", "")]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete, "{:?}", listing.warnings); + assert_eq!(listing.members.len(), 2); + assert_eq!(listing.members[0].kind, MemberKind::Other); + let named = fields.iter().any(|(key, _)| *key == "GNU.sparse.name"); + assert_eq!(listing.members[0].name, if named { "original.bin" } else { "stored-name" }); + assert_eq!(listing.members[1].kind, MemberKind::File); + assert_eq!(member_data(&data, &listing.members[1]).unwrap(), b"ordinary"); + assert_eq!(listing.warnings.len(), 1); + assert!(listing.warnings[0].contains("sparse reconstruction is unsupported")); + } + } + + #[test] + fn sparse_metadata_survives_other_extension_headers() { + let sparse = sparse_pax_record("GNU.sparse.map", "0,3"); + let path = sparse_pax_record("path", "renamed"); + let data = fx::tar_entries(&[ + ("sparse", b'x', &sparse, ""), + ("name", b'L', b"long-name\0", ""), + ("path", b'x', &path, ""), + ("header", b'0', b"abc", ""), + ("next", b'0', b"ok", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert_eq!(listing.members[0].name, "renamed"); + assert_eq!(listing.members[0].kind, MemberKind::Other); + assert_eq!(listing.members[1].kind, MemberKind::File); + } + + #[test] + fn gnu_metadata_stop_reasons_keep_partial_listings_and_marker_compatibility() { + for kind in *b"LK" { + let mut data = + fx::tar_entries(&[("before", b'0', b"kept", ""), ("././@LongLink", kind, b"long\0", ""), ("fallback", b'0', b"later", "")]); + data.truncate(3 * BLOCK + 2); + let listing = tar(&data, 10).unwrap(); + assert_eq!(listing.stop_reason, Some(StopReason::GnuMetadataTruncated)); + assert!(!listing.complete); + assert!(!listing.truncated); + assert_eq!(listing.members.len(), 1); + assert_eq!(member_data(&data, &listing.members[0]).unwrap(), b"kept"); + } + let mut data = fx::tar_entries(&[("file", b'0', b"kept", "")]); + data.truncate(2 * BLOCK); + let listing = tar(&data, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.stop_reason, None); + assert_eq!(member_data(&data, &listing.members[0]).unwrap(), b"kept"); + let cpio_listing = cpio(&fx::cpio_newc(&[("file", b"kept", 0o100644)]), 10).unwrap(); + assert_eq!(cpio_listing.stop_reason, None); + } + + #[test] + fn gnu_metadata_requires_its_complete_padded_record() { + let body = b"next\0"; + for kind in *b"LK" { + let data = fx::tar_entries(&[ + ("before", b'0', b"kept", ""), + ("././@LongLink", kind, body, ""), + ("fallback", if kind == b'L' { b'0' } else { b'2' }, b"", "fallback"), + ]); + for padding in [0, 1, BLOCK - body.len() - 1] { + let short = &data[..3 * BLOCK + body.len() + padding]; + let listing = tar(short, 10).unwrap(); + assert_eq!(listing.stop_reason, Some(StopReason::GnuMetadataTruncated)); + assert!(!listing.complete); + assert_eq!(listing.members.len(), 1); + assert_eq!(member_data(short, &listing.members[0]).unwrap(), b"kept"); + } + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.stop_reason, None); + assert_eq!(listing.members.len(), 2); + } + } + + #[test] + fn walks_tar() { + let t = fx::tar(&[("etc/passwd", b"root:x:0:0\n"), ("bin/", b""), ("long/".repeat(30).as_str(), b"deep")]); + let l = tar(&t, 100).unwrap(); + assert!(l.complete, "{:?}", l.warnings); + assert_eq!(l.members.len(), 3); + assert_eq!(l.members[0].name, "etc/passwd"); + assert_eq!(member_data(&t, &l.members[0]).unwrap(), b"root:x:0:0\n"); + assert_eq!(l.members[1].kind, MemberKind::Dir); + assert!(l.members[2].name.starts_with("long/long/")); + assert_eq!(l.length, t.len() as u64); + let l2 = tar(&t, 1).unwrap(); + assert!(l2.truncated); + assert_eq!(l2.members.len(), 1); + } + + #[test] + fn cpio_names_and_trailers_must_be_complete() { + let bytes = fx::cpio_newc(&[("abc", b"x", 0o100644)]); + let trailer = bytes.windows(6).rposition(|b| b == b"070701").unwrap(); + for (offset, byte) in [(113, b'x'), (111, 0)] { + let mut damaged = bytes.clone(); + damaged[offset] = byte; + let listed = cpio(&damaged, 10).unwrap(); + assert!(!listed.complete); + assert!(listed.members.is_empty()); + } + let mut padded_name = bytes.clone(); + padded_name[112] = 0; + assert_eq!(cpio(&padded_name, 10).unwrap().members[0].name, "ab"); + let mut with_payload = bytes.clone(); + with_payload[trailer + 61] = b'1'; + assert!(!cpio(&with_payload, 10).unwrap().complete); + assert!(!cpio(&bytes[..bytes.len() - 1], 10).unwrap().complete); + } + + #[test] + fn cpio_hard_link_aliases_do_not_appear_as_empty_files() { + for content_first in [true, false] { + let data = if content_first { [b"abc".as_slice(), b""] } else { [b"".as_slice(), b"abc"] }; + let mut archive = fx::cpio_newc(&[("one", data[0], 0o100644), ("two", data[1], 0o100644), ("separate", b"", 0o100644)]); + let starts: Vec<_> = archive.windows(6).enumerate().filter(|(_, bytes)| *bytes == b"070701").map(|(i, _)| i).collect(); + for &start in &starts[..3] { + archive[start + 6..start + 14].copy_from_slice(b"00000015"); + archive[start + 38..start + 46].copy_from_slice(b"00000002"); + } + archive[starts[2] + 70..starts[2] + 78].copy_from_slice(b"00000001"); + let (file, alias) = if content_first { (0, 1) } else { (1, 0) }; + for crc in [false, true] { + if crc { + for &start in &starts { + archive[start..start + 6].copy_from_slice(b"070702"); + } + archive[starts[file] + 102..starts[file] + 110].copy_from_slice(b"00000126"); + } + let listing = cpio(&archive, 10).unwrap(); + assert_eq!(listing.members[file].kind, MemberKind::File); + assert_eq!(member_data(&archive, &listing.members[file]), Some(b"abc".as_slice())); + assert_eq!(listing.members[alias].kind, MemberKind::Hardlink); + assert_eq!(listing.members[alias].link_target.as_deref(), Some(listing.members[file].name.as_str())); + assert_eq!(listing.members[2].kind, MemberKind::File); + assert!(listing.warnings.is_empty()); + } + } + } + + #[test] + fn walks_cpio() { + let c = fx::cpio_newc(&[("init", b"#!/bin/sh\n", 0o100755), ("dev", b"", 0o040755), ("sh", b"busybox", 0o120777)]); + let l = cpio(&c, 100).unwrap(); + assert!(l.complete); + assert_eq!(l.members.len(), 3); + assert_eq!(member_data(&c, &l.members[0]).unwrap(), b"#!/bin/sh\n"); + assert_eq!(l.members[2].kind, MemberKind::Symlink); + assert_eq!(l.members[2].link_target.as_deref(), Some("busybox")); + assert_eq!(l.length, c.len() as u64); + } + + #[test] + fn octal_fields() { + assert_eq!(octal(b"0000644 \0"), Some(0o644)); + assert_eq!(octal(b" \0"), Some(0)); + assert_eq!(octal(b"9"), None); + assert_eq!(octal(&[0x80, 0, 0, 1, 0]), Some(256)); + assert_eq!(octal(&[0xff; 8]), None); + assert_eq!(octal(&[0xff; 12]), None); + } + + #[test] + fn hostile_archives_do_not_panic() { + let t = fx::tar(&[("a", b"hello"), ("b/c", b"world")]); + let c = fx::cpio_newc(&[("a", b"hello", 0o100644)]); + for s in [&t, &c] { + for m in fx::mutations(s) { + let _ = tar(&m, 10); + let _ = cpio(&m, 10); + } + for n in 0..s.len().min(800) { + let _ = tar(&s[..n], 10); + let _ = cpio(&s[..n], 10); + } + } + for seed in 0..50 { + let n = fx::noise(seed, 2048); + let _ = tar(&n, 10); + let _ = cpio(&n, 10); + } + assert!(pax_record(b"12 path=abc\n").is_some()); + assert!(pax_record(b"9999999999999999999999 x").is_none()); + } +} diff --git a/crates/tar/src/tar_tests.rs b/crates/tar/src/tar_tests.rs new file mode 100644 index 0000000000..38f72abd92 --- /dev/null +++ b/crates/tar/src/tar_tests.rs @@ -0,0 +1,404 @@ +// ---- from Craft Anything crates/formats/tests/tar_gnu_names.rs +mod tar_gnu_names { + use crate::testkit as fx; + use crate::{member_data, tar}; + + fn checksum(header: &mut [u8]) { + header[148..156].fill(b' '); + let sum: u32 = header.iter().map(|&b| u32::from(b)).sum(); + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + } + + #[test] + fn old_gnu_timestamps_are_not_posix_path_prefixes() { + let mut archive = fx::tar(&[("program", b"payload")]); + let header = &mut archive[..512]; + header[257..265].copy_from_slice(b"ustar \0"); + header[345..357].copy_from_slice(b"00000000123\0"); + header[357..369].copy_from_slice(b"00000000456\0"); + checksum(header); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members[0].name, "program"); + assert_eq!(member_data(&archive, &listing.members[0]), Some(b"payload".as_slice())); + } + + #[test] + fn posix_ustar_prefixes_are_still_joined() { + let mut archive = fx::tar(&[("program", b"payload")]); + let header = &mut archive[..512]; + header[345..352].copy_from_slice(b"usr/bin"); + checksum(header); + assert_eq!(tar(&archive, 10).unwrap().members[0].name, "usr/bin/program"); + } +} + +// ---- from Craft Anything crates/formats/tests/tar_local_pax_size.rs +mod tar_local_pax_size { + use crate::testkit::tar_entries; + use crate::{member_data, tar}; + + /// Encode the decimal byte count that includes the PAX record itself. + fn record(value: &str) -> String { + let body = format!(" size={value}\n"); + let mut size = body.len() + 1; + loop { + let result = format!("{size}{body}"); + if result.len() == size { + return result; + } + size = result.len(); + } + } + + /// Invalid local sizes cannot silently fall back to a plausible member header. + #[test] + fn malformed_local_sizes_stop_before_the_affected_member() { + for value in ["no", "-1", "+3", " 3", "3 ", "3.0", "18446744073709551616"] { + let pax = record(value); + let bytes = tar_entries(&[("keep", b'0', b"ok", ""), ("PaxHeader", b'x', pax.as_bytes(), ""), ("affected", b'0', b"abc", "")]); + let report = tar(&bytes, 10).unwrap(); + assert!(!report.complete, "size={value}"); + assert_eq!(report.members.len(), 1); + assert_eq!(report.members[0].name, "keep"); + assert_eq!(member_data(&bytes, &report.members[0]), Some(b"ok".as_slice())); + assert!(report.warnings.iter().any(|w| w.contains("pax size"))); + } + } + + /// Decimal sizes, zero, and the existing empty override behavior still work. + #[test] + fn valid_local_sizes_remain_readable() { + for (size, body) in [("3", b"abc".as_slice()), ("0003", b"abc"), ("0", b""), ("", b"abc")] { + let pax = record(size); + let bytes = tar_entries(&[("PaxHeader", b'x', pax.as_bytes(), ""), ("file", b'0', body, "")]); + let report = tar(&bytes, 10).unwrap(); + assert!(report.complete, "{:?}", report.warnings); + assert_eq!(member_data(&bytes, &report.members[0]), Some(body)); + } + } +} + +// ---- from Craft Anything crates/formats/tests/tar_pax_size.rs +mod tar_pax_size { + use crate::testkit as fx; + use crate::{member_data, tar}; + + fn clear_member_size(archive: &mut [u8], offset: usize) { + let header = &mut archive[offset..offset + 512]; + header[124..136].copy_from_slice(b"00000000000\0"); + header[148..156].fill(b' '); + let sum: u32 = header.iter().map(|&b| u32::from(b)).sum(); + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + } + + #[test] + fn pax_size_survives_a_gnu_long_name_record() { + let mut archive = fx::tar_entries(&[ + ("PaxHeader", b'x', b"10 size=3\n", ""), + ("././@LongLink", b'L', b"renamed\0", ""), + ("short", b'0', b"abc", ""), + ("next", b'0', b"later", ""), + ]); + clear_member_size(&mut archive, 2048); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete, "{:?}", listing.warnings); + assert_eq!(listing.members.len(), 2); + assert_eq!(listing.members[0].name, "renamed"); + assert_eq!(listing.members[0].size, 3); + assert_eq!(member_data(&archive, &listing.members[0]), Some(b"abc".as_slice())); + assert_eq!(listing.members[1].size, 5); + assert_eq!(member_data(&archive, &listing.members[1]), Some(b"later".as_slice())); + } + + #[test] + fn pax_size_without_intervening_metadata_still_applies_once() { + let mut archive = fx::tar_entries(&[("PaxHeader", b'x', b"10 size=3\n", ""), ("short", b'0', b"abc", ""), ("next", b'0', b"later", "")]); + clear_member_size(&mut archive, 1024); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members.iter().map(|m| m.size).collect::>(), vec![3, 5]); + } + + fn pax_record(key: &str, value: &str) -> String { + let content = format!(" {key}={value}\n"); + let mut len = content.len() + 1; + loop { + let record = format!("{len}{content}"); + if record.len() == len { + return record; + } + len = record.len(); + } + } + + #[test] + fn malformed_pax_framing_stops_the_listing() { + for invalid in [b"10 size=3!".as_slice(), b"10 size=3!\n", b"20 size=3\n", b"+12 path=no\n", b"5 =x\n", b"12 path=a=b\n11 path=bad"] { + let archive = fx::tar_entries(&[("keep", b'0', b"one", ""), ("PaxHeader", b'x', invalid, ""), ("after", b'0', b"two", "")]); + let listing = tar(&archive, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].name, "keep"); + assert!(listing.warnings.iter().any(|s| s.contains("pax"))); + } + } + + #[test] + fn pax_path_can_contain_an_equals_sign() { + let archive = fx::tar_entries(&[("PaxHeader", b'x', b"12 path=a=b\n", ""), ("short", b'0', b"ok", "")]); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members[0].name, "a=b"); + } + + #[test] + fn the_name_limit_applies_only_to_pax_fields_kept_as_names() { + let exact = "a".repeat(4096); + let large = "b".repeat(100_000); + let pax = pax_record("comment", &large) + &pax_record("path", &exact); + let archive = fx::tar_entries(&[("PaxHeader", b'x', pax.as_bytes(), ""), ("short", b'0', b"ok", "")]); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members[0].name, exact); + for key in ["path", "linkpath"] { + let pax = pax_record(key, &large); + let archive = fx::tar_entries(&[("PaxHeader", b'x', pax.as_bytes(), ""), ("short", b'2', b"", "link")]); + let listing = tar(&archive, 10).unwrap(); + assert!(!listing.complete); + assert!(listing.members.is_empty()); + assert!(listing.warnings.iter().any(|s| s.contains("4096"))); + } + } + + #[test] + fn empty_pax_values_remove_an_earlier_override() { + let pax = pax_record("path", "other") + &pax_record("path", "") + &pax_record("linkpath", "first") + &pax_record("linkpath", ""); + let archive = fx::tar_entries(&[("PaxHeader", b'x', pax.as_bytes(), ""), ("original", b'2', b"", "target")]); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert!(listing.members[0].name.is_empty()); + assert!(listing.members[0].link_target.is_none()); + } + + #[test] + fn tar_sizes_allow_outer_padding_but_do_not_join_separated_digits() { + for (field, valid) in [(b" 000000001\0 ", true), (b" 0000 0001\0 ", false), (b" 0000\x000001\0 ", false)] { + let mut archive = fx::tar_entries(&[("one", b'0', b"1", ""), ("two", b'0', b"2", "")]); + let header = &mut archive[..512]; + header[124..136].copy_from_slice(field); + header[148..156].fill(b' '); + let sum: u32 = header.iter().map(|&b| u32::from(b)).sum(); + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + let listing = tar(&archive, 10).unwrap(); + assert_eq!(listing.complete, valid); + assert_eq!(listing.members.len(), if valid { 2 } else { 0 }); + } + } + + #[test] + fn excess_pax_records_do_not_hide_a_later_override() { + let mut records = pax_record("comment", "").repeat(256); + for excess in [false, true] { + if excess { + records.push_str(&pax_record("size", "9999")); + } + let archive = fx::tar_entries(&[("PaxHeader", b'x', records.as_bytes(), ""), ("member", b'0', b"ok", "")]); + let listing = tar(&archive, 10).unwrap(); + assert_eq!(listing.complete, !excess); + assert_eq!(listing.members.len(), usize::from(!excess)); + } + } +} + +// ---- from Craft Anything crates/formats/tests/tar_global_pax.rs +mod tar_global_pax { + use crate::testkit as fx; + use crate::{MemberKind, member_data, tar}; + + fn record(key: &str, value: &str) -> String { + let tail = format!(" {key}={value}\n"); + let mut len = tail.len() + 1; + loop { + let record = format!("{len}{tail}"); + if record.len() == len { + return record; + } + len = record.len(); + } + } + + fn clear_size(data: &mut [u8], at: usize) { + let header = &mut data[at..at + 512]; + header[124..136].copy_from_slice(b"00000000000\0"); + header[148..156].fill(b' '); + let sum: u32 = header.iter().map(|&b| u32::from(b)).sum(); + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + } + + #[test] + fn global_path_and_size_persist_across_members_and_metadata() { + let global = record("path", "global-name") + &record("size", "3"); + let local = record("comment", "unrelated"); + let mut data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("first", b'0', b"abc", ""), + ("metadata", b'x', local.as_bytes(), ""), + ("second", b'0', b"def", ""), + ]); + clear_size(&mut data, 1024); + clear_size(&mut data, 3072); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete, "{:?}", listing.warnings); + assert_eq!(listing.members.len(), 2); + assert!(listing.members.iter().all(|member| member.name == "global-name" && member.size == 3)); + assert_eq!(member_data(&data, &listing.members[0]), Some(b"abc".as_slice())); + assert_eq!(member_data(&data, &listing.members[1]), Some(b"def".as_slice())); + } + + #[test] + fn local_attributes_override_only_one_member() { + let global = record("path", "inherited") + &record("size", "3"); + let local = record("path", "one-member") + &record("size", "0"); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("local", b'x', local.as_bytes(), ""), + ("first", b'0', b"", ""), + ("second", b'0', b"abc", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members.iter().map(|m| (m.name.as_str(), m.size)).collect::>(), [("one-member", 0), ("inherited", 3)]); + } + + #[test] + fn later_global_records_update_and_delete_only_their_keys() { + let first = record("path", "first-global") + &record("size", "3"); + let second = record("path", "second-global"); + let remove = record("path", "") + &record("size", ""); + let data = fx::tar_entries(&[ + ("global", b'g', first.as_bytes(), ""), + ("one", b'0', b"abc", ""), + ("global", b'g', second.as_bytes(), ""), + ("two", b'0', b"def", ""), + ("global", b'g', remove.as_bytes(), ""), + ("plain", b'0', b"normal", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!( + listing.members.iter().map(|m| (m.name.as_str(), m.size)).collect::>(), + [("first-global", 3), ("second-global", 3), ("plain", 6)] + ); + } + + #[test] + fn global_link_names_persist_until_deleted() { + let global = record("linkpath", "shared-target"); + let local = record("linkpath", "local-target"); + let remove = record("linkpath", ""); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("one", b'2', b"", "fallback"), + ("local", b'x', local.as_bytes(), ""), + ("two", b'1', b"", "fallback"), + ("three", b'2', b"", "fallback"), + ("global", b'g', remove.as_bytes(), ""), + ("four", b'2', b"", "original"), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!( + listing.members.iter().map(|m| m.link_target.as_deref()).collect::>(), + [Some("shared-target"), Some("local-target"), Some("shared-target"), Some("original")] + ); + } + + #[test] + fn malformed_or_excess_global_records_do_not_claim_complete_members() { + for metadata in [String::from("10 size=3!"), record("comment", "").repeat(257), record("path", &"a".repeat(4097))] { + let data = fx::tar_entries(&[("keep", b'0', b"ok", ""), ("global", b'g', metadata.as_bytes(), ""), ("after", b'0', b"later", "")]); + let listing = tar(&data, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].name, "keep"); + assert!(listing.warnings.iter().any(|warning| warning.contains("pax"))); + } + } + + #[test] + fn global_sparse_metadata_keeps_stored_extents_out_of_regular_files() { + let global = record("GNU.sparse.map", "0,3"); + let remove = record("GNU.sparse.map", ""); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("one", b'0', b"abc", ""), + ("two", b'0', b"def", ""), + ("global", b'g', remove.as_bytes(), ""), + ("plain", b'0', b"ghi", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members.iter().map(|m| m.kind).collect::>(), [MemberKind::Other, MemberKind::Other, MemberKind::File]); + assert_eq!(listing.warnings.iter().filter(|warning| warning.contains("sparse")).count(), 2); + } + + #[test] + fn unrelated_global_fields_preserve_local_and_gnu_names() { + let global = record("comment", "not a member name"); + let local = record("path", "local"); + let data = fx::tar_entries(&[ + ("local", b'x', local.as_bytes(), ""), + ("global", b'g', global.as_bytes(), ""), + ("first", b'0', b"one", ""), + ("././@LongLink", b'L', b"gnu-name\0", ""), + ("second", b'0', b"two", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete && listing.warnings.is_empty()); + assert_eq!(listing.members.iter().map(|m| m.name.as_str()).collect::>(), ["local", "gnu-name"]); + } + + #[test] + fn global_names_obey_the_existing_member_limit() { + let path = "a".repeat(4096); + let global = record("path", &path); + let data = fx::tar_entries(&[("global", b'g', global.as_bytes(), ""), ("one", b'0', b"abc", ""), ("two", b'0', b"def", "")]); + let listing = tar(&data, 1).unwrap(); + assert!(listing.truncated && !listing.complete); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].name, path); + } + + #[test] + fn global_pax_names_override_and_consume_gnu_name_records() { + let global = record("path", "global") + &record("linkpath", "global-target"); + let remove = record("path", "") + &record("linkpath", ""); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("LongLink", b'L', b"gnu-name\0", ""), + ("LongLink", b'K', b"gnu-target\0", ""), + ("first", b'2', b"", "fallback"), + ("global", b'g', remove.as_bytes(), ""), + ("plain", b'2', b"", "original"), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!( + listing.members.iter().map(|m| (m.name.as_str(), m.link_target.as_deref())).collect::>(), + [("global", Some("global-target")), ("plain", Some("original"))] + ); + } + + #[test] + fn nonempty_global_sizes_must_be_unsigned_decimal_numbers() { + for size in ["+3", "-3", "3x", " 3", "18446744073709551616"] { + let global = record("size", size); + let data = fx::tar_entries(&[("keep", b'0', b"abc", ""), ("global", b'g', global.as_bytes(), ""), ("after", b'0', b"def", "")]); + let listing = tar(&data, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.members.len(), 1); + assert!(listing.warnings.iter().any(|warning| warning.contains("global pax size"))); + } + } +} diff --git a/crates/tar/src/testkit.rs b/crates/tar/src/testkit.rs new file mode 100644 index 0000000000..828644a4b4 --- /dev/null +++ b/crates/tar/src/testkit.rs @@ -0,0 +1,135 @@ +//! Archive builders and damage generators for the tests, from Craft Anything's testkit. + +#![allow(clippy::indexing_slicing, clippy::cast_possible_truncation)] + +fn tar_header(name: &str, typeflag: u8, size: usize, link: &str) -> Vec { + let mut h = vec![0u8; 512]; + let n = name.as_bytes(); + h[..n.len().min(100)].copy_from_slice(&n[..n.len().min(100)]); + h[100..108].copy_from_slice(b"0000644\0"); + h[108..116].copy_from_slice(b"0000000\0"); + h[116..124].copy_from_slice(b"0000000\0"); + h[124..136].copy_from_slice(format!("{size:011o}\0").as_bytes()); + h[136..148].copy_from_slice(b"00000000000\0"); + h[156] = typeflag; + let l = link.as_bytes(); + h[157..157 + l.len().min(100)].copy_from_slice(&l[..l.len().min(100)]); + h[257..263].copy_from_slice(b"ustar\0"); + h[263..265].copy_from_slice(b"00"); + h[148..156].copy_from_slice(b" "); + let sum: u32 = h.iter().map(|&b| u32::from(b)).sum(); + h[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + h +} + +fn pad512(v: &mut Vec) { + while !v.len().is_multiple_of(512) { + v.push(0); + } +} + +/// A tar entry for [`tar_entries`]: (name, typeflag, data, link target). +pub type TarEntry<'a> = (&'a str, u8, &'a [u8], &'a str); + +/// A ustar archive from raw entries; names longer than 100 bytes get a GNU long-name record. +pub fn tar_entries(entries: &[TarEntry<'_>]) -> Vec { + let mut out = Vec::new(); + for (name, flag, data, link) in entries { + if name.len() > 100 { + let mut long = name.as_bytes().to_vec(); + long.push(0); + out.extend(tar_header("././@LongLink", b'L', long.len(), "")); + out.extend_from_slice(&long); + pad512(&mut out); + } + out.extend(tar_header(name, *flag, data.len(), link)); + out.extend_from_slice(data); + pad512(&mut out); + } + out.extend(vec![0u8; 1024]); + out +} + +/// A ustar archive of files (names ending in `/` become folders). +pub fn tar(files: &[(&str, &[u8])]) -> Vec { + let e: Vec> = files.iter().map(|(n, d)| (*n, if n.ends_with('/') { b'5' } else { b'0' }, *d, "")).collect(); + tar_entries(&e) +} + +/// A cpio newc archive from (name, data, mode). Symlinks (mode 0o120000) store the target as data. +pub fn cpio_newc(files: &[(&str, &[u8], u32)]) -> Vec { + let mut out = Vec::new(); + let mut push = |name: &str, data: &[u8], mode: u32, ino: u32| { + let hdr = format!( + "070701{ino:08x}{mode:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}", + 0, + 0, + 1, + 0, + data.len(), + 0, + 0, + 0, + 0, + name.len() + 1, + 0 + ); + out.extend_from_slice(hdr.as_bytes()); + out.extend_from_slice(name.as_bytes()); + out.push(0); + while !out.len().is_multiple_of(4) { + out.push(0); + } + out.extend_from_slice(data); + while !out.len().is_multiple_of(4) { + out.push(0); + } + }; + for (i, (n, d, m)) in files.iter().enumerate() { + push(n, d, *m, i as u32 + 1); + } + push("TRAILER!!!", b"", 0, 0); + out +} + +/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. +pub fn noise(seed: u64, len: usize) -> Vec { + let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() +} + +/// Every way to damage a sample used by robustness tests: truncations at many lengths and +/// single-byte corruptions spread across the file. +pub fn mutations(sample: &[u8]) -> Vec> { + let mut out = Vec::new(); + let n = sample.len(); + let step = (n / 64).max(1); + let mut len = 0; + while len < n { + out.push(sample[..len].to_vec()); + len += step; + } + for (i, seed) in (0..n).step_by(step).zip(1u64..) { + let mut m = sample.to_vec(); + let noise = noise(seed, 8); + for (j, v) in noise.iter().enumerate() { + if let Some(b) = m.get_mut(i + j) { + *b = *v; + } + } + out.push(m); + let mut m = sample.to_vec(); + if let Some(b) = m.get_mut(i) { + *b = 0xff; + } + out.push(m); + } + out +} diff --git a/crates/tcraft/Cargo.toml b/crates/tcraft/Cargo.toml new file mode 100644 index 0000000000..3ce35abfb0 --- /dev/null +++ b/crates/tcraft/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-tcraft" +description = "Streaming binary payloads of TextureCraft project archives" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-zip = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/tcraft/README.md b/crates/tcraft/README.md new file mode 100644 index 0000000000..e5831ef98b --- /dev/null +++ b/crates/tcraft/README.md @@ -0,0 +1,14 @@ +# craft-tcraft + +Streaming neutral `TCTX` binary payloads used inside TextureCraft `.tcraft` projects. Sparse +paint data stores 64×64 tiles of little-endian `u16` components; baked maps store dense +little-endian `f32` values. This crate does not yet define the project JSON schema or ZIP +envelope and does not depend on TextureCraft's app types. + +`read_tiles` validates the expected dimensions and components, bounds tile count, rejects +out-of-range and repeated tile positions, and delivers one owned tile at a time. `read_baked` +validates dimensions and declared length and decodes in bounded chunks. Both consume the same +caller-owned `craft_zip::Budget` used for the surrounding project and reject trailing data. +`write_tiles` and `write_baked` stream their bodies rather than copying an entire image; a caller +must discard an incomplete output if a write fails. Limits and ownership rules beyond this +binary format remain with the project reader. diff --git a/crates/tcraft/src/lib.rs b/crates/tcraft/src/lib.rs new file mode 100644 index 0000000000..d7af3e8a6d --- /dev/null +++ b/crates/tcraft/src/lib.rs @@ -0,0 +1,428 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Streaming `TCTX` tile and baked-map payloads in TextureCraft `.tcraft` archives. +//! +//! This codec handles the neutral binary payload, not the application's project model or ZIP +//! envelope. Reads use a caller-owned budget shared with other archive entries. No reader opens +//! a file or reserves memory based on a claimed payload before checking it. + +use std::collections::{BTreeMap, HashSet}; +use std::io::{self, Read, Write}; + +use craft_zip::Budget; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub const TILE_SIDE: u32 = 64; +pub const TILE_AREA: usize = 64 * 64; +pub const HEADER_BYTES: u64 = 24; +pub const VERSION: u32 = 1; +const MAGIC: &[u8; 4] = b"TCTX"; +const CHUNK: usize = 1 << 16; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid TCTX payload: {0}")] + Invalid(String), + #[error("TCTX version {0} is newer than supported")] + NewerVersion(u32), + #[error("TCTX budget: {0}")] + Budget(#[from] craft_zip::Exceeded), + #[error("TCTX limit: {0}")] + Limit(String), + #[error("TCTX I/O: {0}")] + Io(#[from] io::Error), +} + +/// Neutral top-level project schema. Nested app-domain values and unknown fields remain JSON +/// so they round-trip without requiring TextureCraft's in-memory model. +#[derive(Clone, Debug, PartialEq, Deserialize)] +pub struct ProjectDocument { + pub format_version: u32, + pub name: String, + pub mesh: String, + pub normal_format: Value, + pub texture_sets: Vec, + pub layers: BTreeMap, + pub next_id: u64, + pub display: Value, + #[serde(default)] + pub cameras: Vec, + #[serde(flatten)] + pub extra: BTreeMap, +} + +impl Serialize for ProjectDocument { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::{Error as _, SerializeMap as _}; + const RESERVED: &[&str] = &["format_version", "name", "mesh", "normal_format", "texture_sets", "layers", "next_id", "display", "cameras"]; + if self.extra.keys().any(|key| RESERVED.contains(&key.as_str())) { + return Err(S::Error::custom("an extra project field duplicates a known field")); + } + let mut map = serializer.serialize_map(Some(9 + self.extra.len()))?; + map.serialize_entry("format_version", &self.format_version)?; + map.serialize_entry("name", &self.name)?; + map.serialize_entry("mesh", &self.mesh)?; + map.serialize_entry("normal_format", &self.normal_format)?; + map.serialize_entry("texture_sets", &self.texture_sets)?; + map.serialize_entry("layers", &self.layers)?; + map.serialize_entry("next_id", &self.next_id)?; + map.serialize_entry("display", &self.display)?; + map.serialize_entry("cameras", &self.cameras)?; + for (key, value) in &self.extra { + map.serialize_entry(key, value)?; + } + map.end() + } +} + +/// Read only the version before an application applies its own recovery policy. Serde's +/// structured parse rejects a duplicate or invalid version field, like the project reader. +pub fn project_version(bytes: &[u8]) -> Result { + #[derive(Deserialize)] + struct Version { + format_version: u32, + } + Ok(serde_json::from_slice::(bytes)?.format_version) +} + +/// Width, height and number of components expected by the enclosing project schema. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Layout { + pub width: u32, + pub height: u32, + pub components: usize, +} + +#[derive(Clone, Copy, Debug)] +struct Header { + layout: Layout, + count: u32, +} + +fn charge(budget: &mut Budget, n: u64) -> Result<(), Error> { + budget.charge(n).map_err(Error::from) +} + +fn read_header(reader: &mut (impl Read + ?Sized), budget: &mut Budget) -> Result { + charge(budget, HEADER_BYTES)?; + let mut bytes = [0u8; HEADER_BYTES as usize]; + reader.read_exact(&mut bytes)?; + if bytes.get(..4) != Some(MAGIC.as_slice()) { + return Err(Error::Invalid("bad magic".into())); + } + let word = |i: usize| bytes.get(i * 4..i * 4 + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).unwrap_or(0); + let version = word(1); + if version > VERSION { + return Err(Error::NewerVersion(version)); + } + Ok(Header { layout: Layout { width: word(2), height: word(3), components: word(4) as usize }, count: word(5) }) +} + +fn write_header(writer: &mut (impl Write + ?Sized), layout: Layout, count: u32) -> Result<(), Error> { + let components = u32::try_from(layout.components).map_err(|_| Error::Limit("too many components".into()))?; + writer.write_all(MAGIC)?; + for value in [VERSION, layout.width, layout.height, components, count] { + writer.write_all(&value.to_le_bytes())?; + } + Ok(()) +} + +fn expect_end(reader: &mut (impl Read + ?Sized)) -> Result<(), Error> { + let mut byte = [0u8; 1]; + if reader.read(&mut byte)? != 0 { + return Err(Error::Invalid("trailing data".into())); + } + Ok(()) +} + +fn tile_dimensions(layout: Layout) -> Result<(u32, u32, usize), Error> { + if layout.width == 0 || layout.height == 0 || layout.components == 0 { + return Err(Error::Invalid("empty tile layout".into())); + } + let x = layout.width.div_ceil(TILE_SIDE); + let y = layout.height.div_ceil(TILE_SIDE); + let bytes = TILE_AREA.checked_mul(layout.components).and_then(|n| n.checked_mul(2)).ok_or_else(|| Error::Limit("tile is too large".into()))?; + Ok((x, y, bytes)) +} + +/// Decode tiles one at a time, transferring each tile to the callback. +/// Positions and duplicate tiles are checked before delivery; the entry must end exactly. +pub fn read_tiles( + reader: &mut (impl Read + ?Sized), + expected: Layout, + max_texels: u64, + budget: &mut Budget, + mut tile: impl FnMut(u32, u32, Vec) -> Result<(), Error>, +) -> Result<(), Error> { + let header = read_header(reader, budget)?; + let texels = u64::from(expected.width) * u64::from(expected.height); + if texels == 0 || texels > max_texels { + return Err(Error::Limit("tile image exceeds its texel limit".into())); + } + if header.layout != expected { + return Err(Error::Invalid("tile layout differs from the project".into())); + } + let (tiles_x, tiles_y, bytes_per_tile) = tile_dimensions(expected)?; + if u64::from(header.count) > u64::from(tiles_x) * u64::from(tiles_y) { + return Err(Error::Invalid("more tiles than the image holds".into())); + } + let mut bytes = Vec::new(); + let mut seen = HashSet::new(); + for _ in 0..header.count { + let payload = u64::try_from(bytes_per_tile).map_err(|_| Error::Limit("tile is too large".into()))?.saturating_add(8); + charge(budget, payload)?; + if bytes.is_empty() { + bytes.try_reserve_exact(bytes_per_tile).map_err(|_| Error::Limit("tile allocation failed".into()))?; + bytes.resize(bytes_per_tile, 0); + } + let mut pos = [0u8; 8]; + reader.read_exact(&mut pos)?; + let x = u32::from_le_bytes([pos[0], pos[1], pos[2], pos[3]]); + let y = u32::from_le_bytes([pos[4], pos[5], pos[6], pos[7]]); + if x >= tiles_x || y >= tiles_y || seen.contains(&(x, y)) { + return Err(Error::Invalid(format!("bad or repeated tile ({x}, {y})"))); + } + seen.try_reserve(1).map_err(|_| Error::Limit("tile index allocation failed".into()))?; + seen.insert((x, y)); + reader.read_exact(&mut bytes)?; + let mut values = Vec::new(); + values.try_reserve_exact(bytes_per_tile / 2).map_err(|_| Error::Limit("tile allocation failed".into()))?; + values.extend(bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b))); + tile(x, y, values)?; + } + expect_end(reader) +} + +/// Write tiles in caller order, without buffering the image. A failure may leave a partial +/// entry; callers writing a project should discard the incomplete output. +pub fn write_tiles<'a>( + writer: &mut (impl Write + ?Sized), + layout: Layout, + count: u32, + tiles: impl IntoIterator, +) -> Result<(), Error> { + let (tiles_x, tiles_y, bytes_per_tile) = tile_dimensions(layout)?; + if u64::from(count) > u64::from(tiles_x) * u64::from(tiles_y) { + return Err(Error::Invalid("more tiles than the image holds".into())); + } + write_header(writer, layout, count)?; + let mut seen = HashSet::new(); + let mut bytes = Vec::new(); + let mut written = 0u32; + for (x, y, values) in tiles { + if written >= count || x >= tiles_x || y >= tiles_y || seen.contains(&(x, y)) || values.len() != bytes_per_tile / 2 { + return Err(Error::Invalid("bad, repeated or incorrectly sized tile".into())); + } + seen.try_reserve(1).map_err(|_| Error::Limit("tile index allocation failed".into()))?; + seen.insert((x, y)); + if bytes.is_empty() { + bytes.try_reserve_exact(bytes_per_tile).map_err(|_| Error::Limit("tile allocation failed".into()))?; + } + bytes.clear(); + bytes.extend(values.iter().flat_map(|v| v.to_le_bytes())); + writer.write_all(&x.to_le_bytes())?; + writer.write_all(&y.to_le_bytes())?; + writer.write_all(&bytes)?; + written += 1; + } + if written != count { + return Err(Error::Invalid("tile count differs from its data".into())); + } + Ok(()) +} + +/// Read a dense f32 map, validating declared size and charging its shared budget first. +pub fn read_baked( + reader: &mut (impl Read + ?Sized), + declared_bytes: u64, + components: usize, + max_texels: u64, + budget: &mut Budget, +) -> Result<(Layout, Vec), Error> { + let header = read_header(reader, budget)?; + let layout = header.layout; + let texels = u64::from(layout.width) * u64::from(layout.height); + if texels == 0 || texels > max_texels || layout.components != components || components == 0 { + return Err(Error::Invalid("bad baked-map dimensions or components".into())); + } + let count = texels.checked_mul(components as u64).ok_or_else(|| Error::Limit("too many map values".into()))?; + let payload = count.checked_mul(4).ok_or_else(|| Error::Limit("map is too large".into()))?; + if declared_bytes != HEADER_BYTES.checked_add(payload).ok_or_else(|| Error::Limit("map is too large".into()))? { + return Err(Error::Invalid(format!("{declared_bytes} bytes for a {}×{}×{} map", layout.width, layout.height, layout.components))); + } + charge(budget, payload)?; + let count = usize::try_from(count).map_err(|_| Error::Limit("too many map values".into()))?; + let mut values = Vec::new(); + let chunk_bytes = CHUNK.min(count) * 4; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(chunk_bytes).map_err(|_| Error::Limit("map chunk allocation failed".into()))?; + bytes.resize(chunk_bytes, 0); + while values.len() < count { + let n = CHUNK.min(count - values.len()); + let chunk = bytes.get_mut(..n * 4).ok_or_else(|| Error::Invalid("bad map chunk".into()))?; + reader.read_exact(chunk)?; + values.try_reserve(n).map_err(|_| Error::Limit("map allocation failed".into()))?; + values.extend(chunk.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b))); + } + expect_end(reader)?; + Ok((layout, values)) +} + +/// Write a dense f32 map in bounded chunks without constructing a second copy of its payload. +pub fn write_baked(writer: &mut (impl Write + ?Sized), layout: Layout, values: &[f32]) -> Result<(), Error> { + let count = u64::from(layout.width).checked_mul(u64::from(layout.height)).and_then(|n| n.checked_mul(layout.components as u64)); + if layout.width == 0 || layout.height == 0 || layout.components == 0 || count != Some(values.len() as u64) { + return Err(Error::Invalid("map dimensions differ from its data".into())); + } + write_header(writer, layout, 0)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(CHUNK * 4).map_err(|_| Error::Limit("map chunk allocation failed".into()))?; + for chunk in values.chunks(CHUNK) { + bytes.clear(); + bytes.extend(chunk.iter().flat_map(|v| v.to_le_bytes())); + writer.write_all(&bytes)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + fn header(layout: Layout, count: u32) -> Vec { + let mut bytes = Vec::new(); + write_header(&mut bytes, layout, count).unwrap(); + bytes + } + + #[test] + fn project_schema_keeps_nested_and_future_fields() { + let json = serde_json::json!({ + "format_version": 2, "name": "Stone", "mesh": "mesh.obj", "normal_format": "openGl", + "texture_sets": [{"name": "main", "futureSet": {"keep": true}}], + "layers": {"1": {"kind": "paint", "futureLayer": [1, 2]}}, "next_id": 2, + "display": {"futureDisplay": 4}, "mesh_file": "source.obj", "futureProject": [3] + }); + let bytes = serde_json::to_vec(&json).unwrap(); + assert_eq!(project_version(&bytes).unwrap(), 2); + let document: ProjectDocument = serde_json::from_slice(&bytes).unwrap(); + let mut expected = json; + expected["cameras"] = serde_json::json!([]); + assert_eq!(serde_json::to_value(&document).unwrap(), expected); + let mut duplicate = document; + duplicate.extra.insert("mesh".into(), serde_json::json!("other.obj")); + assert!(serde_json::to_vec(&duplicate).is_err()); + assert!(project_version(br#"{"format_version":1,"format_version":2}"#).is_err()); + assert!(project_version(br#"{"format_version":-1}"#).is_err()); + } + + #[test] + fn baked_map_matches_the_native_little_endian_wire_layout() { + let layout = Layout { width: 2, height: 1, components: 1 }; + let mut expected = b"TCTX".to_vec(); + for value in [1u32, 2, 1, 1, 0] { + expected.extend_from_slice(&value.to_le_bytes()); + } + expected.extend_from_slice(&1.0f32.to_le_bytes()); + expected.extend_from_slice(&(-0.5f32).to_le_bytes()); + let mut actual = Vec::new(); + write_baked(&mut actual, layout, &[1.0, -0.5]).unwrap(); + assert_eq!(actual, expected); + let (decoded, values) = read_baked(&mut Cursor::new(&expected), expected.len() as u64, 1, 2, &mut Budget::new("project", 32)).unwrap(); + assert_eq!(decoded, layout); + assert_eq!(values, [1.0, -0.5]); + expected[4..8].copy_from_slice(&2u32.to_le_bytes()); + assert!(matches!(read_baked(&mut Cursor::new(&expected), 32, 1, 2, &mut Budget::new("project", 32)), Err(Error::NewerVersion(2)))); + } + + #[test] + fn dense_maps_round_trip_bit_exactly_in_bounded_chunks() { + let layout = Layout { width: 300, height: 300, components: 1 }; + let mut values = vec![0.25; 90_000]; + values[123] = f32::from_bits(0x7fc0_1234); + let mut bytes = Vec::new(); + write_baked(&mut bytes, layout, &values).unwrap(); + let mut budget = Budget::new("project", bytes.len() as u64); + let (decoded_layout, decoded) = read_baked(&mut Cursor::new(&bytes), bytes.len() as u64, 1, 100_000, &mut budget).unwrap(); + assert_eq!(decoded_layout, layout); + assert!(decoded.iter().zip(values.iter()).all(|(a, b)| a.to_bits() == b.to_bits())); + assert_eq!(budget.remaining(), 0); + } + + #[test] + fn dense_maps_refuse_false_lengths_limits_and_trailing_data() { + let layout = Layout { width: 2, height: 2, components: 1 }; + let mut bytes = Vec::new(); + write_baked(&mut bytes, layout, &[1.0; 4]).unwrap(); + let mut budget = Budget::new("project", 100); + assert!(read_baked(&mut Cursor::new(&bytes), 999, 1, 4, &mut budget).is_err()); + let mut budget = Budget::new("project", 39); + assert!(matches!(read_baked(&mut Cursor::new(&bytes), 40, 1, 4, &mut budget), Err(Error::Budget(_)))); + let mut extra = bytes.clone(); + extra.push(0); + let mut budget = Budget::new("project", 100); + assert!(read_baked(&mut Cursor::new(extra), 40, 1, 4, &mut budget).is_err()); + } + + #[test] + fn hostile_headers_and_tiles_are_rejected_without_trusting_counts() { + let layout = Layout { width: 64, height: 64, components: 1 }; + assert!(matches!( + read_tiles(&mut Cursor::new(header(layout, 0)), layout, 4095, &mut Budget::new("project", 100), |_, _, _| Ok(())), + Err(Error::Limit(_)) + )); + let mut bad_magic = header(layout, 0); + bad_magic[0] = b'X'; + assert!(read_tiles(&mut Cursor::new(bad_magic), layout, u64::MAX, &mut Budget::new("project", 100), |_, _, _| Ok(())).is_err()); + assert!(read_tiles(&mut Cursor::new(header(layout, 2)), layout, u64::MAX, &mut Budget::new("project", 100), |_, _, _| Ok(())).is_err()); + let other = Layout { width: 65, ..layout }; + assert!(read_tiles(&mut Cursor::new(header(layout, 0)), other, u64::MAX, &mut Budget::new("project", 100), |_, _, _| Ok(())).is_err()); + let mut outside = header(layout, 1); + outside.extend_from_slice(&1u32.to_le_bytes()); + outside.extend_from_slice(&0u32.to_le_bytes()); + assert!(read_tiles(&mut Cursor::new(outside), layout, u64::MAX, &mut Budget::new("project", 10_000), |_, _, _| Ok(())).is_err()); + let mut truncated = header(layout, 1); + truncated.extend_from_slice(&[0; 8]); + assert!(read_tiles(&mut Cursor::new(truncated), layout, u64::MAX, &mut Budget::new("project", 10_000), |_, _, _| Ok(())).is_err()); + let mut extra = header(layout, 0); + extra.push(1); + assert!(read_tiles(&mut Cursor::new(extra), layout, u64::MAX, &mut Budget::new("project", 100), |_, _, _| Ok(())).is_err()); + } + + #[test] + fn sparse_tiles_stream_and_reject_duplicates_and_short_budget() { + let layout = Layout { width: 128, height: 64, components: 1 }; + let mut bytes = header(layout, 2); + for x in [0u32, 1] { + bytes.extend_from_slice(&x.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + for _ in 0..TILE_AREA { + bytes.extend_from_slice(&(x as u16 + 1).to_le_bytes()); + } + } + let first = vec![1u16; TILE_AREA]; + let second = vec![2u16; TILE_AREA]; + let mut written = Vec::new(); + write_tiles(&mut written, layout, 2, [(0, 0, first.as_slice()), (1, 0, second.as_slice())]).unwrap(); + assert_eq!(written, bytes, "the streamed writer keeps the native wire layout"); + assert!(write_tiles(&mut Vec::new(), layout, 2, [(0, 0, first.as_slice())]).is_err()); + let mut seen = Vec::new(); + let mut budget = Budget::new("project", bytes.len() as u64); + read_tiles(&mut Cursor::new(&bytes), layout, u64::MAX, &mut budget, |x, y, tile| { + seen.push((x, y, tile.first().copied())); + Ok(()) + }) + .unwrap(); + assert_eq!(seen, [(0, 0, Some(1)), (1, 0, Some(2))]); + let mut duplicate = bytes.clone(); + let second = HEADER_BYTES as usize + 8 + TILE_AREA * 2; + duplicate[second..second + 4].copy_from_slice(&0u32.to_le_bytes()); + assert!(read_tiles(&mut Cursor::new(duplicate), layout, u64::MAX, &mut Budget::new("project", u64::MAX), |_, _, _| Ok(())).is_err()); + assert!(matches!( + read_tiles(&mut Cursor::new(bytes), layout, u64::MAX, &mut Budget::new("project", HEADER_BYTES), |_, _, _| Ok(())), + Err(Error::Budget(_)) + )); + } +} diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index ae32a1157c..a37a4c114f 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -11,6 +11,7 @@ description = "Text processing below the Craft composer: hyphenation with a bund workspace = true [dependencies] +kurbo = { workspace = true, optional = true } hypher = { version = "0.1.8", default-features = false, features = ["alloc"], optional = true } miniz_oxide = { version = "0.8", optional = true } unicode-general-category = { version = "1.1", optional = true } @@ -28,6 +29,7 @@ name = "hyphgen" required-features = ["generator"] [features] +positioned = ["dep:kurbo"] default = ["hyphen", "bidi", "segment", "linebreak"] # Hyphenation points; English (bundled dictionary and patterns) needs no further feature. hyphen = ["dep:hypher", "dep:miniz_oxide", "dep:unicode-general-category"] diff --git a/crates/text/src/composer.rs b/crates/text/src/composer.rs new file mode 100644 index 0000000000..fc2067f3fb --- /dev/null +++ b/crates/text/src/composer.rs @@ -0,0 +1,529 @@ +//! Every-line composer: a Knuth–Plass style total-fit line breaker. +//! +//! Boxes are the paragraph's glyphs, glue is its spaces, and penalties are break opportunities +//! after hyphens/dashes/CJK and at hyphenation points. The breaks minimise the sum of squared +//! (badness + penalty) demerits over the whole paragraph, plus a demerit when neighbouring lines +//! fall in fitness classes more than one apart (a tight line next to a loose one). +//! +//! - **Justified** lines: word spacing, letter spacing and glyph scaling may stretch and shrink +//! within the paragraph's Justification options (each glyph's [`Flexibility`]); the badness comes from +//! the stretch/shrink ratio, so loose lines are traded for evenly spaced ones. +//! - **Ragged** lines (left/centre/right aligned): spaces keep their width, so a line never +//! shrinks (it must fit). The badness comes from the line's leftover space measured against a +//! rag zone of a sixth of the line width, so the rag is even rather than full lines followed by +//! a short one, and hyphenating costs less. The last line costs nothing unless it is shorter +//! than a third of the width (a word or two left dangling). + +/// Glyph measurements needed by the paragraph composer. +pub trait Glyph { + fn advance(&self) -> f64; + fn is_space(&self) -> bool; + fn is_soft_hyphen(&self) -> bool; +} + +/// Stretch and shrink available for a glyph. +pub trait Flexibility { + fn stretch(&self) -> f64; + fn shrink(&self) -> f64; +} + +const HYPHEN_PENALTY: f64 = 50.0; +const DOUBLE_HYPHEN_DEMERITS: f64 = 3000.0; +const LINE_PENALTY: f64 = 10.0; +/// Demerits for adjacent lines whose fitness classes differ by more than one. +const ADJ_DEMERITS_JUSTIFIED: f64 = 10_000.0; +const ADJ_DEMERITS_RAGGED: f64 = 1_000.0; +/// Ragged lines only gain from hyphenation by filling the rag, so it costs less than in +/// justified text (where it also evens the word spacing). +const HYPHEN_PENALTY_RAGGED: f64 = 25.0; +/// Ragged text: leftover space is measured in units of this fraction of the line width. +const RAG_ZONE: f64 = 1.0 / 6.0; +/// Ragged text: a last line shorter than this fraction of the width is penalised, by how much +/// shorter it is in units of `SHORT_LAST_ZONE` of the width. +const SHORT_LAST: f64 = 1.0 / 3.0; +const SHORT_LAST_ZONE: f64 = 1.0 / 3.0; +/// Give up (fall back to the single-line composer) beyond this many active breakpoints. +const MAX_ACTIVE: usize = 4096; +const EPS: f64 = 1e-6; + +/// A place a line may end: glyph index `end` (exclusive), plus the width of the hyphen that is +/// added when breaking there (0 = no hyphen). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Breakpoint { + pub end: usize, + pub hyphen: f64, +} + +/// How a paragraph is composed. +#[derive(Clone, Copy, Debug)] +pub struct Params { + /// The last line is justified too (Justify All). + pub justify_last: bool, + /// Left/centre/right aligned text: spaces keep their width and lines are scored by their rag. + pub ragged: bool, + /// Maximum stretch ratio (justified) or leftover space in rag zones (ragged) of a line. + pub tolerance: f64, + /// Lines from this index on all have the same width, so their line numbers are interchangeable + /// (keeps the number of active breakpoints small). + pub uniform_from: usize, + /// Hyphen Limit: the most consecutive lines that may end with a hyphen before a hyphenation + /// point is no longer a break; 0 sets no limit. A soft hyphen stays a break and counts. + pub hyphen_limit: usize, +} + +/// The search gave up: it ran past its budget ([`Measure::line`]). +#[derive(Debug)] +pub struct Exhausted; + +/// Where each line of a paragraph goes and how wide it is: the measure a line gets may depend on +/// the lines set above it (their heights move it down a shaped frame, or past a wrap object). +pub trait Measure { + /// What the measure of the next line depends on; breaks reached with equal states are + /// interchangeable from there on. + type State: Clone + PartialEq; + /// The state of the paragraph's first line. + fn first(&mut self) -> Self::State; + /// The width of the line of glyphs `pos..end` set from `state`, and the state of the line + /// after it; `Ok(None)` when the line can't be set (the frame is full), and [`Exhausted`] when + /// the search is to stop. + fn line(&mut self, state: &Self::State, pos: usize, end: usize) -> Result, Exhausted>; + /// Whether a line from `state` longer than `pos..end`, which [`Measure::line`] just measured, + /// may get more room than it. While it may, a line from `state` that is too long, or that + /// can't be set, does not end the reach of `state`. Lines from a state are all as wide by + /// default. + fn may_widen(&mut self, _state: &Self::State, _pos: usize, _end: usize) -> bool { + false + } +} + +/// Line widths by line number: `width(k)` for line `k`, lines from `uniform_from` on all as wide. +struct ByLine<'a> { + width: &'a dyn Fn(usize) -> f64, + uniform_from: usize, +} + +impl Measure for ByLine<'_> { + type State = usize; + fn first(&mut self) -> usize { + 0 + } + fn line(&mut self, &line: &usize, _: usize, _: usize) -> Result, Exhausted> { + Ok(Some(((self.width)(line), (line + 1).min(self.uniform_from)))) + } +} + +struct Node { + pos: usize, + /// The measure of the next line (its line number, clamped to `uniform_from`, for [`compose`]). + state: S, + fitness: u8, + demerits: f64, + /// Lines in a row ending with a hyphen up to this break (at most `hyphen_limit`, or 1 with no + /// limit); 0 when this break has no hyphen. + hyphens: usize, + prev: Option, +} + +/// Fitness class 0 (tight) … 3 (very loose) of a line with adjustment ratio `r`. +fn fitness(r: f64, ragged: bool) -> u8 { + let bounds = if ragged { [0.15, 0.4, 0.75] } else { [-0.5, 0.5, 1.0] }; + if r < bounds[0] { + 0 + } else if r <= bounds[1] { + 1 + } else if r <= bounds[2] { + 2 + } else { + 3 + } +} + +/// Adjustment ratio for a candidate line; `None` means a ragged line is already too long. +fn adjustment_ratio(natural: f64, width: f64, stretch: f64, shrink: f64, last: bool, p: &Params) -> Option { + if p.ragged { + if natural > width + EPS { + return None; + } + return Some(if last && !p.justify_last { + ((width * SHORT_LAST - natural) / (width * SHORT_LAST_ZONE).max(1.0)).max(0.0) + } else { + (width - natural).max(0.0) / (width * RAG_ZONE).max(1.0) + }); + } + Some(if natural < width { + if last && !p.justify_last { + 0.0 + } else if stretch > EPS { + (width - natural) / stretch + } else { + f64::INFINITY + } + } else if natural > width { + if shrink > EPS { (width - natural) / shrink } else { f64::NEG_INFINITY } + } else { + 0.0 + }) +} + +/// Compose the paragraph `g` into lines. `width(k)` is the available width of line `k`; +/// `start_credit(i)` is the width a wrapped line starting at glyph `i` gives back (Mojikumi sets +/// an opening bracket there flush with the line's start); `end_credit(t)` is the width a line whose +/// last character is glyph `t - 1` gives back (Mojikumi sets a closing mark there half width), at +/// most that glyph's advance, and nothing at a hyphenation point; `cands` are the break opportunities +/// in increasing order (the paragraph end is added); `flex` holds how far each glyph may stretch +/// and shrink in a justified line. +/// Returns `(end, hyphen)` per line, or `None` if no set of breaks fits within the tolerance +/// (the caller then falls back to single-line breaking). +pub fn compose( + g: &[G], + width: &dyn Fn(usize) -> f64, + start_credit: &dyn Fn(usize) -> f64, + end_credit: &dyn Fn(usize) -> f64, + cands: &[Breakpoint], + flex: &[F], + p: &Params, +) -> Option> { + compose_with(g, &mut ByLine { width, uniform_from: p.uniform_from }, start_credit, end_credit, cands, flex, p) +} + +/// [`compose`] with each line's width from `measure`, which follows where the lines above it went. +pub fn compose_with( + g: &[G], + measure: &mut M, + start_credit: &dyn Fn(usize) -> f64, + end_credit: &dyn Fn(usize) -> f64, + cands: &[Breakpoint], + flex: &[F], + p: &Params, +) -> Option> { + let n = g.len(); + // The search assumes increasing break positions when indexing its prefix sums. + // Reject malformed candidates before they can make a later line run backwards. + if cands.windows(2).any(|pair| pair[0].end > pair[1].end) { + return None; + } + if n == 0 { + return Some(vec![]); + } + // Prefix sums of advances and of how far the glyphs may stretch and shrink. + let mut w = vec![0.0; n + 1]; + let mut st = vec![0.0; n + 1]; + let mut sh = vec![0.0; n + 1]; + for (i, gl) in g.iter().enumerate() { + let f = flex.get(i); + w[i + 1] = w[i] + gl.advance(); + st[i + 1] = st[i] + f.map_or(0.0, Flexibility::stretch); + sh[i + 1] = sh[i] + f.map_or(0.0, Flexibility::shrink); + } + if !w[n].is_finite() { + return None; + } + // Trailing spaces are dropped at a break. + let trim = |mut b: usize, a: usize| { + while b > a && g.get(b - 1).is_some_and(Glyph::is_space) { + b -= 1; + } + b + }; + let line_end_credit = |t: usize| { + let credit = end_credit(t); + let most = t.checked_sub(1).and_then(|k| g.get(k)).map_or(0.0, |gl| gl.advance().max(0.0)); + if credit.is_finite() { credit.clamp(0.0, most) } else { 0.0 } + }; + let mut all: Vec = cands.iter().copied().filter(|c| c.end > 0 && c.end < n).collect(); + all.push(Breakpoint { end: n, hyphen: 0.0 }); + let (adj_demerits, hyphen_penalty) = + if p.ragged { (ADJ_DEMERITS_RAGGED, HYPHEN_PENALTY_RAGGED) } else { (ADJ_DEMERITS_JUSTIFIED, HYPHEN_PENALTY) }; + let mut nodes = vec![Node { pos: 0, state: measure.first(), fitness: 1, demerits: 0.0, hyphens: 0, prev: None }]; + let mut active: Vec = vec![0]; + for bp in &all { + let last = bp.end == n; + let hyphen = bp.hyphen > 0.0; + // `automatic` is true for a hyphenation point and false for a soft hyphen typed in the text. + let automatic = hyphen && !bp.end.checked_sub(1).and_then(|k| g.get(k)).is_some_and(Glyph::is_soft_hyphen); + let mut best: Vec<(M::State, u8, usize, f64, usize)> = vec![]; // (state, fitness, hyphens, demerits, from) + let mut keep = Vec::with_capacity(active.len()); + for &ai in &active { + let Some(a) = nodes.get(ai) else { continue }; + let t = trim(bp.end, a.pos); + let credit = if a.pos > 0 { start_credit(a.pos) } else { 0.0 }; + // A line that ends with a hyphen ends with it, not with its last character. At most the + // last glyph's advance, so a longer line from the same node is never narrower. + let end = if hyphen || t <= a.pos { 0.0 } else { line_end_credit(t) }; + let natural = w[t] - w[a.pos] - credit - end + bp.hyphen; + // A line that can't be set (no room left in the frame) ends this node's reach, unless a + // longer line may be placed elsewhere (a taller line steps down the frame by its own + // leading). + let Some((lw, next)) = measure.line(&a.state, a.pos, bp.end).ok()? else { + if measure.may_widen(&a.state, a.pos, bp.end) { + keep.push(ai); + } + continue; + }; + // Adjustment ratio, badness and whether the line ends the active node's reach. + let ratio = adjustment_ratio(natural, lw, st[t] - st[a.pos], sh[t] - sh[a.pos], last, p); + let Some(ratio) = ratio.filter(|&r| r >= -1.0 || r.is_nan()) else { + // Too long already; longer lines from this node only get worse, unless they may + // get more room (a taller line set lower down a shaped frame). + if measure.may_widen(&a.state, a.pos, bp.end) { + keep.push(ai); + } + continue; + }; + keep.push(ai); + if automatic && p.hyphen_limit > 0 && a.hyphens >= p.hyphen_limit { + continue; + } + let free_last = last && (p.ragged || !p.justify_last); + // A line that can't stretch at all (no word spaces, nor letter spacing or glyph scaling + // to vary) never fills its measure, however loose the tolerance. + if (ratio > p.tolerance || ratio == f64::INFINITY) && !(last && (p.ragged || (ratio.is_infinite() && p.justify_last))) { + continue; + } + // Justified lines aren't capped: past a ratio of 4.6 (only reached in the unbounded pass) + // a looser line must still score worse than a less loose one. + let cap = if p.ragged { 10_000.0 } else { f64::INFINITY }; + let badness = if ratio.is_finite() { (100.0 * ratio.abs().powi(3)).min(cap) } else { 10_000.0 }; + let penalty = if hyphen { hyphen_penalty } else { 0.0 }; + let mut d = (LINE_PENALTY + badness).powi(2) + penalty * penalty; + if hyphen && a.hyphens > 0 { + d += DOUBLE_HYPHEN_DEMERITS; + } + // A ragged last line's length says nothing about the rag: it keeps its neighbour's class. + let fit = if p.ragged && free_last { a.fitness } else { fitness(ratio, p.ragged) }; + if a.prev.is_some() && fit.abs_diff(a.fitness) > 1 { + d += adj_demerits; + } + let total = a.demerits + d; + // With a limit, breaks reached with different runs of hyphenated lines stay apart. + let hyphens = match (hyphen, p.hyphen_limit) { + (false, _) => 0, + (true, 0) => 1, + (true, limit) => (a.hyphens + 1).min(limit), + }; + match best.iter_mut().find(|b| b.0 == next && b.1 == fit && b.2 == hyphens) { + Some(b) if b.3 <= total => {} + Some(b) => *b = (next, fit, hyphens, total, ai), + None => best.push((next, fit, hyphens, total, ai)), + } + } + active = keep; + for (state, fitness, hyphens, demerits, from) in best { + nodes.push(Node { pos: bp.end, state, fitness, demerits, hyphens, prev: Some(from) }); + active.push(nodes.len() - 1); + } + if active.is_empty() || active.len() > MAX_ACTIVE { + return None; + } + } + let end = nodes.iter().enumerate().filter(|(_, nd)| nd.pos == n && nd.prev.is_some()).min_by(|a, b| a.1.demerits.total_cmp(&b.1.demerits))?.0; + let mut out = vec![]; + let mut cur = Some(end); + while let Some(i) = cur { + let nd = nodes.get(i)?; + if nd.prev.is_some() { + out.push((nd.pos, nd.hyphens > 0)); + } + cur = nd.prev; + if out.len() > n { + return None; + } + } + out.reverse(); + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Unit(char); + impl Glyph for Unit { + fn advance(&self) -> f64 { + 1.0 + } + fn is_space(&self) -> bool { + self.0 == ' ' + } + fn is_soft_hyphen(&self) -> bool { + self.0 == '\u{ad}' + } + } + struct Rigid; + impl Flexibility for Rigid { + fn stretch(&self) -> f64 { + 0.0 + } + fn shrink(&self) -> f64 { + 0.0 + } + } + #[test] + fn rejects_breaks_that_move_backwards() { + let glyphs: Vec<_> = "abcd".chars().map(Unit).collect(); + let candidates = [Breakpoint { end: 3, hyphen: 0.0 }, Breakpoint { end: 1, hyphen: 0.0 }]; + let params = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + assert_eq!(compose(&glyphs, &|_| 3.0, &|_| 0.0, &|_| 0.0, &candidates, &[] as &[Rigid], ¶ms), None); + } + + #[test] + fn composes_ragged_paragraph_and_trims_spaces() { + let glyphs: Vec<_> = "aa bb cc".chars().map(Unit).collect(); + let candidates = [Breakpoint { end: 3, hyphen: 0.0 }, Breakpoint { end: 6, hyphen: 0.0 }]; + let params = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + let result = compose(&glyphs, &|_| 3.0, &|_| 0.0, &|_| 0.0, &candidates, &[] as &[Rigid], ¶ms); + assert_eq!(result, Some(vec![(3, false), (6, false), (8, false)])); + } + struct Flex(f64, f64); + impl Flexibility for Flex { + fn stretch(&self) -> f64 { + self.0 + } + fn shrink(&self) -> f64 { + self.1 + } + } + struct Wide(f64); + impl Glyph for Wide { + fn advance(&self) -> f64 { + self.0 + } + fn is_space(&self) -> bool { + false + } + fn is_soft_hyphen(&self) -> bool { + false + } + } + fn justified() -> Params { + Params { justify_last: false, ragged: false, tolerance: 10.0, uniform_from: 0, hyphen_limit: 0 } + } + fn units(text: &str) -> Vec { + text.chars().map(Unit).collect() + } + fn brk(end: usize, hyphen: f64) -> Breakpoint { + Breakpoint { end, hyphen } + } + + #[test] + fn fitness_classes_and_adjustment_ratios() { + assert_eq!([-0.6, 0.0, 0.7, 2.0].map(|r| fitness(r, false)), [0, 1, 2, 3]); + assert_eq!([0.1, 0.3, 0.5, 0.9].map(|r| fitness(r, true)), [0, 1, 2, 3]); + let j = justified(); + assert_eq!(adjustment_ratio(8.0, 10.0, 4.0, 0.0, false, &j), Some(0.5)); + assert_eq!(adjustment_ratio(8.0, 10.0, 0.0, 0.0, false, &j), Some(f64::INFINITY)); + assert_eq!(adjustment_ratio(8.0, 10.0, 4.0, 0.0, true, &j), Some(0.0)); + assert_eq!(adjustment_ratio(12.0, 10.0, 0.0, 4.0, false, &j), Some(-0.5)); + assert_eq!(adjustment_ratio(12.0, 10.0, 0.0, 0.0, false, &j), Some(f64::NEG_INFINITY)); + assert_eq!(adjustment_ratio(10.0, 10.0, 0.0, 0.0, false, &j), Some(0.0)); + let all = Params { justify_last: true, ..j }; + assert_eq!(adjustment_ratio(8.0, 10.0, 4.0, 0.0, true, &all), Some(0.5)); + let ragged = Params { ragged: true, ..j }; + assert_eq!(adjustment_ratio(11.0, 10.0, 0.0, 0.0, false, &ragged), None); + } + + #[test] + fn empty_and_unmeasurable_paragraphs() { + let none: [Unit; 0] = []; + assert_eq!(compose(&none, &|_| 3.0, &|_| 0.0, &|_| 0.0, &[], &[] as &[Rigid], &justified()), Some(vec![])); + let huge = [Wide(f64::INFINITY)]; + assert_eq!(compose(&huge, &|_| 3.0, &|_| 0.0, &|_| 0.0, &[], &[] as &[Rigid], &justified()), None); + } + + #[test] + fn justified_lines_stretch_and_shrink_within_tolerance() { + let glyphs = units("a a b b"); + let flex: Vec<_> = glyphs.iter().map(|g| if g.0 == ' ' { Flex(1.0, 0.5) } else { Flex(0.0, 0.0) }).collect(); + let cands = [brk(4, 0.0)]; + // "a a" (the trailing space is dropped) stretches its inner space to fill 4 units... + let lines = compose(&glyphs, &|_| 4.0, &|_| 0.0, &|_| 0.0, &cands, &flex, &justified()); + assert_eq!(lines, Some(vec![(4, false), (7, false)])); + // ...or shrinks it into 2.75. + let lines = compose(&glyphs, &|_| 2.75, &|_| 0.0, &|_| 0.0, &cands, &flex, &justified()); + assert_eq!(lines, Some(vec![(4, false), (7, false)])); + // Rigid glyphs can't fill a wider line except the last, so there is no fit. + let rigid: Vec<_> = glyphs.iter().map(|_| Rigid).collect(); + assert_eq!(compose(&glyphs, &|_| 4.0, &|_| 0.0, &|_| 0.0, &cands, &rigid, &justified()), None); + // Justify All lets an unstretchable last line through. + let all = Params { justify_last: true, ..justified() }; + let word = units("ab"); + assert_eq!(compose(&word, &|_| 4.0, &|_| 0.0, &|_| 0.0, &[], &[Rigid, Rigid], &all), Some(vec![(2, false)])); + } + + #[test] + fn hyphen_limit_and_soft_hyphens() { + // "ab-cd-ef" with hyphenation points after each pair: every line wants a hyphen. + let glyphs = units("abcdef"); + let cands = [brk(2, 1.0), brk(4, 1.0)]; + let ragged = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + let free = compose(&glyphs, &|_| 3.0, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &ragged).unwrap(); + assert_eq!(free, vec![(2, true), (4, true), (6, false)]); + // A limit of one hyphenated line in a row forbids the second automatic hyphen. + let limited = Params { hyphen_limit: 1, ..ragged }; + assert_eq!(compose(&glyphs, &|_| 3.0, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &limited), None); + // A typed soft hyphen stays a break regardless of the limit. + let soft = units("ab\u{ad}cd\u{ad}ef"); + let cands = [brk(3, 1.0), brk(6, 1.0)]; + let out = compose(&soft, &|_| 4.0, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &limited).unwrap(); + assert_eq!(out, vec![(3, true), (6, true), (8, false)]); + } + + #[test] + fn credits_are_clamped_to_the_glyph_and_ignored_when_not_finite() { + let glyphs = units("aa bb"); + let cands = [brk(3, 0.0)]; + let ragged = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + for credit in [f64::NAN, 5.0, -1.0] { + let out = compose(&glyphs, &|_| 2.0, &|_| 0.0, &|_| credit, &cands, &[] as &[Rigid], &ragged); + assert_eq!(out, Some(vec![(3, false), (5, false)]), "{credit}"); + } + // A start credit gives a wrapped line room back. + let out = compose(&units("aa bbb"), &|_| 2.0, &|_| 1.0, &|_| 0.0, &cands, &[] as &[Rigid], &ragged); + assert_eq!(out, Some(vec![(3, false), (6, false)])); + } + + /// Two lines of width 2, then the frame is full; a line may widen when the frame says so. + struct Frame { + widen: bool, + calls: usize, + } + impl Measure for Frame { + type State = usize; + fn first(&mut self) -> usize { + 0 + } + fn line(&mut self, &k: &usize, _: usize, _: usize) -> Result, Exhausted> { + self.calls += 1; + if self.calls > 1_000 { + return Err(Exhausted); + } + Ok((k < 2).then_some((2.0, k + 1))) + } + fn may_widen(&mut self, _: &usize, _: usize, _: usize) -> bool { + self.widen + } + } + + #[test] + fn measure_can_end_reach_widen_or_exhaust() { + let ragged = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + let two = units("aa bb"); + let cands = [brk(3, 0.0)]; + let mut frame = Frame { widen: false, calls: 0 }; + assert_eq!(compose_with(&two, &mut frame, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &ragged), Some(vec![(3, false), (5, false)])); + // A third line can't be set: no fit, whether or not the frame may widen. + let three = units("aa bb cc"); + let cands = [brk(3, 0.0), brk(6, 0.0)]; + for widen in [false, true] { + let mut frame = Frame { widen, calls: 0 }; + assert_eq!(compose_with(&three, &mut frame, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &ragged), None); + } + // Too long for the line, but the frame may widen: the node stays active. + let long = units("aaa b"); + let mut frame = Frame { widen: true, calls: 0 }; + assert_eq!(compose_with(&long, &mut frame, &|_| 0.0, &|_| 0.0, &[brk(4, 0.0)], &[] as &[Rigid], &ragged), None); + // The measure may stop the search. + let mut frame = Frame { widen: false, calls: 1_000 }; + assert_eq!(compose_with(&two, &mut frame, &|_| 0.0, &|_| 0.0, &[brk(3, 0.0)], &[] as &[Rigid], &ragged), None); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07795c3135..62e8d0eb7b 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -15,6 +15,9 @@ //! Language features (`spanish`, `german`, …, `all-languages`) add data for that language and //! turn on the modules that use it. +#[cfg(feature = "positioned")] +pub mod positioned; + #[cfg(feature = "bidi")] pub mod bidi; #[cfg(feature = "hyphen")] @@ -23,3 +26,6 @@ pub mod hyphen; pub mod linebreak; #[cfg(feature = "segment")] pub mod segment; + +/// Paragraph-wide line composition with stateful line measurement. +pub mod composer; diff --git a/crates/text/src/positioned.rs b/crates/text/src/positioned.rs new file mode 100644 index 0000000000..cb749cac58 --- /dev/null +++ b/crates/text/src/positioned.rs @@ -0,0 +1,212 @@ +//! A placed glyph with source mapping, geometry and optional application-owned artwork. + +use kurbo::{Affine, BezPath, Point}; + +/// Application-owned payloads and conversion to document artwork. +pub trait Artwork { + /// Bitmap glyph data. + type Image: Clone + std::fmt::Debug; + /// Colour glyph data. + type Colour: Clone + std::fmt::Debug; + /// Curved-baseline metadata. + type Bend: Clone + std::fmt::Debug; + /// Application document node. + type Node; + /// Transform from image pixels to font space. + fn image_transform(image: &Self::Image) -> Affine; + /// Place a bitmap in document space. + fn image_node(image: &Self::Image, transform: Affine) -> Self::Node; + /// Place colour artwork in document space. + fn colour_node(colour: &Self::Colour, transform: Affine) -> Self::Node; +} + +/// A glyph after shaping and composition. Coordinates are in the composer's text space; +/// `xf`, `pivot` and `unturned` refer to font space. Image, colour artwork and bend metadata +/// stay generic so the model does not own an application's document or rendering types. +#[derive(Clone, Debug)] +pub struct PositionedGlyph { + /// Outline in text space. + pub outline: BezPath, + /// Source style run index. + pub run: usize, + /// Source cluster's byte offset. + pub byte: usize, + /// Pen position on the baseline. + pub origin: Point, + /// Advance including composition spacing. + pub advance: f64, + /// Number of source bytes in the cluster. + pub len: usize, + /// Baseline angle in radians. + pub angle: f64, + /// Composed line index. + pub line: usize, + /// Identity of the resolved face. + pub font_id: u32, + /// Glyph identifier in that face. + pub gid: u32, + /// Transform from glyph font space to text space. + pub xf: Affine, + /// Whether the logical leading edge is on the right. + pub rtl: bool, + /// Paragraph glyph scaling factor. + pub scale: f64, + /// Optional bitmap artwork. + pub image: Option, + /// Optional colour artwork. + pub colour: Option, + /// Optional curved-baseline geometry. + pub bend: Option, + /// Transform restoring the glyph before character rotation. + pub unturned: Affine, + /// Character rotation pivot in font space. + pub pivot: Point, + /// Source-byte caret stops and their fractions of the glyph width. + pub carets: Vec<(usize, f64)>, + /// Glyph width excluding composition spacing. + pub width: f64, + /// Offset from the left end of the advance to the glyph width. + pub width_start: f64, + /// Source byte identifying a warichu block, when present. + pub warichu: Option, + /// Warichu block baseline offset. + pub warichu_line: f64, + /// Glyph lies before an open path and is retained for caret mapping only. + pub off_path: bool, +} + +impl PositionedGlyph { + /// Source caret stops as fractions of glyph width. + pub fn width_stops(&self) -> impl Iterator + '_ { + std::iter::once((self.byte, 0.0)).chain(self.carets.iter().copied()).chain(std::iter::once((self.byte + self.len, 1.0))) + } + + /// Source caret stops measured from the logical leading edge. + pub fn stops_along(&self, extent: f64) -> impl Iterator + '_ { + let (width, start) = if self.width > 0.0 && self.width.is_finite() { + (self.width, if self.width_start.is_finite() { self.width_start } else { 0.0 }) + } else { + (extent, 0.0) + }; + let ends = (self.byte, self.byte + self.len); + self.width_stops().map(move |(b, f)| { + if b == ends.0 { + (b, 0.0) + } else if b == ends.1 { + (b, extent) + } else if self.rtl { + (b, extent - start - (1.0 - f) * width) + } else { + (b, start + f * width) + } + }) + } + + /// Distance from the logical leading edge to the source byte's caret. + pub fn caret_offset(&self, byte: usize, extent: f64) -> f64 { + if byte <= self.byte || self.len == 0 { + return 0.0; + } + let mut from = (self.byte, 0.0); + for (b, d) in self.stops_along(extent).skip(1) { + if byte <= b { + let span = b.saturating_sub(from.0).max(1) as f64; + return from.1 + (d - from.1) * (byte - from.0) as f64 / span; + } + from = (b, d); + } + extent + } + + /// Bitmap data and its transform into text space. + pub fn placed_image(&self) -> Option<(&A::Image, Affine)> { + self.image.as_ref().map(|image| (image, self.xf * A::image_transform(image))) + } + + /// Bitmap artwork placed in document space. + pub fn placed_image_node(&self, to_doc: Affine) -> Option { + let (image, to_text) = self.placed_image()?; + Some(A::image_node(image, to_doc * to_text)) + } + + /// Colour artwork placed in document space. + pub fn placed_colour(&self, to_doc: Affine) -> Option { + Some(A::colour_node(self.colour.as_ref()?, to_doc * self.xf)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Clone, Debug)] + struct TestArt; + impl Artwork for TestArt { + type Image = Affine; + type Colour = (); + type Bend = (); + type Node = Affine; + fn image_transform(image: &Affine) -> Affine { + *image + } + fn image_node(_: &Affine, transform: Affine) -> Affine { + transform + } + fn colour_node(_: &(), transform: Affine) -> Affine { + transform + } + } + fn glyph() -> PositionedGlyph { + PositionedGlyph { + outline: BezPath::new(), + run: 0, + byte: 3, + origin: Point::ZERO, + advance: 12.0, + len: 4, + angle: 0.0, + line: 0, + font_id: 1, + gid: 4, + xf: Affine::translate((3.0, 5.0)), + rtl: false, + scale: 1.0, + image: Some(Affine::scale(2.0)), + colour: Some(()), + bend: None, + unturned: Affine::IDENTITY, + pivot: Point::ZERO, + carets: vec![(5, 0.5)], + width: 10.0, + width_start: 1.0, + warichu: None, + warichu_line: 0.0, + off_path: false, + } + } + #[test] + fn caret_mapping_tracks_ligatures_rtl_and_kerning() { + let mut g = glyph(); + assert_eq!((g.caret_offset(3, 12.0), g.caret_offset(5, 12.0), g.caret_offset(7, 12.0)), (0.0, 6.0, 12.0)); + assert_eq!(g.caret_offset(4, 12.0), 3.0); + g.rtl = true; + assert_eq!(g.caret_offset(5, 12.0), 6.0); + assert_eq!(g.caret_offset(5, 8.0), 2.0); + g.width = f64::NAN; + assert_eq!(g.caret_offset(5, 8.0), 4.0); + } + #[test] + fn artwork_uses_the_same_composition_order() { + let g = glyph(); + let doc = Affine::translate((10.0, 20.0)); + let (_, image) = g.placed_image().unwrap(); + assert_eq!(image, g.xf * Affine::scale(2.0)); + assert_eq!(g.placed_image_node(doc), Some(doc * image)); + assert_eq!(g.placed_colour(doc), Some(doc * g.xf)); + let mut empty = g; + empty.image = None; + empty.colour = None; + assert!(empty.placed_image_node(doc).is_none()); + assert!(empty.placed_colour(doc).is_none()); + } +} diff --git a/crates/texture/Cargo.toml b/crates/texture/Cargo.toml index 78868dd879..173abb0b02 100644 --- a/crates/texture/Cargo.toml +++ b/crates/texture/Cargo.toml @@ -9,6 +9,7 @@ repository.workspace = true [features] default = [] +dds = ["dep:dds", "dep:bytemuck"] parallel = ["dep:rayon"] [lints] @@ -17,3 +18,11 @@ workspace = true [dependencies] rayon = { workspace = true, optional = true } thiserror = { workspace = true } + +# Same decoder used by MaterialCraft; no parallel backend enabled. +dds = { version = "0.2.0", default-features = false, optional = true } +bytemuck = { workspace = true, optional = true } + +[dev-dependencies] +dds = { version = "0.2.0", default-features = false } +bytemuck = { workspace = true } diff --git a/crates/texture/README.md b/crates/texture/README.md index a41b42666f..8c82e5d0ba 100644 --- a/crates/texture/README.md +++ b/crates/texture/README.md @@ -25,7 +25,16 @@ network I/O and has no `unsafe` code. (). Repeat keeps its period at any finite coordinate. A NaN or infinite coordinate gives `[0, 0, 0, 1]`. Bilinear sums are taken in `f64` and clamped to the `f32` range, so finite - texels give a finite sample. + texels give a finite sample. `sample_axes`, `sample_nearest_axes` and `get_axes` take + `tiling: [bool; 2]`, the wrap mode of `u` and of `v` on their own, as glTF's `wrapS` and + `wrapT`; with equal entries they give the same results as the forms with one `tile`. +- **Stored sampling.** `sample_stored` is the texture read of MaterialCraft's function graphs. It + rounds the bilinear weights to multiples of 1/256 and blends the texels by linear interpolation + in `f32`. When the image's integer-sampling flag is on (`with_integer_sampling(true)`, read with + `integer_sampling()`), it then clamps each channel to `0..=1` and rounds it to a multiple of + 1/65535. A channel whose interpolation is not finite is taken from the `f64` weighted sum + instead, so finite texels give a finite sample. New images start with the flag off, clones keep + it, and two images are equal only when their flags are equal. - **Other operations.** `get` reads one texel, `map`, `to_gray`, `to_color` and `to_kind` convert, `resize` box-averages whole-factor shrinks and samples bilinearly otherwise, and `to_rgba8_display` encodes 8-bit sRGB RGBA. `linear_to_srgb`, `srgb_to_linear` and `luminance` @@ -58,7 +67,8 @@ Without `parallel` the crate builds for `wasm32-unknown-unknown`. | Part | Source | |---|---| | `Image`, `Kind`, sampling, resizing, conversions, sRGB helpers, resource keys and the six tests `sample_survives_huge_coordinates`, `resource_keys_round_trip`, `sample_wraps_and_clamps`, `resize_box_and_bilinear`, `hostile_sizes_are_clamped`, `conversions` | MaterialCraft `crates/image/src/lib.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) | -| `Limits`, the `try_` constructors, `from_data`, private fields with getters, the `parallel` feature | written here | +| `get_axes`, `sample_axes`, `sample_nearest_axes`, `sample_stored` and the integer-sampling flag | MaterialCraft `crates/image/src/lib.rs` at [6c3b35c](https://github.com/storytold/materialcraft/commit/6c3b35c39632feafcda3d7a90ff18242f3ad910f), on this crate's coordinate reduction and `f64` bilinear sum | +| `Limits`, the `try_` constructors, `from_data`, private fields with getters, the `parallel` feature, `with_integer_sampling` and `integer_sampling` | written here | ## Migration @@ -73,5 +83,7 @@ For MaterialCraft: | --- | --- | | `image.w`, `image.h`, `image.kind`, `image.data` | `width()`, `height()`, `kind()`, `data()` and `shared_data()` | | `Image { w, h, kind, data }` built by hand | `Image::from_data(w, h, kind, data, &Limits::default())` | +| `image.integer_sampling = on` and `Image { integer_sampling, .. }` | `image.with_integer_sampling(on)`; read it with `integer_sampling()` | +| `sample_axes` blends with `a + (b − a)t` in `f32` | it sums the weighted texels in `f64`, as `sample` does; the results differ by rounding | | `rayon` always on | the `parallel` feature | | `linear_to_srgb(NaN)` returned −0.055 | it returns NaN | diff --git a/crates/texture/src/dds.rs b/crates/texture/src/dds.rs new file mode 100644 index 0000000000..6971ad461b --- /dev/null +++ b/crates/texture/src/dds.rs @@ -0,0 +1,116 @@ +//! First-surface DDS decoding to unmodified RGBA floats. +//! +//! Adapted from MaterialCraft `dds_image.rs` (originally chasse20, cc052aeaa8c61fbe6975674b6d5e28bb3c597b9d). +//! Uses the same `dds` backend and first-surface semantics, including the first cube face or +//! volume slice. This is not a whole-resource decoder. Transfer functions and image policy +//! belong to callers. [`Limits`] bounds the output float plane, not backend scratch buffers. + +use crate::{ImageError, Kind, Limits}; + +/// A malformed DDS/backend failure or rejected output allocation. +#[derive(Debug, thiserror::Error)] +pub enum DecodeError { + /// Output size or allocation failed shared image limits. + #[error(transparent)] + Image(#[from] ImageError), + /// The decoder rejected input or output geometry. + #[error("DDS decode failed: {0}")] + Decode(String), +} + +/// Unmodified backend output. Alpha and out-of-range float values are not clamped. +#[derive(Debug)] +pub struct Surface { + /// Width of the first surface in pixels. + pub width: u32, + /// Height of the first surface in pixels. + pub height: u32, + /// Row-major RGBA float samples without transfer conversion. + pub rgba: Vec, + /// Exactly the backend's `Precision::F32` classification, as used by MaterialCraft. + pub source_precision_is_f32: bool, +} + +/// Decode the first surface after validating dimensions, pixels and output-byte limits. +/// The output reservation is fallible; no second full-sized float plane is created. +pub fn decode_first(bytes: &[u8], limits: &Limits) -> Result { + let error = |e: ::dds::DecodingError| DecodeError::Decode(e.to_string()); + let mut decoder = ::dds::Decoder::new(std::io::Cursor::new(bytes)).map_err(error)?; + let size = decoder.main_size(); + let len = limits.check(size.width, size.height, Kind::Color)?; + let mut rgba = Vec::new(); + rgba.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(size.width, size.height))?; + rgba.resize(len, 0.0_f32); + let view = ::dds::ImageViewMut::new(bytemuck::cast_slice_mut(&mut rgba), size, ::dds::ColorFormat::RGBA_F32) + .ok_or_else(|| DecodeError::Decode("invalid DDS output dimensions".into()))?; + decoder.read_surface(view).map_err(error)?; + Ok(Surface { width: size.width, height: size.height, rgba, source_precision_is_f32: decoder.format().precision() == ::dds::Precision::F32 }) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn bytes(format: ::dds::Format, payload: &[u8]) -> Vec { + let mut bytes = Vec::new(); + ::dds::header::Header::new_image(1, 1, format).write(&mut bytes).unwrap(); + bytes.extend_from_slice(payload); + bytes + } + + #[test] + fn rgba8_keeps_transfer_and_alpha_unmodified() { + let data = bytes(::dds::Format::R8G8B8A8_UNORM, &[128, 64, 255, 32]); + let image = decode_first(&data, &Limits::default()).unwrap(); + assert_eq!((image.width, image.height), (1, 1)); + assert!(!image.source_precision_is_f32); + for (actual, expected) in image.rgba.iter().zip([128.0 / 255.0, 64.0 / 255.0, 1.0, 32.0 / 255.0]) { + assert!((actual - expected).abs() < 1e-6); + } + } + + #[test] + fn float_hdr_and_negative_values_survive() { + let values = [-0.5_f32, 2.0, 0.25, 0.75]; + let payload: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + let image = decode_first(&bytes(::dds::Format::R32G32B32A32_FLOAT, &payload), &Limits::default()).unwrap(); + assert!(image.source_precision_is_f32); + assert_eq!(image.rgba, values); + } + + #[test] + fn half_float_and_compressed_pixels_preserve_backend_values() { + let half: Vec = [0xb800u16, 0x4000, 0x3400, 0x3a00].iter().flat_map(|v| v.to_le_bytes()).collect(); + let image = decode_first(&bytes(::dds::Format::R16G16B16A16_FLOAT, &half), &Limits::default()).unwrap(); + assert_eq!(image.rgba, [-0.5, 2.0, 0.25, 0.75]); + assert_eq!(image.source_precision_is_f32, ::dds::Format::R16G16B16A16_FLOAT.precision() == ::dds::Precision::F32); + let mut compressed = Vec::new(); + ::dds::header::Header::new_image(4, 4, ::dds::Format::BC1_UNORM).write(&mut compressed).unwrap(); + compressed.extend_from_slice(&[0, 0xf8, 0, 0, 0, 0, 0, 0]); + let image = decode_first(&compressed, &Limits::default()).unwrap(); + assert!(!image.source_precision_is_f32); + assert!(image.rgba.as_chunks::<4>().0.iter().all(|p| *p == [1.0, 0.0, 0.0, 1.0])); + } + + #[test] + fn cube_keeps_first_surface_only_like_materialcraft() { + let mut data = Vec::new(); + ::dds::header::Header::new_cube_map(1, 1, ::dds::Format::R8G8B8A8_UNORM).write(&mut data).unwrap(); + data.extend_from_slice(&[255, 0, 0, 255]); + data.extend_from_slice(&[0; 20]); + let image = decode_first(&data, &Limits::default()).unwrap(); + assert_eq!(image.rgba, [1.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn checks_output_budget_and_truncation() { + let data = bytes(::dds::Format::R8G8B8A8_UNORM, &[1, 2, 3, 4]); + let mut limits = Limits { max_bytes: 15, ..Limits::default() }; + assert!(matches!(decode_first(&data, &limits), Err(DecodeError::Image(ImageError::TooLarge(1, 1))))); + limits.max_bytes = 16; + assert!(decode_first(&data, &limits).is_ok()); + assert!(decode_first(&data[..data.len() - 1], &limits).is_err()); + assert!(decode_first(&[], &limits).is_err()); + } +} diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs index 2aaef3e8bc..baaabee66e 100644 --- a/crates/texture/src/lib.rs +++ b/crates/texture/src/lib.rs @@ -12,6 +12,10 @@ //! [`Image::sample_nearest`] and [`Image::sample`] (bilinear) use the texel coordinates, wrapping //! and weights of the Vulkan specification, sections 20.4.1, 20.6.1 and 20.6.3 //! (). +//! [`Image::get_axes`], [`Image::sample_axes`] and [`Image::sample_nearest_axes`] take the wrap +//! mode of each axis on its own. [`Image::sample_stored`] is MaterialCraft's function-graph texture +//! read: bilinear with weights rounded to eight fractional bits, and with its result rounded to 16 +//! bits when the image's integer-sampling flag is on ([`Image::with_integer_sampling`]). //! //! Sizes are bounded. [`Limits`] caps the side, the pixel count and the bytes, and the `try_` //! constructors return an [`ImageError`] before allocating anything over them. A plane is also @@ -29,6 +33,9 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(any(feature = "dds", test))] +pub mod dds; + use std::sync::Arc; #[cfg(feature = "parallel")] @@ -130,15 +137,18 @@ pub struct Image { w: u32, h: u32, kind: Kind, + /// Whether [`Image::sample_stored`] rounds its result to 16 bits, as for a normalized integer + /// texture. Off for every new image. + integer_sampling: bool, /// Row-major, `kind.channels()` floats per pixel. data: Arc>, } -/// Images are equal when their size, kind and floats are equal. Floats compare as `f32` does, so -/// an image holding NaN is unequal to every image, its clones included. +/// Images are equal when their size, kind, integer-sampling flag and floats are equal. Floats +/// compare as `f32` does, so an image holding NaN is unequal to every image, its clones included. impl PartialEq for Image { fn eq(&self, o: &Image) -> bool { - self.w == o.w && self.h == o.h && self.kind == o.kind && self.data == o.data + self.w == o.w && self.h == o.h && self.kind == o.kind && self.integer_sampling == o.integer_sampling && self.data == o.data } } @@ -187,6 +197,13 @@ fn reduce(t: f32, tile: bool) -> Option { Some(if tile { t.rem_euclid(1.0).min(BELOW_ONE) } else { t.clamp(-1.0, 2.0) }) } +/// A bilinear sum taken in `f64` as an `f32`: a finite sum clamped to the `f32` range, and an +/// infinite or NaN sum as it is. +#[inline] +fn f32_of_sum(v: f64) -> f32 { + if v.is_finite() { v.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32 } else { v as f32 } +} + /// Fill `data` row by row with `f(x, y)`, keeping the first `c` channels of each result. fn fill [f32; 4] + Sync>(data: &mut [f32], w: u32, c: usize, f: &F) { let row_len = (w as usize).max(1) * c; @@ -209,7 +226,7 @@ impl Image { let (w, h, len) = bounded_size(w, h, kind, MAX_ALLOC_BYTES); let mut data = vec![0.0f32; len]; fill(&mut data, w, kind.channels(), &f); - Image { w, h, kind, data: Arc::new(data) } + Image { w, h, kind, integer_sampling: false, data: Arc::new(data) } } /// An image checked against `limits`, with its memory reserved before any pixel is generated. @@ -219,7 +236,7 @@ impl Image { data.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(w, h))?; data.resize(len, 0.0); fill(&mut data, w, kind.channels(), &f); - Ok(Image { w, h, kind, data: Arc::new(data) }) + Ok(Image { w, h, kind, integer_sampling: false, data: Arc::new(data) }) } /// A constant image, each side clamped to `1..=MAX_SIDE`. @@ -272,7 +289,21 @@ impl Image { if data.len() != expected { return Err(ImageError::BadDataLength { expected, found: data.len() }); } - Ok(Image { w, h, kind, data }) + Ok(Image { w, h, kind, integer_sampling: false, data }) + } + + /// This image with the integer-sampling flag set to `on`. The flag only changes + /// [`Image::sample_stored`], which then rounds its result to 16 bits. Clones keep the flag. + /// [`Image::map`], [`Image::resize`] to a new size and the other operations that make a new + /// buffer return an image with the flag off. The pixels are not changed or copied. + pub fn with_integer_sampling(mut self, on: bool) -> Image { + self.integer_sampling = on; + self + } + + /// Whether [`Image::sample_stored`] rounds its result to 16 bits. + pub fn integer_sampling(&self) -> bool { + self.integer_sampling } pub fn width(&self) -> u32 { @@ -308,7 +339,14 @@ impl Image { /// The pixel at integer coordinates (wrapped or clamped), as RGBA (gray → `[v, v, v, 1]`). #[inline] pub fn get(&self, x: i64, y: i64, tile: bool) -> [f32; 4] { - let (x, y) = (wrap(x, self.w, tile), wrap(y, self.h, tile)); + self.get_axes(x, y, [tile; 2]) + } + + /// [`Image::get`] with the wrap mode of each axis given on its own: `tiling[0]` repeats `x` + /// and `tiling[1]` repeats `y`; an axis whose entry is `false` is clamped to its edge texels. + #[inline] + pub fn get_axes(&self, x: i64, y: i64, tiling: [bool; 2]) -> [f32; 4] { + let (x, y) = (wrap(x, self.w, tiling[0]), wrap(y, self.h, tiling[1])); let i = y * self.w as usize + x; match self.kind { Kind::Gray => { @@ -339,7 +377,15 @@ impl Image { /// leaves a sample at a texel center unchanged. NaN or infinite coordinates give `[0, 0, 0, 1]`. #[inline] pub fn sample(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + self.sample_axes(u, v, [tile; 2]) + } + + /// [`Image::sample`] with the wrap mode of each axis given on its own: `tiling[0]` for `u` and + /// `tiling[1]` for `v`, as glTF samplers set `wrapS` and `wrapT` separately. With both entries + /// equal the result is the same as [`Image::sample`] with that `tile`. + #[inline] + pub fn sample_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tiling[0]), reduce(v, tiling[1])) else { return [0.0, 0.0, 0.0, 1.0]; }; let fx = u * self.w as f32 - 0.5; @@ -356,12 +402,12 @@ impl Image { if weight == 0.0 { continue; } - let p = self.get(x, y, tile); + let p = self.get_axes(x, y, tiling); for (o, p) in o.iter_mut().zip(p) { *o += f64::from(weight) * f64::from(p); } } - o.map(|v| if v.is_finite() { v.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32 } else { v as f32 }) + o.map(f32_of_sum) } #[inline] @@ -373,18 +419,73 @@ impl Image { } } + /// Bilinear sample at normalized `(u, v)` with filter weights of eight fractional bits, the + /// texture read of MaterialCraft's function graphs. The texel coordinate and wrapping are those + /// of [`Image::sample`]. Each fractional part `α` and `β` is rounded to the nearest multiple of + /// 1/256 (a half rounds away from zero), and the four texels are blended by linear + /// interpolation in `f32`: `a + (b − a)α` along each of the two rows, then the same between + /// the rows with `β`. When the image's integer-sampling flag is on + /// ([`Image::with_integer_sampling`]), each channel is then clamped to `0..=1` and rounded to + /// the nearest multiple of 1/65535, as a filtered 16-bit texel. A NaN channel stays NaN. + /// + /// A channel whose interpolation is infinite or NaN is computed again as the weighted sum of + /// [`Image::sample`], skipping texels of weight 0 and clamping a finite sum to the `f32` + /// range, so finite texels give a finite sample. NaN or infinite coordinates give + /// `[0, 0, 0, 1]`. + #[inline] + pub fn sample_stored(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let pixel = self.sample_fixed_weights(u, v, tile); + if self.integer_sampling { pixel.map(|value| (value.clamp(0.0, 1.0) * 65535.0).round() / 65535.0) } else { pixel } + } + + /// The bilinear interpolation of [`Image::sample_stored`] before its 16-bit rounding. + #[inline] + fn sample_fixed_weights(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + return [0.0, 0.0, 0.0, 1.0]; + }; + let fx = u * self.w as f32 - 0.5; + let fy = v * self.h as f32 - 0.5; + let (x0, y0) = (fx.floor(), fy.floor()); + let tx = ((fx - x0) * 256.0).round() / 256.0; + let ty = ((fy - y0) * 256.0).round() / 256.0; + let (x0, y0) = (x0 as i64, y0 as i64); + let (a, b, c, d) = (self.get(x0, y0, tile), self.get(x0 + 1, y0, tile), self.get(x0, y0 + 1, tile), self.get(x0 + 1, y0 + 1, tile)); + let mut o = [0.0f32; 4]; + for (k, o) in o.iter_mut().enumerate() { + let top = a[k] + (b[k] - a[k]) * tx; + let bot = c[k] + (d[k] - c[k]) * tx; + *o = top + (bot - top) * ty; + if !o.is_finite() { + let taps = [((1.0 - tx) * (1.0 - ty), a[k]), (tx * (1.0 - ty), b[k]), ((1.0 - tx) * ty, c[k]), (tx * ty, d[k])]; + let sum = taps.iter().filter(|(weight, _)| *weight != 0.0).map(|(weight, p)| f64::from(*weight) * f64::from(*p)).sum(); + *o = f32_of_sum(sum); + } + } + o + } + /// Nearest sample at normalized `(u, v)`: the texel `floor(u × w)`, wrapped or clamped. NaN or /// infinite coordinates give `[0, 0, 0, 1]`. #[inline] pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + self.sample_nearest_axes(u, v, [tile; 2]) + } + + /// [`Image::sample_nearest`] with the wrap mode of each axis given on its own: `tiling[0]` for + /// `u` and `tiling[1]` for `v`. With both entries equal the result is the same as + /// [`Image::sample_nearest`] with that `tile`. + #[inline] + pub fn sample_nearest_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tiling[0]), reduce(v, tiling[1])) else { return [0.0, 0.0, 0.0, 1.0]; }; let (x, y) = ((u * self.w as f32).floor() as i64, (v * self.h as f32).floor() as i64); // A repeated coordinate is below 1, so its texel is below the size even where `u × w` // rounds up to it. - let (x, y) = if tile { (x.min(i64::from(self.w) - 1), y.min(i64::from(self.h) - 1)) } else { (x, y) }; - self.get(x, y, tile) + let x = if tiling[0] { x.min(i64::from(self.w) - 1) } else { x }; + let y = if tiling[1] { y.min(i64::from(self.h) - 1) } else { y }; + self.get_axes(x, y, tiling) } /// Map every pixel (as RGBA) to a new image of `kind`, same size. When a result of that size @@ -892,4 +993,247 @@ mod tests { assert_eq!(half.data(), &[0.5, 0.5, 0.0, 1.0, 2.5, 0.5, 0.0, 1.0]); assert_eq!(img.to_gray().width(), 4); } + + /// The four wrap combinations of the two axes. + const TILINGS: [[bool; 2]; 4] = [[false, false], [true, true], [true, false], [false, true]]; + + /// Gray texels of 8-bit values, `k / 255`. + fn gray8() -> Image { + Image::gray(5, 3, |x, y| ((x * 37 + y * 91 + 13) % 256) as f32 / 255.0) + } + + /// Color texels from −2.5 to 3.42, with negative values and values above 1. + fn color() -> Image { + Image::generate(4, 3, Kind::Color, |x, y| { + let s = |k: u32| ((x * 7 + y * 13 + k * 5) % 17) as f32 * 0.37 - 2.5; + [s(0), s(1), s(2), s(3)] + }) + } + + /// 65 even steps from `lo` to `hi`, then the texel centers and edges of sides 3, 4 and 5. + fn coordinates(lo: f32, hi: f32) -> Vec { + let mut v: Vec = (0..=64).map(|i| lo + (hi - lo) * i as f32 / 64.0).collect(); + for side in [3u32, 4, 5] { + v.extend((0..=2 * side).map(|i| i as f32 / (2 * side) as f32)); + } + v + } + + /// FNV-1a over the bits of every channel. + fn hash(h: &mut u64, p: [f32; 4]) { + for b in p.iter().flat_map(|v| v.to_bits().to_le_bytes()) { + *h ^= u64::from(b); + *h = h.wrapping_mul(0x100_0000_01b3); + } + } + + const FNV_START: u64 = 0xcbf2_9ce4_8422_2325; + + /// Hash of `f(u, v)` over every pair of `coordinates`. + fn hash_grid(us: &[f32], f: impl Fn(f32, f32) -> [f32; 4]) -> u64 { + let mut h = FNV_START; + for &u in us { + for &v in us { + hash(&mut h, f(u, v)); + } + } + h + } + + /// Hashes of `sample_stored`, `sample_nearest_axes` and `get_axes` computed with MaterialCraft's + /// `crates/image` at storytold/materialcraft `6c3b35c396`, over the fixtures and grids above. + #[test] + fn stored_and_axis_reads_match_materialcraft() { + // (range, image, integer sampling, tile, sample_stored hash) + let stored = [ + ("unit", "gray8", false, false, 0x702b_0f81_2833_5e06u64), + ("unit", "gray8", false, true, 0x4ac5_b29c_45b2_d0ca), + ("unit", "gray8", true, false, 0x8400_a867_00fc_389a), + ("unit", "gray8", true, true, 0x47ea_befd_7fd6_cc5e), + ("unit", "color", false, false, 0x25f6_2544_f084_4182), + ("unit", "color", false, true, 0x607f_3c9f_896b_5975), + ("unit", "color", true, false, 0x0261_02eb_451b_36d6), + ("unit", "color", true, true, 0x51f8_9417_f5e9_2341), + ("wide", "gray8", false, false, 0xb0e7_096c_c64b_0f72), + ("wide", "gray8", false, true, 0x7a8a_4059_68ac_2a07), + ("wide", "gray8", true, false, 0x418c_9c08_2718_2171), + ("wide", "gray8", true, true, 0xe0b7_0088_256f_ccb2), + ("wide", "color", false, false, 0x51b4_8bb3_2885_f844), + ("wide", "color", false, true, 0xab4b_72d5_25ff_aaed), + ("wide", "color", true, false, 0x6570_eaa2_25f3_4d29), + ("wide", "color", true, true, 0x15a3_5aa7_7f50_4f92), + ]; + // (range, image, sample_nearest_axes hash for each entry of TILINGS) + let nearest = [ + ("unit", "gray8", [0xe427_9012_572d_b173u64, 0x76b9_e33c_849f_069d, 0x42ab_5ecd_8f1a_5dd2, 0x190c_23b8_f3e9_a2e5]), + ("unit", "color", [0x6a0e_0370_810d_1ad9, 0x0ab0_d62b_8308_4f9d, 0xa839_3cdf_db7d_844a, 0x1fc4_027e_bb8d_7c45]), + ("wide", "gray8", [0xd1cf_daaf_d7db_239c, 0x1d22_a6db_ad03_0960, 0x754e_fabf_5203_d6a0, 0xfe73_7385_df89_4dd4]), + ("wide", "color", [0xb894_834b_96fe_684d, 0x7eb4_0a21_3a51_c6bc, 0x2443_5503_2fea_4068, 0x4705_30d0_9afc_dc75]), + ]; + // (image, get_axes hash over x and y in -12..12 for each entry of TILINGS) + let get = [ + ("gray8", [0x6c95_1e05_c9c6_8f21u64, 0xac4a_e19a_4da7_b625, 0xcee5_f582_facb_f043, 0x7f1d_ff0e_357b_5eb5]), + ("color", [0x21af_a81f_327a_d3af, 0x9cf4_2557_9880_5345, 0x9b58_bde1_8021_2779, 0x6bb0_a98f_13d5_6635]), + ]; + let image = |name: &str| if name == "gray8" { gray8() } else { color() }; + let grid = |range: &str| if range == "unit" { coordinates(0.0, 0.99) } else { coordinates(-2.5, 3.5) }; + for (range, name, integer, tile, expected) in stored { + let img = image(name).with_integer_sampling(integer); + let h = hash_grid(&grid(range), |u, v| img.sample_stored(u, v, tile)); + assert_eq!(h, expected, "sample_stored {range} {name} integer {integer} tile {tile}"); + } + for (range, name, expected) in nearest { + let img = image(name); + for (tiling, expected) in TILINGS.into_iter().zip(expected) { + let h = hash_grid(&grid(range), |u, v| img.sample_nearest_axes(u, v, tiling)); + assert_eq!(h, expected, "sample_nearest_axes {range} {name} {tiling:?}"); + } + } + for (name, expected) in get { + let img = image(name); + for (tiling, expected) in TILINGS.into_iter().zip(expected) { + let mut h = FNV_START; + for x in -12..12 { + for y in -12..12 { + hash(&mut h, img.get_axes(x, y, tiling)); + } + } + assert_eq!(h, expected, "get_axes {name} {tiling:?}"); + } + } + } + + /// Values of MaterialCraft's `sample_axes` at storytold/materialcraft `6c3b35c396`. It blends + /// by linear interpolation in `f32`, and this crate sums the weighted texels in `f64`, so the + /// results differ by rounding only. + #[test] + fn axis_bilinear_matches_materialcraft_up_to_rounding() { + let img = color(); + let cases = [ + (0.3, 0.7, [true, false], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]), + (0.3, 0.7, [false, true], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]), + (1.2, -0.4, [true, false], [-1.722_999_5, 0.127_000_57, 0.089_999_32, 1.939_999_3]), + (1.2, -0.4, [false, true], [-1.057_000_3, -1.094, 0.756_000_1, 2.606_000_2]), + (-0.15, 1.1, [true, false], [2.051, -1.76, 0.090_000_15, 1.311_000_1]), + (-0.15, 1.1, [false, true], [-1.834_000_6, 0.015_999_317, 0.608_000_5, 2.458_000_7]), + (0.95, 0.05, [true, false], [-1.464, 0.386_000_04, 2.236_000_3, -0.317_000_15]), + (0.95, 0.05, [false, true], [0.145_500_18, -0.206_000_21, 1.644_000_2, -0.594_499_8]), + ]; + for (u, v, tiling, expected) in cases { + let p = img.sample_axes(u, v, tiling); + for (p, e) in p.iter().zip(expected) { + assert!((p - e).abs() <= 2.0e-6, "u {u} v {v} {tiling:?}: {p} against {e}"); + } + } + } + + #[test] + fn equal_axes_give_the_shared_results() { + let us = coordinates(-2.5, 3.5); + for img in [gray8(), color()] { + for tile in [false, true] { + for &u in &us { + for &v in &us { + assert_eq!(img.sample_axes(u, v, [tile; 2]).map(f32::to_bits), img.sample(u, v, tile).map(f32::to_bits)); + assert_eq!(img.sample_nearest_axes(u, v, [tile; 2]).map(f32::to_bits), img.sample_nearest(u, v, tile).map(f32::to_bits)); + } + } + for x in -12..12 { + assert_eq!(img.get_axes(x, -x, [tile; 2]), img.get(x, -x, tile)); + } + } + } + } + + #[test] + fn axes_wrap_independently() { + // Texel (x, y) holds x + 10y. + let img = Image::gray(4, 2, |x, y| (x + 10 * y) as f32); + assert_eq!(img.get_axes(-1, -1, [true, false])[0], 3.0); + assert_eq!(img.get_axes(-1, -1, [false, true])[0], 10.0); + assert_eq!(img.get_axes(5, 3, [true, false])[0], 11.0); + assert_eq!(img.sample_nearest_axes(1.1, 1.5, [true, false])[0], 10.0); + assert_eq!(img.sample_nearest_axes(1.1, 1.5, [false, true])[0], 13.0); + // v = 0.25 is the center of row 0; u = 1 is halfway between texels 3 and 0 when repeating. + assert!((img.sample_axes(1.0, 0.25, [true, false])[0] - 1.5).abs() < 1e-6); + assert_eq!(img.sample_axes(1.0, 0.25, [false, true])[0], 3.0); + assert_eq!(img.sample_axes(f32::NAN, 0.5, [false, true]), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(img.sample_nearest_axes(0.5, f32::INFINITY, [true, false]), [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn stored_sampling_rounds_weights_to_eight_bits() { + let img = Image::gray(2, 1, |x, _| x as f32); + // u × 2 − 0.5 = 0.3: the weight 0.3 rounds to 77/256. + assert_eq!(img.sample_stored(0.4, 0.5, false)[0], 77.0 / 256.0); + assert!((img.sample(0.4, 0.5, false)[0] - 0.3).abs() < 1e-6); + // A fraction of 255.5/256 or more rounds up to the next texel. + assert_eq!(img.sample_stored((1.5 - 0.25 / 256.0) / 2.0, 0.5, false)[0], 1.0); + assert_eq!(img.sample_stored(f32::NAN, 0.5, true), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(img.sample_stored(0.5, f32::NEG_INFINITY, false), [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn integer_sampling_rounds_stored_samples_to_sixteen_bits() { + let img = Image::gray(2, 1, |x, _| x as f32); + assert!(!img.integer_sampling()); + let int = img.clone().with_integer_sampling(true); + assert!(int.integer_sampling()); + // 77/256 × 65535 = 19711.64, which rounds to 19712. + assert_eq!(int.sample_stored(0.4, 0.5, false)[0], 19_712.0 / 65_535.0); + assert_eq!(int.sample(0.4, 0.5, false), img.sample(0.4, 0.5, false)); + assert_eq!(int.sample_nearest(0.4, 0.5, false), img.sample_nearest(0.4, 0.5, false)); + let l = Limits::default(); + let Ok(wide) = Image::from_data(3, 1, Kind::Gray, vec![-0.5, 2.0, f32::NAN], &l) else { panic!("valid 3 x 1 image") }; + let wide = wide.with_integer_sampling(true); + assert_eq!(wide.sample_stored(0.5 / 3.0, 0.5, false)[0], 0.0); + assert_eq!(wide.sample_stored(1.5 / 3.0, 0.5, false)[0], 1.0); + assert!(wide.sample_stored(2.5 / 3.0, 0.5, false)[0].is_nan()); + assert_eq!(wide.sample_stored(0.5 / 3.0, 0.5, false)[3], 1.0); + } + + #[test] + fn integer_sampling_follows_clones_and_not_new_buffers() { + let img = Image::gray(4, 2, |x, y| (x + y) as f32 / 8.0).with_integer_sampling(true); + let plain = img.clone().with_integer_sampling(false); + assert_eq!(img.clone(), img); + assert_ne!(img, plain); + assert_eq!(img.data(), plain.data()); + assert!(img.clone().integer_sampling()); + assert!(img.to_gray().integer_sampling()); + assert!(img.resize(4, 2, false).integer_sampling()); + assert!(!img.resize(2, 1, false).integer_sampling()); + assert!(!img.map(Kind::Gray, |p| p).integer_sampling()); + assert!(!img.to_color().integer_sampling()); + assert!(img.try_to_kind(Kind::Gray, &Limits::default()).is_ok_and(|i| i.integer_sampling())); + assert!(Arc::ptr_eq(img.shared_data(), plain.shared_data())); + } + + #[test] + fn stored_sampling_keeps_finite_texels_finite() { + let l = Limits::default(); + let Ok(inf) = Image::from_data(2, 1, Kind::Gray, vec![1.0, f32::INFINITY], &l) else { panic!("valid 2 x 1 image") }; + // The center of texel 0 gives texel 0, though its neighbor is infinite. + assert_eq!(inf.sample_stored(0.25, 0.5, false)[0], 1.0); + assert_eq!(inf.sample_stored(0.5, 0.5, false)[0], f32::INFINITY); + let Ok(hdr) = Image::from_data(2, 1, Kind::Gray, vec![f32::MAX, -f32::MAX], &l) else { panic!("valid 2 x 1 image") }; + assert_eq!(hdr.sample_stored(0.5, 0.5, false)[0], 0.0); + assert_eq!(hdr.clone().with_integer_sampling(true).sample_stored(0.5, 0.5, false)[0], 0.0); + let max = Image::filled(2, 2, Kind::Gray, [f32::MAX; 4]); + for tile in [false, true] { + assert_eq!(max.sample_stored(0.3, 0.6, tile)[0], f32::MAX, "tile = {tile}"); + } + } + + #[test] + fn stored_sampling_keeps_the_repeat_period_at_large_coordinates() { + let img = stripe(); + let at_zero = img.sample_stored(0.0, 0.5, true)[0]; + assert_eq!(at_zero, 0.5); + for u in [1.0e9_f32, -1.0e9, 4.0e9, 3.0e12, f32::MAX] { + assert_eq!(img.sample_stored(u, 0.5, true)[0], at_zero, "u = {u}"); + let edge = if u > 0.0 { 1.0 } else { 0.0 }; + assert_eq!(img.sample_stored(u, 0.5, false)[0], edge, "u = {u}"); + } + } } diff --git a/crates/tga/src/lib.rs b/crates/tga/src/lib.rs index ac9d21497b..cf968cf573 100644 --- a/crates/tga/src/lib.rs +++ b/crates/tga/src/lib.rs @@ -18,6 +18,11 @@ //! 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. +/// Uncompressed RGBA8-to-Targa encoding. +pub mod rgba8_raw; + +#[cfg(test)] +mod metadata_tests; #[cfg(test)] mod tests; @@ -57,11 +62,13 @@ pub type Result = std::result::Result; pub struct Limits { /// Most pixels (width × height) a picture may have. Default 2^28 (16384 × 16384). pub max_pixels: u64, + /// Maximum combined palette, stored-pixel and RGBA allocation bytes. Default 256 MiB. + pub max_decoded_bytes: usize, } impl Default for Limits { fn default() -> Self { - Self { max_pixels: 1 << 28 } + Self { max_pixels: 1 << 28, max_decoded_bytes: 256 << 20 } } } @@ -180,6 +187,102 @@ impl Stored { } } +fn metadata_offset(body: &[u8], offset: usize, first_pixel: usize) -> Option { + // Optional metadata cannot replace the header, image ID, or colour map. + (offset >= first_pixel && offset < body.len()).then_some(offset) +} + +/// The start of every developer-directory payload with a nonzero length, from the directory at +/// `directory` in `body` (none when that offset holds no readable directory). +fn developer_payload_starts(body: &[u8], directory: usize) -> Vec { + let Some(count) = + body.get(directory..directory.saturating_add(2)).and_then(|v| v.first_chunk::<2>()).map(|v| usize::from(u16::from_le_bytes(*v))) + else { + return Vec::new(); + }; + let Some(fields) = body.get(directory.saturating_add(2)..) else { return Vec::new() }; + fields + .chunks(10) + .take(count) + .filter_map(|field| { + let start = field.get(2..6).and_then(|v| v.first_chunk::<4>()).map(|v| u32::from_le_bytes(*v) as usize)?; + let length = field.get(6..10).and_then(|v| v.first_chunk::<4>()).map(|v| u32::from_le_bytes(*v))?; + (length != 0).then_some(start) + }) + .collect() +} + +fn image_data_end(bytes: &[u8], first_pixel: usize) -> Result { + if !bytes.ends_with(SIGNATURE) { + return Ok(bytes.len()); + } + // A TGA 2.0 footer cannot begin inside the mandatory header. A legacy image + // may end with the same signature as pixel bytes. + let Some(footer) = bytes.len().checked_sub(SIGNATURE.len() + 8).filter(|&at| at >= HEADER) else { + return Ok(bytes.len()); + }; + let offsets = bytes.get(footer..footer + 8).and_then(|b| b.first_chunk::<8>()).ok_or(Error::Malformed("truncated footer"))?; + let extension = offsets.first_chunk::<4>().map(|v| u32::from_le_bytes(*v) as usize).ok_or(Error::Malformed("truncated footer"))?; + let directory = + offsets.get(4..).and_then(|v| v.first_chunk::<4>()).map(|v| u32::from_le_bytes(*v) as usize).ok_or(Error::Malformed("truncated footer"))?; + let body = bytes.get(..footer).ok_or(Error::Malformed("truncated footer"))?; + let mut end = footer; + + if let Some(offset) = metadata_offset(body, extension, first_pixel) { + // An in-body reference is a conservative image boundary, even if it overlaps + // required pixels. Those bytes cannot be distinguished from a truncated image + // whose missing pixels are supplied by metadata. + end = end.min(offset); + // TGA 2.0 extension fields at byte offsets 482, 486 and 490 point to the colour + // correction, postage-stamp and scan-line tables. The record's first two bytes give + // its size (495 in TGA 2.0); a shorter record has no such fields, and a record never + // reaches into a developer directory that follows it, so those bytes are not read as + // table offsets. Tables may precede the record. + let declared = + body.get(offset..offset.saturating_add(2)).and_then(|v| v.first_chunk::<2>()).map_or(0, |v| usize::from(u16::from_le_bytes(*v))); + let mut record_end = offset.saturating_add(declared.min(495)); + // The developer directory and its payloads may sit anywhere after the pixels, a payload + // before its directory included; whichever starts first after the extension ends it. + // A directory offset of zero means there is none: the header is not read as one. + let payloads = metadata_offset(body, directory, first_pixel).map(|d| developer_payload_starts(body, d)).unwrap_or_default(); + for next in std::iter::once(directory).chain(payloads) { + if next > offset { + record_end = record_end.min(next); + } + } + if let Some(area) = body.get(offset..record_end.min(body.len())) { + for field in [482, 486, 490] { + if let Some(value) = area.get(field..field + 4).and_then(|v| v.first_chunk::<4>()) + && let Some(table) = metadata_offset(body, u32::from_le_bytes(*value) as usize, first_pixel) + { + end = end.min(table); + } + } + } + } + + if let Some(offset) = metadata_offset(body, directory, first_pixel) { + end = end.min(offset); + if let Some(count) = + body.get(offset..offset.saturating_add(2)).and_then(|v| v.first_chunk::<2>()).map(|v| usize::from(u16::from_le_bytes(*v))) + && let Some(fields) = body.get(offset.saturating_add(2)..) + { + // A corrupt count or final entry does not hide earlier payload offsets. Each + // entry has a 2-byte tag followed by a 4-byte offset and 4-byte length. + for field in fields.chunks(10).take(count) { + if let Some(value) = field.get(2..6).and_then(|v| v.first_chunk::<4>()) + && let Some(length) = field.get(6..10).and_then(|v| v.first_chunk::<4>()) + && u32::from_le_bytes(*length) != 0 + && let Some(payload) = metadata_offset(body, u32::from_le_bytes(*value) as usize, first_pixel) + { + end = end.min(payload); + } + } + } + } + Ok(end) +} + /// Decodes a Targa file to straight-alpha RGBA8, top row first. pub fn decode(bytes: &[u8], limits: &Limits) -> Result { let err = Error::Malformed; @@ -208,13 +311,14 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result { } 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 map_start = HEADER + id_len; + let first_pixel = match map_entry { + Some(layout) => map_start.checked_add(map_len * layout.bytes()).ok_or(err("colour map"))?, + None => map_start, + }; + let end = image_data_end(bytes, first_pixel)?; + let bytes = bytes.get(..end).ok_or(err("truncated image data"))?; + let at = first_pixel; let (stored_as, mapped) = match kind & 7 { 1 => { if map_type != 1 || !matches!(depth, 8 | 16) { @@ -232,14 +336,35 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result { }; let data = bytes.get(at..).unwrap_or_default(); let bpp = stored_as.bytes(); + let stored_bytes = pixels.checked_mul(bpp).ok_or(Error::LimitExceeded("image size"))?; + let rgba_bytes = pixels.checked_mul(4).ok_or(Error::LimitExceeded("image size"))?; + let palette_bytes = if map_entry.is_some() { map_len * 4 } else { 0 }; + let aggregate = + stored_bytes.checked_add(rgba_bytes).and_then(|n| n.checked_add(palette_bytes)).ok_or(Error::LimitExceeded("decode allocation bytes"))?; + if aggregate > limits.max_decoded_bytes { + return Err(Error::LimitExceeded("decode allocation bytes")); + } + if let Some(layout) = map_entry { + let map = bytes.get(map_start..first_pixel).ok_or(err("truncated colour map"))?; + palette.try_reserve_exact(map_len).map_err(|_| Error::LimitExceeded("allocation failed"))?; + palette.extend(map.chunks_exact(layout.bytes()).map(|entry| layout.rgba(entry))); + } // 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 source = data.get(..n).ok_or(err("truncated pixel data"))?; + let mut values = Vec::new(); + values.try_reserve_exact(n).map_err(|_| Error::LimitExceeded("allocation failed"))?; + values.extend_from_slice(source); + values + } }; - let mut rgba = vec![0u8; pixels.checked_mul(4).ok_or(Error::LimitExceeded("image size"))?]; + let mut rgba = Vec::new(); + rgba.try_reserve_exact(rgba_bytes).map_err(|_| Error::LimitExceeded("allocation failed"))?; + rgba.resize(rgba_bytes, 0u8); 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 }; @@ -283,7 +408,8 @@ fn unpack_rle(mut data: &[u8], pixels: usize, bpp: usize) -> Result> { return Err(short); } let total = pixels.checked_mul(bpp).ok_or(Error::LimitExceeded("image size"))?; - let mut out = Vec::with_capacity(total); + let mut out = Vec::new(); + out.try_reserve_exact(total).map_err(|_| Error::LimitExceeded("allocation failed"))?; while out.len() < total { let (&head, rest) = data.split_first().ok_or(short.clone())?; let count = usize::from(head & 0x7F) + 1; diff --git a/crates/tga/src/metadata_tests.rs b/crates/tga/src/metadata_tests.rs new file mode 100644 index 0000000000..85c434bf4d --- /dev/null +++ b/crates/tga/src/metadata_tests.rs @@ -0,0 +1,425 @@ +//! Metadata-boundary regressions ported from FilmCraft #1932 (nuclearspike). +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 legacy_pixels_that_end_in_signature_are_not_a_footer_before_header() { + for prefix in [0usize, 7] { + let width = (prefix + SIGNATURE.len()) as u16; + let mut file = header(3, width, 1, 8, 0x20); + file.extend(vec![0; prefix]); + file.extend_from_slice(SIGNATURE); + let image = dec(&file).unwrap(); + assert_eq!((image.width, image.height), (u32::from(width), 1)); + let pixels: Vec = std::iter::repeat_n(0, prefix).chain(SIGNATURE.iter().copied()).flat_map(|gray| [gray, gray, gray, 255]).collect(); + assert_eq!(image.rgba, pixels); + let source = dec(&file).unwrap(); + assert_eq!(source.rgba, pixels); + } +} + +#[test] +fn short_extension_followed_by_a_developer_payload_keeps_the_pixels() { + // a 482-byte extension whose size field still says 495, then a developer payload whose + // first bytes land where a full extension keeps its colour-correction offset, then the + // directory that points back at that payload + let mut file = header(2, 1, 1, 24, 0x20); + file.extend_from_slice(&[10, 20, 30]); + let extension = file.len() as u32; + let mut area = vec![0; 482]; + area[..2].copy_from_slice(&495u16.to_le_bytes()); + file.extend_from_slice(&area); + let payload = file.len() as u32; + file.extend_from_slice(&18u32.to_le_bytes()); + file.extend_from_slice(&[0; 14]); + let directory = file.len() as u32; + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&0u16.to_le_bytes()); + file.extend_from_slice(&payload.to_le_bytes()); + file.extend_from_slice(&18u32.to_le_bytes()); + file.extend_from_slice(&extension.to_le_bytes()); + file.extend_from_slice(&directory.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + let source = dec(&file).expect("the image decodes"); + assert_eq!((source.width, source.height), (1, 1)); + assert_eq!(source.rgba, vec![30, 20, 10, 255]); +} + +#[test] +fn a_footer_without_a_directory_does_not_read_the_header_as_one() { + // no developer directory (offset 0). Read as one, the header's three-byte image ID + // length is an entry count, and the third "entry" is the first words of a colour + // correction table that sits right after a short pixel area; the extension points at + // that table, so the image is incomplete and must stay so. + let mut file = header(2, 2, 1, 24, 0x20); + file[0] = 3; + file.extend_from_slice(&[7, 8, 9]); + file.extend_from_slice(&[0, 0, 255]); + let table = file.len() as u32; + let mut words = vec![0; 2048]; + words[..4].copy_from_slice(&2074u32.to_le_bytes()); + words[4..8].copy_from_slice(&1u32.to_le_bytes()); + file.extend_from_slice(&words); + let extension = file.len() as u32; + let mut area = vec![0; 495]; + area[..2].copy_from_slice(&495u16.to_le_bytes()); + area[482..486].copy_from_slice(&table.to_le_bytes()); + file.extend_from_slice(&area); + file.extend_from_slice(&extension.to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + let decoded = dec(&file); + assert!(decoded.is_err(), "the second pixel is missing"); +} + +#[test] +fn short_extension_followed_by_a_developer_directory_keeps_the_pixels() { + // a complete 1x1 image, a 482-byte extension (its size says so) and right after it a + // developer directory whose entry's length lands where a full extension keeps its + // scan-line table offset; reading it as one would move the image end into the header + let mut file = header(2, 1, 1, 24, 0x20); + file.extend_from_slice(&[10, 20, 30]); + let extension = file.len() as u32; + let mut area = vec![0; 482]; + area[..2].copy_from_slice(&482u16.to_le_bytes()); + file.extend_from_slice(&area); + let directory = file.len() as u32; + let payload = directory + 2 + 10; + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&0u16.to_le_bytes()); + file.extend_from_slice(&payload.to_le_bytes()); + file.extend_from_slice(&18u32.to_le_bytes()); + file.extend_from_slice(&[0; 18]); + file.extend_from_slice(&extension.to_le_bytes()); + file.extend_from_slice(&directory.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + let source = dec(&file).expect("the image decodes"); + assert_eq!((source.width, source.height), (1, 1)); +} + +#[test] +fn importing_truncated_pixels_does_not_consume_tga_footer() { + for (kind, data) in [(2, vec![0, 0, 255]), (10, vec![0x80, 0, 0, 255])] { + for metadata in [None, Some(0usize), Some(1)] { + let mut file = header(kind, 2, 1, 24, 0x20); + file.extend_from_slice(&data); // only the first of two pixels + let mut offsets = [0u8; 8]; + if let Some(field) = metadata { + let offset = file.len() as u32; + offsets[field * 4..field * 4 + 4].copy_from_slice(&offset.to_le_bytes()); + let mut area = vec![0; 495]; + if field == 0 { + area[..2].copy_from_slice(&495u16.to_le_bytes()); + } + file.extend_from_slice(&area); // optional metadata is not pixel data + } + file.extend_from_slice(&offsets); + file.extend_from_slice(SIGNATURE); + let result = dec(&file); + assert!(result.is_err(), "kind {kind}, metadata {metadata:?}: metadata is not a second pixel"); + } + } + for kind in [1, 9] { + let mut file = header(kind, 1, 1, 8, 0x20); + file[1] = 1; + file[5] = 1; + file[7] = 24; + file.extend_from_slice(&[0, 0]); // missing third palette byte and the index + file.extend_from_slice(&[0; 8]); + file.extend_from_slice(SIGNATURE); + let result = dec(&file); + assert!(result.is_err(), "kind {kind}: the footer is not colour-map data"); + } +} + +#[test] +fn complete_tga_footer_and_metadata_do_not_change_pixels() { + for metadata in [None, Some(0usize), Some(1)] { + let mut file = header(2, 1, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255]); + let mut offsets = [0u8; 8]; + if let Some(field) = metadata { + let offset = file.len() as u32; + offsets[field * 4..field * 4 + 4].copy_from_slice(&offset.to_le_bytes()); + let mut area = vec![0; 495]; + if field == 0 { + area[..2].copy_from_slice(&495u16.to_le_bytes()); + } + file.extend_from_slice(&area); + } + file.extend_from_slice(&offsets); + file.extend_from_slice(SIGNATURE); + let source = dec(&file).unwrap(); + assert_eq!(source.rgba, [255, 0, 0, 255]); + } +} + +fn preceding_metadata(complete: bool, metadata: usize) -> Vec { + assert!(metadata <= 3, "test metadata selector must be 0..=3"); + let mut file = header(2, if complete { 1 } else { 2 }, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255]); + let payload_offset = file.len() as u32; + let mut offsets = [0u8; 8]; + if metadata == 0 { + file.extend_from_slice(&[0, 255, 0]); + let directory_offset = file.len() as u32; + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&payload_offset.to_le_bytes()); + file.extend_from_slice(&3u32.to_le_bytes()); + offsets[4..].copy_from_slice(&directory_offset.to_le_bytes()); + } else { + match metadata { + 1 => file.extend_from_slice(&[0; 2048]), + 2 => file.extend_from_slice(&[1, 1, 0, 255, 0]), + 3 => file.extend_from_slice(&18u32.to_le_bytes()), + _ => {} + } + let extension_offset = file.len() as u32; + let mut extension = [0; 495]; + extension[..2].copy_from_slice(&495u16.to_le_bytes()); + let field = [0, 482, 486, 490][metadata]; + extension[field..field + 4].copy_from_slice(&payload_offset.to_le_bytes()); + file.extend_from_slice(&extension); + offsets[..4].copy_from_slice(&extension_offset.to_le_bytes()); + } + file.extend_from_slice(&offsets); + file.extend_from_slice(SIGNATURE); + file +} + +#[test] +fn preceding_metadata_cannot_supply_missing_pixels() { + let mut accepted = Vec::new(); + for metadata in 0..4 { + let result = dec(&preceding_metadata(false, metadata)); + if result.is_ok() { + accepted.push(metadata); + } + } + assert!(accepted.is_empty(), "metadata payloads supplied missing pixels: {accepted:?}"); +} + +#[test] +fn complete_pixels_before_metadata_keep_their_colour() { + for metadata in 0..4 { + let source = dec(&preceding_metadata(true, metadata)).unwrap(); + assert_eq!(source.rgba, [255, 0, 0, 255], "metadata {metadata}"); + } + let mut file = preceding_metadata(true, 1); + let footer = file.len() - SIGNATURE.len() - 8; + let extension = u32::from_le_bytes(file[footer..footer + 4].try_into().unwrap()) as usize; + file[extension..extension + 2].copy_from_slice(&496u16.to_le_bytes()); + file.insert(footer, 0); + let source = dec(&file).unwrap(); + assert_eq!(source.rgba, [255, 0, 0, 255], "larger complete extensions preserve pixels"); +} + +#[test] +fn malformed_optional_metadata_keeps_complete_pixels_readable() { + let accept = |file: Vec| { + let source = dec(&file).unwrap(); + assert_eq!(source.rgba, [255, 0, 0, 255]); + }; + for field in [0, 4] { + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + file[footer + field..footer + field + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + accept(file); + } + for metadata in 1..4 { + let mut file = preceding_metadata(true, metadata); + let footer = file.len() - SIGNATURE.len() - 8; + let extension = u32::from_le_bytes(file[footer..footer + 4].try_into().unwrap()) as usize; + let field = [0, 482, 486, 490][metadata]; + file[extension + field..extension + field + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + accept(file); + } + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file.drain(directory + 2..footer); + accept(file); + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory + 8..directory + 12].copy_from_slice(&u32::MAX.to_le_bytes()); + accept(file); + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory..directory + 2].copy_from_slice(&2u16.to_le_bytes()); + accept(file); + // A zero-length entry cannot mark a payload boundary, even if its offset overlaps pixels. + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory + 4..directory + 8].copy_from_slice(&19u32.to_le_bytes()); + file[directory + 8..directory + 12].copy_from_slice(&0u32.to_le_bytes()); + accept(file); + let mut file = preceding_metadata(true, 2); + file[21..23].copy_from_slice(&[255, 255]); + accept(file); + let mut file = preceding_metadata(true, 2); + let footer = file.len() - SIGNATURE.len() - 8; + let extension = u32::from_le_bytes(file[footer..footer + 4].try_into().unwrap()) as usize; + file[extension..extension + 2].copy_from_slice(&494u16.to_le_bytes()); + accept(file); + let mut file = preceding_metadata(true, 2); + let footer = file.len() - SIGNATURE.len() - 8; + file.remove(footer - 1); // extension is physically short, but its postage offset remains + accept(file); +} + +#[test] +fn malformed_metadata_offsets_inside_id_or_palette_keep_complete_pixels() { + let mut file = header(1, 1, 1, 8, 0x20); + file[0] = 4; // image ID length + file[1] = 1; // colour map present + file[5..7].copy_from_slice(&1u16.to_le_bytes()); + file[7] = 24; // one BGR palette entry + file.extend_from_slice(&[7, 8, 9, 10]); // image ID + file.extend_from_slice(&[0, 0, 255]); // red palette entry + file.push(0); // palette index + for (field, offset) in [(0, HEADER + 1), (4, HEADER + 4 + 1)] { + let mut candidate = file.clone(); + let mut footer_offsets = [0u8; 8]; + footer_offsets[field..field + 4].copy_from_slice(&(offset as u32).to_le_bytes()); + candidate.extend_from_slice(&footer_offsets); + candidate.extend_from_slice(SIGNATURE); + let image = dec(&candidate).unwrap(); + assert_eq!(image.rgba, [255, 0, 0, 255], "footer field {field}"); + } +} + +#[test] +fn malformed_optional_metadata_cannot_supply_missing_pixels() { + let mut file = preceding_metadata(false, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory + 8..directory + 12].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(dec(&file).is_err()); + + // The declared entry count exceeds the bytes before the footer, but the first entry's + // payload still precedes the directory and cannot be used as a second pixel. + let mut file = preceding_metadata(false, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory..directory + 2].copy_from_slice(&2u16.to_le_bytes()); + assert!(dec(&file).is_err()); + + let mut file = preceding_metadata(false, 2); + let footer = file.len() - SIGNATURE.len() - 8; + let extension = u32::from_le_bytes(file[footer..footer + 4].try_into().unwrap()) as usize; + file[extension..extension + 2].copy_from_slice(&494u16.to_le_bytes()); + assert!(dec(&file).is_err()); + let mut file = preceding_metadata(false, 2); + let footer = file.len() - SIGNATURE.len() - 8; + file.remove(footer - 1); + assert!(dec(&file).is_err()); +} + +#[test] +fn valid_developer_directory_with_overlapping_payload_rejects_pixels() { + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory..directory + 2].copy_from_slice(&2u16.to_le_bytes()); + let mut extra = [0u8; 10]; + extra[..2].copy_from_slice(&2u16.to_le_bytes()); + extra[2..6].copy_from_slice(&(HEADER as u32).to_le_bytes()); + extra[6..10].copy_from_slice(&1u32.to_le_bytes()); + file.splice(footer..footer, extra); + let moved_footer = file.len() - SIGNATURE.len() - 8; + assert_eq!(u32::from_le_bytes(file[moved_footer + 4..moved_footer + 8].try_into().unwrap()), directory as u32); + assert_eq!(u16::from_le_bytes(file[directory..directory + 2].try_into().unwrap()), 2); + assert_eq!(&file[directory + 12..directory + 22], &extra); + assert!(dec(&file).is_err()); +} + +#[test] +fn nonempty_developer_reference_inside_pixels_rejects_the_whole_image() { + let mut file = header(2, 2, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255, 0, 255, 0]); + let directory = file.len() as u32; + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&(HEADER as u32 + 3).to_le_bytes()); + file.extend_from_slice(&1u32.to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(&directory.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + assert!(dec(&file).is_err(), "an overlapping reference must not return a partial image"); +} + +#[test] +fn inflated_developer_count_scans_the_next_chunk_as_an_entry_and_rejects_its_pixel_payload() { + // a directory claiming two entries over one real entry: the ten bytes after it, scanned as + // the second entry, name a payload inside the pixels, which is refused like any other + let mut file = header(2, 2, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255, 0, 255, 0]); + let directory = file.len() as u32; + file.extend_from_slice(&2u16.to_le_bytes()); + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&(directory + 22).to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(&2u16.to_le_bytes()); + file.extend_from_slice(&(HEADER as u32 + 3).to_le_bytes()); + file.extend_from_slice(&1u32.to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(&directory.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + assert!(dec(&file).is_err(), "a scanned entry's payload inside the pixels is refused"); +} + +#[test] +fn legacy_pixels_that_end_in_signature_at_or_after_the_header_are_read_as_a_footer() { + // a footerless 36×1 grayscale image whose last 26 bytes happen to be eight zeros and the + // signature: the putative trailer begins at byte 28, so it is taken for a footer and the + // image, left with 10 pixel bytes, is rejected as truncated (the ambiguity the body states) + let prefix = 18usize; + let width = (prefix + SIGNATURE.len()) as u16; + let mut file = header(3, width, 1, 8, 0x20); + file.extend(vec![0; prefix]); + file.extend_from_slice(SIGNATURE); + assert!(dec(&file).is_err()); +} + +#[test] +fn mutated_tga_footer_files_never_panic() { + let mut file = header(2, 2, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255, 0, 255, 0]); + file.extend_from_slice(&[0; 8]); + file.extend_from_slice(SIGNATURE); + for end in 0..file.len() { + assert!(std::panic::catch_unwind(|| dec(&file[..end])).is_ok(), "truncation at {end}"); + } + for at in 0..file.len() { + let mut mutated = file.clone(); + mutated[at] ^= 0xFF; + assert!(std::panic::catch_unwind(|| dec(&mutated)).is_ok(), "mutation at {at}"); + } + for metadata in 0..4 { + let file = preceding_metadata(true, metadata); + assert!(dec(&file).is_ok()); + let footer = file.len() - SIGNATURE.len() - 8; + for end in 0..footer { + let mut truncated = file[..end].to_vec(); + truncated.extend_from_slice(&file[footer..]); + assert!(std::panic::catch_unwind(|| dec(&truncated)).is_ok(), "metadata {metadata}, footer-preserving truncation at {end}"); + } + for at in 0..file.len() { + let mut mutated = file.clone(); + mutated[at] ^= 0xFF; + assert!(std::panic::catch_unwind(|| dec(&mutated)).is_ok(), "metadata {metadata}, mutation at {at}"); + } + } +} diff --git a/crates/tga/src/rgba8_raw.rs b/crates/tga/src/rgba8_raw.rs new file mode 100644 index 0000000000..a671462c90 --- /dev/null +++ b/crates/tga/src/rgba8_raw.rs @@ -0,0 +1,77 @@ +//! Uncompressed RGB(A) output from top-down RGBA8 pixels. +/// Why the supplied frame cannot be encoded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Rgba8EncodeError { + /// Empty, overflowing, or mismatched dimensions. + FrameSize, + /// A dimension cannot fit the 16-bit Targa header. + Dimensions, + /// The output buffer could not be allocated. + OutOfMemory, +} +/// An empty buffer with room for `len` bytes, or [`Rgba8EncodeError::OutOfMemory`] when the +/// allocation fails (instead of aborting the process). +fn output_buffer(len: usize) -> std::result::Result, Rgba8EncodeError> { + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|_| Rgba8EncodeError::OutOfMemory)?; + Ok(out) +} +fn checked_len(rgba: &[u8], w: u32, h: u32) -> std::result::Result { + let n = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or(Rgba8EncodeError::FrameSize)?; + if w == 0 || h == 0 || rgba.len() != n { + return Err(Rgba8EncodeError::FrameSize); + } + Ok(n) +} +/// An uncompressed Targa file: 24-bit BGR, or 32-bit BGRA with `alpha` (straight alpha, as the +/// frame carries it). +pub fn encode_rgba8_raw(rgba: &[u8], w: u32, h: u32, alpha: bool) -> std::result::Result, Rgba8EncodeError> { + checked_len(rgba, w, h)?; + let (tw, th) = match (u16::try_from(w), u16::try_from(h)) { + (Ok(tw), Ok(th)) => (tw, th), + _ => return Err(Rgba8EncodeError::Dimensions), + }; + let bpp: usize = if alpha { 4 } else { 3 }; + let row = w as usize * 4; + // The caller already holds the frame; reserve the second, output-sized buffer fallibly so a + // large export reports an error instead of aborting the process. + let len = (w as usize * h as usize).checked_mul(bpp).and_then(|n| n.checked_add(18 + 26)).ok_or(Rgba8EncodeError::FrameSize)?; + let mut out = output_buffer(len)?; + out.extend_from_slice(&[0, 0, 2]); // no ID, no colour map, uncompressed true-colour + out.extend_from_slice(&[0; 5]); // colour map specification (unused) + out.extend_from_slice(&[0, 0, 0, 0]); // x / y origin + out.extend_from_slice(&tw.to_le_bytes()); + out.extend_from_slice(&th.to_le_bytes()); + out.push(if alpha { 32 } else { 24 }); + out.push(if alpha { 8 } else { 0 }); // attribute bits; bottom-left origin + // bottom-left origin: the last frame row comes first + for line in rgba.chunks_exact(row).rev() { + for &[r, g, b, a] in line.as_chunks::<4>().0 { + out.extend_from_slice(&[b, g, r]); + if alpha { + out.push(a); + } + } + } + // TGA 2.0 footer without extension or developer areas + out.extend_from_slice(&[0; 8]); + out.extend_from_slice(b"TRUEVISION-XFILE.\0"); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn raw_round_trip() { + let bytes = encode_rgba8_raw(&[1, 2, 3, 4], 1, 1, true).unwrap(); + assert_eq!(&bytes[18..22], &[3, 2, 1, 4]); + assert_eq!(&bytes[bytes.len() - 18..], b"TRUEVISION-XFILE.\0"); + assert_eq!(encode_rgba8_raw(&[], 0, 1, false), Err(Rgba8EncodeError::FrameSize)); + } + #[test] + fn a_failed_output_allocation_is_an_error() { + assert_eq!(output_buffer(usize::MAX), Err(Rgba8EncodeError::OutOfMemory)); + assert!(output_buffer(16).is_ok_and(|b| b.is_empty() && b.capacity() >= 16)); + } +} diff --git a/crates/tga/src/tests.rs b/crates/tga/src/tests.rs index 06109a1794..bec6b69726 100644 --- a/crates/tga/src/tests.rs +++ b/crates/tga/src/tests.rs @@ -92,6 +92,11 @@ fn hostile_headers_fail_without_allocating() { 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]); + // The aggregate decoded-storage budget rejects this before any allocation. + assert_eq!(dec(&f), Err(Error::LimitExceeded("decode allocation bytes"))); + // Under budget, an incomplete RLE stream must still fail as truncated. + let mut f = header(10, 16, 16, 32, 0); + f.extend_from_slice(&[0xFF, 1, 2, 3, 4]); // only 128 of 256 pixels 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]); @@ -116,8 +121,8 @@ fn hostile_headers_fail_without_allocating() { 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"))); + assert!(decode(&f, &Limits { max_pixels: 4, ..Limits::default() }).is_ok()); + assert_eq!(decode(&f, &Limits { max_pixels: 3, ..Limits::default() }), Err(Error::LimitExceeded("pixel count"))); } #[test] @@ -235,3 +240,30 @@ fn written_files_read_back() { assert_eq!(r.rgba, want, "{layout:?}"); } } + +#[test] +fn aggregate_decode_budget_applies_before_rle_expansion() { + let mut file = header(10, 16, 16, 32, 0x28); + file.extend_from_slice(&[255, 0, 0, 255, 255, 255, 0, 0, 255, 255]); + let mut limits = Limits { max_decoded_bytes: 2047, ..Limits::default() }; + assert_eq!(decode(&file, &limits), Err(Error::LimitExceeded("decode allocation bytes"))); + limits.max_decoded_bytes = 2048; + assert_eq!(decode(&file, &limits).unwrap().rgba.len(), 1024); +} +#[test] +fn default_budget_rejects_large_rle_header_without_large_fixture() { + let file = header(10, 16384, 16384, 32, 0x28); + assert_eq!(decode(&file, &Limits::default()), Err(Error::LimitExceeded("decode allocation bytes"))); +} +#[test] +fn aggregate_decode_budget_counts_raw_and_palette_storage() { + let mut file = header(1, 1, 1, 8, 0x20); + file[1] = 1; + file[5] = 1; + file[7] = 24; + file.extend_from_slice(&[0, 0, 255, 0]); + let mut limits = Limits { max_decoded_bytes: 8, ..Limits::default() }; + assert_eq!(decode(&file, &limits), Err(Error::LimitExceeded("decode allocation bytes"))); + limits.max_decoded_bytes = 9; + assert_eq!(decode(&file, &limits).unwrap().rgba, [255, 0, 0, 255]); +} diff --git a/crates/tiff/src/classic.rs b/crates/tiff/src/classic.rs new file mode 100644 index 0000000000..c1ab6f64ad --- /dev/null +++ b/crates/tiff/src/classic.rs @@ -0,0 +1,470 @@ +//! The TIFF container (TIFF 6.0 §2, as DNG uses it): byte order, image file directories (IFDs), +//! their entries and values, and the SubIFD tree. +//! +//! Every offset and count comes from the file and is checked before use: an entry whose value lies +//! outside the file is an error when it is read, the walk visits at most [`MAX_IFDS`] directories, +//! never the same one twice (cyclic chains end), and goes at most [`MAX_DEPTH`] SubIFD levels deep. + +use std::collections::HashSet; + +/// Why a classic TIFF directory could not be read. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The input has no supported classic TIFF header. + #[error("not a classic TIFF")] + NotTiff, + /// The directory or a referenced value is invalid. + #[error("{0}")] + Malformed(&'static str), +} +/// Result of the bounded classic TIFF reader. +pub type Result = std::result::Result; + +/// Most IFDs one file may have (main chain and SubIFDs together). +pub const MAX_IFDS: usize = 64; +/// Deepest SubIFD nesting followed. +pub const MAX_DEPTH: usize = 4; +/// Invalid SubIFD edges count too: otherwise a file can make failed offset probes quadratic. +const MAX_IFD_ATTEMPTS: usize = MAX_IFDS * 16; +/// SubIFD references (zero, repeated and invalid ones included) accepted over the whole walk, +/// counted before a list is read: many directories can name the same long SubIFD table. +const MAX_SUB_IFD_REFS: usize = MAX_IFD_ATTEMPTS; + +/// TIFF field types (TIFF 6.0 §2, plus type 13 IFD from TIFF Technical Note 1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Type { + Byte, + Ascii, + Short, + Long, + Rational, + SByte, + Undefined, + SShort, + SLong, + SRational, + Float, + Double, + Ifd, +} + +impl Type { + fn from_code(c: u16) -> Option { + Some(match c { + 1 => Type::Byte, + 2 => Type::Ascii, + 3 => Type::Short, + 4 => Type::Long, + 5 => Type::Rational, + 6 => Type::SByte, + 7 => Type::Undefined, + 8 => Type::SShort, + 9 => Type::SLong, + 10 => Type::SRational, + 11 => Type::Float, + 12 => Type::Double, + 13 => Type::Ifd, + _ => return None, + }) + } + + /// Bytes per value. + pub fn size(self) -> usize { + match self { + Type::Byte | Type::Ascii | Type::SByte | Type::Undefined => 1, + Type::Short | Type::SShort => 2, + Type::Long | Type::SLong | Type::Float | Type::Ifd => 4, + Type::Rational | Type::SRational | Type::Double => 8, + } + } +} + +/// One directory entry. +#[derive(Clone, Copy, Debug)] +pub struct Entry { + pub tag: u16, + pub ty: Type, + pub count: u32, + /// Where the value bytes start: inside the entry when they fit in four bytes, else the offset + /// the entry holds (not yet checked against the file length). + value_at: u64, +} + +/// One image file directory. +#[derive(Clone, Debug, Default)] +pub struct Ifd { + /// File offset of the directory. + pub offset: u64, + pub entries: Vec, + /// Nesting: 0 for the main chain, 1 for its SubIFDs, … + pub depth: usize, +} + +impl Ifd { + pub fn get(&self, tag: u16) -> Option<&Entry> { + self.entries.iter().find(|e| e.tag == tag) + } +} + +/// A TIFF file in memory. +#[derive(Clone, Copy)] +pub struct Tiff<'a> { + pub data: &'a [u8], + pub big_endian: bool, +} + +impl<'a> Tiff<'a> { + /// Read the header. Classic TIFF only (BigTIFF, version 43, is not used by DNG). + pub fn new(data: &'a [u8]) -> Result<(Tiff<'a>, u64)> { + let big_endian = match data.get(0..4) { + Some(b"II*\0") => false, + Some(b"MM\0*") => true, + _ => return Err(Error::NotTiff), + }; + let t = Tiff { data, big_endian }; + let first = u64::from(t.u32_at(4)?); + Ok((t, first)) + } + + fn bytes_at(&self, off: u64, len: usize) -> Result<&'a [u8]> { + let start = usize::try_from(off).map_err(|_| Error::Malformed("offset outside the file"))?; + let end = start.checked_add(len).ok_or(Error::Malformed("offset outside the file"))?; + self.data.get(start..end).ok_or(Error::Malformed("offset outside the file")) + } + + pub fn u16_of(&self, b: [u8; 2]) -> u16 { + if self.big_endian { u16::from_be_bytes(b) } else { u16::from_le_bytes(b) } + } + + pub fn u32_of(&self, b: [u8; 4]) -> u32 { + if self.big_endian { u32::from_be_bytes(b) } else { u32::from_le_bytes(b) } + } + + fn u16_at(&self, off: u64) -> Result { + let b = self.bytes_at(off, 2)?; + Ok(self.u16_of([b[0], b[1]])) + } + + fn u32_at(&self, off: u64) -> Result { + let b = self.bytes_at(off, 4)?; + Ok(self.u32_of([b[0], b[1], b[2], b[3]])) + } + + /// Read the IFD at `off`: its entries and the offset of the next IFD (0 at the end of a chain). + pub fn read_ifd(&self, off: u64, depth: usize) -> Result<(Ifd, u64)> { + let n = self.u16_at(off)?; + let mut entries = Vec::with_capacity(usize::from(n)); + for i in 0..u64::from(n) { + let at = off + 2 + i * 12; + let e = self.bytes_at(at, 12)?; + let tag = self.u16_of([e[0], e[1]]); + let code = self.u16_of([e[2], e[3]]); + let count = self.u32_of([e[4], e[5], e[6], e[7]]); + // unknown field types are skipped (TIFF 6.0: readers ignore them) + let Some(ty) = Type::from_code(code) else { continue }; + let len = u64::from(count).saturating_mul(ty.size() as u64); + let value_at = if len <= 4 { at + 8 } else { u64::from(self.u32_of([e[8], e[9], e[10], e[11]])) }; + entries.push(Entry { tag, ty, count, value_at }); + } + let next = u64::from(self.u32_at(off + 2 + u64::from(n) * 12)?); + Ok((Ifd { offset: off, entries, depth }, next)) + } + + /// Every IFD of the file: the main chain from `first` and, depth first, the SubIFDs (tag 330) of + /// each. Bounded by [`MAX_IFDS`] and [`MAX_DEPTH`]; a directory reached twice ends that branch. + pub fn all_ifds(&self, first: u64) -> Result> { + let mut out: Vec = Vec::new(); + let mut seen = HashSet::new(); + let mut attempts = 0usize; + let mut sub_refs = 0usize; + let mut stack: Vec<(u64, usize)> = vec![(first, 0)]; + while let Some((off, depth)) = stack.pop() { + let mut next = off; + while next != 0 { + if !seen.insert(next) { + break; + } + attempts += 1; + if attempts > MAX_IFD_ATTEMPTS { + return Err(Error::Malformed("too many IFD offsets")); + } + if out.len() >= MAX_IFDS { + return Err(Error::Malformed("too many IFDs")); + } + let (ifd, after) = match self.read_ifd(next, depth) { + Ok(x) => x, + // a broken directory ends the chain; the first one must be readable + Err(e) if out.is_empty() => return Err(e), + Err(_) => break, + }; + if depth < MAX_DEPTH + && let Some(sub) = ifd.get(tags::SUB_IFDS) + { + sub_refs = sub_refs.saturating_add(usize::try_from(sub.count).unwrap_or(usize::MAX)); + if sub_refs > MAX_SUB_IFD_REFS { + return Err(Error::Malformed("too many SubIFD references")); + } + if let Ok(offs) = self.uints(sub) { + for o in offs.into_iter().rev().filter(|o| *o != 0 && !seen.contains(o)) { + stack.push((o, depth + 1)); + } + } + } + out.push(ifd); + next = after; + } + } + Ok(out) + } + + /// The value bytes of an entry. + pub fn value_bytes(&self, e: &Entry) -> Result<&'a [u8]> { + let len = (e.count as usize).checked_mul(e.ty.size()).ok_or(Error::Malformed("entry too large"))?; + self.bytes_at(e.value_at, len) + } + + /// The `i`-th value of a numeric entry as f64 (rationals divided; a zero denominator is an + /// error). + fn number(&self, e: &Entry, b: &[u8], i: usize) -> Result { + let s = e.ty.size(); + let v = b.get(i * s..i * s + s).ok_or(Error::Malformed("entry too short"))?; + let u16v = |o: usize| self.u16_of([v[o], v[o + 1]]); + let u32v = |o: usize| self.u32_of([v[o], v[o + 1], v[o + 2], v[o + 3]]); + Ok(match e.ty { + Type::Byte | Type::Undefined => f64::from(v[0]), + Type::SByte => f64::from(v[0] as i8), + Type::Short => f64::from(u16v(0)), + Type::SShort => f64::from(u16v(0) as i16), + Type::Long | Type::Ifd => f64::from(u32v(0)), + Type::SLong => f64::from(u32v(0) as i32), + Type::Rational => { + let d = u32v(4); + if d == 0 { + return Err(Error::Malformed("rational with a zero denominator")); + } + f64::from(u32v(0)) / f64::from(d) + } + Type::SRational => { + let d = u32v(4) as i32; + if d == 0 { + return Err(Error::Malformed("rational with a zero denominator")); + } + f64::from(u32v(0) as i32) / f64::from(d) + } + Type::Float => f64::from(f32::from_bits(u32v(0))), + Type::Double => { + let mut a = [0u8; 8]; + a.copy_from_slice(&v[..8]); + if self.big_endian { f64::from_be_bytes(a) } else { f64::from_le_bytes(a) } + } + Type::Ascii => return Err(Error::Malformed("text where a number belongs")), + }) + } + + /// All values of a numeric entry as f64. Non-finite values are an error. + pub fn floats(&self, e: &Entry) -> Result> { + let b = self.value_bytes(e)?; + let mut out = Vec::with_capacity(e.count as usize); + for i in 0..e.count as usize { + let v = self.number(e, b, i)?; + if !v.is_finite() { + return Err(Error::Malformed("non-finite number")); + } + out.push(v); + } + Ok(out) + } + + /// All values of an unsigned integer entry (BYTE, SHORT, LONG, IFD). + pub fn uints(&self, e: &Entry) -> Result> { + if !matches!(e.ty, Type::Byte | Type::Undefined | Type::Short | Type::Long | Type::Ifd) { + return Err(Error::Malformed("expected an unsigned integer field")); + } + let b = self.value_bytes(e)?; + let s = e.ty.size(); + Ok(b.chunks_exact(s) + .map(|v| match s { + 1 => u64::from(v[0]), + 2 => u64::from(self.u16_of([v[0], v[1]])), + _ => u64::from(self.u32_of([v[0], v[1], v[2], v[3]])), + }) + .collect()) + } + + /// The first value of an unsigned integer entry. + pub fn uint(&self, e: &Entry) -> Result { + self.uints(e)?.first().copied().ok_or(Error::Malformed("empty field")) + } + + /// An ASCII entry up to its first NUL, lossily decoded. + pub fn ascii(&self, e: &Entry) -> Result { + let b = self.value_bytes(e)?; + let end = b.iter().position(|&c| c == 0).unwrap_or(b.len()); + Ok(String::from_utf8_lossy(&b[..end]).trim().to_string()) + } +} + +/// Tag numbers (TIFF 6.0, TIFF/EP, DNG 1.7, CinemaDNG). +pub mod tags { + pub const NEW_SUBFILE_TYPE: u16 = 254; + pub const IMAGE_WIDTH: u16 = 256; + pub const IMAGE_LENGTH: u16 = 257; + pub const BITS_PER_SAMPLE: u16 = 258; + pub const COMPRESSION: u16 = 259; + pub const PHOTOMETRIC: u16 = 262; + pub const MAKE: u16 = 271; + pub const MODEL: u16 = 272; + pub const STRIP_OFFSETS: u16 = 273; + pub const SAMPLES_PER_PIXEL: u16 = 277; + pub const ROWS_PER_STRIP: u16 = 278; + pub const STRIP_BYTE_COUNTS: u16 = 279; + pub const PLANAR_CONFIGURATION: u16 = 284; + pub const PREDICTOR: u16 = 317; + pub const TILE_WIDTH: u16 = 322; + pub const TILE_LENGTH: u16 = 323; + pub const TILE_OFFSETS: u16 = 324; + pub const TILE_BYTE_COUNTS: u16 = 325; + pub const SUB_IFDS: u16 = 330; + pub const SAMPLE_FORMAT: u16 = 339; + pub const CFA_REPEAT_PATTERN_DIM: u16 = 33421; + pub const CFA_PATTERN: u16 = 33422; + pub const DNG_VERSION: u16 = 50706; + pub const UNIQUE_CAMERA_MODEL: u16 = 50708; + pub const CFA_PLANE_COLOR: u16 = 50710; + pub const CFA_LAYOUT: u16 = 50711; + pub const LINEARIZATION_TABLE: u16 = 50712; + pub const BLACK_LEVEL_REPEAT_DIM: u16 = 50713; + pub const BLACK_LEVEL: u16 = 50714; + pub const BLACK_LEVEL_DELTA_H: u16 = 50715; + pub const BLACK_LEVEL_DELTA_V: u16 = 50716; + pub const WHITE_LEVEL: u16 = 50717; + pub const DEFAULT_CROP_ORIGIN: u16 = 50719; + pub const DEFAULT_CROP_SIZE: u16 = 50720; + pub const COLOR_MATRIX_1: u16 = 50721; + pub const COLOR_MATRIX_2: u16 = 50722; + pub const CAMERA_CALIBRATION_1: u16 = 50723; + pub const CAMERA_CALIBRATION_2: u16 = 50724; + pub const ANALOG_BALANCE: u16 = 50727; + pub const AS_SHOT_NEUTRAL: u16 = 50728; + pub const AS_SHOT_WHITE_XY: u16 = 50729; + pub const BASELINE_EXPOSURE: u16 = 50730; + pub const CALIBRATION_ILLUMINANT_1: u16 = 50778; + pub const CALIBRATION_ILLUMINANT_2: u16 = 50779; + pub const ACTIVE_AREA: u16 = 50829; + pub const OPCODE_LIST_1: u16 = 51008; + pub const OPCODE_LIST_2: u16 = 51009; + pub const OPCODE_LIST_3: u16 = 51022; + pub const FORWARD_MATRIX_1: u16 = 50964; + pub const FORWARD_MATRIX_2: u16 = 50965; + /// CinemaDNG: SMPTE ST 12-1 time codes, 8 bytes each. + pub const TIME_CODES: u16 = 51043; + /// CinemaDNG: frames per second (SRATIONAL). + pub const FRAME_RATE: u16 = 51044; + /// CinemaDNG: the camera's reel name. + pub const REEL_NAME: u16 = 51081; +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A little-endian TIFF: a chain of `ifds` directories, each with one SubIFDs entry of + /// `count` LONGs, all naming the same table (of zeros, or of `target`). + fn chain(ifds: usize, count: u32, target: u32) -> Vec { + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&8u32.to_le_bytes()); + let table = 8 + ifds * 18; + for i in 0..ifds { + let next = if i + 1 < ifds { 8 + (i + 1) * 18 } else { 0 }; + b.extend_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&tags::SUB_IFDS.to_le_bytes()); + b.extend_from_slice(&4u16.to_le_bytes()); + b.extend_from_slice(&count.to_le_bytes()); + b.extend_from_slice(&(table as u32).to_le_bytes()); + b.extend_from_slice(&(next as u32).to_le_bytes()); + } + for _ in 0..count.max(2) { + b.extend_from_slice(&target.to_le_bytes()); + } + b + } + + #[test] + fn shared_sub_ifd_tables_are_budgeted_before_they_are_queued() { + // 60 directories each naming one 100 000-entry table: 6 million queued edges before + let b = chain(60, 100_000, 0); + let (t, first) = Tiff::new(&b).unwrap(); + assert!(matches!(t.all_ifds(first), Err(Error::Malformed("too many SubIFD references")))); + } + + #[test] + fn matches_general_reader_for_a_simple_ifd_chain() { + let bytes = chain(3, 0, 0); + let (reader, first) = Tiff::new(&bytes).unwrap(); + let classic = reader.all_ifds(first).unwrap(); + let general = crate::Tiff::parse(&bytes).unwrap(); + assert_eq!(classic.len(), general.ifds.len()); + assert!(classic.iter().all(|ifd| ifd.get(tags::SUB_IFDS).is_some())); + } + + #[test] + fn ordinary_sub_ifds_are_still_walked() { + // one directory whose SubIFD is the same directory: visited once + let b = chain(1, 1, 8); + let (t, first) = Tiff::new(&b).unwrap(); + assert_eq!(t.all_ifds(first).unwrap().len(), 1); + // a short chain with a few zero SubIFD offsets + let b = chain(3, 4, 0); + let (t, first) = Tiff::new(&b).unwrap(); + assert_eq!(t.all_ifds(first).unwrap().len(), 3); + } + #[test] + fn numeric_field_types_and_malformed_values() { + fn field(code: u16, payload: &[u8]) -> Vec { + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&8u32.to_le_bytes()); + b.extend_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&256u16.to_le_bytes()); + b.extend_from_slice(&code.to_le_bytes()); + b.extend_from_slice(&1u32.to_le_bytes()); + if payload.len() <= 4 { + let mut inline = [0; 4]; + inline[..payload.len()].copy_from_slice(payload); + b.extend_from_slice(&inline); + } else { + b.extend_from_slice(&26u32.to_le_bytes()); + } + b.extend_from_slice(&0u32.to_le_bytes()); + if payload.len() > 4 { + b.extend_from_slice(payload); + } + b + } + let cases: &[(u16, &[u8], f64)] = &[ + (1, &[7], 7.0), + (6, &[255], -1.0), + (3, &[2, 0], 2.0), + (8, &[255, 255], -1.0), + (4, &[3, 0, 0, 0], 3.0), + (9, &[255, 255, 255, 255], -1.0), + (5, &[3, 0, 0, 0, 2, 0, 0, 0], 1.5), + (10, &[253, 255, 255, 255, 2, 0, 0, 0], -1.5), + (11, &1.5_f32.to_le_bytes(), 1.5), + (12, &1.5_f64.to_le_bytes(), 1.5), + ]; + for &(code, data, expected) in cases { + let bytes = field(code, data); + let (t, at) = Tiff::new(&bytes).unwrap(); + let (ifd, _) = t.read_ifd(at, 0).unwrap(); + assert_eq!(t.floats(&ifd.entries[0]).unwrap(), [expected], "type {code}"); + } + let bytes = field(5, &[1, 0, 0, 0, 0, 0, 0, 0]); + let (t, at) = Tiff::new(&bytes).unwrap(); + let (ifd, _) = t.read_ifd(at, 0).unwrap(); + assert!(t.floats(&ifd.entries[0]).is_err()); + let bytes = field(11, &f32::NAN.to_le_bytes()); + let (t, at) = Tiff::new(&bytes).unwrap(); + let (ifd, _) = t.read_ifd(at, 0).unwrap(); + assert!(t.floats(&ifd.entries[0]).is_err()); + } +} diff --git a/crates/tiff/src/lib.rs b/crates/tiff/src/lib.rs index bd095f4f09..5d6d78a213 100644 --- a/crates/tiff/src/lib.rs +++ b/crates/tiff/src/lib.rs @@ -22,9 +22,13 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +/// Bounded classic TIFF directory reader with lazy value access. +pub mod classic; + pub mod image; pub mod makernote; pub mod packbits; +pub mod probe; mod reader; pub mod tags; pub mod writer; diff --git a/crates/tiff/src/probe.rs b/crates/tiff/src/probe.rs new file mode 100644 index 0000000000..9ed4f3bb1e --- /dev/null +++ b/crates/tiff/src/probe.rs @@ -0,0 +1,111 @@ +//! Allocation-free classic TIFF compression inspection. + +/// Return the first image's compression, or 1 when its tag is absent. +/// +/// Only classic TIFF is accepted. A duplicate Compression tag, non-scalar value, +/// unsupported field type, out-of-range LONG, or unreadable required field returns +/// `None`. Duplicate tags are refused rather than choosing one: decoders may use +/// a different copy, bypassing a caller's compression/resource policy. +/// +/// This inspects only compression, not image validity. Unrelated tag payloads, +/// next-IFD pointers and image data are not read. The caller chooses allowed +/// compression values and must still validate/decode the image with its limits. +/// No allocation occurs; at most 65,535 first-directory entries are inspected. +pub fn first_image_compression(bytes: &[u8]) -> Option { + let le = match bytes.get(..4)? { + b"II*\0" => true, + b"MM\0*" => false, + _ => return None, + }; + let u16_at = |at: usize| -> Option { + let b = [*bytes.get(at)?, *bytes.get(at.checked_add(1)?)?]; + Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) + }; + let u32_at = |at: usize| -> Option { + let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?; + Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) + }; + let ifd = usize::try_from(u32_at(4)?).ok()?; + let mut found = None; + for i in 0..usize::from(u16_at(ifd)?) { + let entry = ifd.checked_add(2)?.checked_add(i.checked_mul(12)?)?; + if u16_at(entry)? != 259 { + continue; + } + if found.is_some() || u32_at(entry.checked_add(4)?)? != 1 { + return None; + } + found = Some(match u16_at(entry.checked_add(2)?)? { + 3 => u16_at(entry.checked_add(8)?)?, + 4 => u16::try_from(u32_at(entry.checked_add(8)?)?).ok()?, + _ => return None, + }); + } + Some(found.unwrap_or(1)) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + use crate::ByteOrder; + + fn fixture(order: ByteOrder, entries: &[(u16, u16, u32, u32)]) -> Vec { + let mut bytes = match order { + ByteOrder::Little => b"II*\0".to_vec(), + ByteOrder::Big => b"MM\0*".to_vec(), + }; + order.put_u32(&mut bytes, 8); + order.put_u16(&mut bytes, u16::try_from(entries.len()).unwrap()); + for &(tag, ty, count, value) in entries { + order.put_u16(&mut bytes, tag); + order.put_u16(&mut bytes, ty); + order.put_u32(&mut bytes, count); + if ty == 3 { + order.put_u16(&mut bytes, u16::try_from(value).unwrap()); + order.put_u16(&mut bytes, 0); + } else { + order.put_u32(&mut bytes, value); + } + } + bytes + } + + #[test] + fn both_byte_orders_and_scalar_types() { + for order in [ByteOrder::Little, ByteOrder::Big] { + assert_eq!(first_image_compression(&fixture(order, &[])), Some(1)); + for ty in [3, 4] { + for value in [1, 5, 6, 7, 32773] { + let bytes = fixture(order, &[(259, ty, 1, value)]); + assert_eq!(first_image_compression(&bytes), u16::try_from(value).ok()); + // Every prefix missing a required byte is refused; SHORT padding and + // the next-IFD pointer are intentionally unnecessary for this probe. + let needed = if ty == 3 { 20 } else { 22 }; + for end in 0..needed { + assert_eq!(first_image_compression(&bytes[..end]), None); + } + } + } + } + } + + #[test] + fn ambiguous_compression_is_refused() { + for order in [ByteOrder::Little, ByteOrder::Big] { + for pair in [(1, 7), (7, 1), (1, 1)] { + assert_eq!(first_image_compression(&fixture(order, &[(259, 3, 1, pair.0), (259, 3, 1, pair.1)])), None); + } + for entry in [(259, 3, 0, 1), (259, 3, 2, 1), (259, 1, 1, 1), (259, 4, 1, 65536)] { + assert_eq!(first_image_compression(&fixture(order, &[entry])), None); + } + // Unrelated values are not decoded or allocated, including unknown types. + assert_eq!(first_image_compression(&fixture(order, &[(999, 65535, u32::MAX, u32::MAX)])), Some(1)); + let mut absent = fixture(order, &[(999, 4, 1, 0)]); + absent.truncate(12); // Only the unrelated tag is needed, matching Word's probe. + assert_eq!(first_image_compression(&absent), Some(1)); + } + assert_eq!(first_image_compression(b"II+\0\x08\0\0\0"), None); + assert_eq!(first_image_compression(b"II*\0\xff\xff\xff\xff"), None); + } +} diff --git a/crates/tiff/src/ycbcr.rs b/crates/tiff/src/ycbcr.rs index a0b7e7dde8..38e8d7c9b4 100644 --- a/crates/tiff/src/ycbcr.rs +++ b/crates/tiff/src/ycbcr.rs @@ -199,6 +199,103 @@ pub fn expand_units(units: &[u8], width: u32, height: u32, (h, v): (u32, u32)) - /// uncompressed or PackBits; anything else is [`TiffError::Invalid`]. More than `max_pixels` /// pixels is [`TiffError::Limit`], and a file too small to hold the image is refused before the data units are allocated. pub fn decode_rgb8(data: &[u8], ifd: &Ifd, max_pixels: u64) -> crate::Result> { + let DecodedUnits { width, height, sub, units } = decode_units(data, ifd, max_pixels)?; + let mut rgb = expand_units(&units, width, height, sub).ok_or_else(|| TiffError::Invalid("YCbCr image: data units".into()))?; + YCbCr::from_ifd(ifd, 255).convert_u8(&mut rgb, 3); + Ok(rgb) +} + +/// Colour interpretation for direct RGBA decoding. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ColorPolicy { + /// Existing shared/libtiff conversion; unusable colour tags use defaults. + Libtiff, + /// Literal TIFF 6.0 green equation, with malformed colour tags rejected. + /// Retains the historical FilmCraft interpretation, including non-unit-sum weights. + TiffEquation, +} + +/// Decode directly into opaque RGBA without an intermediate RGB image. +/// Uses the same strip/subsampling/PackBits validation as [`decode_rgb8`]. +/// Output allocation is checked and fallible. Orientation is left to the caller. +pub fn decode_rgba8(data: &[u8], ifd: &Ifd, max_pixels: u64, policy: ColorPolicy) -> crate::Result> { + let color = match policy { + ColorPolicy::Libtiff => YCbCr::from_ifd(ifd, 255), + ColorPolicy::TiffEquation => strict_color(ifd)?, + }; + let DecodedUnits { width, height, sub: (sh, sv), units } = decode_units(data, ifd, max_pixels)?; + let len = u64::from(width) + .checked_mul(u64::from(height)) + .and_then(|n| n.checked_mul(4)) + .filter(|&n| n <= isize::MAX as u64) + .and_then(|n| usize::try_from(n).ok()) + .ok_or(TiffError::Limit("pixel count"))?; + let mut rgba = Vec::new(); + rgba.try_reserve_exact(len).map_err(|_| TiffError::Limit("memory"))?; + rgba.resize(len, 255); + let (w, h, sh, sv) = (width as usize, height as usize, sh as usize, sv as usize); + let units_x = w.div_ceil(sh); + let tables = (policy == ColorPolicy::Libtiff).then(|| color.tables(255)); + for (i, unit) in units.chunks_exact(sh * sv + 2).enumerate() { + let (ux, uy) = (i % units_x, i / units_x); + let (luma, chroma) = unit.split_at(sh * sv); + let [cb, cr] = <[u8; 2]>::try_from(chroma).map_err(|_| TiffError::Invalid("YCbCr data unit".into()))?; + for (k, &y) in luma.iter().enumerate() { + let (x, row) = (ux * sh + k % sh, uy * sv + k / sh); + if x < w && row < h { + let rgb = match &tables { + Some(t) => t.rgb(usize::from(y), usize::from(cb), usize::from(cr)).map(|v| v as u8), + None => tiff_rgb(&color, y, cb, cr), + }; + let at = (row * w + x) * 4; + if let Some(px) = rgba.get_mut(at..at + 3) { + px.copy_from_slice(&rgb); + } + } + } + } + Ok(rgba) +} + +fn strict_color(ifd: &Ifd) -> crate::Result { + let defaults = YCbCr::defaults(255); + let luma = match ifd.f64s(YCBCR_COEFFICIENTS) { + None => defaults.luma, + Some(v) => v.get(..3).and_then(|v| v.try_into().ok()).ok_or_else(|| TiffError::Invalid("invalid YCbCrCoefficients".into()))?, + }; + let reference_black_white = match ifd.f64s(REFERENCE_BLACK_WHITE) { + None => defaults.reference_black_white, + Some(v) => v.get(..6).and_then(|v| v.try_into().ok()).ok_or_else(|| TiffError::Invalid("invalid ReferenceBlackWhite".into()))?, + }; + if luma.iter().any(|v| !v.is_finite()) || luma[1].abs() < 1e-6 { + return Err(TiffError::Invalid("invalid YCbCrCoefficients".into())); + } + if reference_black_white.iter().any(|v| !v.is_finite()) || reference_black_white.as_chunks::<2>().0.iter().any(|[b, w]| (w - b).abs() < 1e-6) { + return Err(TiffError::Invalid("invalid ReferenceBlackWhite".into())); + } + Ok(YCbCr { luma, reference_black_white }) +} + +fn tiff_rgb(color: &YCbCr, y: u8, cb: u8, cr: u8) -> [u8; 3] { + let [lr, lg, lb] = color.luma; + let [yb, yw, cbb, cbw, crb, crw] = color.reference_black_white; + let y = (f64::from(y) - yb) * 255.0 / (yw - yb); + let cb = (f64::from(cb) - cbb) * 127.0 / (cbw - cbb); + let cr = (f64::from(cr) - crb) * 127.0 / (crw - crb); + let r = cr * (2.0 - 2.0 * lr) + y; + let b = cb * (2.0 - 2.0 * lb) + y; + let g = (y - lb * b - lr * r) / lg; + [r, g, b].map(|v| v.round().clamp(0.0, 255.0) as u8) +} + +struct DecodedUnits { + width: u32, + height: u32, + sub: (u32, u32), + units: Vec, +} + +fn decode_units(data: &[u8], ifd: &Ifd, max_pixels: u64) -> crate::Result { // TiffError has no "unsupported" variant; adding one would break exhaustive matches downstream. let unsupported = |what: &str| TiffError::Invalid(format!("unsupported YCbCr image with {what}")); let invalid = |what: &str| TiffError::Invalid(format!("YCbCr image: {what}")); @@ -265,7 +362,5 @@ pub fn decode_rgb8(data: &[u8], ifd: &Ifd, max_pixels: u64) -> crate::Result = rgb.as_chunks::<3>().0.iter().flat_map(|px| [px[0], px[1], px[2], 255]).collect(); + for policy in [ycbcr::ColorPolicy::Libtiff, ycbcr::ColorPolicy::TiffEquation] { + assert_eq!(ycbcr::decode_rgba8(&bytes, &t.ifds[0], 15, policy).unwrap(), expected); + assert_eq!(ycbcr::decode_rgba8(&bytes, &t.ifds[0], 14, policy), Err(TiffError::Limit("pixel count"))); + } + } + } + } +} + +#[test] +fn explicit_tiff_policy_keeps_literal_green_equation_and_rejects_bad_tags() { + use ycbcr::ColorPolicy::{Libtiff, TiffEquation}; + let run = |extra: &[(u16, Value)], policy| { + let bytes = file(1, 1, (1, 1), &[128, 128, 128], false, extra); + let t = Tiff::parse(&bytes).unwrap(); + ycbcr::decode_rgba8(&bytes, &t.ifds[0], 1, policy) + }; + let weights = [(YCBCR_COEFFICIENTS, Value::Rational(vec![(4, 10); 3]))]; + assert_eq!(run(&weights, Libtiff).unwrap(), [128, 128, 128, 255]); + assert_eq!(run(&weights, TiffEquation).unwrap(), [128, 64, 128, 255]); + for bad in [ + (YCBCR_COEFFICIENTS, Value::Rational(vec![(1, 2)])), + (YCBCR_COEFFICIENTS, Value::Double(vec![0.3, 0.0, 0.7])), + (YCBCR_COEFFICIENTS, Value::Double(vec![f64::NAN, 0.5, 0.5])), + (REFERENCE_BLACK_WHITE, Value::Rational(vec![(0, 1); 6])), + (REFERENCE_BLACK_WHITE, Value::Double(vec![0.0, 255.0])), + ] { + assert!(matches!(run(std::slice::from_ref(&bad), TiffEquation), Err(TiffError::Invalid(_)))); + assert!(run(&[bad], Libtiff).is_ok()); + } +} diff --git a/crates/timeline/src/build.rs b/crates/timeline/src/build.rs index 597040de6d..d82e8b5773 100644 --- a/crates/timeline/src/build.rs +++ b/crates/timeline/src/build.rs @@ -34,26 +34,36 @@ impl Imported { /// above [`crate::rate::MAX_RATE`] per second and start timecodes beyond [`MAX_START_TIMECODE`] /// frames. Every importer ends with this pass, so no format can let such a number through. pub fn bound(&mut self, report: &mut Report) { + self.bound_with_report_limit(report, None); + } + /// Apply numeric bounds with an optional limit on distinct warning messages. + pub fn bound_with_report_limit(&mut self, report: &mut Report, limit: Option) { for item in self.project.items.values_mut() { let name = item.name.clone(); if let Some(seq) = item.as_sequence_mut() { if !plausible_rate(seq.settings.frame_rate) { - report.warn(format!("sequence \"{name}\" has an implausible frame rate ({}); the default was used", seq.settings.frame_rate)); + report.warn_limited( + limit, + format!("sequence \"{name}\" has an implausible frame rate ({}); the default was used", seq.settings.frame_rate), + ); seq.settings.frame_rate = FrameRate::default(); } if seq.start_timecode.unsigned_abs() > MAX_START_TIMECODE { - report.warn(format!("sequence \"{name}\" has an out-of-range start timecode ({} frames); it starts at 0", seq.start_timecode)); + report.warn_limited( + limit, + format!("sequence \"{name}\" has an out-of-range start timecode ({} frames); it starts at 0", seq.start_timecode), + ); seq.start_timecode = 0; } } else if let Some(media) = item.as_media_mut() { if let Some(v) = media.info.video.as_mut() && !plausible_rate(v.frame_rate) { - report.warn(format!("media \"{name}\" has an implausible frame rate ({}); the default was used", v.frame_rate)); + report.warn_limited(limit, format!("media \"{name}\" has an implausible frame rate ({}); the default was used", v.frame_rate)); v.frame_rate = FrameRate::default(); } if media.info.start_timecode.is_some_and(|tc| tc.unsigned_abs() > MAX_START_TIMECODE) { - report.warn(format!("media \"{name}\" has an out-of-range start timecode; it was ignored")); + report.warn_limited(limit, format!("media \"{name}\" has an out-of-range start timecode; it was ignored")); media.info.start_timecode = None; } } diff --git a/crates/timeline/src/edl.rs b/crates/timeline/src/edl.rs index 84251fece0..02970785db 100644 --- a/crates/timeline/src/edl.rs +++ b/crates/timeline/src/edl.rs @@ -156,6 +156,10 @@ pub struct Edl { /// Read a list. Never fails: lines that cannot be read are named in `report` and skipped. pub fn parse(text: &str, report: &mut Report) -> Edl { + parse_with_report_limit(text, report, None) +} +/// Parse an EDL with an optional limit on distinct warning messages. +pub fn parse_with_report_limit(text: &str, report: &mut Report, report_limit: Option) -> Edl { let mut p = Edl { title: None, events: Vec::new(), any_df: false, max_ff: 0 }; let mut df = false; let mut skip_metadata = false; @@ -224,7 +228,7 @@ pub fn parse(text: &str, report: &mut Report) -> Edl { if (1..=99).contains(&n) { extra.push(Channel::A(n)); } else { - report.warn(format!("EDL AUD channel {n} is outside 1..99; ignored")); + report.warn_limited(report_limit, format!("EDL AUD channel {n} is outside 1..99; ignored")); } } if let Some(line) = p.events.last_mut().and_then(|e| e.lines.last_mut()) { @@ -233,7 +237,7 @@ pub fn parse(text: &str, report: &mut Report) -> Edl { continue; } if upper.starts_with("SPLIT:") { - report.warn("EDL split (L-cut/J-cut) lines are not supported; the split was ignored"); + report.warn_limited(report_limit, "EDL split (L-cut/J-cut) lines are not supported; the split was ignored"); continue; } if let Some(line) = parse_event_line(l) { @@ -256,7 +260,7 @@ pub fn parse(text: &str, report: &mut Report) -> Edl { // Comments and auxiliary lines after a rejected event do not belong to the previous one. skip_metadata = true; } - report.warn(format!("unrecognised EDL line ignored: {}", l.chars().take(60).collect::())); + report.warn_limited(report_limit, format!("unrecognised EDL line ignored: {}", l.chars().take(60).collect::())); } p } @@ -586,3 +590,20 @@ M2 A001 -012.0 00;00;00;00\n\ assert_eq!(channel_name(Channel::A(7)), "A7"); } } + +#[cfg(test)] +mod report_limit_tests { + use super::*; + + #[test] + fn caps_distinct_unrecognized_lines_without_changing_default() { + let text = (0..10).map(|i| format!("unrecognized-{i}\n")).collect::(); + let mut limited = Report::default(); + let _ = parse_with_report_limit(&text, &mut limited, Some(2)); + assert_eq!(limited.entries.len(), 3); + assert!(limited.mentions("further diagnostics omitted")); + let mut ordinary = Report::default(); + let _ = parse(&text, &mut ordinary); + assert_eq!(ordinary.entries.len(), 10); + } +} diff --git a/crates/timeline/src/fcp7.rs b/crates/timeline/src/fcp7.rs index 41243baf65..b528e43c48 100644 --- a/crates/timeline/src/fcp7.rs +++ b/crates/timeline/src/fcp7.rs @@ -69,7 +69,7 @@ const BLEND_XML: &[(&str, u32)] = &[ /// The generator of a `generatoritem`: an application's own payload (`:` as /// the effect id), one of the generators every editor has by name, or one the catalog knows. -fn generator_from(name: &str, id: &str, opts: &ImportOptions, report: &mut Report) -> Generator { +fn generator_from(name: &str, id: &str, opts: &ImportOptions, report: &mut Report, limit: Option) -> Generator { if let Some(data) = id.strip_prefix(opts.namespace).and_then(|rest| rest.strip_prefix(':')) && !opts.namespace.is_empty() { @@ -85,7 +85,7 @@ fn generator_from(name: &str, id: &str, opts: &ImportOptions, report: &mut Repor if let Some(g) = opts.catalog.generator_by_name(n) { return g; } - report.warn(format!("generator \"{name}\" is not supported; imported as Black Video")); + report.warn_limited(limit, format!("generator \"{name}\" is not supported; imported as Black Video")); Generator::BlackVideo } } @@ -117,15 +117,22 @@ struct PendingLink { refs: Vec, } +const MAX_NESTING_DEPTH: usize = 64; +const MAX_REIMPORTS: usize = 4096; + struct Imp<'a, 'c, 'r> { b: Builder<'c>, opts: &'a ImportOptions<'a>, report: &'r mut Report, + report_limit: Option, files: HashMap>, seq_defs: HashMap>, file_items: HashMap, seq_items: HashMap, in_progress: HashSet, + depth_hits: usize, + truncated_at: HashMap, + reimports_left: usize, links: Vec, xml_clip_ids: HashMap<(ItemId, String), ClipId>, /// `(sequence key, file key)` pairs where some audio clip item of that file uses `sourcetrack/trackindex` > 1, @@ -154,6 +161,10 @@ fn node_key(n: Node) -> String { /// Read an `xmeml` document. Media paths are resolved against `opts.base_dir`; effects the format /// does not name itself are looked up in `opts.catalog`. What cannot be represented is in `report`. pub fn import(text_in: &str, opts: &ImportOptions, report: &mut Report) -> Result { + import_with_report_limit(text_in, opts, report, None) +} +/// Read FCP7 XML with an optional distinct-diagnostic limit. +pub fn import_with_report_limit(text_in: &str, opts: &ImportOptions, report: &mut Report, report_limit: Option) -> Result { let doc = crate::xml::parse(text_in).map_err(|e| Error::parse(Format::Fcp7Xml, e))?; let root = Node(&doc); if root.name() != "xmeml" { @@ -163,7 +174,7 @@ pub fn import(text_in: &str, opts: &ImportOptions, report: &mut Report) -> Resul .descendants() .any(|n| n.has_tag_name("timebase") && n.text().and_then(|t| t.trim().parse::().ok()).is_some_and(|tb| tb > MAX_RATE as f64)) { - report.warn(format!("a timebase above {MAX_RATE} per second is not a frame rate; it was limited to {MAX_RATE}")); + report.warn_limited(report_limit, format!("a timebase above {MAX_RATE} per second is not a frame rate; it was limited to {MAX_RATE}")); } let mut imp = Imp { b: Builder::new( @@ -172,11 +183,15 @@ pub fn import(text_in: &str, opts: &ImportOptions, report: &mut Report) -> Resul ), opts, report, + report_limit, files: HashMap::new(), seq_defs: HashMap::new(), file_items: HashMap::new(), seq_items: HashMap::new(), in_progress: HashSet::new(), + depth_hits: 0, + truncated_at: HashMap::new(), + reimports_left: MAX_REIMPORTS, links: Vec::new(), xml_clip_ids: HashMap::new(), split_files: HashSet::new(), @@ -215,7 +230,7 @@ pub fn import(text_in: &str, opts: &ImportOptions, report: &mut Report) -> Resul return Err(Error::Empty); } let mut imported = imp.b.finish(); - imported.bound(report); + imported.bound_with_report_limit(report, report_limit); Ok(imported) } @@ -333,7 +348,7 @@ impl<'a> Imp<'a, '_, '_> { self.b.file_media(&format!("file:{p}"), &name, &p, &spec, bin) } None => { - self.report.warn(format!("file \"{name}\" has no pathurl; imported offline")); + self.report.warn_limited(self.report_limit, format!("file \"{name}\" has no pathurl; imported offline")); let p = resolve_path(&name, self.opts.base_dir); let id = self.b.file_media(&format!("fileid:{key}"), &name, &p, &spec, bin); if let Some(m) = self.b.p.item_mut(id).and_then(|i| i.as_media_mut()) { @@ -349,12 +364,29 @@ impl<'a> Imp<'a, '_, '_> { /// Sequence item for a `` element (definition or reference). fn sequence(&mut self, n: Node<'a>, bin: Option) -> Option { let key = node_key(n); + let depth = self.in_progress.len(); + let mut again = None; if let Some(id) = self.seq_items.get(&key) { - return Some(*id); + let shallower = self.truncated_at.get(&key).is_some_and(|d| depth < *d) && !self.in_progress.contains(&key); + if !shallower { + return Some(*id); + } + if self.reimports_left == 0 { + self.report.warn_limited(self.report_limit, "truncated nested sequence kept incomplete after the re-import limit was reached"); + return Some(*id); + } + self.reimports_left -= 1; + again = Some(*id); } let def = if child(n, "media").is_some() { n } else { *self.seq_defs.get(&key)? }; + if depth >= MAX_NESTING_DEPTH { + self.depth_hits += 1; + self.report.warn_limited(self.report_limit, "nested sequence is nested too deeply; imported as a gap"); + return None; + } + let hits_before = self.depth_hits; if !self.in_progress.insert(key.clone()) { - self.report.warn("recursive nested sequence ignored"); + self.report.warn_limited(self.report_limit, "recursive nested sequence ignored"); return None; } let name = child_text(def, "name").unwrap_or("Sequence").to_string(); @@ -374,12 +406,18 @@ impl<'a> Imp<'a, '_, '_> { { settings.sample_rate = sr as u32; } - let id = self.b.reserve_sequence(&name, settings.clone(), bin); - if let Some(l) = path_text(def, &["labels", "label2"]).and_then(label_from) - && let Some(it) = self.b.p.item_mut(id) - { - it.label = l; - } + let id = match again { + Some(id) => id, + None => { + let id = self.b.reserve_sequence(&name, settings.clone(), bin); + if let Some(l) = path_text(def, &["labels", "label2"]).and_then(label_from) + && let Some(it) = self.b.p.item_mut(id) + { + it.label = l; + } + id + } + }; self.seq_items.insert(key.clone(), id); let mut seq = empty_sequence(settings); seq.start_timecode = tc.and_then(|t| child_i64(t, "frame")).unwrap_or(0); @@ -389,7 +427,7 @@ impl<'a> Imp<'a, '_, '_> { let Some(m) = media.and_then(|m| child(m, tag)) else { continue }; for (ti, tn) in children(m, "track").enumerate() { if !self.b.ensure_tracks(&mut seq, kind, ti + 1) { - self.report.warn(format!("FCP7 {kind:?} tracks beyond {MAX_IMPORTED_TRACKS} were skipped")); + self.report.warn_limited(self.report_limit, format!("FCP7 {kind:?} tracks beyond {MAX_IMPORTED_TRACKS} were skipped")); break; } self.track(&mut seq, id, kind, ti, tn, TrackFormat { rate, frame: (w, h) }); @@ -403,6 +441,11 @@ impl<'a> Imp<'a, '_, '_> { } self.b.put_sequence(id, seq); self.in_progress.remove(&key); + if self.depth_hits > hits_before { + self.truncated_at.insert(key, depth); + } else { + self.truncated_at.remove(&key); + } Some(id) } @@ -425,10 +468,13 @@ impl<'a> Imp<'a, '_, '_> { } let t = &mut seq.tracks_mut(kind)[ti]; if t.items.iter().any(|o| o.start < ti_item.end() && ti_item.start < o.end()) { - self.report.warn("overlapping clip items on one track; the later one was moved to a new track"); + self.report + .warn_limited(self.report_limit, "overlapping clip items on one track; the later one was moved to a new track"); if self.b.place(seq, kind, ti + 1, ti_item).is_none() { - self.report - .warn(format!("FCP7 {kind:?} track exceeds the {MAX_IMPORTED_TRACKS}-track import limit; clip was skipped")); + self.report.warn_limited( + self.report_limit, + format!("FCP7 {kind:?} track exceeds the {MAX_IMPORTED_TRACKS}-track import limit; clip was skipped"), + ); } } else { t.items.push(ti_item); @@ -470,7 +516,7 @@ impl<'a> Imp<'a, '_, '_> { (seq_rate.tick_of(end) - d, d) } (false, false) => { - self.report.warn(format!("clip \"{name}\" has neither start nor end; skipped")); + self.report.warn_limited(self.report_limit, format!("clip \"{name}\" has neither start nor end; skipped")); return None; } }; @@ -495,7 +541,7 @@ impl<'a> Imp<'a, '_, '_> { match BLEND_XML.iter().find(|(n, _)| n.eq_ignore_ascii_case(mode)) { Some((_, v)) if *v != 0 => set_param(self.b.catalog, &mut ti, "opacity", "blend", Param::new(ParamValue::Choice(*v))), Some(_) => {} - None => self.report.warn(format!("composite mode \"{mode}\" is not supported")), + None => self.report.warn_limited(self.report_limit, format!("composite mode \"{mode}\" is not supported")), } } ti.markers = read_markers(c, rate, &mut self.b); @@ -512,7 +558,7 @@ impl<'a> Imp<'a, '_, '_> { let eff = child(c, "effect"); let gname = eff.and_then(|e| child_text(e, "name")).unwrap_or(name).to_string(); let gid = eff.and_then(|e| child_text(e, "effectid")).unwrap_or("").to_string(); - let mut g = generator_from(&gname, &gid, self.opts, self.report); + let mut g = generator_from(&gname, &gid, self.opts, self.report, self.report_limit); if let (Generator::ColorMatte { color }, Some(e)) = (&mut g, eff) && let Some(v) = e.descendants().find(|d| d.has_tag_name("value") && child(*d, "red").is_some()) { @@ -526,14 +572,24 @@ impl<'a> Imp<'a, '_, '_> { match self.file(f, Some(name), None) { Some(item) => Some(item), None => { - self.report.warn(format!("clip \"{name}\" refers to a file the document does not define; skipped")); + self.report.warn_limited(self.report_limit, format!("clip \"{name}\" refers to a file the document does not define; skipped")); None } } } else if let Some(s) = child(c, "sequence") { - self.sequence(s, None) + if let Some(id) = self.sequence(s, None) { + return Some(id); + } + self.report.warn_limited(self.report_limit, format!("clip \"{name}\" refers to a nested sequence that was left out; imported offline")); + Some(self.offline_media(kind, seq_rate, frame, name)) } else { - self.report.warn(format!("clip \"{name}\" has no media reference; imported offline")); + self.report.warn_limited(self.report_limit, format!("clip \"{name}\" has no media reference; imported offline")); + Some(self.offline_media(kind, seq_rate, frame, name)) + } + } + + fn offline_media(&mut self, kind: TrackKind, seq_rate: FrameRate, frame: (u32, u32), name: &str) -> ItemId { + { let spec = MediaSpec { video: (kind == TrackKind::Video).then_some((frame.0, frame.1, seq_rate)), audio: (kind == TrackKind::Audio).then_some((48_000, 2)), @@ -545,7 +601,7 @@ impl<'a> Imp<'a, '_, '_> { if let Some(m) = self.b.p.item_mut(id).and_then(|i| i.as_media_mut()) { m.offline = true; } - Some(id) + id } } @@ -565,12 +621,16 @@ impl<'a> Imp<'a, '_, '_> { remap.reverse |= v < 0.0; } if child(p, "keyframe").is_some() { - self.report.warn("variable speed (time remap keyframes) is not supported; a constant speed was used"); + self.report.warn_limited( + self.report_limit, + "variable speed (time remap keyframes) is not supported; a constant speed was used", + ); } } Some("reverse") => remap.reverse |= child_bool(p, "value").unwrap_or(false), Some("variablespeed") if child_bool(p, "value") == Some(true) || child_f64(p, "value").is_some_and(|v| v != 0.0) => { - self.report.warn("variable speed (time remap keyframes) is not supported; a constant speed was used"); + self.report + .warn_limited(self.report_limit, "variable speed (time remap keyframes) is not supported; a constant speed was used"); } _ => {} } @@ -671,7 +731,7 @@ impl<'a> Imp<'a, '_, '_> { let catalog = self.b.catalog; let def = catalog.effect(id).filter(|d| !d.intrinsic).or_else(|| catalog.effect_by_name(name).filter(|d| !d.intrinsic)); let Some(def) = def else { - self.report.warn(format!("effect \"{name}\" is not supported and was skipped")); + self.report.warn_limited(self.report_limit, format!("effect \"{name}\" is not supported and was skipped")); return; }; let mut inst = def.instance(); @@ -703,7 +763,13 @@ impl<'a> Imp<'a, '_, '_> { } let eff = child(c, "effect"); let name = eff.and_then(|x| child_text(x, "name")).or_else(|| eff.and_then(|x| child_text(x, "effectid"))).unwrap_or("Cross Dissolve"); - let effect = transition_effect(self.b.catalog, name, kind == TrackKind::Audio, self.report); + let mut temporary = Report::default(); + let effect = transition_effect(self.b.catalog, name, kind == TrackKind::Audio, &mut temporary); + for e in temporary.entries { + for _ in 0..e.count { + self.report.warn_limited(self.report_limit, &e.message); + } + } let align_s = child_text(c, "alignment").unwrap_or("").to_ascii_lowercase(); let track = &mut seq.tracks_mut(kind)[ti]; let (mut from, mut to) = (None, None); @@ -724,7 +790,7 @@ impl<'a> Imp<'a, '_, '_> { } } if from.is_none() && to.is_none() { - self.report.warn(format!("transition \"{name}\" at frame {start} has no adjacent clip; skipped")); + self.report.warn_limited(self.report_limit, format!("transition \"{name}\" at frame {start} has no adjacent clip; skipped")); return; } let cut = from.map(|f| f.1).or(to.map(|t| t.1)).unwrap_or(s); @@ -864,6 +930,7 @@ struct Exp<'a, 'r> { p: &'a Project, opts: &'a ExportOptions<'a>, report: &'r mut Report, + report_limit: Option, w: XmlWriter, file_ids: HashMap, seq_ids: HashMap, @@ -874,11 +941,22 @@ struct Exp<'a, 'r> { } pub fn export(p: &Project, seq_id: ItemId, opts: &ExportOptions, report: &mut Report) -> Result { + export_with_report_limit(p, seq_id, opts, report, None) +} +/// Write FCP7 XML with an optional distinct-diagnostic limit. +pub fn export_with_report_limit( + p: &Project, + seq_id: ItemId, + opts: &ExportOptions, + report: &mut Report, + report_limit: Option, +) -> Result { p.sequence(seq_id).ok_or(Error::NoSequence(seq_id))?; let mut x = Exp { p, opts, report, + report_limit, w: XmlWriter::new(Some("xmeml")), file_ids: HashMap::new(), seq_ids: HashMap::new(), @@ -953,11 +1031,11 @@ impl Exp<'_, '_> { } // Each clip lists every member of its group, so a group of n clips writes n * n links. if let Some(n) = link_members.values().map(Vec::len).filter(|&n| n > MAX_LINK_MEMBERS).max() { - self.report.warn(format!("a link group of {n} clips was exported with its first {MAX_LINK_MEMBERS} members")); + self.report.warn_limited(self.report_limit, format!("a link group of {n} clips was exported with its first {MAX_LINK_MEMBERS} members")); link_members.values_mut().for_each(|m| m.truncate(MAX_LINK_MEMBERS)); } if seq.all_tracks().any(|t| t.items.iter().any(|i| i.group.is_some())) { - self.report.info("clip groups have no FCP7 XML equivalent and were not exported"); + self.report.info_limited(self.report_limit, "clip groups have no FCP7 XML equivalent and were not exported"); } for kind in [TrackKind::Video, TrackKind::Audio] { let tag = if kind == TrackKind::Video { "video" } else { "audio" }; @@ -1014,7 +1092,7 @@ impl Exp<'_, '_> { fn write_transition(&mut self, tr: &Transition, kind: TrackKind, rate: FrameRate, t: &crate::model::Track) { if !on_frame(rate, tr.start) || !on_frame(rate, tr.duration) { - self.report.warn("sub-frame transition positions were rounded to frames"); + self.report.warn_limited(self.report_limit, "sub-frame transition positions were rounded to frames"); } let align = match (tr.from, tr.to, tr.align) { (None, Some(_), _) => "start-black", @@ -1100,12 +1178,13 @@ impl Exp<'_, '_> { fn write_clip(&mut self, c: &TrackItem, kind: TrackKind, seq: &Sequence, xid: &str, links: &[(String, TrackKind, usize, usize)]) { let rate = seq.settings.frame_rate; if !on_frame(rate, c.start) || !on_frame(rate, c.duration) { - self.report.warn("sub-frame clip positions were rounded to frames"); + self.report.warn_limited(self.report_limit, "sub-frame clip positions were rounded to frames"); } if let Some(clip) = crate::build::uncarried_clip(self.p, c, rate) { - self.report.warn(format!( - "{clip} has no Final Cut Pro 7 XML equivalent: it is written as a clip item without media and is not read back on import" - )); + self.report.warn_limited( + self.report_limit, + format!("{clip} has no Final Cut Pro 7 XML equivalent: it is written as a clip item without media and is not read back on import"), + ); } let base = base_item(self.p, c.item); let generator = crate::build::generator_of(self.p, base).cloned(); @@ -1151,7 +1230,7 @@ impl Exp<'_, '_> { if let Some(blend) = param(c, "opacity", "blend").and_then(|p| p.value.as_f64()).map(|v| v as u32).filter(|v| *v != 0) { match BLEND_XML.iter().find(|(_, v)| *v == blend) { Some((n, _)) => self.w.text("compositemode", n), - None => self.report.warn("blend mode not representable in FCP7 XML; Normal used"), + None => self.report.warn_limited(self.report_limit, "blend mode not representable in FCP7 XML; Normal used"), } } self.write_filters(c, kind, seq, base); @@ -1197,7 +1276,8 @@ impl Exp<'_, '_> { self.w.text("effectid", g.label()); } Generator::Other { name, data } => { - self.report.info(format!("generator \"{name}\" is written with an effect id only {} reads", self.opts.namespace)); + self.report + .info_limited(self.report_limit, format!("generator \"{name}\" is written with an effect id only {} reads", self.opts.namespace)); self.w.text("name", name); self.w.text("effectid", format!("{}:{data}", self.opts.namespace)); } @@ -1276,7 +1356,7 @@ impl Exp<'_, '_> { if param_modified(self.opts.catalog, c, "motion", "scale_width") || param(c, "motion", "uniform_scale").and_then(|p| p.value.as_bool()) == Some(false) { - self.report.warn("non-uniform scale is not supported by FCP7 Basic Motion; uniform scale written"); + self.report.warn_limited(self.report_limit, "non-uniform scale is not supported by FCP7 Basic Motion; uniform scale written"); } let enabled = c.effect("motion").is_none_or(|e| e.enabled); self.open_effect("Basic Motion", "basic", "motion", "motion", "video", enabled); @@ -1323,7 +1403,7 @@ impl Exp<'_, '_> { } if c.speed != 1.0 || c.reverse || c.frame_hold.is_some() { if param(c, "time_remap", "speed").is_some_and(|p| p.is_animated()) { - self.report.warn("speed ramps (time remapping keyframes) are not exported to FCP7 XML"); + self.report.warn_limited(self.report_limit, "speed ramps (time remapping keyframes) are not exported to FCP7 XML"); } self.open_effect("Time Remap", "timeremap", "motion", "motion", "video", true); let sp = if c.frame_hold.is_some() { 0.0 } else { c.speed * 100.0 }; @@ -1335,7 +1415,7 @@ impl Exp<'_, '_> { } } else { if c.gain_db != 0.0 { - self.report.info("clip gain was folded into Audio Levels"); + self.report.info_limited(self.report_limit, "clip gain was folded into Audio Levels"); } if param_modified(self.opts.catalog, c, "volume", "level") || c.gain_db != 0.0 { let g = c.gain_db; @@ -1358,7 +1438,7 @@ impl Exp<'_, '_> { self.close_effect(); } if param_modified(self.opts.catalog, c, "channel_volume", "left") || param_modified(self.opts.catalog, c, "channel_volume", "right") { - self.report.warn("Channel Volume is not supported by FCP7 XML and was not exported"); + self.report.warn_limited(self.report_limit, "Channel Volume is not supported by FCP7 XML and was not exported"); } } for e in standard_effects(self.opts.catalog, c) { @@ -1442,7 +1522,7 @@ impl Exp<'_, '_> { self.w.close(); } _ => { - self.report.info("Bezier keyframe easing is written as FCP curve keyframes (handles not preserved)"); + self.report.info_limited(self.report_limit, "Bezier keyframe easing is written as FCP curve keyframes (handles not preserved)"); self.w.open("interpolation", &[]); self.w.text("name", "FCPCurve"); self.w.close(); @@ -1460,7 +1540,7 @@ impl Exp<'_, '_> { for k in &p.keyframes { let Some(v) = val(&k.value) else { continue }; if !on_frame(rate, k.time) { - self.report.info("sub-frame keyframes were rounded to frames"); + self.report.info_limited(self.report_limit, "sub-frame keyframes were rounded to frames"); } self.w.open("keyframe", &[]); self.w.text("when", frames_round(rate, k.time)); @@ -1472,7 +1552,7 @@ impl Exp<'_, '_> { fn generic_effect(&mut self, e: &EffectInstance, kind: TrackKind, rate: FrameRate) { let Some(def) = self.opts.catalog.effect(&e.effect) else { - self.report.warn(format!("unknown effect \"{}\" was not exported", e.effect)); + self.report.warn_limited(self.report_limit, format!("unknown effect \"{}\" was not exported", e.effect)); return; }; let media = if kind == TrackKind::Video { "video" } else { "audio" }; @@ -1500,7 +1580,7 @@ impl Exp<'_, '_> { self.w.close(); self.w.close(); if p.is_animated() { - self.report.warn(format!("point keyframes of \"{}\" were not exported", def.name)); + self.report.warn_limited(self.report_limit, format!("point keyframes of \"{}\" were not exported", def.name)); } } ParamValue::Bool(b) => self.simple_param(&pd.id, &pd.label, bool_str(*b)), @@ -1514,7 +1594,7 @@ impl Exp<'_, '_> { self.w.close(); } ParamValue::Opaque(_) => { - self.report.warn(format!("curve parameters of \"{}\" are not supported by FCP7 XML", def.name)); + self.report.warn_limited(self.report_limit, format!("curve parameters of \"{}\" are not supported by FCP7 XML", def.name)); } } } diff --git a/crates/timeline/src/fcpxml.rs b/crates/timeline/src/fcpxml.rs index 198574718f..8a002689e8 100644 --- a/crates/timeline/src/fcpxml.rs +++ b/crates/timeline/src/fcpxml.rs @@ -125,16 +125,34 @@ struct Asset { has_audio: bool, } +// Bound semantic resource chains separately from XML syntax: flat media resources can +// reference one another without adding any XML nesting. +const MAX_MEDIA_DEPTH: usize = 64; +const MAX_XML_DEPTH: usize = 128; +// Retrying truncated resources is useful at shallower depths, but must remain bounded. +const MAX_REIMPORTS: usize = 4096; +// A hostile document may reference the same large cached graph repeatedly. Bound total +// reachability work, not just one walk, and refuse reuse when safety cannot be established. +const MAX_CACHE_EDGES: usize = 1_000_000; + struct Imp<'a, 'c, 'r> { b: Builder<'c>, opts: &'a ImportOptions<'a>, report: &'r mut Report, + report_limit: Option, formats: HashMap, asset_nodes: HashMap>, assets: HashMap, media_nodes: HashMap>, media_items: HashMap, media_active: HashSet, + depth_hits: usize, + // Depths at which a cached resource was truncated. A retry may improve neither limit + // at the expense of the other, and reuses the same item so earlier references stay valid. + media_truncated_at: HashMap, + reimports_left: usize, + cache_edges_left: usize, + depth: usize, effects: HashMap, } @@ -164,6 +182,10 @@ struct Ctx { /// Read an FCPXML document. Media paths are resolved against `opts.base_dir`; filters are looked /// up in `opts.catalog` by name. What cannot be represented is in `report`. pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result { + import_with_report_limit(text, opts, report, None) +} +/// Read FCPXML with an optional distinct-diagnostic limit. +pub fn import_with_report_limit(text: &str, opts: &ImportOptions, report: &mut Report, report_limit: Option) -> Result { let doc = crate::xml::parse(text).map_err(|e| Error::parse(Format::Fcpxml, e))?; let root = Node(&doc); if root.name() != "fcpxml" { @@ -172,7 +194,7 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result().ok()).unwrap_or(0); if !v.starts_with("1.") || minor > 11 { - report.info(format!("FCPXML version {v} is newer than 1.11; unknown elements were ignored")); + report.info_limited(report_limit, format!("FCPXML version {v} is newer than 1.11; unknown elements were ignored")); } } let lib_name = child(root, "library").and_then(|l| child(l, "event")).and_then(|e| e.attribute("name")).unwrap_or("Imported FCPXML"); @@ -180,12 +202,18 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result Result { let rate = match r.attribute("frameDuration") { Some(fd) => rate_from_frame_duration(fd).unwrap_or_else(|| { - imp.report.warn(format!("format \"{id}\" has an invalid frameDuration \"{fd}\"; the default frame rate was used")); + imp.report.warn_limited( + imp.report_limit, + format!("format \"{id}\" has an invalid frameDuration \"{fd}\"; the default frame rate was used"), + ); FrameRate::default() }), None => FrameRate::default(), @@ -229,7 +260,7 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result { if let Some(s) = child(c, "sequence") { let name = c.attribute("name").unwrap_or("Project"); - let id = imp.sequence(s, name, Some(bin)); + let id = imp.sequence(s, name, Some(bin), None); imp.b.top.push(id); } } @@ -244,7 +275,7 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result Result Imp<'a, '_, '_> { self.b.file_media(&format!("file:{p}"), &name, &p, &spec, bin) } None => { - self.report.warn(format!("asset \"{name}\" has no media; imported offline")); + self.report.warn_limited(self.report_limit, format!("asset \"{name}\" has no media; imported offline")); let p = resolve_path(&name, self.opts.base_dir); let it = self.b.file_media(&format!("asset:{id}"), &name, &p, &spec, bin); if let Some(m) = self.b.p.item_mut(it).and_then(|i| i.as_media_mut()) { @@ -308,34 +339,101 @@ impl<'a> Imp<'a, '_, '_> { Some(a) } + /// A rebuilt item retains its ID. A cached ancestor that already points to it must + /// not be inserted underneath it, even when the resource names are not directly active. + fn cache_reaches_active(&mut self, root: ItemId) -> bool { + let active: HashSet = self.media_active.iter().filter_map(|id| self.media_items.get(id).copied()).collect(); + if active.is_empty() { + return false; + } + let mut seen = HashSet::from([root]); + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + if active.contains(&id) { + return true; + } + let Some(seq) = self.b.p.sequence(id) else { continue }; + for item in seq.all_tracks().flat_map(|track| &track.items) { + if self.cache_edges_left == 0 { + return true; + } + self.cache_edges_left -= 1; + if active.contains(&item.item) { + return true; + } + if seen.insert(item.item) { + pending.push(item.item); + } + } + } + false + } + /// Nested sequence from a `` resource. fn media(&mut self, id: &str) -> Option { - if let Some(i) = self.media_items.get(id) { - return Some(*i); + // Check before the cache: a truncated resource may already have an item while it + // is being rebuilt, but a back-edge must never turn that item into a self-cycle. + if self.media_active.contains(id) { + self.report.warn_limited(self.report_limit, format!("recursive FCPXML media resource {id:?} ignored")); + return None; + } + let depth = self.media_active.len(); + let mut again = None; + if let Some(i) = self.media_items.get(id).copied() { + // Imported with a nested one cut off: import it again (into the same item) where that + // one now fits. + let shallower = self + .media_truncated_at + .get(id) + .is_some_and(|&(media, xml)| depth <= media && self.depth <= xml && (depth < media || self.depth < xml)) + && !self.media_active.contains(id); + if !shallower || self.reimports_left == 0 { + if self.cache_reaches_active(i) { + self.depth_hits += 1; + self.report.warn_limited( + self.report_limit, + format!("FCPXML cached media {id:?} could form a recursive graph or exceeds the cache traversal budget; imported as a gap"), + ); + return None; + } + return Some(i); + } + self.reimports_left -= 1; + again = Some(i); } let n = *self.media_nodes.get(id)?; let s = child(n, "sequence")?; - if !self.media_active.insert(id.into()) { - self.report.warn(format!("recursive FCPXML media resource {id:?} ignored")); + // The active set is the current nesting chain: a long acyclic chain of compound clips + // would otherwise recurse once per resource. + if depth >= MAX_MEDIA_DEPTH { + self.depth_hits += 1; + self.report.warn_limited(self.report_limit, format!("FCPXML media resource {id:?} is nested too deeply; imported as a gap")); return None; } + self.media_active.insert(id.into()); // Mark the resource before descending: a compound clip can reference itself through a // ref-clip before a completed sequence is available to cache. let name = n.attribute("name").unwrap_or("Compound Clip").to_string(); - let item = self.sequence(s, &name, None); + let hits_before = self.depth_hits; + let item = self.sequence(s, &name, None, again); self.media_active.remove(id); self.media_items.insert(id.into(), item); + if self.depth_hits > hits_before { + self.media_truncated_at.insert(id.into(), (depth, self.depth)); + } else { + self.media_truncated_at.remove(id); + } Some(item) } - fn sequence(&mut self, s: Node<'a>, name: &str, bin: Option) -> ItemId { + fn sequence(&mut self, s: Node<'a>, name: &str, bin: Option, reuse: Option) -> ItemId { let (rate, w, h) = s.attribute("format").and_then(|f| self.formats.get(f)).copied().unwrap_or((FrameRate::default(), 1920, 1080)); let df = s.attribute("tcFormat") == Some("DF"); let mut settings = settings_for(rate, w, h, df); if let Some(sr) = s.attribute("audioRate").and_then(parse_audio_rate) { settings.sample_rate = sr; } - let id = self.b.reserve_sequence(name, settings.clone(), bin); + let id = reuse.unwrap_or_else(|| self.b.reserve_sequence(name, settings.clone(), bin)); let mut seq = empty_sequence(settings); let tc_start = attr_time(s, "tcStart").unwrap_or(Tick::ZERO); seq.start_timecode = rate.frame_at(tc_start); @@ -353,7 +451,22 @@ impl<'a> Imp<'a, '_, '_> { /// Lay out a storyline. `origin` maps the storyline's offsets to timeline time /// (`timeline = origin + offset`). `lane` is the storyline's lane (0 = primary). + /// Refuses nesting past [`MAX_XML_DEPTH`]. fn storyline(&mut self, seq: &mut Sequence, ctx: &Ctx, spine: Node<'a>, origin: Tick, lane: i32, primary: bool) { + if self.depth >= MAX_XML_DEPTH { + self.depth_hits += 1; + self.report.warn_limited( + self.report_limit, + format!("XML storylines are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped"), + ); + return; + } + self.depth += 1; + self.storyline_inner(seq, ctx, spine, origin, lane, primary); + self.depth -= 1; + } + + fn storyline_inner(&mut self, seq: &mut Sequence, ctx: &Ctx, spine: Node<'a>, origin: Tick, lane: i32, primary: bool) { // (timeline start, timeline end, video clip on this storyline's track) let mut laid: Vec<(Tick, Tick, Option)> = Vec::new(); let mut transitions: Vec<(usize, Node)> = Vec::new(); @@ -371,7 +484,7 @@ impl<'a> Imp<'a, '_, '_> { let vidx = if lane >= 0 { lane as usize } else { usize::MAX }; for (pos, el) in transitions { if vidx == usize::MAX { - self.report.warn("transitions on audio storylines are not supported"); + self.report.warn_limited(self.report_limit, "transitions on audio storylines are not supported"); continue; } let start = origin + attr_time(el, "offset").unwrap_or(Tick::ZERO); @@ -399,7 +512,13 @@ impl<'a> Imp<'a, '_, '_> { } else { TransitionAlign::CenterAtCut }; - let effect = transition_effect(self.b.catalog, &name, false, self.report); + let mut temporary = Report::default(); + let effect = transition_effect(self.b.catalog, &name, false, &mut temporary); + for e in temporary.entries { + for _ in 0..e.count { + self.report.push_limited(e.level, self.report_limit, &e.message); + } + } let id = TransitionId(self.b.alloc()); // The clips may have been moved to another track by placement; find the track holding them. let clip = from.or(to).map(|c| c.0); @@ -421,7 +540,23 @@ impl<'a> Imp<'a, '_, '_> { } /// Lay out one storyline element at timeline time `t0`. Returns (timeline end, video clip). + /// Refuses nesting past [`MAX_XML_DEPTH`]. fn element(&mut self, seq: &mut Sequence, ctx: &Ctx, el: Node<'a>, t0: Tick, lane: i32, primary: bool) -> (Tick, Option) { + if self.depth >= MAX_XML_DEPTH { + self.depth_hits += 1; + self.report.warn_limited( + self.report_limit, + format!("XML elements are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped"), + ); + return (t0, None); + } + self.depth += 1; + let out = self.element_inner(seq, ctx, el, t0, lane, primary); + self.depth -= 1; + out + } + + fn element_inner(&mut self, seq: &mut Sequence, ctx: &Ctx, el: Node<'a>, t0: Tick, lane: i32, primary: bool) -> (Tick, Option) { let tag = el.name(); let dur = attr_time(el, "duration").unwrap_or(Tick::ZERO); let local_start = attr_time(el, "start").unwrap_or(Tick::ZERO); @@ -441,7 +576,8 @@ impl<'a> Imp<'a, '_, '_> { .flatten() .filter(|a| a.has_video); if asset.is_none() { - self.report.warn(format!("FCPXML ]]>"#; + assert_eq!(xml_depth(input), 2); + assert_eq!(xml_depth(b""), 0); +} + +#[test] +fn lexical_scans_do_not_claim_to_validate_malformed_documents() { + assert_eq!(xml_depth(b""), 1); + assert_eq!(xml_depth(b"\tx\n ").is_ok()); } + +#[test] +fn strict_attributes_are_unique_before_name_rewriting() { + use craft_xml::{Names, Options}; + for names in [Names::AsWritten, Names::Local] { + let strict = Options { names, ..Options::default() }.strict(); + for xml in [ + "", + "", + "", + "", + ] { + assert!(strict.parse(xml.as_bytes()).is_err(), "{xml}"); + let mut events = strict.events(xml.as_bytes()); + assert!( + loop { + match events.next() { + Ok(Some(_)) => {} + Ok(None) => break false, + Err(_) => break true, + } + }, + "{xml}" + ); + } + for xml in [ + "", + "", + "", + ] { + assert!(strict.parse(xml.as_bytes()).is_ok(), "{xml}"); + } + assert!(Options { names, ..Options::default() }.parse(b"").is_ok()); + } + let strict = Options { limits: craft_xml::Limits { max_attrs: 2, ..craft_xml::Limits::DEFAULT }, ..Options::default() }.strict(); + assert!(strict.parse(b"").is_err()); + assert!(strict.parse(b"").is_err()); +} diff --git a/crates/zip/Cargo.toml b/crates/zip/Cargo.toml index 6d50b5352f..89cb2d1a73 100644 --- a/crates/zip/Cargo.toml +++ b/crates/zip/Cargo.toml @@ -17,10 +17,28 @@ thiserror = { workspace = true } zip = { version = "9", default-features = false, features = ["deflate-flate2"] } # The backend of zip's deflate: `deflate-flate2` leaves the choice to the build. flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +# `lenient`: DEFLATE for the raw-bytes reader. +miniz_oxide = { workspace = true, optional = true } +# `lenient` entry methods beyond stored and DEFLATE. All pure Rust and wasm32-safe. +bzip2-rs = { version = "0.1", optional = true } # MIT OR Apache-2.0 +lzma-rs = { version = "0.3", optional = true } # MIT +ruzstd = { version = "0.9.1", default-features = false, features = ["std"], optional = true } # MIT +# `serde`: `Serialize` on the `lenient` listing types, for apps that report listings as JSON. +serde = { workspace = true, optional = true } [features] # `zip64_entry_count_sample`, the regression input for a reader's own entry-count test. test-support = [] +# `craft_zip::lenient`: the raw-bytes reader for inspectors (from Craft Anything), without `zip`. +lenient = ["dep:miniz_oxide"] +# Method 12. +lenient-bzip2 = ["lenient", "dep:bzip2-rs"] +# Methods 14 (ZIP LZMA) and 95 (XZ). +lenient-lzma = ["lenient", "dep:lzma-rs"] +# Method 93. +lenient-zstd = ["lenient", "dep:ruzstd"] +serde = ["dep:serde"] [dev-dependencies] -craft-zip = { path = ".", features = ["test-support"] } +craft-zip = { path = ".", features = ["test-support", "lenient-bzip2", "lenient-lzma", "lenient-zstd", "serde"] } +serde_json = { workspace = true } diff --git a/crates/zip/README.md b/crates/zip/README.md index 079267b9f4..071d2124da 100644 --- a/crates/zip/README.md +++ b/crates/zip/README.md @@ -70,3 +70,22 @@ calls it first. `preflight`, `read_entry` and `Budget`: the ZIP half of the craft-archive proposal (#126, #129). `check_entry_count`: craft-opc's `guard`. Duplicate detection: craft-penpot's rule, made exact by walking the directory. The writer: craft-opc's `ZipOut`. + +## Seekable indexing + +`MetadataReader::new(reader, metadata_bytes)` wraps a `Read + Seek` source without loading its +payload into memory. During ZIP indexing it admits reads only from the last `metadata_bytes` +bytes and charges repeated reads against twice that number. Call `Indexing::finish` on the +returned handle after the ZIP index has been parsed to permit normal streaming payload reads. +The caller must still enforce entry-count, declared-size and overlap limits: the wrapper only +bounds metadata reads and does not validate the archive. + +## Lenient reading (feature `lenient`) + +`craft_zip::lenient` reads an archive from its raw bytes without the `zip` crate, for inspectors +(Craft Anything) that must list and describe damaged, prepended, split or oddly encoded archives +instead of refusing them. Only the central directory is trusted for the listing; entry reads are +bounded, checked against the declared size and CRC-32, and decode stored and DEFLATE entries, plus +bzip2 (`lenient-bzip2`), ZIP LZMA and XZ (`lenient-lzma`) and Zstandard (`lenient-zstd`). +`lenient::file::read_named_entry` reads one entry from a seekable file without loading the +archive. With `serde`, the listing types are `Serialize`. diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index 5739e830ae..49da63585e 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -2,6 +2,7 @@ use std::borrow::Cow; use std::io::{Cursor, Read}; +use std::sync::Arc; use crate::preflight::{ReadError, read_entry}; use crate::{Budget, Error, check_entry_count}; @@ -21,11 +22,26 @@ pub struct Limits { /// caller that reads through a clone keeps its own count. #[derive(Clone)] pub struct Archive<'a> { - zip: zip::ZipArchive>, + zip: zip::ZipArchive>>, budget: Budget, duplicates: bool, } +#[derive(Clone)] +enum Input<'a> { + Borrowed(&'a [u8]), + Owned(Arc>), +} + +impl AsRef<[u8]> for Input<'_> { + fn as_ref(&self) -> &[u8] { + match self { + Self::Borrowed(bytes) => bytes, + Self::Owned(bytes) => bytes.as_slice(), + } + } +} + const CENTRAL_HEADER: &[u8; 4] = b"PK\x01\x02"; const CENTRAL_HEADER_LEN: usize = 46; @@ -46,15 +62,20 @@ impl<'a> Archive<'a> { /// Indexes `bytes`. The declared entry count is checked against /// [`Limits::max_entries`] before `zip` parses the central directory, and again after. pub fn open(bytes: &'a [u8], limits: Limits) -> Result { - check_entry_count(bytes, limits.max_entries)?; - let zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| Error::NotZip(e.to_string()))?; + Self::open_input(Input::Borrowed(bytes), limits) + } + + fn open_input(input: Input<'a>, limits: Limits) -> Result { + check_entry_count(input.as_ref(), limits.max_entries)?; + let bytes = input.clone(); + let zip = zip::ZipArchive::new(Cursor::new(input)).map_err(|e| Error::NotZip(e.to_string()))?; let found = zip.len() as u64; if found > limits.max_entries { return Err(Error::TooManyEntries { declared: found, limit: limits.max_entries }); } // `zip` keeps one entry per name, so a directory with more headers than `zip` has entries // repeats a name. - let duplicates = count_central_headers(bytes, zip.central_directory_start(), zip.len().saturating_add(1)) > zip.len(); + let duplicates = count_central_headers(bytes.as_ref(), zip.central_directory_start(), zip.len().saturating_add(1)) > zip.len(); Ok(Archive { zip, budget: Budget::new("archive", limits.max_total_bytes), duplicates }) } @@ -180,3 +201,28 @@ impl<'a> Archive<'a> { &mut self.budget } } + +impl Archive<'static> { + /// Indexes owned bytes without copying them. Clones share the backing storage. + pub fn open_owned(bytes: Vec, limits: Limits) -> Result { + Self::open_input(Input::Owned(Arc::new(bytes)), limits) + } +} + +#[cfg(test)] +mod ownership_tests { + use super::*; + + #[test] + fn owned_storage_lives_until_last_archive_clone_is_dropped() { + let bytes = crate::Writer::new().finish().unwrap(); + let bytes = Arc::new(bytes); + let weak = Arc::downgrade(&bytes); + let archive = Archive::open_input(Input::Owned(bytes), Limits { max_entries: 1, max_total_bytes: 1 }).unwrap(); + let clone = archive.clone(); + drop(archive); + assert!(weak.upgrade().is_some()); + drop(clone); + assert!(weak.upgrade().is_none()); + } +} diff --git a/crates/zip/src/guard.rs b/crates/zip/src/guard.rs index dd3ebe4515..553e1532f4 100644 --- a/crates/zip/src/guard.rs +++ b/crates/zip/src/guard.rs @@ -46,7 +46,7 @@ pub fn check_entry_count(bytes: &[u8], max_entries: u64) -> Result<(), Error> { continue; } let (Some(on_disk), Some(total), Some(cd_offset)) = (u16_at(at + 8), u16_at(at + 10), u32_at(at + 16)) else { continue }; - let zip64 = total == u16::MAX || cd_offset == u32::MAX; + let zip64 = total == u16::MAX || u32_at(at + 12) == Some(u32::MAX) || cd_offset == u32::MAX; if zip64 && let Some(locator) = at.checked_sub(20) && bytes.get(locator..locator + 4) == Some(EOCD64_LOCATOR.as_slice()) @@ -155,6 +155,17 @@ mod tests { assert!(check(&prefixed, 20_000).is_err()); } + #[test] + fn zip64_directory_size_sentinel_alone_cannot_bypass_the_count_limit() { + let mut bytes = zip64_entry_count_sample(21); + let eocd = bytes.len() - 22; + // zip recognizes ZIP64 when only the directory size is a sentinel. + bytes[eocd + 8..eocd + 12].copy_from_slice(&[1, 0, 1, 0]); + bytes[eocd + 16..eocd + 20].copy_from_slice(&0u32.to_le_bytes()); + assert!(zip::ZipArchive::new(std::io::Cursor::new(&bytes)).is_ok()); + assert_eq!(check(&bytes, 20), Err(Error::TooManyEntries { declared: 21, limit: 20 })); + } + #[test] fn a_plain_end_record_is_checked_as_zip_reads_it() { assert!(check(&plain(3, b""), 20_000).is_ok()); diff --git a/crates/zip/src/lenient.rs b/crates/zip/src/lenient.rs new file mode 100644 index 0000000000..c9bed3764d --- /dev/null +++ b/crates/zip/src/lenient.rs @@ -0,0 +1,552 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +//! ZIP archives (also APK, JAR, IPA, MSIX, HAP…) read leniently from the raw bytes, for +//! inspectors that must list and describe damaged, prepended, split or oddly encoded archives +//! rather than refuse them (feature `lenient`). The rest of this crate is the strict side: it +//! refuses what fails [`crate::preflight`] and reads through the `zip` crate; nothing here uses +//! `zip`. +//! +//! Only the central directory is trusted for the listing. Entry data is located through the local +//! header, decompressed with a hard output cap, and checked against the recorded CRC-32. Stored, +//! DEFLATE, bzip2, ZIP LZMA, XZ and Zstandard entries are supported; other methods and encrypted entries are listed. +//! +//! The bzip2, LZMA/XZ and Zstandard methods sit behind the `lenient-bzip2`, `lenient-lzma` and +//! `lenient-zstd` features; without one, entries using it are listed and reading them is +//! [`ZipError::Unsupported`]. [`file::read_named_entry`] reads one entry from a seekable file +//! without loading the archive. With the `serde` feature the listing types are `Serialize`. +//! +//! From Craft Anything (`crates/formats/src/zip.rs` and `zip_file.rs`), with its hardening: +//! directory and extra-field bounds, ZIP64 end-record recovery after a prepended stub, refusal of +//! multi-volume archives, Info-ZIP Unicode Path names checked by CRC, decoded sizes checked +//! against the directory, and CRC-32 verification. + +mod bytes; +#[cfg(any(feature = "lenient-bzip2", feature = "lenient-lzma", feature = "lenient-zstd"))] +mod decode; +pub mod file; + +use crate::lenient::bytes::Reader; + +/// Biggest tail we search for the end-of-central-directory record (64 KiB comment + record). +pub const EOCD_SEARCH: usize = 22 + 0xffff; +const ZIP64_FIXED_SIZE: usize = 56; +/// Bound the search for a record shifted by a prepended stub, including extensible data. +const ZIP64_RECOVERY_SEARCH: usize = 64 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ZipError { + #[error("not a ZIP archive (no end-of-central-directory record)")] + NotZip, + #[error("ZIP is truncated: {0}")] + Truncated(&'static str), + #[error("ZIP is corrupt: {0}")] + Corrupt(String), + #[error("unsupported ZIP feature: {0}")] + Unsupported(String), + #[error("entry is larger than the {0}-byte limit")] + TooLarge(u64), + #[error("CRC-32 mismatch (expected {expected:08x}, found {found:08x})")] + CrcMismatch { expected: u32, found: u32 }, +} + +/// One central-directory entry. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct ZipEntry { + /// Entry name as stored (forward slashes). Bit 11 selects lossy UTF-8; otherwise + /// a valid Unicode Path extra field takes precedence over the UTF-8/CP437 fallback. + pub name: String, + pub method: u16, + pub flags: u16, + pub crc32: u32, + pub compressed_size: u64, + pub uncompressed_size: u64, + /// Offset of the local header, already adjusted for any prepended data. + pub local_header_offset: u64, + pub is_dir: bool, + pub encrypted: bool, + /// Unix mode from the external attributes (when stored by Unix or macOS). + #[cfg_attr(feature = "serde", serde(skip))] + pub unix_mode: Option, +} + +impl ZipEntry { + /// Why this entry is not a regular file or directory (symlink, device, FIFO, socket), if so. + pub fn special_kind(&self) -> Option<&'static str> { + match self.unix_mode? & 0o170000 { + 0o120000 => Some("symlink"), + 0o020000 => Some("character device"), + 0o060000 => Some("block device"), + 0o010000 => Some("FIFO"), + 0o140000 => Some("socket"), + _ => None, + } + } + + /// Human name of the compression method. + pub fn method_name(&self) -> &'static str { + match self.method { + 0 => "stored", + 8 => "deflate", + 9 => "deflate64", + 12 => "bzip2", + 14 => "lzma", + 93 => "zstd", + 95 => "xz", + 99 => "aes", + _ => "other", + } + } +} + +/// The parsed central directory. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct ZipArchive { + pub entries: Vec, + /// Entries the directory declares (may exceed `entries.len()` when truncated). + pub declared_entries: u64, + /// True when `max_entries` stopped the listing early. + pub truncated: bool, + pub zip64: bool, + /// Bytes before the archive proper (self-extracting stubs). + pub prefix_bytes: u64, + /// Inconsistent end-record metadata retained without hiding a readable directory. + #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))] + pub warnings: Vec, +} + +/// True when the bytes start like a ZIP (local header or empty archive). +pub fn looks_like_zip(data: &[u8]) -> bool { + data.starts_with(b"PK\x03\x04") || data.starts_with(b"PK\x05\x06") || data.starts_with(b"PK\x07\x08") +} + +/// Recover a shifted end record only when its fixed fields still describe the classic +/// directory. Longer records must frame their extension exactly; the adjacent fixed +/// record can still report an inconsistent size through the normal warning path. +fn recover_zip64_record(data: &[u8], loc: usize, disk_entries: u64, total: u64, cd_size: u64, cd_offset: u64) -> Option { + let r = Reader::new(data); + let last = loc.checked_sub(ZIP64_FIXED_SIZE)?; + let first = loc.saturating_sub(ZIP64_RECOVERY_SEARCH); + let candidates = data.get(first..last.checked_add(4)?)?; + candidates.windows(4).enumerate().rev().find_map(|(relative, signature)| { + if signature != b"PK\x06\x06" { + return None; + } + let rec = first.checked_add(relative)?; + let fixed = Reader::new(r.slice(rec, ZIP64_FIXED_SIZE)?); + let payload_size = fixed.u64_le(4)?; + if payload_size < 44 { + return None; + } + let declared_end = (rec as u64).checked_add(12)?.checked_add(payload_size)?; + if rec != last && declared_end != loc as u64 { + return None; + } + let record_disk_entries = fixed.u64_le(24)?; + let record_total = fixed.u64_le(32)?; + let record_cd_size = fixed.u64_le(40)?; + let record_cd_offset = fixed.u64_le(48)?; + if fixed.u32_le(16)? != 0 + || fixed.u32_le(20)? != 0 + || record_disk_entries != record_total + || (disk_entries != 0xffff && disk_entries != record_disk_entries) + || (total != 0xffff && total != record_total) + || (cd_size != 0xffff_ffff && cd_size != record_cd_size) + || (cd_offset != 0xffff_ffff && cd_offset != record_cd_offset) + || record_cd_offset.checked_add(record_cd_size)? > rec as u64 + { + return None; + } + if record_total > 0 { + let directory = rec.checked_sub(usize::try_from(record_cd_size).ok()?)?; + if record_cd_size < 46 || r.slice(directory, 4) != Some(b"PK\x01\x02") { + return None; + } + } + Some(rec) + }) +} + +/// Parse the central directory, keeping at most `max_entries`. +pub fn parse(data: &[u8], max_entries: usize) -> Result { + parse_directory(data, max_entries, None) +} + +/// Search the validated directory while retaining only the requested entry. +pub fn has_entry(data: &[u8], name: &str) -> bool { + parse_directory(data, 1, Some(name)).is_ok_and(|archive| !archive.entries.is_empty()) +} + +/// List directory entries, optionally retaining only a matching decoded name. +fn parse_directory(data: &[u8], max_entries: usize, name_filter: Option<&str>) -> Result { + let r = Reader::new(data); + let eocd = find_eocd(data).ok_or(ZipError::NotZip)?; + let mut disk = u32::from(r.u16_le(eocd + 4).ok_or(ZipError::Truncated("end record"))?); + let mut directory_disk = u32::from(r.u16_le(eocd + 6).ok_or(ZipError::Truncated("end record"))?); + let mut disk_entries = u64::from(r.u16_le(eocd + 8).ok_or(ZipError::Truncated("end record"))?); + if !matches!(disk, 0 | 0xffff) || !matches!(directory_disk, 0 | 0xffff) { + return Err(ZipError::Unsupported("multi-volume ZIP archives".into())); + } + let mut total = u64::from(r.u16_le(eocd + 10).ok_or(ZipError::Truncated("end record"))?); + let mut cd_size = u64::from(r.u32_le(eocd + 12).ok_or(ZipError::Truncated("end record"))?); + let mut cd_offset = u64::from(r.u32_le(eocd + 16).ok_or(ZipError::Truncated("end record"))?); + let mut zip64 = false; + let mut warnings = Vec::new(); + let mut eocd_record_start = eocd as u64; + if total == 0xffff || disk_entries == 0xffff || disk == 0xffff || directory_disk == 0xffff || cd_size == 0xffff_ffff || cd_offset == 0xffff_ffff { + // ZIP64 locator sits right before the classic record. + if let Some(loc) = eocd.checked_sub(20) + && r.slice(loc, 4) == Some(b"PK\x06\x07") + { + if r.u32_le(loc + 4) != Some(0) || r.u32_le(loc + 16) != Some(1) { + return Err(ZipError::Unsupported("multi-volume ZIP archives".into())); + } + let rec = r.u64_le(loc + 8).ok_or(ZipError::Truncated("zip64 locator"))?; + let rec = usize::try_from(rec).ok().filter(|&rec| r.slice(rec, 4) == Some(b"PK\x06\x06")); + let rec = rec.or_else(|| { + let recovered = recover_zip64_record(data, loc, disk_entries, total, cd_size, cd_offset); + if recovered.is_some() { + warnings.push("ZIP64 locator offset does not identify its end record; recovered the record before the locator".into()); + } + recovered + }); + if let Some(rec) = rec { + let payload_size = r.u64_le(rec + 4).ok_or(ZipError::Truncated("zip64 record size"))?; + if payload_size < 44 { + return Err(ZipError::Corrupt("ZIP64 end record is smaller than its fixed fields".into())); + } + let declared_end = (rec as u64) + .checked_add(12) + .and_then(|start| start.checked_add(payload_size)) + .ok_or_else(|| ZipError::Corrupt("ZIP64 end record extent overflows".into()))?; + // Fixed fields must be present before the locator. A bad declared extension + // length cannot make the reader borrow locator or classic end-record bytes. + if rec.checked_add(ZIP64_FIXED_SIZE).is_none_or(|end| end > loc) { + return Err(ZipError::Truncated("zip64 record fixed fields")); + } + if declared_end != loc as u64 { + warnings.push("ZIP64 end record's declared extent does not end at its locator; using bounded fixed fields".into()); + } + disk = r.u32_le(rec + 16).ok_or(ZipError::Truncated("zip64 record"))?; + directory_disk = r.u32_le(rec + 20).ok_or(ZipError::Truncated("zip64 record"))?; + let zip64_disk_entries = r.u64_le(rec + 24).ok_or(ZipError::Truncated("zip64 record"))?; + let zip64_total = r.u64_le(rec + 32).ok_or(ZipError::Truncated("zip64 record"))?; + if (disk_entries != 0xffff && disk_entries != zip64_disk_entries) || (total != 0xffff && total != zip64_total) { + return Err(ZipError::Unsupported("multi-volume ZIP archives".into())); + } + disk_entries = zip64_disk_entries; + total = zip64_total; + let zip64_cd_size = r.u64_le(rec + 40).ok_or(ZipError::Truncated("zip64 record"))?; + let zip64_cd_offset = r.u64_le(rec + 48).ok_or(ZipError::Truncated("zip64 record"))?; + if (cd_size != 0xffff_ffff && cd_size != zip64_cd_size) || (cd_offset != 0xffff_ffff && cd_offset != zip64_cd_offset) { + return Err(ZipError::Corrupt("ZIP64 and classic directory bounds disagree".into())); + } + cd_size = zip64_cd_size; + cd_offset = zip64_cd_offset; + zip64 = true; + eocd_record_start = rec as u64; + } else { + // A prepended stub can invalidate the locator's absolute offset. Keep the + // classic-directory fallback, including its existing prefix adjustment. + warnings.push("ZIP64 locator does not point to an end record; using the classic end record".into()); + } + } + } + if disk != 0 || directory_disk != 0 || disk_entries != total { + return Err(ZipError::Unsupported("multi-volume ZIP archives".into())); + } + // Self-extracting archives: the directory sits later than it claims by the stub length. + let expected_end = cd_offset.checked_add(cd_size).ok_or_else(|| ZipError::Corrupt("directory bounds overflow".into()))?; + let prefix = eocd_record_start.saturating_sub(expected_end); + let start = usize::try_from(cd_offset.saturating_add(prefix)).map_err(|_| ZipError::Corrupt("directory offset".into()))?; + let directory_end = (start as u64) + .checked_add(cd_size) + .filter(|&end| end <= eocd_record_start) + .and_then(|end| usize::try_from(end).ok()) + .ok_or_else(|| ZipError::Corrupt("directory extends into its end record".into()))?; + let mut entries = Vec::new(); + let mut pos = start; + let mut truncated = false; + let mut seen = 0u64; + while seen < total { + if entries.len() >= max_entries { + truncated = true; + break; + } + if pos.checked_add(46).is_none_or(|end| end > directory_end) { + return Err(ZipError::Truncated("directory entry")); + } + if r.slice(pos, 4) != Some(b"PK\x01\x02") { + if entries.is_empty() { + return Err(ZipError::Corrupt(format!("no central directory header at offset {pos}"))); + } + truncated = true; + break; + } + let flags = r.u16_le(pos + 8).ok_or(ZipError::Truncated("directory entry"))?; + let method = r.u16_le(pos + 10).ok_or(ZipError::Truncated("directory entry"))?; + let crc32 = r.u32_le(pos + 16).ok_or(ZipError::Truncated("directory entry"))?; + let mut csize = u64::from(r.u32_le(pos + 20).ok_or(ZipError::Truncated("directory entry"))?); + let mut usize_ = u64::from(r.u32_le(pos + 24).ok_or(ZipError::Truncated("directory entry"))?); + let name_len = usize::from(r.u16_le(pos + 28).ok_or(ZipError::Truncated("directory entry"))?); + let extra_len = usize::from(r.u16_le(pos + 30).ok_or(ZipError::Truncated("directory entry"))?); + let comment_len = usize::from(r.u16_le(pos + 32).ok_or(ZipError::Truncated("directory entry"))?); + let entry_end = pos + .checked_add(46 + name_len + extra_len + comment_len) + .filter(|&end| end <= directory_end) + .ok_or(ZipError::Truncated("directory entry fields"))?; + let host = r.slice(pos + 5, 1).and_then(|b| b.first().copied()).unwrap_or(0); + let attrs = r.u32_le(pos + 38).ok_or(ZipError::Truncated("entry attributes"))?; + let unix_mode = matches!(host, 3 | 19).then_some(attrs >> 16); + let mut local = u64::from(r.u32_le(pos + 42).ok_or(ZipError::Truncated("directory entry"))?); + let mut entry_disk = u32::from(r.u16_le(pos + 34).ok_or(ZipError::Truncated("directory entry"))?); + let name_bytes = r.slice(pos + 46, name_len).ok_or(ZipError::Truncated("entry name"))?; + let extra = r.slice(pos + 46 + name_len, extra_len).ok_or(ZipError::Truncated("entry extra fields"))?; + // Each extra field owns its payload: ZIP64 values cannot borrow a following field's bytes. + let needs_zip64 = usize_ == 0xffff_ffff || csize == 0xffff_ffff || local == 0xffff_ffff || entry_disk == 0xffff; + let mut found_zip64 = false; + let mut unicode_name = None; + let mut name_crc = None; + let mut x = 0usize; + let er = Reader::new(extra); + // Trailing bytes too short for a field header are padding, not truncation. + while x.saturating_add(4) <= extra.len() { + let id = er.u16_le(x).ok_or(ZipError::Truncated("extra field header"))?; + let len = usize::from(er.u16_le(x + 2).ok_or(ZipError::Truncated("extra field header"))?); + let body = x + 4; + let field = er.slice(body, len).ok_or(ZipError::Truncated("extra field payload"))?; + if id == 0x0001 && !found_zip64 { + let values = Reader::new(field); + let mut f = 0; + if usize_ == 0xffff_ffff { + usize_ = values.u64_le(f).ok_or(ZipError::Truncated("zip64 uncompressed size"))?; + f += 8; + } + if csize == 0xffff_ffff { + csize = values.u64_le(f).ok_or(ZipError::Truncated("zip64 compressed size"))?; + f += 8; + } + if local == 0xffff_ffff { + local = values.u64_le(f).ok_or(ZipError::Truncated("zip64 local header offset"))?; + f += 8; + } + if entry_disk == 0xffff { + entry_disk = values.u32_le(f).ok_or(ZipError::Truncated("zip64 entry disk"))?; + } + found_zip64 = true; + } else if id == 0x7075 && flags & (1 << 11) == 0 && unicode_name.is_none() { + let field = Reader::new(field); + if field.u8(0) == Some(1) && field.u32_le(1) == Some(*name_crc.get_or_insert_with(|| self::crc32(name_bytes))) { + unicode_name = field.data().get(5..).and_then(|bytes| std::str::from_utf8(bytes).ok()).filter(|s| !s.is_empty()); + } + } + x = body + len; + } + if needs_zip64 && !found_zip64 { + return Err(ZipError::Corrupt("missing ZIP64 extended information".into())); + } + if entry_disk != 0 { + return Err(ZipError::Unsupported("multi-volume ZIP archives".into())); + } + let name = unicode_name.map(str::to_owned).unwrap_or_else(|| decode_name(name_bytes, flags)).replace('\\', "/"); + if name_filter.is_none_or(|wanted| wanted == name) { + entries.push(ZipEntry { + is_dir: name.ends_with('/') + || unix_mode.is_some_and(|m| m & 0o170000 == 0o040000) + || (matches!(host, 0 | 10 | 14) && attrs & 0x10 != 0), + name, + method, + flags, + crc32, + compressed_size: csize, + uncompressed_size: usize_, + local_header_offset: local.saturating_add(prefix), + encrypted: flags & 1 != 0, + unix_mode, + }); + } + seen += 1; + pos = entry_end; + } + Ok(ZipArchive { entries, declared_entries: total, truncated, zip64, prefix_bytes: prefix, warnings }) +} + +fn decode_name(bytes: &[u8], flags: u16) -> String { + if flags & 0x0800 != 0 || bytes.is_ascii() { + return String::from_utf8_lossy(bytes).into_owned(); + } + if let Ok(name) = std::str::from_utf8(bytes) { + return name.to_owned(); + } + const CP437: [char; 128] = [ + 'Ç', 'ü', 'é', 'â', 'ä', 'à', 'Ã¥', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Ã…', 'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', '¢', + '£', 'Â¥', 'â‚§', 'Æ’', 'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', 'âŒ�', '¬', '½', '¼', '¡', '«', '»', 'â–‘', 'â–’', 'â–“', '│', '┤', 'â•¡', 'â•¢', 'â•–', + 'â••', 'â•£', 'â•‘', 'â•—', 'â•�', '╜', 'â•›', 'â”�', 'â””', 'â”´', '┬', '├', '─', '┼', '╞', '╟', '╚', 'â•”', 'â•©', '╦', 'â• ', 'â•�', '╬', 'â•§', '╨', '╤', 'â•¥', 'â•™', + '╘', 'â•’', 'â•“', 'â•«', '╪', '┘', '┌', 'â–ˆ', 'â–„', 'â–Œ', 'â–�', 'â–€', 'α', 'ß', 'Γ', 'Ï€', 'Σ', 'σ', 'µ', 'Ï„', 'Φ', 'Θ', 'Ω', 'δ', '∞', 'φ', 'ε', '∩', + '≡', '±', '≥', '≤', '⌠', '⌡', '÷', '≈', '°', '∙', '·', '√', 'â�¿', '²', 'â– ', '\u{00a0}', + ]; + bytes + .iter() + .map(|&byte| if byte.is_ascii() { char::from(byte) } else { CP437.get(usize::from(byte - 0x80)).copied().unwrap_or('\u{fffd}') }) + .collect() +} + +/// Where the end-of-central-directory record starts, searching backwards through the last +/// [`EOCD_SEARCH`] bytes. +pub fn find_eocd(data: &[u8]) -> Option { + if data.len() < 22 { + return None; + } + let from = data.len().saturating_sub(EOCD_SEARCH); + let tail = data.get(from..)?; + // Search backwards so a stray signature in the comment can't shadow the real record. + let mut i = tail.len().checked_sub(22)?; + let mut found = None; + let mut last_signature = None; + loop { + if tail.get(i..i + 4) == Some(b"PK\x05\x06") { + last_signature.get_or_insert(from + i); + if let Some(comment_len) = tail.get(i + 20..i + 22).and_then(|bytes| <[u8; 2]>::try_from(bytes).ok()).map(u16::from_le_bytes) + && i + 22 + usize::from(comment_len) == tail.len() + { + found = Some(from + i); + } + } + if i == 0 { + return found.or(last_signature); + } + i -= 1; + } +} + +/// The raw (possibly compressed) bytes of an entry. +pub fn raw_entry_data<'a>(data: &'a [u8], e: &ZipEntry) -> Result<&'a [u8], ZipError> { + let r = Reader::new(data); + let off = usize::try_from(e.local_header_offset).map_err(|_| ZipError::Corrupt("local header offset".into()))?; + if r.slice(off, 4) != Some(b"PK\x03\x04") { + return Err(ZipError::Corrupt(format!("no local header for {}", e.name))); + } + let n = usize::from(r.u16_le(off + 26).ok_or(ZipError::Truncated("local header"))?); + let x = usize::from(r.u16_le(off + 28).ok_or(ZipError::Truncated("local header"))?); + let start = off.checked_add(30 + n + x).ok_or(ZipError::Truncated("local header"))?; + let len = usize::try_from(e.compressed_size).map_err(|_| ZipError::TooLarge(e.compressed_size))?; + r.slice(start, len).ok_or(ZipError::Truncated("entry data")) +} + +/// Read and decompress one entry, refusing to produce more than `max_bytes`. +pub fn read_entry(data: &[u8], e: &ZipEntry, max_bytes: u64) -> Result, ZipError> { + let out = read_entry_unverified(data, e, max_bytes)?; + let found = crc32(&out); + if found != e.crc32 { + return Err(ZipError::CrcMismatch { expected: e.crc32, found }); + } + Ok(out) +} + +/// Like [`read_entry`] but without comparing the stored CRC-32, so a caller that accepts a mismatch can still get the bytes. +pub fn read_entry_unverified(data: &[u8], e: &ZipEntry, max_bytes: u64) -> Result, ZipError> { + if e.encrypted { + return Err(ZipError::Unsupported(format!("{} is encrypted", e.name))); + } + if e.uncompressed_size > max_bytes { + return Err(ZipError::TooLarge(max_bytes)); + } + let raw = raw_entry_data(data, e)?; + let cap = usize::try_from(max_bytes).unwrap_or(usize::MAX); + let out = match e.method { + 0 if raw.len() as u64 > max_bytes => return Err(ZipError::TooLarge(max_bytes)), + 0 => raw.to_vec(), + 8 => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, cap).map_err(|err| match err.status { + miniz_oxide::inflate::TINFLStatus::HasMoreOutput => ZipError::TooLarge(max_bytes), + _ => ZipError::Corrupt(format!("deflate stream for {} is damaged", e.name)), + })?, + 12 | 95 => decode_bzip2_or_xz(raw, e, max_bytes)?, + 14 => decode_lzma(raw, e, max_bytes)?, + 93 => decode_zstd(raw, e, max_bytes)?, + m => return Err(ZipError::Unsupported(format!("compression method {m} ({}) for {}", e.method_name(), e.name))), + }; + if out.len() as u64 != e.uncompressed_size { + return Err(ZipError::Corrupt(format!( + "decoded size for {} is {}, but its directory entry declares {}", + e.name, + out.len(), + e.uncompressed_size + ))); + } + Ok(out) +} + +#[cfg(any(feature = "lenient-bzip2", feature = "lenient-lzma"))] +fn decode_bzip2_or_xz(raw: &[u8], e: &ZipEntry, max_bytes: u64) -> Result, ZipError> { + let decoded = match e.method { + #[cfg(feature = "lenient-bzip2")] + 12 => decode::bzip2(raw, max_bytes), + #[cfg(feature = "lenient-lzma")] + 95 => decode::xz(raw, max_bytes), + _ => return Err(not_built(e)), + }; + decoded.map_err(|error| match error { + decode::DecompressError::TooLarge => ZipError::TooLarge(max_bytes), + _ => ZipError::Corrupt(format!("{} stream for {} is damaged: {error}", e.method_name(), e.name)), + }) +} + +#[cfg(not(any(feature = "lenient-bzip2", feature = "lenient-lzma")))] +fn decode_bzip2_or_xz(_: &[u8], e: &ZipEntry, _: u64) -> Result, ZipError> { + Err(not_built(e)) +} + +#[cfg(feature = "lenient-lzma")] +fn decode_lzma(raw: &[u8], e: &ZipEntry, max_bytes: u64) -> Result, ZipError> { + let header = Reader::new(raw); + let properties_size = header.u16_le(2).ok_or(ZipError::Truncated("LZMA properties header"))?; + if properties_size != 5 { + return Err(ZipError::Unsupported(format!("LZMA properties size {properties_size} for {}", e.name))); + } + let stream = raw.get(4..).ok_or(ZipError::Truncated("LZMA properties"))?; + decode::lzma_zip(stream, e.uncompressed_size, e.flags & 2 != 0, max_bytes).map_err(|error| match error { + decode::DecompressError::TooLarge => ZipError::TooLarge(max_bytes), + _ => ZipError::Corrupt(format!("LZMA stream for {} is damaged: {error}", e.name)), + }) +} + +#[cfg(not(feature = "lenient-lzma"))] +fn decode_lzma(_: &[u8], e: &ZipEntry, _: u64) -> Result, ZipError> { + Err(not_built(e)) +} + +#[cfg(feature = "lenient-zstd")] +fn decode_zstd(raw: &[u8], e: &ZipEntry, max_bytes: u64) -> Result, ZipError> { + decode::zstd(raw, max_bytes).map_err(|err| ZipError::Corrupt(format!("zstd stream for {} is damaged: {err}", e.name))) +} + +#[cfg(not(feature = "lenient-zstd"))] +fn decode_zstd(_: &[u8], e: &ZipEntry, _: u64) -> Result, ZipError> { + Err(not_built(e)) +} + +/// An entry whose method this build leaves out (see the crate features). +#[cfg_attr(all(feature = "lenient-bzip2", feature = "lenient-lzma", feature = "lenient-zstd"), allow(dead_code))] +fn not_built(e: &ZipEntry) -> ZipError { + ZipError::Unsupported(format!("compression method {} ({}) for {} is not built in", e.method, e.method_name(), e.name)) +} + +/// CRC-32 (IEEE, as used by ZIP and PNG). +pub fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xffff_ffffu32; + for &b in data { + crc ^= u32::from(b); + for _ in 0..8 { + let mask = (crc & 1).wrapping_neg(); + crc = (crc >> 1) ^ (0xedb8_8320 & mask); + } + } + !crc +} + +#[cfg(test)] +mod testkit; + +#[cfg(test)] +mod tests; diff --git a/crates/zip/src/lenient/bytes.rs b/crates/zip/src/lenient/bytes.rs new file mode 100644 index 0000000000..be7aa3ebe3 --- /dev/null +++ b/crates/zip/src/lenient/bytes.rs @@ -0,0 +1,41 @@ +//! Checked little-endian reads over untrusted bytes. Every read returns `None` when out of range. + +#[derive(Debug, Clone, Copy)] +pub(crate) struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + pub(crate) fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + pub(crate) fn data(&self) -> &'a [u8] { + self.data + } + + pub(crate) fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub(crate) fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub(crate) fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub(crate) fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } + + pub(crate) fn u64_le(&self, off: usize) -> Option { + self.arr(off).map(u64::from_le_bytes) + } +} diff --git a/crates/zip/src/lenient/decode.rs b/crates/zip/src/lenient/decode.rs new file mode 100644 index 0000000000..1189451b43 --- /dev/null +++ b/crates/zip/src/lenient/decode.rs @@ -0,0 +1,352 @@ +//! Bounded decoders for the bzip2, ZIP LZMA, XZ and Zstandard entry methods, from Craft +//! Anything's `decompress.rs`. Each caps its output at `max_out` bytes (`TooLarge` rather than +//! allocating without limit) and never panics on a corrupt or truncated stream. + +use std::io; +#[cfg(any(feature = "lenient-bzip2", feature = "lenient-lzma"))] +use std::io::Read; +#[cfg(any(feature = "lenient-lzma", feature = "lenient-zstd"))] +use std::io::Write; + +/// Why a decode stopped. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub(crate) enum DecompressError { + #[error("the compressed stream is damaged")] + Corrupt, + #[error("the compressed stream ends early")] + #[cfg(any(feature = "lenient-lzma", feature = "lenient-zstd"))] + Truncated, + #[error("the output would exceed the size limit")] + TooLarge, +} + +/// A `Write` sink that collects at most `cap` bytes, then refuses the rest. The `exceeded` flag lets +/// the caller tell a size-limit stop from a genuine decode error. +#[cfg(any(feature = "lenient-lzma", feature = "lenient-zstd"))] +struct CapWrite { + buf: Vec, + cap: usize, + exceeded: bool, +} + +#[cfg(any(feature = "lenient-lzma", feature = "lenient-zstd"))] +impl CapWrite { + fn new(cap: usize) -> Self { + CapWrite { buf: Vec::new(), cap, exceeded: false } + } +} + +#[cfg(any(feature = "lenient-lzma", feature = "lenient-zstd"))] +impl Write for CapWrite { + fn write(&mut self, data: &[u8]) -> io::Result { + if self.buf.len().saturating_add(data.len()) > self.cap { + self.exceeded = true; + return Err(io::Error::other("output size limit reached")); + } + self.buf.extend_from_slice(data); + Ok(data.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +fn cap_of(max_out: u64) -> usize { + usize::try_from(max_out).unwrap_or(usize::MAX) +} + +/// Read a `Read` source into a `Vec`, capped at `cap` bytes. +#[cfg(feature = "lenient-bzip2")] +fn read_capped(mut src: impl Read, cap: usize) -> Result, DecompressError> { + let mut out = Vec::new(); + let mut chunk = [0u8; 64 * 1024]; + loop { + match src.read(&mut chunk) { + Ok(0) => return Ok(out), + Ok(n) => { + let slice = chunk.get(..n).unwrap_or(&[]); + if out.len().saturating_add(slice.len()) > cap { + return Err(DecompressError::TooLarge); + } + out.extend_from_slice(slice); + } + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(_) => return Err(DecompressError::Corrupt), + } + } +} + +#[cfg(feature = "lenient-lzma")] +/// Decompress every xz stream, including standard stream padding, within one output budget. +pub(crate) fn xz(input: &[u8], max_out: u64) -> Result, DecompressError> { + let ranges = xz_stream_ranges(input, max_out)?; + let mut out = CapWrite::new(cap_of(max_out)); + for range in ranges.into_iter().rev() { + let stream = input.get(range).ok_or(DecompressError::Truncated)?; + let mut cursor = io::Cursor::new(stream); + match lzma_rs::xz_decompress(&mut cursor, &mut out) { + Ok(()) => {} + Err(_) if out.exceeded => return Err(DecompressError::TooLarge), + Err(lzma_rs::error::Error::HeaderTooShort(_)) => return Err(DecompressError::Truncated), + Err(_) => return Err(DecompressError::Corrupt), + } + } + Ok(out.buf) +} + +#[cfg(feature = "lenient-lzma")] +/// Find stream boundaries backwards through their checked footer/index sizes, without +/// repeatedly trying the decoder at candidate magic bytes inside compressed data. +fn xz_stream_ranges(input: &[u8], max_out: u64) -> Result>, DecompressError> { + let mut ranges = Vec::new(); + let mut end = input.len(); + let mut declared = 0u64; + while end > 0 { + let padded_end = end; + while end > 0 && input.get(end - 1) == Some(&0) { + end -= 1; + } + if end == 0 || !(padded_end - end).is_multiple_of(4) { + return Err(DecompressError::Corrupt); + } + let footer_at = end.checked_sub(12).ok_or(DecompressError::Truncated)?; + let footer = input.get(footer_at..end).ok_or(DecompressError::Truncated)?; + let read = crate::lenient::bytes::Reader::new(footer); + let footer_fields = footer.get(4..10).ok_or(DecompressError::Truncated)?; + if footer.get(10..) != Some(b"YZ") || read.u32_le(0) != Some(crate::lenient::crc32(footer_fields)) { + return Err(DecompressError::Corrupt); + } + let backward = u64::from(read.u32_le(4).ok_or(DecompressError::Truncated)?); + let index_len = usize::try_from((backward + 1) * 4).map_err(|_| DecompressError::Corrupt)?; + let index_at = footer_at.checked_sub(index_len).ok_or(DecompressError::Truncated)?; + let index = input.get(index_at..footer_at).ok_or(DecompressError::Truncated)?; + let crc_at = index.len().checked_sub(4).ok_or(DecompressError::Truncated)?; + let index_read = crate::lenient::bytes::Reader::new(index); + let index_fields = index.get(..crc_at).ok_or(DecompressError::Truncated)?; + if index.first() != Some(&0) || index_read.u32_le(crc_at) != Some(crate::lenient::crc32(index_fields)) { + return Err(DecompressError::Corrupt); + } + let mut records = index.get(1..crc_at).ok_or(DecompressError::Corrupt)?; + let count = xz_vli(&mut records)?; + if count > (records.len() / 2) as u64 { + return Err(DecompressError::Corrupt); + } + let mut block_bytes = 0usize; + for _ in 0..count { + let unpadded = xz_vli(&mut records)?; + if unpadded == 0 { + return Err(DecompressError::Corrupt); + } + let padded = usize::try_from(unpadded.checked_add(3).ok_or(DecompressError::Corrupt)? & !3).map_err(|_| DecompressError::Corrupt)?; + block_bytes = block_bytes.checked_add(padded).filter(|bytes| *bytes <= index_at).ok_or(DecompressError::Corrupt)?; + declared = declared.checked_add(xz_vli(&mut records)?).filter(|size| *size <= max_out).ok_or(DecompressError::TooLarge)?; + } + if records.len() > 3 || records.iter().any(|&byte| byte != 0) { + return Err(DecompressError::Corrupt); + } + let start = index_at.checked_sub(block_bytes).and_then(|at| at.checked_sub(12)).ok_or(DecompressError::Corrupt)?; + let magic_end = start.checked_add(6).ok_or(DecompressError::Corrupt)?; + if input.get(start..magic_end) != Some(b"\xfd7zXZ\0") { + return Err(DecompressError::Corrupt); + } + ranges.push(start..end); + end = start; + } + if ranges.is_empty() { + return Err(DecompressError::Corrupt); + } + Ok(ranges) +} + +#[cfg(feature = "lenient-lzma")] +/// XZ variable-length integers have at most nine bytes and no redundant final zero. +fn xz_vli(input: &mut &[u8]) -> Result { + let mut value = 0u64; + for shift in (0..63).step_by(7) { + let (&byte, rest) = input.split_first().ok_or(DecompressError::Truncated)?; + *input = rest; + value |= u64::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + return if shift != 0 && byte == 0 { Err(DecompressError::Corrupt) } else { Ok(value) }; + } + } + Err(DecompressError::Corrupt) +} + +#[cfg(feature = "lenient-lzma")] +/// Decode the property bytes and raw stream of a ZIP method-14 member. +pub(crate) fn lzma_zip(input: &[u8], expected_size: u64, has_end_marker: bool, max_out: u64) -> Result, DecompressError> { + let cap = cap_of(max_out).min(isize::MAX as usize); + if expected_size > cap as u64 { + return Err(DecompressError::TooLarge); + } + let (properties, stream) = input.split_at_checked(5).ok_or(DecompressError::Truncated)?; + let [property, d0, d1, d2, d3] = <[u8; 5]>::try_from(properties).map_err(|_| DecompressError::Truncated)?; + let window_limit = u32::try_from(cap).unwrap_or(u32::MAX).max(4096); + let dictionary = u32::from_le_bytes([d0, d1, d2, d3]).max(4096).min(window_limit); + let [d0, d1, d2, d3] = dictionary.to_le_bytes(); + let properties = [property, d0, d1, d2, d3]; + let size = if has_end_marker { None } else { Some(expected_size) }; + let options = lzma_rs::decompress::Options { + unpacked_size: lzma_rs::decompress::UnpackedSize::UseProvided(size), + memlimit: Some(dictionary as usize), + ..Default::default() + }; + let mut out = CapWrite::new(cap); + let mut cursor = io::Cursor::new(properties).chain(io::Cursor::new(stream)); + match lzma_rs::lzma_decompress_with_options(&mut cursor, &mut out, &options) { + Ok(()) if cursor.get_ref().1.position() == stream.len() as u64 => Ok(out.buf), + Ok(()) => Err(DecompressError::Corrupt), + Err(_) if out.exceeded => Err(DecompressError::TooLarge), + Err(lzma_rs::error::Error::HeaderTooShort(_)) => Err(DecompressError::Truncated), + Err(_) => Err(DecompressError::Corrupt), + } +} + +#[cfg(feature = "lenient-bzip2")] +/// Decompress a bzip2 stream, producing at most `max_out` bytes. +pub(crate) fn bzip2(input: &[u8], max_out: u64) -> Result, DecompressError> { + read_capped(bzip2_rs::DecoderReader::new(input), cap_of(max_out)) +} + +#[cfg(feature = "lenient-zstd")] +/// Decompress a Zstandard stream, producing at most `max_out` bytes. +pub(crate) fn zstd(mut input: &[u8], max_out: u64) -> Result, DecompressError> { + if input.is_empty() { + return Err(DecompressError::Corrupt); + } + let mut out = CapWrite::new(cap_of(max_out)); + while !input.is_empty() { + if matches!(input.get(..4), Some([0x50..=0x5f, 0x2a, 0x4d, 0x18])) { + let header = input.get(4..8).and_then(|s| s.try_into().ok()).ok_or(DecompressError::Truncated)?; + let len = u32::from_le_bytes(header) as usize; + input = input.get(8..).and_then(|body| body.get(len..)).ok_or(DecompressError::Truncated)?; + continue; + } + let mut decoder = ruzstd::decoding::StreamingDecoder::new(&mut input).map_err(|_| DecompressError::Corrupt)?; + if io::copy(&mut decoder, &mut out).is_err() { + return Err(if out.exceeded { DecompressError::TooLarge } else { DecompressError::Corrupt }); + } + } + Ok(out.buf) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::lenient::testkit as fx; + + #[cfg(feature = "lenient-lzma")] + #[test] + fn xz_round_trip() { + let c = fx::XZ_FIXTURE; + assert_eq!(xz(c, 1 << 20).unwrap(), fx::XZ_PLAIN); + // A tiny cap reports TooLarge, never a partial lie. + assert_eq!(xz(c, 4), Err(DecompressError::TooLarge)); + // Truncation never panics. + for len in 0..c.len() { + let _ = xz(&c[..len], 1 << 20); + } + } + + #[cfg(feature = "lenient-lzma")] + #[test] + fn xz_concatenated_streams_and_padding_share_one_budget() { + let input = [fx::XZ_FIXTURE, &[0; 4], fx::XZ_FIXTURE, &[0; 8]].concat(); + let expected = [fx::XZ_PLAIN, fx::XZ_PLAIN].concat(); + assert_eq!(xz(&input, expected.len() as u64).unwrap(), expected); + assert_eq!(xz(&input, expected.len() as u64 - 1), Err(DecompressError::TooLarge)); + let mut empty = Vec::new(); + lzma_rs::xz_compress(&mut io::Cursor::new(b""), &mut empty).unwrap(); + let with_empty = [&empty[..], fx::XZ_FIXTURE, &empty[..]].concat(); + assert_eq!(xz(&with_empty, fx::XZ_PLAIN.len() as u64).unwrap(), fx::XZ_PLAIN); + assert!(xz(&empty, 0).unwrap().is_empty()); + } + + #[cfg(feature = "lenient-lzma")] + #[test] + fn xz_rejects_incomplete_members_and_nonstandard_padding() { + for padding in [1, 2, 3, 5] { + let input = [fx::XZ_FIXTURE, &vec![0; padding]].concat(); + assert!(xz(&input, 1000).is_err()); + } + assert!(xz(&[&[0; 4][..], fx::XZ_FIXTURE].concat(), 1000).is_err()); + assert!(xz(&[fx::XZ_FIXTURE, b"junk"].concat(), 1000).is_err()); + for missing in 1..fx::XZ_FIXTURE.len() { + let input = [fx::XZ_FIXTURE, &fx::XZ_FIXTURE[..fx::XZ_FIXTURE.len() - missing]].concat(); + assert!(xz(&input, 1000).is_err(), "missing {missing} bytes"); + } + for at in [fx::XZ_FIXTURE.len() - 13, fx::XZ_FIXTURE.len() - 12] { + let mut damaged = fx::XZ_FIXTURE.to_vec(); + damaged[at] ^= 1; + assert!(xz(&damaged, 1000).is_err()); + } + } + + #[cfg(feature = "lenient-lzma")] + #[test] + fn xz_index_sizes_and_integer_encodings_are_checked() { + assert_eq!(xz_vli(&mut &[0x80, 0][..]), Err(DecompressError::Corrupt)); + assert_eq!(xz_vli(&mut &[0xff; 10][..]), Err(DecompressError::Corrupt)); + assert_eq!(xz_vli(&mut &[0x81, 1][..]), Ok(129)); + let mut damaged = fx::XZ_FIXTURE.to_vec(); + let footer = damaged.len() - 12; + let backward = u32::from_le_bytes(damaged[footer + 4..footer + 8].try_into().unwrap()); + let index = footer - (backward as usize + 1) * 4; + damaged[index + 2] = 0; + let checksum = crate::lenient::crc32(&damaged[index..footer - 4]); + damaged[footer - 4..footer].copy_from_slice(&checksum.to_le_bytes()); + assert!(xz(&damaged, 1000).is_err()); + } + + #[cfg(feature = "lenient-bzip2")] + #[test] + fn bzip2_round_trip() { + let c = fx::BZIP2_FIXTURE; + assert_eq!(bzip2(c, 1 << 20).unwrap(), fx::BZIP2_PLAIN); + assert_eq!(bzip2(c, 2), Err(DecompressError::TooLarge)); + for len in 0..c.len() { + let _ = bzip2(&c[..len], 1 << 20); + } + } + + #[cfg(feature = "lenient-zstd")] + #[test] + fn zstd_round_trip() { + let c = fx::ZSTD_FIXTURE; + assert_eq!(zstd(c, 1 << 20).unwrap(), fx::ZSTD_PLAIN); + assert_eq!(zstd(c, 2), Err(DecompressError::TooLarge)); + for len in 0..c.len() { + let _ = zstd(&c[..len], 1 << 20); + } + } + + #[cfg(feature = "lenient-zstd")] + #[test] + fn zstandard_members_can_contain_multiple_frames() { + let frame = fx::ZSTD_FIXTURE; + let plain = fx::ZSTD_PLAIN; + let skip = [0x50, 0x2a, 0x4d, 0x18, 3, 0, 0, 0, 1, 2, 3]; + let input = [frame, &skip, frame].concat(); + let expected = [plain, plain].concat(); + assert_eq!(zstd(&input, expected.len() as u64).unwrap(), expected); + assert_eq!(zstd(&input, plain.len() as u64), Err(DecompressError::TooLarge)); + assert!(zstd(&[frame, &skip[..9]].concat(), u64::MAX).is_err()); + assert!(zstd(&[frame, &frame[..5]].concat(), u64::MAX).is_err()); + } + + #[test] + fn garbage_never_panics() { + for seed in 0..64u64 { + let n = fx::noise(seed, 400); + #[cfg(feature = "lenient-lzma")] + let _ = xz(&n, 1 << 20); + #[cfg(feature = "lenient-bzip2")] + let _ = bzip2(&n, 1 << 20); + #[cfg(feature = "lenient-zstd")] + let _ = zstd(&n, 1 << 20); + let _ = &n; + } + } +} diff --git a/crates/zip/src/lenient/file.rs b/crates/zip/src/lenient/file.rs new file mode 100644 index 0000000000..fc50dfd26f --- /dev/null +++ b/crates/zip/src/lenient/file.rs @@ -0,0 +1,262 @@ +//! One entry read straight from a ZIP file without loading the file: only its end records, its +//! central directory and that entry's bytes are read. For archives too big to hold in memory just +//! to look at one small entry (a JAR's manifest). + +use crate::lenient::bytes::Reader; +use crate::lenient::{self as zip, ZipError}; +use std::io::{Read, Seek, SeekFrom}; + +/// Most central directory read (some hundreds of thousands of entries); a bigger one is refused. +const MAX_DIRECTORY: u64 = 16 << 20; +/// The ZIP64 end record as `zip::parse` reads it, without any extensible data after it. +const ZIP64_RECORD: u64 = 56; + +/// The entry named `name` (not a folder), decompressed to at most `max_bytes` and checked against +/// its CRC-32. `None`: the archive has no such entry. +pub fn read_named_entry(file: &mut (impl Read + Seek), name: &str, max_bytes: u64) -> Result>, ZipError> { + let len = file.seek(SeekFrom::End(0)).map_err(io)?; + let tail_start = len.saturating_sub(zip::EOCD_SEARCH as u64); + let tail = read_at(file, tail_start, len - tail_start)?; + let eocd = zip::find_eocd(&tail).ok_or(ZipError::NotZip)?; + let mut end = tail.get(eocd..).ok_or(ZipError::Truncated("end record"))?.to_vec(); + let r = Reader::new(&end); + let field = |at| r.u16_le(at).ok_or(ZipError::Truncated("end record")); + let (size, classic_offset) = (r.u32_le(12).ok_or(ZipError::Truncated("end record"))?, r.u32_le(16).ok_or(ZipError::Truncated("end record"))?); + // Any of these saturated makes `zip::parse` read the ZIP64 records, as below. + let saturated = [field(4)?, field(6)?, field(8)?, field(10)?].contains(&0xffff) || size == 0xffff_ffff || classic_offset == 0xffff_ffff; + let end_at = tail_start + eocd as u64; + // A ZIP64 archive puts its own end record and a locator between the directory and the classic + // end record, whether or not the classic fields are saturated. + let locator_at = end_at.checked_sub(20); + let locator = match locator_at { + Some(at) => read_at(file, at, 20)?, + None => Vec::new(), + }; + // Its stated offset doesn't count a prepended stub; it then sits right before the locator. A + // locator signature with no record at either place is other data (an entry's comment). + let record_at = match (locator_at, locator.starts_with(b"PK\x06\x07")) { + (Some(at), true) => { + let declared = Reader::new(&locator).u64_le(8).ok_or(ZipError::Truncated("zip64 locator"))?; + [declared, at.saturating_sub(ZIP64_RECORD)].into_iter().find(|&at| read_at(file, at, 4).is_ok_and(|sig| sig == b"PK\x06\x06")) + } + _ => None, + }; + let zip64 = match record_at { + Some(record_at) => { + let record = read_at(file, record_at, ZIP64_RECORD)?; + let rr = Reader::new(&record); + let size = rr.u64_le(40).ok_or(ZipError::Truncated("zip64 record"))?; + let offset = rr.u64_le(48).ok_or(ZipError::Truncated("zip64 record"))?; + Some((record_at, size, offset, record)) + } + None => None, + }; + // Unsaturated classic fields must agree with a real ZIP64 record, as `zip::parse` requires; + // one that disagrees is other data shaped like it. + let zip64 = zip64.filter(|&(_, z_size, z_offset, _)| saturated || (z_size == u64::from(size) && z_offset == u64::from(classic_offset))); + let (directory_end, size, offset, zip64) = match zip64 { + Some((record_at, size, offset, record)) => (record_at, size, offset, saturated.then_some((record, locator))), + None => (end_at, u64::from(size), u64::from(classic_offset), None), + }; + if size > MAX_DIRECTORY { + return Err(ZipError::TooLarge(MAX_DIRECTORY)); + } + // The directory ends where the end records start; anything before its stated offset is a + // prepended stub, as `zip::parse` allows. + let start = directory_end.checked_sub(size).ok_or(ZipError::Corrupt("directory starts before the file".into()))?; + let prefix = start.checked_sub(offset).ok_or(ZipError::Corrupt("directory sits before its stated offset".into()))?; + // The directory and its end records alone, their offsets rewritten for that buffer. The + // ZIP64 records go along only when the classic fields need them, as `zip::parse` reads them. + let mut directory = read_at(file, start, size)?; + if let Some((mut record, mut locator)) = zip64 { + put(&mut record, 4, &(ZIP64_RECORD - 12).to_le_bytes())?; + put(&mut record, 48, &0u64.to_le_bytes())?; + put(&mut locator, 8, &size.to_le_bytes())?; + directory.extend_from_slice(&record); + directory.extend_from_slice(&locator); + } + // A saturated classic offset stays so: `zip::parse` then takes the rewritten ZIP64 one. + if classic_offset != 0xffff_ffff { + put(&mut end, 16, &[0; 4])?; + } + directory.extend_from_slice(&end); + // `MAX_DIRECTORY` already bounds how many entries there can be. + let archive = zip::parse(&directory, usize::MAX)?; + let Some(mut entry) = archive.entries.into_iter().find(|e| e.name == name && !e.is_dir) else { return Ok(None) }; + if entry.compressed_size > max_bytes.saturating_add(1 << 16) { + return Err(ZipError::TooLarge(max_bytes)); + } + let at = entry.local_header_offset.checked_add(prefix).ok_or(ZipError::Corrupt("local header offset".into()))?; + let header = read_at(file, at, 30)?; + let fields = Reader::new(&header); + let name_len = u64::from(fields.u16_le(26).ok_or(ZipError::Truncated("local header"))?); + let extra_len = u64::from(fields.u16_le(28).ok_or(ZipError::Truncated("local header"))?); + let local_len = (30 + name_len + extra_len).checked_add(entry.compressed_size).ok_or(ZipError::Corrupt("entry size".into()))?; + let local = read_at(file, at, local_len)?; + entry.local_header_offset = 0; + zip::read_entry(&local, &entry, max_bytes).map(Some) +} + +/// Overwrite `bytes` at `at` in a record read from the file. +fn put(record: &mut [u8], at: usize, bytes: &[u8]) -> Result<(), ZipError> { + record.get_mut(at..at + bytes.len()).ok_or(ZipError::Truncated("end record"))?.copy_from_slice(bytes); + Ok(()) +} + +/// Exactly `len` bytes from `at`; a file that ends sooner is truncated. +fn read_at(file: &mut (impl Read + Seek), at: u64, len: u64) -> Result, ZipError> { + file.seek(SeekFrom::Start(at)).map_err(io)?; + let mut out = Vec::new(); + file.take(len).read_to_end(&mut out).map_err(io)?; + if (out.len() as u64) < len { + return Err(ZipError::Truncated("file")); + } + Ok(out) +} + +fn io(e: std::io::Error) -> ZipError { + ZipError::Corrupt(format!("couldn't read it: {e}")) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + const MANIFEST: &[u8] = b"Manifest-Version: 1.0\r\nMain-Class: app.Main\r\n\r\n"; + + fn read(bytes: &[u8], name: &str) -> Result>, ZipError> { + read_named_entry(&mut Cursor::new(bytes.to_vec()), name, 1 << 20) + } + + /// The same archive with a ZIP64 end record and locator before its classic end record, whose + /// fields at these offsets are saturated (entry counts and disk numbers 2 bytes, others 4). + fn as_zip64(archive: &[u8], saturate: &[usize]) -> Vec { + let end = archive.len() - 22; + let r = Reader::new(archive); + let (entries, size, offset) = + (u64::from(r.u16_le(end + 10).unwrap()), u64::from(r.u32_le(end + 12).unwrap()), u64::from(r.u32_le(end + 16).unwrap())); + let mut out = archive[..end].to_vec(); + let record_at = out.len() as u64; + out.extend_from_slice(b"PK\x06\x06"); + out.extend_from_slice(&44u64.to_le_bytes()); + out.extend_from_slice(&[45, 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + for v in [entries, entries, size, offset] { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(b"PK\x06\x07\0\0\0\0"); + out.extend_from_slice(&record_at.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + let mut classic = archive[end..].to_vec(); + for &at in saturate { + let width = if at < 12 { 2 } else { 4 }; + classic[at..at + width].fill(0xff); + } + out.extend_from_slice(&classic); + out + } + + #[test] + fn an_entry_is_read_from_the_directory_without_the_whole_file() { + let filler = vec![7u8; 200_000]; + let archive = crate::lenient::testkit::zip_stored(&[("app/Big.class", &filler), ("META-INF/MANIFEST.MF", MANIFEST), ("META-INF/", b"")]); + assert_eq!(read(&archive, "META-INF/MANIFEST.MF").unwrap().as_deref(), Some(MANIFEST)); + assert_eq!(read(&archive, "META-INF/MISSING").unwrap(), None); + assert_eq!(read(&archive, "META-INF/").unwrap(), None, "a folder isn't an entry to read"); + + let mut stubbed = b"#!/bin/sh\nexec java -jar \"$0\" \"$@\"\n".to_vec(); + stubbed.extend_from_slice(&archive); + assert_eq!(read(&stubbed, "META-INF/MANIFEST.MF").unwrap().as_deref(), Some(MANIFEST), "a launcher stub before the archive"); + + assert_eq!(read(b"not a zip", "META-INF/MANIFEST.MF"), Err(ZipError::NotZip)); + assert!(read(&archive[..archive.len() - 30], "META-INF/MANIFEST.MF").is_err(), "a cut-off file"); + assert_eq!(read_named_entry(&mut Cursor::new(archive), "app/Big.class", 1000), Err(ZipError::TooLarge(1000))); + } + + #[test] + fn a_directory_bigger_than_the_searched_tail_is_read() { + let names: Vec = (0..3000).map(|i| format!("com/example/generated/Class{i:05}.class")).collect(); + let mut files: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), &b"x"[..])).collect(); + files.push(("META-INF/MANIFEST.MF", MANIFEST)); + let archive = crate::lenient::testkit::zip_stored(&files); + assert_eq!(read(&archive, "META-INF/MANIFEST.MF").unwrap().as_deref(), Some(MANIFEST)); + } + + /// A one-entry archive whose entry is deflated, as `jar` writes a manifest. + fn zip_deflated(name: &str, body: &[u8]) -> Vec { + let packed = miniz_oxide::deflate::compress_to_vec(body, 6); + let fixed = |out: &mut Vec| { + out.extend_from_slice(&[20, 0, 0, 0, 8, 0, 0, 0, 0, 0]); + out.extend_from_slice(&zip::crc32(body).to_le_bytes()); + out.extend_from_slice(&(packed.len() as u32).to_le_bytes()); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&[0, 0]); + }; + let mut out = b"PK\x03\x04".to_vec(); + fixed(&mut out); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(&packed); + let directory_at = out.len() as u32; + out.extend_from_slice(b"PK\x01\x02\x14\0"); + fixed(&mut out); + out.extend_from_slice(&[0; 14]); + out.extend_from_slice(name.as_bytes()); + let directory_len = out.len() as u32 - directory_at; + out.extend_from_slice(b"PK\x05\x06\0\0\0\0\x01\0\x01\0"); + out.extend_from_slice(&directory_len.to_le_bytes()); + out.extend_from_slice(&directory_at.to_le_bytes()); + out.extend_from_slice(&[0, 0]); + out + } + + #[test] + fn a_deflated_entry_and_a_comment_that_looks_like_an_end_record() { + let deflated = zip_deflated("META-INF/MANIFEST.MF", MANIFEST); + assert_eq!(read(&deflated, "META-INF/MANIFEST.MF").unwrap().as_deref(), Some(MANIFEST)); + + let mut commented = crate::lenient::testkit::zip_stored(&[("META-INF/MANIFEST.MF", MANIFEST)]); + let comment = b"built by PK\x05\x06 tools"; + let at = commented.len() - 2; + commented[at..].copy_from_slice(&(comment.len() as u16).to_le_bytes()); + commented.extend_from_slice(comment); + assert_eq!(read(&commented, "META-INF/MANIFEST.MF").unwrap().as_deref(), Some(MANIFEST)); + } + + /// The last entry's comment ends like a ZIP64 record and locator, saying the directory is huge; + /// the classic fields disagree with it and win, as they do for `zip::parse`. + #[test] + fn a_comment_shaped_like_zip64_records_is_not_read_as_them() { + let mut archive = crate::lenient::testkit::zip_stored(&[("META-INF/MANIFEST.MF", MANIFEST)]); + let end = archive.len() - 22; + let last = archive.windows(4).rposition(|w| w == b"PK\x01\x02").unwrap(); + let mut fake = b"PK\x06\x06".to_vec(); + fake.extend_from_slice(&44u64.to_le_bytes()); + fake.extend_from_slice(&[0; 28]); + fake.extend_from_slice(&(MAX_DIRECTORY + 1).to_le_bytes()); + fake.extend_from_slice(&0u64.to_le_bytes()); + fake.extend_from_slice(b"PK\x06\x07\0\0\0\0"); + fake.extend_from_slice(&0u64.to_le_bytes()); + fake.extend_from_slice(&1u32.to_le_bytes()); + archive[last + 32..last + 34].copy_from_slice(&(fake.len() as u16).to_le_bytes()); + let size = Reader::new(&archive).u32_le(end + 12).unwrap() + fake.len() as u32; + archive[end + 12..end + 16].copy_from_slice(&size.to_le_bytes()); + archive.splice(end..end, fake); + assert!(zip::parse(&archive, 10).is_ok(), "precondition: a valid archive"); + assert_eq!(read(&archive, "META-INF/MANIFEST.MF").unwrap().as_deref(), Some(MANIFEST)); + } + + /// ZIP64 end records are read with any classic fields saturated or none (`zip -fz` saturates + /// only the offset), after a stub too. + #[test] + fn zip64_archives_are_read_in_parts() { + let archive = crate::lenient::testkit::zip_stored(&[("app/Main.class", b"x"), ("META-INF/MANIFEST.MF", MANIFEST)]); + for saturate in [&[][..], &[8, 10, 12, 16], &[16], &[12], &[10], &[4]] { + let zip64 = as_zip64(&archive, saturate); + assert_eq!(read(&zip64, "META-INF/MANIFEST.MF").unwrap().as_deref(), Some(MANIFEST), "saturated {saturate:?}"); + let mut stubbed = b"#!/bin/sh\n".to_vec(); + stubbed.extend_from_slice(&zip64); + assert_eq!(read(&stubbed, "META-INF/MANIFEST.MF").unwrap().as_deref(), Some(MANIFEST), "saturated {saturate:?}, after a stub"); + } + } +} diff --git a/crates/zip/src/lenient/testkit.rs b/crates/zip/src/lenient/testkit.rs new file mode 100644 index 0000000000..ca87510e9c --- /dev/null +++ b/crates/zip/src/lenient/testkit.rs @@ -0,0 +1,80 @@ +//! Test fixtures from Craft Anything's testkit: known-good compressed streams built with the +//! reference encoders (`xz`, `bzip2`, `zstd`), a stored-only ZIP writer and a noise generator. + +#![allow(clippy::cast_possible_truncation, dead_code)] + +use crate::lenient::crc32; + +/// Plaintext of [`XZ_FIXTURE`] and [`LZMA_FIXTURE`]. +pub const XZ_PLAIN: &[u8] = b"Hello, xz compression world!\n"; +/// An xz stream of [`XZ_PLAIN`]. +pub const XZ_FIXTURE: &[u8] = &[ + 0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00, 0x00, 0x04, 0xe6, 0xd6, 0xb4, 0x46, 0x02, 0x00, 0x21, 0x01, 0x16, 0x00, 0x00, 0x00, 0x74, 0x2f, 0xe5, 0xa3, + 0x01, 0x00, 0x1c, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x78, 0x7a, 0x20, 0x63, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, + 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x5f, 0x47, 0xab, 0x2a, 0x4c, 0xd2, 0xb2, 0x00, 0x01, 0x35, 0x1d, + 0x44, 0x1b, 0xb1, 0xe1, 0x1f, 0xb6, 0xf3, 0x7d, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x59, 0x5a, +]; +/// Plaintext of [`BZIP2_FIXTURE`]. +pub const BZIP2_PLAIN: &[u8] = b"Hello, bzip2!\n"; +/// A bzip2 stream of [`BZIP2_PLAIN`]. +pub const BZIP2_FIXTURE: &[u8] = &[ + 0x42, 0x5a, 0x68, 0x39, 0x31, 0x41, 0x59, 0x26, 0x53, 0x59, 0x04, 0xad, 0x5a, 0x6b, 0x00, 0x00, 0x02, 0xdd, 0x80, 0x00, 0x10, 0x60, 0x04, 0x10, + 0x00, 0x00, 0x40, 0x12, 0x24, 0xc0, 0x10, 0x20, 0x00, 0x22, 0x00, 0x03, 0x42, 0x01, 0xa0, 0x05, 0x67, 0xde, 0x89, 0xa1, 0xa0, 0x80, 0xf1, 0x77, + 0x24, 0x53, 0x85, 0x09, 0x00, 0x4a, 0xd5, 0xa6, 0xb0, +]; +/// Plaintext of [`ZSTD_FIXTURE`]. +pub const ZSTD_PLAIN: &[u8] = b"Hello, zstd!\n"; +/// A Zstandard frame of [`ZSTD_PLAIN`]. +pub const ZSTD_FIXTURE: &[u8] = &[ + 0x28, 0xb5, 0x2f, 0xfd, 0x24, 0x0d, 0x69, 0x00, 0x00, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x7a, 0x73, 0x74, 0x64, 0x21, 0x0a, 0x41, 0xb4, + 0x53, 0xb2, +]; + +/// A stored-only ZIP of `files`. +pub fn zip_stored(files: &[(&str, &[u8])]) -> Vec { + let mut out = Vec::new(); + let mut cd = Vec::new(); + for (name, body) in files { + let off = out.len() as u32; + let crc = crc32(body); + let len = body.len() as u32; + out.extend_from_slice(b"PK\x03\x04\x14\0\0\0\0\0\0\0\0\0"); + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(body); + cd.extend_from_slice(b"PK\x01\x02\x14\0\x14\0\0\0\0\0\0\0\0\0"); + cd.extend_from_slice(&crc.to_le_bytes()); + cd.extend_from_slice(&len.to_le_bytes()); + cd.extend_from_slice(&len.to_le_bytes()); + cd.extend_from_slice(&(name.len() as u16).to_le_bytes()); + cd.extend_from_slice(&[0; 12]); + cd.extend_from_slice(&off.to_le_bytes()); + cd.extend_from_slice(name.as_bytes()); + } + let cd_off = out.len() as u32; + out.extend_from_slice(&cd); + out.extend_from_slice(b"PK\x05\x06\0\0\0\0"); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(cd.len() as u32).to_le_bytes()); + out.extend_from_slice(&cd_off.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out +} + +/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. +pub fn noise(seed: u64, len: usize) -> Vec { + let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() +} diff --git a/crates/zip/src/lenient/tests.rs b/crates/zip/src/lenient/tests.rs new file mode 100644 index 0000000000..c2ca973940 --- /dev/null +++ b/crates/zip/src/lenient/tests.rs @@ -0,0 +1,393 @@ +//! The reader's tests, from Craft Anything's `zip.rs`. + +use super::*; + +/// Minimal stored-only ZIP writer for tests. +pub(crate) fn build(files: &[(&str, &[u8])]) -> Vec { + let mut out = Vec::new(); + let mut cd = Vec::new(); + for (name, body) in files { + let off = out.len() as u32; + let crc = crc32(body); + out.extend_from_slice(b"PK\x03\x04"); + out.extend_from_slice(&[20, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(body); + cd.extend_from_slice(b"PK\x01\x02"); + cd.extend_from_slice(&[20, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + cd.extend_from_slice(&crc.to_le_bytes()); + cd.extend_from_slice(&(body.len() as u32).to_le_bytes()); + cd.extend_from_slice(&(body.len() as u32).to_le_bytes()); + cd.extend_from_slice(&(name.len() as u16).to_le_bytes()); + cd.extend_from_slice(&[0; 12]); + cd.extend_from_slice(&off.to_le_bytes()); + cd.extend_from_slice(name.as_bytes()); + } + let cd_off = out.len() as u32; + out.extend_from_slice(&cd); + out.extend_from_slice(b"PK\x05\x06\0\0\0\0"); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(cd.len() as u32).to_le_bytes()); + out.extend_from_slice(&cd_off.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out +} + +#[cfg(all(feature = "lenient-bzip2", feature = "lenient-lzma"))] +fn build_codec_entry(method: u16, compressed: &[u8], plain: &[u8]) -> Vec { + let mut file = build(&[("entry", compressed)]); + let central = 30 + "entry".len() + compressed.len(); + let version: u16 = if method == 12 { 46 } else { 63 }; + file[4..6].copy_from_slice(&version.to_le_bytes()); + file[8..10].copy_from_slice(&method.to_le_bytes()); + file[14..18].copy_from_slice(&crc32(plain).to_le_bytes()); + file[22..26].copy_from_slice(&(plain.len() as u32).to_le_bytes()); + file[central + 6..central + 8].copy_from_slice(&version.to_le_bytes()); + file[central + 10..central + 12].copy_from_slice(&method.to_le_bytes()); + file[central + 16..central + 20].copy_from_slice(&crc32(plain).to_le_bytes()); + file[central + 24..central + 28].copy_from_slice(&(plain.len() as u32).to_le_bytes()); + file +} + +#[cfg(all(feature = "lenient-bzip2", feature = "lenient-lzma"))] +#[test] +fn bzip2_and_xz_zip_entries_keep_size_crc_and_output_checks() { + use crate::lenient::testkit::{BZIP2_FIXTURE, BZIP2_PLAIN, XZ_FIXTURE, XZ_PLAIN}; + for (method, compressed, plain) in [(12, BZIP2_FIXTURE, BZIP2_PLAIN), (95, XZ_FIXTURE, XZ_PLAIN)] { + let file = build_codec_entry(method, compressed, plain); + let original = parse(&file, 1).unwrap().entries.remove(0); + assert_eq!(read_entry(&file, &original, plain.len() as u64).unwrap(), plain); + let mut entry = original.clone(); + entry.crc32 ^= 1; + assert!(matches!(read_entry(&file, &entry, 100), Err(ZipError::CrcMismatch { .. }))); + assert_eq!(read_entry_unverified(&file, &entry, 100).unwrap(), plain); + entry = original.clone(); + entry.uncompressed_size = 0; + assert!(matches!(read_entry(&file, &entry, 100), Err(ZipError::Corrupt(_)))); + assert!(matches!(read_entry(&file, &entry, plain.len() as u64 - 1), Err(ZipError::TooLarge(_)))); + let mut damaged = file.clone(); + damaged[30 + "entry".len()] ^= 0xff; + assert!(matches!(read_entry(&damaged, &original, 100), Err(ZipError::Corrupt(_)))); + entry = original; + entry.encrypted = true; + assert!(matches!(read_entry(&file, &entry, 100), Err(ZipError::Unsupported(_)))); + } +} + +#[cfg(feature = "lenient-lzma")] +fn zip_lzma_member(plain: &[u8], end_marker: bool) -> Vec { + let mut encoded = Vec::new(); + let size = if end_marker { None } else { Some(plain.len() as u64) }; + let options = lzma_rs::compress::Options { unpacked_size: lzma_rs::compress::UnpackedSize::WriteToHeader(size) }; + lzma_rs::lzma_compress_with_options(&mut std::io::Cursor::new(plain), &mut encoded, &options).unwrap(); + let mut compressed = vec![9, 4, 5, 0]; + compressed.extend_from_slice(&encoded[..5]); + compressed.extend_from_slice(&encoded[13..]); + let mut file = build(&[("entry", &compressed)]); + let central = 30 + "entry".len() + compressed.len(); + let flags: u16 = if end_marker { 2 } else { 0 }; + for (version_at, flags_at, method_at, crc_at, size_at) in + [(4, 6, 8, 14, 22), (central + 6, central + 8, central + 10, central + 16, central + 24)] + { + file[version_at..version_at + 2].copy_from_slice(&63u16.to_le_bytes()); + file[flags_at..flags_at + 2].copy_from_slice(&flags.to_le_bytes()); + file[method_at..method_at + 2].copy_from_slice(&14u16.to_le_bytes()); + file[crc_at..crc_at + 4].copy_from_slice(&crc32(plain).to_le_bytes()); + file[size_at..size_at + 4].copy_from_slice(&(plain.len() as u32).to_le_bytes()); + } + file +} + +#[cfg(feature = "lenient-lzma")] +#[test] +fn zip_lzma_reads_size_delimited_and_end_marked_streams() { + for end_marker in [false, true] { + for plain in [&b"ZIP LZMA contents"[..], &[0; 23][..]] { + let file = zip_lzma_member(plain, end_marker); + let original = parse(&file, 1).unwrap().entries.remove(0); + assert_eq!(read_entry(&file, &original, plain.len() as u64).unwrap(), plain); + assert!(matches!(read_entry(&file, &original, plain.len() as u64 - 1), Err(ZipError::TooLarge(_)))); + let mut entry = original.clone(); + entry.crc32 ^= 1; + assert!(matches!(read_entry(&file, &entry, 100), Err(ZipError::CrcMismatch { .. }))); + entry = original.clone(); + entry.uncompressed_size -= 1; + assert!(read_entry(&file, &entry, 100).is_err()); + entry = original.clone(); + entry.compressed_size -= 1; + assert!(read_entry(&file, &entry, 100).is_err()); + entry = original; + entry.compressed_size += 1; + assert!(read_entry(&file, &entry, 100).is_err()); + } + } +} + +#[cfg(feature = "lenient-lzma")] +#[test] +fn zip_lzma_rejects_bad_properties_without_unbounded_dictionaries() { + let mut file = zip_lzma_member(b"small", true); + let entry = parse(&file, 1).unwrap().entries.remove(0); + let body = 30 + "entry".len(); + file[body + 5..body + 9].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(read_entry(&file, &entry, 5).unwrap(), b"small"); + file[body + 4] = 255; + assert!(read_entry(&file, &entry, 5).is_err()); + file[body + 2..body + 4].copy_from_slice(&6u16.to_le_bytes()); + assert!(matches!(read_entry(&file, &entry, 5), Err(ZipError::Unsupported(_)))); +} + +fn build_named_entry(name: &[u8], flags: u16) -> Vec { + let mut zip = build(&[(&"x".repeat(name.len()), b"")]); + let central = 30 + name.len(); + zip[6..8].copy_from_slice(&flags.to_le_bytes()); + zip[30..central].copy_from_slice(name); + zip[central + 8..central + 10].copy_from_slice(&flags.to_le_bytes()); + zip[central + 46..central + 46 + name.len()].copy_from_slice(name); + zip +} + +#[test] +fn verified_unicode_path_overrides_a_legacy_zip_name() { + let raw = b"notes.txt"; + let unicode = "笔记.txt"; + for (flags, version, checksum, expected) in + [(0, 1, crc32(raw), unicode), (0, 1, crc32(b"old-name"), "notes.txt"), (0, 2, crc32(raw), "notes.txt"), (1 << 11, 1, crc32(raw), "notes.txt")] + { + let mut zip = build_named_entry(raw, flags); + let central = 30 + raw.len(); + let end = central + 46 + raw.len(); + let mut extra = 0x7075_u16.to_le_bytes().to_vec(); + extra.extend_from_slice(&((5 + unicode.len()) as u16).to_le_bytes()); + extra.push(version); + extra.extend_from_slice(&checksum.to_le_bytes()); + extra.extend_from_slice(unicode.as_bytes()); + zip[central + 30..central + 32].copy_from_slice(&(extra.len() as u16).to_le_bytes()); + zip[end + 12..end + 16].copy_from_slice(&((end - central + extra.len()) as u32).to_le_bytes()); + zip.splice(end..end, extra); + assert_eq!(parse(&zip, 1).unwrap().entries[0].name, expected); + } +} + +#[test] +fn directory_markers_do_not_require_a_trailing_slash() { + let sample = build(&[("folder", b"")]); + let central = 30 + "folder".len(); + for (host, attrs, directory, special) in [ + (0, 0x10u32, true, None), + (10, 0x10, true, None), + (3, 0o040755 << 16, true, None), + (3, 0o120777 << 16, false, Some("symlink")), + (0, 0x20, false, None), + (14, 0x10, true, None), + (14, 0x20, false, None), + (19, 0o040755 << 16, true, None), + (19, 0o100644 << 16, false, None), + (19, 0o120777 << 16, false, Some("symlink")), + (42, 0x10, false, None), + ] { + let mut file = sample.clone(); + file[central + 5] = host; + file[central + 38..central + 42].copy_from_slice(&attrs.to_le_bytes()); + let archive = parse(&file, 1).unwrap(); + let entry = &archive.entries[0]; + assert_eq!((entry.is_dir, entry.special_kind()), (directory, special), "host {host}, attributes {attrs:#x}"); + } +} + +#[test] +fn a_cp437_name_without_the_utf8_flag_is_decoded() { + let zip = build_named_entry(b"caf\x82.txt", 0); + assert_eq!(parse(&zip, 10).unwrap().entries[0].name, "café.txt"); +} + +#[test] +fn a_cp437_box_drawing_name_without_the_utf8_flag_is_decoded() { + let zip = build_named_entry(b"\xc9.txt", 0); + assert_eq!(parse(&zip, 10).unwrap().entries[0].name, "â•”.txt"); +} + +#[test] +fn a_utf8_name_with_the_utf8_flag_is_preserved() { + let zip = build_named_entry("한글/é.txt".as_bytes(), 0x0800); + assert_eq!(parse(&zip, 10).unwrap().entries[0].name, "한글/é.txt"); +} + +#[test] +fn a_valid_utf8_name_without_the_utf8_flag_is_preserved() { + let zip = build_named_entry("é.txt".as_bytes(), 0); + assert_eq!(parse(&zip, 10).unwrap().entries[0].name, "é.txt"); +} + +#[test] +fn an_ascii_name_is_preserved() { + let zip = build_named_entry(b"dir/file.txt", 0); + assert_eq!(parse(&zip, 10).unwrap().entries[0].name, "dir/file.txt"); +} + +#[test] +fn valid_entry_survives_eocd_signature_in_comment() { + let mut zip = build(&[("a.txt", b"hello")]); + let comment = b"PK\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; + let eocd = zip.len() - 22; + zip[eocd + 20..eocd + 22].copy_from_slice(&(comment.len() as u16).to_le_bytes()); + zip.extend_from_slice(comment); + + assert_eq!(parse(&zip, 10).unwrap().entries.len(), 1); +} + +#[test] +fn valid_entry_survives_bytes_after_eocd_comment() { + let mut zip = build(&[("a.txt", b"hello")]); + zip.extend_from_slice(b"tail"); + + assert_eq!(parse(&zip, 10).unwrap().entries.len(), 1); +} + +#[test] +fn checks_the_zip64_record_extent_including_extension_bytes() { + let mut record = vec![0; 56]; + record[..4].copy_from_slice(b"PK\x06\x06"); + record[4..12].copy_from_slice(&46u64.to_le_bytes()); + record.extend([1, 2]); // extensible data + record.extend(b"PK\x06\x07"); + record.extend([0; 12]); + record.extend(1u32.to_le_bytes()); + record.extend(b"PK\x05\x06"); + record.extend([0; 4]); + record.extend([0xff; 4]); + record.extend([0; 10]); + assert!(parse(&record, 1).unwrap().zip64); + for len in [44u64, 47] { + record[4..12].copy_from_slice(&len.to_le_bytes()); + let archive = parse(&record, 1).unwrap(); + assert!(archive.zip64); + assert_eq!(archive.warnings.len(), 1); + } + for len in [43u64, u64::MAX] { + record[4..12].copy_from_slice(&len.to_le_bytes()); + assert!(parse(&record, 1).is_err(), "{len}"); + } +} + +#[test] +fn lists_and_reads_stored_entries() { + let z = build(&[("a.txt", b"hello"), ("dir/b.js", b"console.log(1)")]); + let a = parse(&z, 100).unwrap(); + assert_eq!(a.entries.len(), 2); + assert_eq!(a.entries[1].name, "dir/b.js"); + assert_eq!(read_entry(&z, &a.entries[0], 100).unwrap(), b"hello"); + assert!(matches!(read_entry(&z, &a.entries[1], 3), Err(ZipError::TooLarge(3)))); +} + +#[cfg(feature = "lenient-zstd")] +#[test] +fn zstandard_members_are_read_with_their_limits_and_checks() { + // A raw Zstandard frame holding "hello zip" (single segment, one raw block). + let body = b"hello zip"; + let mut frame = vec![0x28, 0xb5, 0x2f, 0xfd, 0x20, body.len() as u8]; + let block_header = ((body.len() as u32) << 3) | 1; + frame.extend(&block_header.to_le_bytes()[..3]); + frame.extend(body); + let mut file = vec![0u8; 30]; + file[..4].copy_from_slice(b"PK\x03\x04"); + file.extend(&frame); + let mut e = ZipEntry { + name: "x".into(), + method: 93, + flags: 0, + crc32: crc32(body), + compressed_size: frame.len() as u64, + uncompressed_size: body.len() as u64, + local_header_offset: 0, + is_dir: false, + encrypted: false, + unix_mode: None, + }; + assert_eq!(read_entry(&file, &e, 100).unwrap(), body); + assert!(matches!(read_entry(&file, &e, 3), Err(ZipError::TooLarge(3)))); + e.crc32 ^= 1; + assert!(matches!(read_entry(&file, &e, 100), Err(ZipError::CrcMismatch { .. }))); +} + +#[test] +fn deflate_round_trip_and_crc_check() { + let body = b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".repeat(20); + let comp = miniz_oxide::deflate::compress_to_vec(&body, 6); + let e = ZipEntry { + name: "x".into(), + method: 8, + flags: 0, + crc32: crc32(&body), + compressed_size: comp.len() as u64, + uncompressed_size: body.len() as u64, + local_header_offset: 0, + is_dir: false, + encrypted: false, + unix_mode: None, + }; + let mut z = b"PK\x03\x04".to_vec(); + z.extend_from_slice(&[0; 26]); + z.extend_from_slice(&comp); + assert_eq!(read_entry(&z, &e, 1 << 20).unwrap(), body); + // A lying uncompressed size can't make us exceed the cap. + let liar = ZipEntry { uncompressed_size: 10, ..e.clone() }; + assert!(matches!(read_entry(&z, &liar, 10), Err(ZipError::TooLarge(10)))); + let bad = ZipEntry { crc32: 1, ..e }; + assert!(matches!(read_entry(&z, &bad, 1 << 20), Err(ZipError::CrcMismatch { .. }))); +} + +#[test] +fn hostile_inputs_do_not_panic() { + let z = build(&[("a", b"1"), ("b", b"22")]); + for cut in 0..z.len() { + if let Ok(a) = parse(&z[..cut], 10) { + for e in &a.entries { + let _ = read_entry(&z[..cut], e, 100); + } + } + } + for i in 0..z.len() { + let mut m = z.clone(); + m[i] ^= 0xff; + if let Ok(a) = parse(&m, 10) { + for e in &a.entries { + let _ = read_entry(&m, e, 100); + } + } + } + assert_eq!(parse(b"", 1), Err(ZipError::NotZip)); +} + +#[test] +fn crc_known_value() { + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); +} + +#[cfg(feature = "serde")] +#[test] +fn listings_serialize_without_empty_warnings_or_unix_mode() { + let data = crate::lenient::testkit::zip_stored(&[("a.txt", b"hi")]); + let archive = parse(&data, 10).unwrap(); + let value = serde_json::to_value(&archive).unwrap(); + assert!(value.get("warnings").is_none()); + assert_eq!(value["entries"][0]["name"], "a.txt"); + assert!(value["entries"][0].get("unix_mode").is_none()); +} + +#[cfg(not(feature = "lenient-zstd"))] +#[test] +fn a_method_left_out_of_the_build_is_unsupported() { + let mut data = crate::lenient::testkit::zip_stored(&[("a", b"abc")]); + let archive = parse(&data, 10).unwrap(); + let mut entry = archive.entries[0].clone(); + entry.method = 93; + data[8..10].copy_from_slice(&93u16.to_le_bytes()); + assert!(matches!(read_entry_unverified(&data, &entry, 100), Err(ZipError::Unsupported(m)) if m.contains("not built in"))); +} diff --git a/crates/zip/src/lib.rs b/crates/zip/src/lib.rs index 452351ee36..ff8ce17a63 100644 --- a/crates/zip/src/lib.rs +++ b/crates/zip/src/lib.rs @@ -13,6 +13,9 @@ //! timestamp on every entry so equal input gives equal bytes. //! - [`preflight`] is a stricter check of the whole end-record and central-directory structure //! on the raw bytes, for a caller that wants nothing ambiguous to reach a ZIP reader at all. +//! - `lenient` (feature `lenient`) is the other way round: a reader of the raw bytes without +//! `zip`, for inspectors that list and describe damaged or unusual archives instead of refusing +//! them, with bounded, CRC-checked entry reads. //! //! Every limit is the caller's number. Entry-name rules (which names are safe, which spellings //! are one part) stay with the format that knows them. @@ -23,13 +26,19 @@ struct ReadmeExamples; mod archive; mod guard; +#[cfg(feature = "lenient")] +pub mod lenient; +mod metadata_reader; pub mod preflight; +mod seekable; mod write; pub use archive::{Archive, Limits}; pub use guard::check_entry_count; #[cfg(any(test, feature = "test-support"))] pub use guard::zip64_entry_count_sample; +pub use metadata_reader::{Indexing, MetadataReader}; +pub use seekable::{InspectError, inspect_seekable}; pub use write::{Compression, Writer}; /// The payload of a ZIP's first entry when it is a stored file named `mimetype` of at most 256 diff --git a/crates/zip/src/metadata_reader.rs b/crates/zip/src/metadata_reader.rs new file mode 100644 index 0000000000..6bba5759d4 --- /dev/null +++ b/crates/zip/src/metadata_reader.rs @@ -0,0 +1,114 @@ +//! Bound the reads a ZIP indexer may perform before accessing entry payloads. + +use std::io::{self, Read, Seek, SeekFrom}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// A seekable reader whose indexing phase is restricted to a tail window and read budget. +/// +/// Keep the returned [`Indexing`] handle until the ZIP central directory has been parsed, then +/// call [`Indexing::finish`] to allow normal entry reads. Repeated reads during indexing count +/// towards the allowance, including reads after seeks. This bounds metadata scanning without +/// buffering the whole file or restricting the size of its payload entries. +pub struct MetadataReader { + inner: R, + indexing: Arc, + metadata_start: u64, + remaining: u64, + position: u64, +} + +/// Controls the indexing restriction for the associated reader. +#[derive(Clone)] +pub struct Indexing(Arc); + +impl Indexing { + /// Permit reads outside the metadata window once indexing is finished. + pub fn finish(&self) { + self.0.store(false, Ordering::Release); + } +} + +impl MetadataReader { + /// Limit indexing to the last `metadata_bytes` bytes and at most twice that many bytes read. + pub fn new(mut inner: R, metadata_bytes: u64) -> io::Result<(Self, Indexing)> { + let end = inner.seek(SeekFrom::End(0))?; + let indexing = Arc::new(AtomicBool::new(true)); + let handle = Indexing(indexing.clone()); + Ok(( + Self { inner, indexing, metadata_start: end.saturating_sub(metadata_bytes), remaining: metadata_bytes.saturating_mul(2), position: end }, + handle, + )) + } +} + +impl Read for MetadataReader { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + if bytes.is_empty() { + return Ok(0); + } + let indexing = self.indexing.load(Ordering::Acquire); + if indexing && (self.position < self.metadata_start || self.remaining == 0) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "ZIP metadata exceeds the indexing limit")); + } + let length = if indexing { bytes.len().min(usize::try_from(self.remaining).unwrap_or(usize::MAX)) } else { bytes.len() }; + let read = self.inner.read(bytes.get_mut(..length).unwrap_or_default())?; + self.position = self.position.saturating_add(read as u64); + if indexing { + self.remaining -= read as u64; + } + Ok(read) + } +} + +impl Seek for MetadataReader { + fn seek(&mut self, from: SeekFrom) -> io::Result { + self.position = self.inner.seek(from)?; + Ok(self.position) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn indexing_cannot_read_payloads_outside_the_metadata_window() { + let (mut reader, indexing) = MetadataReader::new(Cursor::new(vec![7; 100]), 8).unwrap(); + reader.seek(SeekFrom::Start(91)).unwrap(); + assert!(reader.read(&mut [0; 1]).is_err()); + reader.seek(SeekFrom::Start(92)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + indexing.finish(); + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 100]).unwrap(); + } + + #[test] + fn zip_indexing_is_tail_bounded_then_payload_reads_stream() { + let mut writer = crate::Writer::new(); + writer.add("large.bin", &vec![42; 131_072], crate::Compression::Stored).unwrap(); + let bytes = writer.finish().unwrap(); + let (reader, indexing) = MetadataReader::new(Cursor::new(bytes), 16_384).unwrap(); + let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) }; + let mut archive = zip::ZipArchive::with_config(config, reader).unwrap(); + assert!(archive.by_name("large.bin").is_err(), "indexing must not read the payload header"); + indexing.finish(); + let mut entry = archive.by_name("large.bin").unwrap(); + let mut payload = Vec::new(); + entry.read_to_end(&mut payload).unwrap(); + assert_eq!(payload, vec![42; 131_072]); + } + + #[test] + fn repeated_metadata_scans_share_one_read_allowance() { + let (mut reader, _indexing) = MetadataReader::new(Cursor::new(vec![7; 8]), 8).unwrap(); + for _ in 0..2 { + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + } + reader.seek(SeekFrom::Start(0)).unwrap(); + assert!(reader.read(&mut [0; 1]).is_err()); + } +} diff --git a/crates/zip/src/seekable.rs b/crates/zip/src/seekable.rs new file mode 100644 index 0000000000..2750a0123d --- /dev/null +++ b/crates/zip/src/seekable.rs @@ -0,0 +1,75 @@ +//! Checks for an already indexed, seekable ZIP archive. + +use std::io::{Read, Seek}; + +/// Why an indexed seekable archive exceeded its caller's limits. +#[derive(Debug, thiserror::Error)] +pub enum InspectError { + #[error("the archive has {actual} entries, more than {limit}")] + TooManyEntries { actual: usize, limit: usize }, + #[error("declared entry sizes exceed {limit} bytes")] + DeclaredBytesExceeded { limit: u64 }, + #[error("ZIP entries overlap")] + OverlappingEntries, + #[error("ZIP index: {0}")] + Zip(#[from] zip::result::ZipError), +} + +/// Check every declared payload, including entries the caller may ignore, and reject overlapping +/// entry headers and compressed ranges. This is a post-index check; it does not replace a pre-index count guard or +/// bound bytes actually decompressed by a caller. +pub fn inspect_seekable(archive: &mut zip::ZipArchive, max_entries: usize, max_declared_bytes: u64) -> Result<(), InspectError> { + if archive.len() > max_entries { + return Err(InspectError::TooManyEntries { actual: archive.len(), limit: max_entries }); + } + let mut remaining = max_declared_bytes; + for index in 0..archive.len() { + remaining = + remaining.checked_sub(archive.by_index_raw(index)?.size()).ok_or(InspectError::DeclaredBytesExceeded { limit: max_declared_bytes })?; + } + if archive.has_overlapping_entries()? { + return Err(InspectError::OverlappingEntries); + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use std::io::{Cursor, Write}; + + #[test] + fn counts_all_declared_entries_and_detects_aliases() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + writer.start_file("first", options).unwrap(); + writer.write_all(b"payload").unwrap(); + writer.shallow_copy_file("first", "alias").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); + assert!(matches!(inspect_seekable(&mut archive, 1, 14), Err(InspectError::TooManyEntries { .. }))); + assert!(matches!(inspect_seekable(&mut archive, 2, 13), Err(InspectError::DeclaredBytesExceeded { .. }))); + assert!(matches!(inspect_seekable(&mut archive, 2, 14), Err(InspectError::OverlappingEntries))); + } + + #[test] + fn empty_aliases_still_overlap_at_the_header() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("empty", zip::write::SimpleFileOptions::default()).unwrap(); + writer.shallow_copy_file("empty", "alias").unwrap(); + let mut archive = zip::ZipArchive::new(Cursor::new(writer.finish().unwrap().into_inner())).unwrap(); + assert!(matches!(inspect_seekable(&mut archive, 2, 0), Err(InspectError::OverlappingEntries))); + } + + #[test] + fn permits_exact_limits_and_empty_archive() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("a", zip::write::SimpleFileOptions::default()).unwrap(); + writer.write_all(b"123").unwrap(); + let mut archive = zip::ZipArchive::new(Cursor::new(writer.finish().unwrap().into_inner())).unwrap(); + assert!(inspect_seekable(&mut archive, 1, 3).is_ok()); + let empty = zip::ZipWriter::new(Cursor::new(Vec::new())).finish().unwrap().into_inner(); + assert!(inspect_seekable(&mut zip::ZipArchive::new(Cursor::new(empty)).unwrap(), 0, 0).is_ok()); + } +} diff --git a/crates/zip/tests/archive.rs b/crates/zip/tests/archive.rs index 2c4b84113e..d3b135a9c2 100644 --- a/crates/zip/tests/archive.rs +++ b/crates/zip/tests/archive.rs @@ -182,3 +182,26 @@ fn a_clone_keeps_its_own_count() { assert_eq!((c.budget().used(), z.budget().used()), (3, 0)); assert!(z.read("a", 10).unwrap().is_some()); } + +#[test] +fn owned_archive_reads_and_clones_with_independent_budgets() { + let bytes = archive(&[("a", b"abc", Compression::Deflated)]); + let mut z = Archive::open_owned(bytes, Limits { max_total_bytes: 3, ..ROOMY }).unwrap(); + let mut clone = z.clone(); + assert_eq!(z.read("a", 3).unwrap().as_deref(), Some(&b"abc"[..])); + assert!(matches!(z.read("a", 3), Err(Error::BudgetSpent { .. }))); + assert_eq!(clone.read("a", 3).unwrap().as_deref(), Some(&b"abc"[..])); + assert_eq!(clone.budget().used(), 3); +} + +#[test] +fn owned_archive_applies_directory_guards() { + let mut bytes = archive(&[("a", b"1", Compression::Stored), ("b", b"2", Compression::Stored)]); + assert!(matches!(Archive::open_owned(bytes.clone(), Limits { max_entries: 1, ..ROOMY }), Err(Error::TooManyEntries { .. }))); + let local = find(&bytes, b"PK\x03\x04", 4); + bytes[local + 30] = b'a'; + let central = find(&bytes, b"PK\x01\x02", find(&bytes, b"PK\x01\x02", 0) + 4); + bytes[central + 46] = b'a'; + assert!(Archive::open_owned(bytes, ROOMY).unwrap().has_duplicate_names()); + assert!(Archive::open_owned(b"invalid".to_vec(), ROOMY).is_err()); +} diff --git a/crates/zip/tests/lenient_common/mod.rs b/crates/zip/tests/lenient_common/mod.rs new file mode 100644 index 0000000000..05d8c5fff5 --- /dev/null +++ b/crates/zip/tests/lenient_common/mod.rs @@ -0,0 +1,41 @@ +//! The stored-only ZIP writer the integration tests share, as in Craft Anything's testkit. + +#![allow(dead_code, clippy::cast_possible_truncation)] + +use craft_zip::lenient::crc32; + +/// A stored-only ZIP of `files`. +pub fn zip_stored(files: &[(&str, &[u8])]) -> Vec { + let mut out = Vec::new(); + let mut cd = Vec::new(); + for (name, body) in files { + let off = out.len() as u32; + let crc = crc32(body); + let len = body.len() as u32; + out.extend_from_slice(b"PK\x03\x04\x14\0\0\0\0\0\0\0\0\0"); + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(body); + cd.extend_from_slice(b"PK\x01\x02\x14\0\x14\0\0\0\0\0\0\0\0\0"); + cd.extend_from_slice(&crc.to_le_bytes()); + cd.extend_from_slice(&len.to_le_bytes()); + cd.extend_from_slice(&len.to_le_bytes()); + cd.extend_from_slice(&(name.len() as u16).to_le_bytes()); + cd.extend_from_slice(&[0; 12]); + cd.extend_from_slice(&off.to_le_bytes()); + cd.extend_from_slice(name.as_bytes()); + } + let cd_off = out.len() as u32; + out.extend_from_slice(&cd); + out.extend_from_slice(b"PK\x05\x06\0\0\0\0"); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(cd.len() as u32).to_le_bytes()); + out.extend_from_slice(&cd_off.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out +} diff --git a/crates/zip/tests/lenient_zip64_end_record_compatibility.rs b/crates/zip/tests/lenient_zip64_end_record_compatibility.rs new file mode 100644 index 0000000000..ed599fbdae --- /dev/null +++ b/crates/zip/tests/lenient_zip64_end_record_compatibility.rs @@ -0,0 +1,171 @@ +#![cfg(feature = "lenient")] +// From Craft Anything crates/formats/tests/zip64_end_record_compatibility.rs. +use craft_zip::lenient::{self as zip, ZipArchive, ZipError}; +#[path = "lenient_common/mod.rs"] +mod common; +use common::zip_stored; + +fn warning_contains(archive: &ZipArchive, text: &str) -> bool { + archive.warnings.iter().any(|warning| warning.contains(text)) +} + +fn zip64_with_extension(extension: &[u8]) -> (Vec, usize) { + let mut data = zip_stored(&[("a.txt", b"retained payload")]); + let end = data.len() - 22; + let size = u32::from_le_bytes(data[end + 12..end + 16].try_into().unwrap()); + let offset = u32::from_le_bytes(data[end + 16..end + 20].try_into().unwrap()); + let mut record = b"PK\x06\x06".to_vec(); + record.extend((44 + extension.len() as u64).to_le_bytes()); + record.extend([45, 0, 45, 0]); + record.extend([0; 8]); + record.extend(1u64.to_le_bytes()); + record.extend(1u64.to_le_bytes()); + record.extend(u64::from(size).to_le_bytes()); + record.extend(u64::from(offset).to_le_bytes()); + record.extend(extension); + record.extend(b"PK\x06\x07"); + record.extend(0u32.to_le_bytes()); + record.extend((end as u64).to_le_bytes()); + record.extend(1u32.to_le_bytes()); + data[end + 8..end + 12].fill(0xff); + data.splice(end..end, record); + (data, end) +} + +#[test] +fn readable_fixed_fields_survive_inconsistent_declared_extents() { + let (original, record) = zip64_with_extension(&[1, 2, 3, 4]); + for declared in [44u64, 47, 49, 4096] { + let mut data = original.clone(); + data[record + 4..record + 12].copy_from_slice(&declared.to_le_bytes()); + let archive = zip::parse(&data, 10).unwrap(); + assert!(archive.zip64); + assert_eq!(archive.declared_entries, 1); + assert_eq!(archive.entries.len(), 1); + assert_eq!(archive.prefix_bytes, 0); + assert!(warning_contains(&archive, "extent"), "declared payload {declared}"); + assert_eq!(zip::read_entry(&data, &archive.entries[0], 100).unwrap(), b"retained payload"); + } +} + +#[test] +fn correctly_sized_extensions_need_no_warning() { + for extension in [&[][..], &[1, 2, 3, 4][..]] { + let (data, _) = zip64_with_extension(extension); + let archive = zip::parse(&data, 10).unwrap(); + assert!(archive.zip64); + assert!(archive.warnings.is_empty()); + assert_eq!(zip::read_entry(&data, &archive.entries[0], 100).unwrap(), b"retained payload"); + } +} + +#[test] +fn too_small_and_overflowing_record_extents_remain_untrusted() { + let (original, record) = zip64_with_extension(&[]); + for declared in [0u64, 43, u64::MAX - 12, u64::MAX] { + let mut data = original.clone(); + data[record + 4..record + 12].copy_from_slice(&declared.to_le_bytes()); + assert!(matches!(zip::parse(&data, 10), Err(ZipError::Corrupt(_))), "declared payload {declared}"); + } +} + +#[test] +fn fixed_fields_cannot_borrow_bytes_from_the_locator() { + let (mut data, record) = zip64_with_extension(&[]); + data.drain(record + 48..record + 56); + assert!(zip::parse(&data, 10).is_err()); +} + +#[test] +fn prepended_stubs_keep_real_zip64_directories_and_entry_offsets() { + for extension in [&[][..], &[1, 2, 3, 4][..], &[0; 1024][..]] { + let (original, _) = zip64_with_extension(extension); + for prefix in [&b"MZ"[..], &b"MZ synthetic self-extracting prefix"[..]] { + for saturated_bounds in [false, true] { + let mut data = prefix.to_vec(); + data.extend(&original); + if saturated_bounds { + let end = data.len() - 22; + data[end + 12..end + 20].fill(0xff); + } + let archive = zip::parse(&data, 10).unwrap(); + assert!(archive.zip64); + assert_eq!(archive.declared_entries, 1); + assert_eq!(archive.entries.len(), 1); + assert_eq!(archive.prefix_bytes, prefix.len() as u64); + assert_eq!(archive.entries[0].local_header_offset, prefix.len() as u64); + assert!(warning_contains(&archive, "recovered")); + assert_eq!(zip::read_entry(&data, &archive.entries[0], 100).unwrap(), b"retained payload"); + } + } + } +} + +#[test] +fn shifted_fixed_records_keep_extent_warnings() { + let (original, record) = zip64_with_extension(&[]); + let prefix = b"MZ synthetic self-extracting prefix"; + for declared in [45u64, 4096] { + let mut data = prefix.to_vec(); + data.extend(&original); + let record = record + prefix.len(); + data[record + 4..record + 12].copy_from_slice(&declared.to_le_bytes()); + let archive = zip::parse(&data, 10).unwrap(); + assert_eq!(archive.prefix_bytes, prefix.len() as u64); + assert!(warning_contains(&archive, "recovered")); + assert!(warning_contains(&archive, "extent")); + assert_eq!(zip::read_entry(&data, &archive.entries[0], 100).unwrap(), b"retained payload"); + } +} + +#[test] +fn shifted_record_recovery_has_a_bounded_lookbehind() { + let (original, _) = zip64_with_extension(&[0; 65_536]); + let mut data = b"MZ synthetic self-extracting prefix".to_vec(); + data.extend(&original); + assert!(zip::parse(&data, 10).is_err()); +} + +#[test] +fn an_unusable_locator_keeps_the_classic_directory_and_prefix_adjustment() { + // 65,535 is a valid classic count as well as a ZIP64 sentinel. A final entry comment + // can look like a locator without actually pointing to a ZIP64 end record. + let files = vec![("a.txt", &b"retained payload"[..]); 65_535]; + let original = zip_stored(&files); + let end = original.len() - 22; + let size = u32::from_le_bytes(original[end + 12..end + 16].try_into().unwrap()); + let last_entry = end - 46 - "a.txt".len(); + let mut locator = b"PK\x06\x07".to_vec(); + locator.extend(0u32.to_le_bytes()); + locator.extend(1u64.to_le_bytes()); + locator.extend(1u32.to_le_bytes()); + // A nearby record-shaped comment is still not a ZIP64 directory when its bounds + // disagree with the explicit classic fields. + let mut fake_record = [0; 56]; + fake_record[..4].copy_from_slice(b"PK\x06\x06"); + fake_record[4..12].copy_from_slice(&44u64.to_le_bytes()); + for record_shaped_comment in [&[][..], &fake_record[..]] { + let mut comment = record_shaped_comment.to_vec(); + comment.extend(&locator); + let mut archive_data = original.clone(); + archive_data[last_entry + 32..last_entry + 34].copy_from_slice(&(comment.len() as u16).to_le_bytes()); + archive_data[end + 12..end + 16].copy_from_slice(&(size + comment.len() as u32).to_le_bytes()); + archive_data.splice(end..end, comment); + for prefix in [&[][..], &b"MZ synthetic self-extracting prefix"[..]] { + for offset in [1u64, u64::MAX] { + let mut data = prefix.to_vec(); + data.extend(&archive_data); + let locator = data.len() - 22 - 20; + data[locator + 8..locator + 16].copy_from_slice(&offset.to_le_bytes()); + let archive = zip::parse(&data, 2).unwrap(); + assert!(!archive.zip64); + assert_eq!(archive.declared_entries, 65_535); + assert_eq!(archive.entries.len(), 2); + assert!(archive.truncated); + assert_eq!(archive.prefix_bytes, prefix.len() as u64); + assert!(warning_contains(&archive, "classic end record")); + assert_eq!(zip::read_entry(&data, &archive.entries[0], 100).unwrap(), b"retained payload"); + } + } + } +} diff --git a/crates/zip/tests/lenient_zip64_extra_boundaries.rs b/crates/zip/tests/lenient_zip64_extra_boundaries.rs new file mode 100644 index 0000000000..fae4fd5f91 --- /dev/null +++ b/crates/zip/tests/lenient_zip64_extra_boundaries.rs @@ -0,0 +1,66 @@ +#![cfg(feature = "lenient")] +// From Craft Anything crates/formats/tests/zip64_extra_boundaries.rs. + +#[path = "lenient_common/mod.rs"] +mod common; +use craft_zip::lenient as zip; + +fn archive(extra: &[u8], sentinel: usize) -> Vec { + let mut data = common::zip_stored(&[("a", b"x")]); + let central = data.windows(4).position(|w| w == b"PK\x01\x02").unwrap(); + let end = data.len() - 22; + data[central + sentinel..central + sentinel + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + data[central + 30..central + 32].copy_from_slice(&(extra.len() as u16).to_le_bytes()); + data.splice(end..end, extra.iter().copied()); + let end = data.len() - 22; + data[end + 12..end + 16].copy_from_slice(&((47 + extra.len()) as u32).to_le_bytes()); + data +} + +#[test] +fn a_short_zip64_field_cannot_borrow_values_from_its_neighbor() { + for field in [20, 24, 42] { + let mut extra = vec![1, 0, 0, 0, 2, 0, 8, 0]; + extra.extend_from_slice(&1u64.to_le_bytes()); + assert!(zip::parse(&archive(&extra, field), 10).is_err(), "field {field}"); + } +} + +#[test] +fn zip64_sentinels_require_complete_values() { + for field in [20, 24, 42] { + assert!(zip::parse(&archive(&[], field), 10).is_err()); + assert!(zip::parse(&archive(&[1, 0, 7, 0, 1, 0, 0, 0, 0, 0, 0], field), 10).is_err()); + } +} + +#[test] +fn a_complete_zip64_field_preserves_the_value() { + for field in [20, 24, 42] { + let value = if field == 42 { 0u64 } else { 1u64 }; + let mut extra = vec![1, 0, 8, 0]; + extra.extend_from_slice(&value.to_le_bytes()); + let data = archive(&extra, field); + let parsed = zip::parse(&data, 10).unwrap(); + assert_eq!(zip::read_entry(&data, &parsed.entries[0], 1).unwrap(), b"x"); + } +} + +#[test] +fn a_legitimate_64_bit_value_equal_to_the_32_bit_sentinel_is_preserved() { + let mut extra = vec![1, 0, 8, 0]; + extra.extend_from_slice(&u64::from(u32::MAX).to_le_bytes()); + let archive = zip::parse(&archive(&extra, 24), 10).unwrap(); + assert_eq!(archive.entries[0].uncompressed_size, u64::from(u32::MAX)); +} + +#[test] +fn trailing_bytes_too_short_for_a_field_header_are_padding() { + for stray in 1..=3usize { + let mut extra = vec![0xaa, 0xbb, 0, 0]; + extra.extend(std::iter::repeat_n(0u8, stray)); + let data = archive(&extra, 36); + let parsed = zip::parse(&data, 10).unwrap(); + assert_eq!(zip::read_entry(&data, &parsed.entries[0], 1).unwrap(), b"x", "stray {stray}"); + } +} diff --git a/crates/zip/tests/lenient_zip_decoded_size.rs b/crates/zip/tests/lenient_zip_decoded_size.rs new file mode 100644 index 0000000000..9db3ec80e9 --- /dev/null +++ b/crates/zip/tests/lenient_zip_decoded_size.rs @@ -0,0 +1,45 @@ +#![cfg(feature = "lenient")] +// From Craft Anything crates/formats/tests/zip_decoded_size.rs. + +#[path = "lenient_common/mod.rs"] +mod common; +use craft_zip::lenient::{self as zip, ZipEntry, ZipError}; + +fn deflated(body: &[u8]) -> (Vec, ZipEntry) { + let compressed = miniz_oxide::deflate::compress_to_vec(body, 6); + let mut data = vec![0; 30]; + data[..4].copy_from_slice(b"PK\x03\x04"); + data.extend_from_slice(&compressed); + let entry = ZipEntry { + name: "payload".into(), + method: 8, + flags: 0, + crc32: zip::crc32(body), + compressed_size: compressed.len() as u64, + uncompressed_size: body.len() as u64, + local_header_offset: 0, + is_dir: false, + encrypted: false, + unix_mode: None, + }; + (data, entry) +} + +#[test] +fn decoded_length_must_match_the_directory_even_when_the_crc_matches() { + let (data, good) = deflated(b"complete body"); + for declared in [1, good.uncompressed_size + 1] { + let entry = ZipEntry { uncompressed_size: declared, ..good.clone() }; + assert!(matches!(zip::read_entry(&data, &entry, 100), Err(ZipError::Corrupt(_)))); + assert!(matches!(zip::read_entry_unverified(&data, &entry, 100), Err(ZipError::Corrupt(_)))); + } + assert_eq!(zip::read_entry(&data, &good, 100).unwrap(), b"complete body"); +} + +#[test] +fn stored_length_must_also_match_the_directory() { + let data = common::zip_stored(&[("payload", b"hello")]); + let mut entry = zip::parse(&data, 10).unwrap().entries.remove(0); + entry.uncompressed_size = 4; + assert!(matches!(zip::read_entry(&data, &entry, 100), Err(ZipError::Corrupt(_)))); +} diff --git a/crates/zip/tests/lenient_zip_directory_bounds.rs b/crates/zip/tests/lenient_zip_directory_bounds.rs new file mode 100644 index 0000000000..8e912fc3b7 --- /dev/null +++ b/crates/zip/tests/lenient_zip_directory_bounds.rs @@ -0,0 +1,76 @@ +#![cfg(feature = "lenient")] +// From Craft Anything crates/formats/tests/zip_directory_bounds.rs. +use craft_zip::lenient::{self as zip, ZipError}; +#[path = "lenient_common/mod.rs"] +mod common; +use common::zip_stored; + +#[test] +fn a_short_declared_entry_is_rejected_before_its_signature_is_checked() { + for remaining in 0..46 { + let mut data = zip_stored(&[("a", b"x")]); + let end = data.len() - 22; + let size = u32::from_le_bytes(data[end + 12..end + 16].try_into().unwrap()); + data[end + 8..end + 12].copy_from_slice(&[2, 0, 2, 0]); + data[end + 12..end + 16].copy_from_slice(&(size + remaining).to_le_bytes()); + data.splice(end..end, vec![0; remaining as usize]); + assert!(matches!(zip::parse(&data, 10), Err(ZipError::Truncated("directory entry"))), "remaining {remaining} bytes"); + } +} + +#[test] +fn directory_names_and_comments_cannot_borrow_end_record_bytes() { + for field in [28, 32] { + let mut data = zip_stored(&[("a", b"x")]); + let central = data.windows(4).position(|w| w == b"PK\x01\x02").unwrap(); + let length = if field == 28 { 2u16 } else { 1 }; + data[central + field..central + field + 2].copy_from_slice(&length.to_le_bytes()); + assert!(zip::parse(&data, 10).is_err(), "field {field}"); + } +} + +#[test] +fn directory_extra_fields_cannot_borrow_end_record_bytes() { + let mut data = zip_stored(&[("a", b"x")]); + let central = data.windows(4).position(|w| w == b"PK\x01\x02").unwrap(); + data[central + 30..central + 32].copy_from_slice(&2u16.to_le_bytes()); + assert_eq!(zip::parse(&data, 10), Err(ZipError::Truncated("directory entry fields"))); +} + +#[test] +fn a_directory_cannot_extend_into_its_end_record() { + let mut data = zip_stored(&[("a", b"x")]); + let end = data.len() - 22; + let size = u32::from_le_bytes(data[end + 12..end + 16].try_into().unwrap()); + data[end + 12..end + 16].copy_from_slice(&(size + 1).to_le_bytes()); + assert!(zip::parse(&data, 10).is_err()); +} + +#[test] +fn self_extracting_archives_keep_both_offset_conventions() { + for adjusted in [false, true] { + let mut data = zip_stored(&[("a", b"x")]); + let central = data.windows(4).position(|w| w == b"PK\x01\x02").unwrap(); + let end = data.len() - 22; + let stub = b"executable stub"; + if adjusted { + data[central + 42..central + 46].copy_from_slice(&(stub.len() as u32).to_le_bytes()); + data[end + 16..end + 20].copy_from_slice(&((central + stub.len()) as u32).to_le_bytes()); + } + let mut file = stub.to_vec(); + file.extend(data); + let archive = zip::parse(&file, 10).unwrap(); + assert_eq!(zip::read_entry(&file, &archive.entries[0], 10).unwrap(), b"x"); + } +} + +#[test] +fn a_directory_signature_after_the_entries_is_not_an_extra_file() { + let mut data = zip_stored(&[("a", b"x")]); + let end = data.len() - 22; + let size = u32::from_le_bytes(data[end + 12..end + 16].try_into().unwrap()); + let signature = b"PK\x05\x05\x01\x00x"; + data[end + 12..end + 16].copy_from_slice(&(size + signature.len() as u32).to_le_bytes()); + data.splice(end..end, signature.iter().copied()); + assert_eq!(zip::parse(&data, 10).unwrap().entries.len(), 1); +} diff --git a/crates/zip/tests/lenient_zip_entry_detection.rs b/crates/zip/tests/lenient_zip_entry_detection.rs new file mode 100644 index 0000000000..8708b64000 --- /dev/null +++ b/crates/zip/tests/lenient_zip_entry_detection.rs @@ -0,0 +1,45 @@ +#![cfg(feature = "lenient")] +// From Craft Anything crates/formats/tests/zip_entry_detection.rs. +use craft_zip::lenient::has_entry as zip_has_entry; +#[path = "lenient_common/mod.rs"] +mod common; +use common::zip_stored; + +/// A directory-shaped payload is ordinary file content, not an archive member. +#[test] +fn embedded_archive_does_not_supply_outer_entries() { + let inner = zip_stored(&[("AndroidManifest.xml", b"manifest")]); + let outer = zip_stored(&[("backup.zip", &inner)]); + assert!(!zip_has_entry(&outer, "AndroidManifest.xml")); + assert!(zip_has_entry(&outer, "backup.zip")); +} + +/// A ZIP comment can contain another directory without changing the archive's entries. +#[test] +fn comment_does_not_supply_entries() { + let mut outer = zip_stored(&[("readme.txt", b"notes")]); + let inner = zip_stored(&[("AndroidManifest.xml", b"manifest")]); + let len = outer.len(); + outer[len - 2..].copy_from_slice(&(inner.len() as u16).to_le_bytes()); + outer.extend(inner); + assert!(!zip_has_entry(&outer, "AndroidManifest.xml")); + assert!(zip_has_entry(&outer, "readme.txt")); +} + +/// Actual manifests are found regardless of member order, including prefixed archives. +#[test] +fn actual_entries_are_found() { + let data = zip_stored(&[("classes.dex", b"dex"), ("AndroidManifest.xml", b"manifest")]); + assert!(zip_has_entry(&data, "AndroidManifest.xml")); + let mut prefixed = b"stub".to_vec(); + prefixed.extend(data); + assert!(zip_has_entry(&prefixed, "AndroidManifest.xml")); + assert!(!zip_has_entry(&prefixed, "missing")); +} + +/// A stray central-directory signature without an archive is not an entry. +#[test] +fn incomplete_archive_is_not_a_manifest() { + let data = zip_stored(&[("AndroidManifest.xml", b"manifest")]); + assert!(!zip_has_entry(&data[..data.len() - 22], "AndroidManifest.xml")); +} diff --git a/crates/zip/tests/lenient_zip_split_volumes.rs b/crates/zip/tests/lenient_zip_split_volumes.rs new file mode 100644 index 0000000000..9675177ce0 --- /dev/null +++ b/crates/zip/tests/lenient_zip_split_volumes.rs @@ -0,0 +1,167 @@ +#![cfg(feature = "lenient")] +// From Craft Anything crates/formats/tests/zip_split_volumes.rs. +use craft_zip::lenient::{self as zip, ZipError}; +#[path = "lenient_common/mod.rs"] +mod common; +use common::zip_stored; + +fn assert_split(data: &[u8]) { + assert!(matches!(zip::parse(data, 10), Err(ZipError::Unsupported(_)))); +} + +#[test] +fn classic_end_records_must_describe_one_complete_volume() { + for field in [4, 6, 8] { + let mut data = zip_stored(&[("a", b"x")]); + let end = data.len() - 22; + let value = if field == 8 { 0u16 } else { 1 }; + data[end + field..end + field + 2].copy_from_slice(&value.to_le_bytes()); + assert_split(&data); + } +} + +#[test] +fn central_entries_cannot_point_to_another_volume() { + let mut data = zip_stored(&[("a", b"x")]); + let central = data.windows(4).position(|w| w == b"PK\x01\x02").unwrap(); + data[central + 34..central + 36].copy_from_slice(&1u16.to_le_bytes()); + assert_split(&data); +} + +fn zip64_entry_disk(disk: u32, with_sizes_and_offset: bool) -> Vec { + let mut data = zip_stored(&[("a", b"x")]); + let central = data.windows(4).position(|w| w == b"PK\x01\x02").unwrap(); + let end = data.len() - 22; + data[central + 34..central + 36].copy_from_slice(&u16::MAX.to_le_bytes()); + let mut extra = vec![1, 0, 4, 0]; + if with_sizes_and_offset { + data[central + 20..central + 28].fill(0xff); + data[central + 42..central + 46].fill(0xff); + extra[2..4].copy_from_slice(&28u16.to_le_bytes()); + // Uncompressed size, compressed size, and local header offset precede the disk. + for value in [1u64, 1, 0] { + extra.extend(value.to_le_bytes()); + } + } + extra.extend(disk.to_le_bytes()); + data[central + 30..central + 32].copy_from_slice(&(extra.len() as u16).to_le_bytes()); + let directory_size = (end - central + extra.len()) as u32; + data.splice(end..end, extra); + let end = data.len() - 22; + data[end + 12..end + 16].copy_from_slice(&directory_size.to_le_bytes()); + data +} + +#[test] +fn a_zip64_disk_sentinel_is_resolved_before_rejecting_the_entry() { + let data = zip64_entry_disk(0, false); + let archive = zip::parse(&data, 10).unwrap(); + assert_eq!(zip::read_entry(&data, &archive.entries[0], 10).unwrap(), b"x"); + assert_split(&zip64_entry_disk(1, false)); +} + +#[test] +fn a_zip64_disk_sentinel_follows_sizes_and_the_local_offset() { + let data = zip64_entry_disk(0, true); + let archive = zip::parse(&data, 10).unwrap(); + assert_eq!(archive.entries[0].uncompressed_size, 1); + assert_eq!(archive.entries[0].compressed_size, 1); + assert_eq!(archive.entries[0].local_header_offset, 0); + assert_eq!(zip::read_entry(&data, &archive.entries[0], 10).unwrap(), b"x"); + assert_split(&zip64_entry_disk(1, true)); +} + +fn zip64_archive(record_disk: u32, central_disk: u32, locator_disk: u32, disks: u32, entries_on_disk: u64) -> Vec { + let mut data = zip_stored(&[("a", b"x")]); + let end = data.len() - 22; + let central = u32::from_le_bytes(data[end + 16..end + 20].try_into().unwrap()); + let size = u32::from_le_bytes(data[end + 12..end + 16].try_into().unwrap()); + let mut record = b"PK\x06\x06".to_vec(); + record.extend(44u64.to_le_bytes()); + record.extend([45, 0, 45, 0]); + record.extend(record_disk.to_le_bytes()); + record.extend(central_disk.to_le_bytes()); + record.extend(entries_on_disk.to_le_bytes()); + record.extend(1u64.to_le_bytes()); + record.extend(u64::from(size).to_le_bytes()); + record.extend(u64::from(central).to_le_bytes()); + record.extend(b"PK\x06\x07"); + record.extend(locator_disk.to_le_bytes()); + record.extend((end as u64).to_le_bytes()); + record.extend(disks.to_le_bytes()); + data[end + 8..end + 12].fill(0xff); + data.splice(end..end, record); + data +} + +#[test] +fn zip64_end_records_and_locators_must_also_describe_one_volume() { + for fields in [(1, 0, 0, 1, 1), (0, 1, 0, 1, 1), (0, 0, 1, 1, 1), (0, 0, 0, 2, 1), (0, 0, 0, 1, 0)] { + assert_split(&zip64_archive(fields.0, fields.1, fields.2, fields.3, fields.4)); + } + assert_eq!(zip::parse(&zip64_archive(0, 0, 0, 1, 1), 10).unwrap().entries.len(), 1); +} + +#[test] +fn zip64_does_not_erase_explicit_classic_volume_markers() { + for field in [4, 6] { + let mut data = zip64_archive(0, 0, 0, 1, 1); + let end = data.len() - 22; + data[end + field..end + field + 2].copy_from_slice(&1u16.to_le_bytes()); + assert_split(&data); + data[end + field..end + field + 2].fill(0xff); + assert_eq!(zip::parse(&data, 10).unwrap().entries.len(), 1); + } +} + +#[test] +fn zip64_does_not_erase_explicit_classic_entry_counts() { + for field in [8, 10] { + for count in [0u16, 2] { + let mut data = zip64_archive(0, 0, 0, 1, 1); + let end = data.len() - 22; + data[end + field..end + field + 2].copy_from_slice(&count.to_le_bytes()); + assert!(matches!(zip::parse(&data, 10), Err(ZipError::Unsupported(_))), "field {field}, count {count}"); + } + } +} + +#[test] +fn mixed_classic_and_zip64_entry_counts_can_describe_one_volume() { + for field in [8, 10] { + let mut data = zip64_archive(0, 0, 0, 1, 1); + let end = data.len() - 22; + data[end + field..end + field + 2].copy_from_slice(&1u16.to_le_bytes()); + let archive = zip::parse(&data, 10).unwrap(); + assert_eq!(archive.entries.len(), 1, "field {field}"); + assert_eq!(zip::read_entry(&data, &archive.entries[0], 10).unwrap(), b"x"); + } +} + +#[test] +fn zip64_cannot_replace_explicit_classic_directory_bounds() { + for field in [12, 16] { + let mut data = zip64_archive(0, 0, 0, 1, 1); + let end = data.len() - 22; + let value = u32::from_le_bytes(data[end + field..end + field + 4].try_into().unwrap()); + data[end + field..end + field + 4].copy_from_slice(&(value + 1).to_le_bytes()); + assert!(matches!(zip::parse(&data, 10), Err(ZipError::Corrupt(_))), "field {field}"); + } +} + +#[test] +fn each_zip64_field_can_resolve_its_own_classic_sentinel() { + for (field, width) in [(4, 2), (6, 2), (8, 2), (10, 2), (12, 4), (16, 4)] { + let mut data = zip64_archive(0, 0, 0, 1, 1); + let end = data.len() - 22; + data[end + 8..end + 10].copy_from_slice(&1u16.to_le_bytes()); + data[end + 10..end + 12].copy_from_slice(&1u16.to_le_bytes()); + data[end + field..end + field + width].fill(0xff); + let archive = zip::parse(&data, 10).unwrap(); + assert!(archive.zip64, "field {field}"); + assert_eq!(archive.declared_entries, 1, "field {field}"); + assert_eq!(archive.entries.len(), 1, "field {field}"); + assert_eq!(archive.prefix_bytes, 0, "field {field}"); + assert_eq!(zip::read_entry(&data, &archive.entries[0], 10).unwrap(), b"x", "field {field}"); + } +} diff --git a/crates/zip/tests/lenient_zip_stored_cap.rs b/crates/zip/tests/lenient_zip_stored_cap.rs new file mode 100644 index 0000000000..a5424605fc --- /dev/null +++ b/crates/zip/tests/lenient_zip_stored_cap.rs @@ -0,0 +1,23 @@ +#![cfg(feature = "lenient")] +// From Craft Anything crates/formats/tests/zip_stored_cap.rs. + +#[path = "lenient_common/mod.rs"] +mod common; +use craft_zip::lenient::{self as zip, ZipError}; + +#[test] +fn a_stored_entry_cannot_understate_its_size_to_bypass_the_output_limit() { + let data = common::zip_stored(&[("payload", &[0x5a; 64])]); + let mut entry = zip::parse(&data, 10).unwrap().entries.remove(0); + entry.uncompressed_size = 1; + assert!(matches!(zip::read_entry(&data, &entry, 8), Err(ZipError::TooLarge(8)))); + assert!(matches!(zip::read_entry_unverified(&data, &entry, 8), Err(ZipError::TooLarge(8)))); +} + +#[test] +fn stored_entries_at_the_limit_and_empty_entries_still_read() { + let data = common::zip_stored(&[("payload", b"hello"), ("empty", b"")]); + let entries = zip::parse(&data, 10).unwrap().entries; + assert_eq!(zip::read_entry(&data, &entries[0], 5).unwrap(), b"hello"); + assert_eq!(zip::read_entry(&data, &entries[1], 0).unwrap(), b""); +} diff --git a/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt new file mode 100644 index 0000000000..4fcb9b583b --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt @@ -0,0 +1,72 @@ +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE new file mode 100644 index 0000000000..dae6969815 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-MIT b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT new file mode 100644 index 0000000000..6a4eb87467 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt new file mode 100644 index 0000000000..58e09bf431 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt @@ -0,0 +1,8 @@ +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/licenses/jpeg-encoder-0.6.1/SOURCE.json b/licenses/jpeg-encoder-0.6.1/SOURCE.json new file mode 100644 index 0000000000..8a7fb7ab24 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SOURCE.json @@ -0,0 +1,29 @@ +{ + "package": "jpeg-encoder", + "version": "0.6.1", + "source": "https://crates.io/crates/jpeg-encoder/0.6.1", + "registry_checksum": "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f", + "license": "(MIT OR Apache-2.0) AND IJG", + "files": { + "LICENSE-MIT": { + "source": "LICENSE-MIT", + "source_sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503", + "sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503" + }, + "LICENSE-APACHE": { + "source": "LICENSE-APACHE", + "source_sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0", + "sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0" + }, + "IJG-NOTICE.txt": { + "source": "src/fdct.rs", + "source_sha256": "0b59244bbd05b2593ded252ecf0d010a8a4c6ec1d4713b3caeb6fb724586e4d6", + "sha256": "432424ca69caaa82565c0491c11cdab311a2e7d39180970b8ba22017996bf678" + }, + "SIMD-NOTICE.txt": { + "source": "src/avx2/fdct.rs", + "source_sha256": "bc362322f568f92c3699f4ca2922b261c12b7dd997120b01fd3cab58d9d2f9ab", + "sha256": "ee36eeaa9df1f7f09c7046f428ce4a848fcf518394e63d3e2125ec261949e8ba" + } + } +} diff --git a/scripts/test-workspace-concurrency.py b/scripts/test-workspace-concurrency.py new file mode 100644 index 0000000000..96bfae3047 --- /dev/null +++ b/scripts/test-workspace-concurrency.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Check the Workspace workflow's pull-request-only cancellation policy. + +The policy is the top-level `concurrency` block of .github/workflows/workspace.yml. This script +reads those fields, requires the documented expression shapes, and checks which group each event +would be given. The rest of the workflow is left to diff review, not frozen here. + +Use --workflow PATH to read a baseline or a deliberately wrong variant without touching this +checkout. +""" + +import argparse +import re +import sys +import unittest +from pathlib import Path + +try: # cross-check only; the reader below is what a plain `python3` run needs + import yaml +except ImportError: + yaml = None + +DEFAULT_WORKFLOW = Path(__file__).resolve().parent.parent / ".github" / "workflows" / "workspace.yml" +PULL_REQUEST, PUSH, DISPATCH = "pull_request", "push", "workflow_dispatch" + +# The two shapes this policy may use. GitHub reads `a && b || c` as "b, or c when a is false"; these +# patterns are the whole of that expression language this script understands, so a reworded policy +# has to be reworded here too, on purpose. github.ref, never github.head_ref or github.sha. +GROUP_SHAPE = re.compile( + r"(?P[A-Za-z0-9._-]+)-\$\{\{\s*github\.event_name\s*==\s*'(?P[a-z_]+)'\s*" + r"&&\s*github\.ref\s*\|\|\s*github\.run_id\s*\}\}" +) +CANCEL_SHAPE = re.compile(r"\$\{\{\s*github\.event_name\s*==\s*'(?P[a-z_]+)'\s*\}\}") + + +def read_concurrency(text): + """The top-level `concurrency` mapping. A deliberately limited reader: two-space fields.""" + lines = text.splitlines() + starts = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(starts) != 1: + raise AssertionError(f"expected one top-level concurrency block, found {len(starts)}") + header = lines[starts[0]].partition("#")[0].strip() + if header != "concurrency:": + # `concurrency: |` and `concurrency: some-string` are scalars, not a mapping. Reading the + # lines under one as fields would let a workflow that is not this policy pass every check. + raise AssertionError(f"concurrency must be a mapping, not a scalar: {lines[starts[0]]!r}") + fields = {} + for line in lines[starts[0] + 1:]: + stripped = line.strip() + if stripped and not line.startswith(" "): + break # the next top-level key + if not stripped or stripped.startswith("#"): + continue + if not line.startswith(" ") or line.startswith(" "): + raise AssertionError(f"unexpected indentation under concurrency: {line!r}") + key, separator, value = stripped.partition(":") + if not separator: + raise AssertionError(f"not a field of concurrency: {line!r}") + fields[key.strip()] = value.strip() + return fields + + +def pull_request(number, run_id): + # github.ref for a pull request is refs/pull//merge: the PR number, never the branch name. + return (PULL_REQUEST, f"refs/pull/{number}/merge", run_id) + + +def other_run(event_name, ref, run_id): + return (event_name, ref, run_id) + + +MAIN, TAG = ("refs/heads/main", "refs/tags/v1.2.3") +SAME_GROUP = [ + ("a newer commit on the same pull request", pull_request(1316, 43599251877), pull_request(1316, 43600899878)), + ("a rerun of one main run", other_run(PUSH, MAIN, 7001), other_run(PUSH, MAIN, 7001)), +] +DIFFERENT_GROUPS = [ + ("two pull requests", pull_request(1316, 1), pull_request(1317, 1)), + ("the same branch name in two forks", pull_request(1316, 2), pull_request(1400, 2)), + ("two pushes to main", other_run(PUSH, MAIN, 3), other_run(PUSH, MAIN, 4)), + ("two release tag runs", other_run(PUSH, TAG, 5), other_run(PUSH, TAG, 6)), + ("two manual runs", other_run(DISPATCH, MAIN, 7), other_run(DISPATCH, MAIN, 8)), + ("a main push and a pull request", other_run(PUSH, MAIN, 9), pull_request(1316, 9)), + ("a release tag and a pull request", other_run(PUSH, TAG, 10), pull_request(1316, 10)), +] +CANCELLATION = [ + ("a push supersedes the previous run of its pull request", pull_request(1316, 11), True), + ("a push to main is never cancelled", other_run(PUSH, MAIN, 12), False), + ("a release tag run is never cancelled", other_run(PUSH, TAG, 13), False), + ("a manual run is never cancelled", other_run(DISPATCH, MAIN, 14), False), +] + + +class ConcurrencyTests(unittest.TestCase): + workflow = DEFAULT_WORKFLOW + + @classmethod + def setUpClass(cls): + cls.text = cls.workflow.read_text() + cls.fields = read_concurrency(cls.text) + cls.group_shape = GROUP_SHAPE.fullmatch(cls.fields.get("group", "")) + cls.cancel_shape = CANCEL_SHAPE.fullmatch(cls.fields.get("cancel-in-progress", "")) + if not cls.group_shape or not cls.cancel_shape: + raise AssertionError(f"the concurrency fields are not the documented shapes: {cls.fields}") + + def cancels(self, event_name): + return event_name == self.cancel_shape["event"] + + def group(self, event_name, ref, run_id): + return self.group_shape["prefix"] + "-" + (ref if event_name == self.group_shape["event"] else str(run_id)) + + def test_policy_is_the_two_documented_fields(self): + self.assertEqual(sorted(self.fields), ["cancel-in-progress", "group"]) + self.assertEqual(self.group_shape["prefix"], "workspace") + self.assertEqual(self.group_shape["event"], PULL_REQUEST) + self.assertEqual(self.cancel_shape["event"], PULL_REQUEST) + + def test_a_scalar_concurrency_value_is_not_read_as_a_mapping(self): + cases = { + "a block scalar": "concurrency: |\n group: workspace-x\n cancel-in-progress: true\n", + "a plain scalar": "concurrency: workspace-x\njobs: {}\n", + } + for description, text in cases.items(): + with self.subTest(description): + with self.assertRaises(AssertionError): + read_concurrency(text) + + def test_one_group_per_pull_request_and_run(self): + for description, first, second in SAME_GROUP: + with self.subTest(description): + self.assertEqual(self.group(*first), self.group(*second), description) + for description, first, second in DIFFERENT_GROUPS: + with self.subTest(description): + self.assertNotEqual(self.group(*first), self.group(*second), description) + + def test_only_a_pull_request_cancels(self): + for description, context, expected in CANCELLATION: + with self.subTest(description): + self.assertEqual(self.cancels(context[0]), expected, description) + + def test_pyyaml_reads_the_same_fields(self): + if yaml is None: + self.skipTest("PyYAML is not installed; the limited reader above ran alone") + document = yaml.load(self.text, Loader=yaml.BaseLoader) # BaseLoader keeps `on:` a string + self.assertEqual(document["concurrency"], self.fields) + + def test_no_per_job_concurrency_is_added(self): + indented = [line for line in self.text.splitlines() + if line.strip().startswith("concurrency:") and not line.startswith("concurrency:")] + self.assertEqual(indented, [], "the policy belongs to the workflow, not to one job") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--workflow", type=Path, default=DEFAULT_WORKFLOW, help="workflow to read (default: %(default)s)") + arguments, remaining = parser.parse_known_args() + ConcurrencyTests.workflow = arguments.workflow + unittest.main(argv=[sys.argv[0], *remaining]) + + +if __name__ == "__main__": + main() diff --git a/sonar-project.properties b/sonar-project.properties index f30f3ae5fe..c2be7b1929 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -7,7 +7,11 @@ sonar.organization=storytold # *_tests.rs), which includes the browser fault-injection fixtures in crates/platform/tests. sonar.sources=. sonar.tests=. -sonar.test.inclusions=**/tests/**,**/tests.rs,**/*_tests.rs +# scripts/test-workspace-concurrency.py is a unit-test module for the Workspace workflow's +# cancellation policy: its unittest cases read a workflow and assert on it, so it is test +# code, analysed as a test and still linted, indexed and reported, not counted as production +# code that needs coverage. Its name is listed exactly, so no other script is classified. +sonar.test.inclusions=**/tests/**,**/tests.rs,**/*_tests.rs,scripts/test-workspace-concurrency.py # Codec constant tables are transcribed from the format specifications; their repeated rows are # data, not copy-pasted logic.