diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index 37796f6816..22d90712e8 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -15,8 +15,10 @@ on: - "crates/silhouette-studio/**" - "crates/tiff/**" - "crates/heif/**" + - "crates/pst/**" - "crates/cms/**" - "crates/cdr/**" + - "crates/texture/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/formats.yml" @@ -33,8 +35,10 @@ on: - "crates/silhouette-studio/**" - "crates/tiff/**" - "crates/heif/**" + - "crates/pst/**" - "crates/cms/**" - "crates/cdr/**" + - "crates/texture/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/formats.yml" @@ -67,9 +71,11 @@ jobs: - { crate: craft-svg-paths, features: "" } - { crate: craft-silhouette-studio, features: "" } - { crate: craft-tiff, features: "" } - - { crate: craft-heif, features: "testdata" } + - { crate: craft-heif, features: "testdata test-support" } + - { crate: craft-pst, features: "test-writer test-support" } - { crate: craft-cms, features: "" } - { crate: craft-cdr, features: "synth" } + - { crate: craft-texture, features: "dds parallel" } # fmt, clippy with default and with all features, and the tests run in the Workspace gate on # every OS; this lints each feature alone and checks the web build. name: ${{ matrix.crate }} feature sets, WASM diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 34e0bcd6f3..112bfe4e93 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -94,6 +94,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso | `crates/raster-codecs/src/xpm/x11_colors.rs` | X.Org Foundation and X11 contributors (X11 `rgb.txt` colour names and values, normalised into a lookup table) | , via [PhotoCraft `crates/codecs`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/codecs/src/codecs/xpm) | MIT (X.Org app/rgb) | | `crates/psd/tests/fixtures/atn/*.atn` (seven synthetic action sets, encoded field by field; `crates/psd/tests/fixtures/atn/README.md`) | PhotoCraft contributors | [PhotoCraft `crates/psd/tests/fixtures/atn`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/psd/tests/fixtures/atn) | MIT OR Apache-2.0 | | `crates/lottie/tests/fixtures/` | EffectCraft contributors (original work: four hand-written Lottie JSON documents, written from the public Lottie format description; not exported from any Adobe product or third-party file) | [EffectCraft `crates/lottie/tests/fixtures`](https://github.com/storytold/effectcraft/tree/e18f48fb/crates/lottie/tests/fixtures) | MIT OR Apache-2.0 | +| `crates/i18n-build/tests/fixture/` | craft-libs contributors (original work: nine hand-written catalogs of a few common interface words, in craft-i18n's catalog format; not copied from craft-i18n or any app) | this repository | MIT OR Apache-2.0 | | `crates/pkcs7/tests/data/` | PdfCraft contributors (original work: throw-away test keys and certificates made with OpenSSL 3 for these tests, as seven PKCS #12 files with the password `test` and two PEM certificates; they protect nothing; commands in `crates/pkcs7/tests/data/README.md`) | [PdfCraft `crates/sign/tests/data`](https://github.com/storytold/pdfcraft/tree/1d7a9f9f/crates/sign/tests/data) | MIT OR Apache-2.0 | | `crates/affinity/tests/support/corpus.tsv`, `crates/affinity/tests/support/affinity3-signatures.txt` (manifest and measured signatures only; the 113 files, 90 of them documents, are not bundled, `scripts/fetch-affinity-corpus.sh` downloads them outside the checkout) | The authors of each document: samuel-etver (vector-art), satoshoe-dev (affinity-samples), Seth A. Robinson (Patchy fixtures), Nick Beeuwsaert (AFDesignLoad), Jeremy Cantu (Branding), eviltwo (AssetStoreTemplate), Square (leakcanary) | each file's pinned upstream URL and SHA-256 in the manifest; every name from [VectorCraft `xtask/src/affinity_corpus.rs`](https://github.com/storytold/vectorcraft/blob/bada8e17103db9917de44e40a1cead5a7fc71c3c/xtask/src/affinity_corpus.rs) and [PhotoCraft `xtask/affinity-corpus.sha256`](https://github.com/storytold/photocraft/blob/629751503165118d5fec5f70e64fe2d6592f7b53/xtask/affinity-corpus.sha256) | CC0-1.0, MIT or Apache-2.0 (per file, in the manifest) | | `crates/raw/docs/coverage/adobe-cameras.tsv` | Facts (maker, model, extension, profile, minimum Camera Raw version) parsed by LightCraft contributors from Adobe's published list | [Adobe Camera Raw supported cameras](https://helpx.adobe.com/camera-raw/desktop/dng-and-file-formats/camera-raw-plug-supported-cameras.html), Wayback capture 20261003133011; moved from [LightCraft `docs/raw`](https://github.com/storytold/lightcraft/tree/5ff567a4a2e067bef1b6bce152c11e7f727ccbaf/docs/raw) | Facts, not copyrightable expression; the file is MIT OR Apache-2.0 | @@ -124,6 +125,8 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper `crates/audio-dsp` combines FilmCraft `crates/audio-dsp` at `3f137a7ed420cac79b32145f5243b7f98b31f71c` and SoundCraft `crates/dsp` at `648ed9db9a0e98cc55643babffac381521a556c8` (both MIT OR Apache-2.0). `crates/audio-dsp/NOTICE` keeps the copyright notices of both projects. +`crates/audio-dsp/src/effects/voice.rs` adapts the two crossfaded read taps of SoundCraft `crates/dsp/src/plugins/pitch.rs` and the YIN pitch tracker of `crates/dsp/src/pitch_detect.rs` at `915481be1b49d7e0502e07b059d0c0198c61911a` (MIT OR Apache-2.0). The taps are centered on a fixed 10 ms latency and spaced by whole periods of the tracked pitch, and the tracker runs on a decimated copy of the input in buffers sized at creation. + ## GIMP palette reader `crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. diff --git a/Cargo.lock b/Cargo.lock index 7ce18795f9..2e14ca9825 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1125,32 +1125,36 @@ dependencies = [ [[package]] name = "candle-core" -version = "0.9.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c15b675b80d994b2eadb20a4bbe434eabeb454eac3ee5e2b4cf6f147ee9be091" +checksum = "d11c8be87cfbaef9ebb62fb3f850d1fc8e00cc1d11d393fdbe55a4d5c2cdb325" dependencies = [ "byteorder", "float8", "gemm", "half", + "libc", "libm", "memmap2", "num-traits", "num_cpus", + "parking_lot", "rand 0.9.5", "rand_distr", "rayon", "safetensors", "thiserror 2.0.21", + "tokenizers", "yoke", - "zip 7.4.0", + "zerocopy", + "zip", ] [[package]] name = "candle-nn" -version = "0.9.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3045fa9e7aef8567d209a27d56b692f60b96f4d0569f4c3011f8ca6715c65e03" +checksum = "437fabe77547c2447c7bdf3cc946e19db29a2832440176b419f77c80b0a9a05e" dependencies = [ "candle-core", "half", @@ -1164,14 +1168,14 @@ dependencies = [ [[package]] name = "candle-transformers" -version = "0.9.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b538ec4aa807c416a2ddd3621044888f188827862e2a6fcacba4738e89795d01" +checksum = "2b1e1abeac23d7df4f94e8a3852b3dbb661d332e37c3bef479507bac867187b2" dependencies = [ "byteorder", "candle-core", "candle-nn", - "fancy-regex 0.17.0", + "fancy-regex 0.19.2", "num-traits", "rand 0.9.5", "rayon", @@ -1786,6 +1790,7 @@ dependencies = [ "craft-drawingml", "craft-dwg", "craft-dxf", + "craft-ease", "craft-ecproj-format", "craft-elf", "craft-eps", @@ -1826,6 +1831,7 @@ dependencies = [ "craft-html", "craft-http-url", "craft-i18n", + "craft-i18n-build", "craft-ical", "craft-idml", "craft-image-codecs", @@ -1869,6 +1875,7 @@ dependencies = [ "craft-ora", "craft-pages", "craft-palette", + "craft-pbr", "craft-pcap", "craft-pcraft-bundle", "craft-pcraft-format", @@ -2271,6 +2278,7 @@ version = "0.1.0" dependencies = [ "craft-ai-agents", "craft-atomic", + "craft-control-protocol", "craft-flags", "dirs", "getrandom 0.3.4", @@ -2278,6 +2286,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "socket2", "tempfile", ] @@ -2339,7 +2348,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -2478,7 +2487,7 @@ dependencies = [ "craft-zip", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -2503,7 +2512,7 @@ dependencies = [ "thiserror 2.0.21", "unicode-bidi", "zeroize", - "zip 9.1.3", + "zip", ] [[package]] @@ -2563,6 +2572,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ease" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "craft-ecproj-format" version = "0.1.0" @@ -2598,7 +2615,7 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -2637,6 +2654,7 @@ dependencies = [ "exr", "flate2", "half", + "serde", "serde_json", "thiserror 2.0.21", ] @@ -2662,7 +2680,7 @@ dependencies = [ "ruzstd", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -2673,7 +2691,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3020,6 +3038,21 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-i18n-build" +version = "0.1.0" +dependencies = [ + "craft-i18n", + "craft-i18n-build-consumer", +] + +[[package]] +name = "craft-i18n-build-consumer" +version = "0.1.0" +dependencies = [ + "craft-i18n-build", +] + [[package]] name = "craft-ical" version = "0.1.0" @@ -3035,7 +3068,7 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3043,6 +3076,7 @@ name = "craft-image-codecs" version = "0.1.0" dependencies = [ "avif-serialize", + "craft-cms", "craft-dds", "craft-heif", "craft-jpeg", @@ -3058,7 +3092,7 @@ dependencies = [ "hayro-jpeg2000", "image", "image-webp", - "jpeg-encoder 0.6.1", + "jpeg-encoder 0.7.1", "jxl-oxide", "png 0.18.1", "proptest", @@ -3202,7 +3236,7 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3334,6 +3368,7 @@ dependencies = [ "craft-frame", "craft-media", "craft-time", + "craft-video", "craft-y4m", "serde", "serde_json", @@ -3433,6 +3468,8 @@ dependencies = [ "base64 0.23.1", "chrono", "craft-flow", + "craft-html", + "craft-markdown", "craft-math", "craft-metafile", "craft-wordmodel", @@ -3448,7 +3485,7 @@ dependencies = [ "sha2 0.11.1", "thiserror 2.0.21", "zeroize", - "zip 9.1.3", + "zip", ] [[package]] @@ -3456,6 +3493,7 @@ name = "craft-ods" version = "0.1.0" dependencies = [ "craft-odf", + "craft-ods", "craft-sheet", "craft-xml", "thiserror 2.0.21", @@ -3485,7 +3523,7 @@ dependencies = [ "craft-zip", "log", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3511,7 +3549,7 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3534,6 +3572,18 @@ dependencies = [ name = "craft-palette" version = "0.1.0" +[[package]] +name = "craft-pbr" +version = "0.1.0" +dependencies = [ + "craft-pbr", + "craft-texture", + "glam 0.30.10", + "naga", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-pcap" version = "0.1.0" @@ -3637,7 +3687,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -4061,7 +4111,7 @@ dependencies = [ "kurbo", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -4228,6 +4278,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "rustix 1.1.6", +] [[package]] name = "craft-text" @@ -4627,7 +4680,7 @@ dependencies = [ "verifysign", "winreg", "winsafe", - "zip 9.1.3", + "zip", ] [[package]] @@ -4860,6 +4913,7 @@ name = "craft-xtask" version = "0.1.0" dependencies = [ "craft-atomic", + "libc", "serde_json", "tempfile", ] @@ -4884,7 +4938,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -5115,6 +5169,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "daachorse" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d" + [[package]] name = "darling" version = "0.20.11" @@ -5188,7 +5248,7 @@ checksum = "e917a58e17b27d2f15626c490754ccced7f46592dc5b5f39a3013b89cba5f068" dependencies = [ "astc-decode", "bitflags 2.13.2", - "glam", + "glam 0.25.0", "resize", "zerocopy", ] @@ -6194,9 +6254,9 @@ dependencies = [ [[package]] name = "float8" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719a903cc23e4a89e87962c2a80fdb45cdaad0983a89bd150bb57b4c8571a7d5" +checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc" dependencies = [ "half", "num-traits", @@ -6735,6 +6795,12 @@ version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" +[[package]] +name = "glam" +version = "0.30.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9" + [[package]] name = "glifo" version = "0.1.1" @@ -11419,13 +11485,15 @@ checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" [[package]] name = "safetensors" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "675656c1eabb620b921efea4f9199f97fc86e36dd6ffd1fbbe48d0f59a4987f5" +checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846" dependencies = [ "hashbrown 0.16.1", + "libc", "serde", "serde_json", + "tempfile", ] [[package]] @@ -12819,16 +12887,17 @@ dependencies = [ [[package]] name = "tokenizers" -version = "0.22.2" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223" +checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc" dependencies = [ "ahash", - "aho-corasick", "compact_str", + "daachorse", "dary_heap", "derive_builder", "esaxx-rs", + "fancy-regex 0.17.0", "getrandom 0.3.4", "itertools 0.14.0", "log", @@ -13074,12 +13143,6 @@ dependencies = [ "rustc-hash 2.1.3", ] -[[package]] -name = "typed-path" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" - [[package]] name = "typed-path" version = "0.13.0" @@ -15134,18 +15197,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "zip" -version = "7.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980" -dependencies = [ - "crc32fast", - "indexmap", - "memchr", - "typed-path 0.12.4", -] - [[package]] name = "zip" version = "9.1.3" @@ -15158,7 +15209,7 @@ dependencies = [ "indexmap", "memchr", "nix", - "typed-path 0.13.0", + "typed-path", "windows-sys 0.61.2", ] diff --git a/Cargo.toml b/Cargo.toml index 3608b63e20..0782449467 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -102,6 +102,7 @@ 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-ease = { path = "crates/ease" } craft-eps = { path = "crates/eps" } craft-elf = { path = "crates/elf" } craft-file-formats = { path = "crates/file-formats" } @@ -145,6 +146,7 @@ craft-gpu-null = { path = "crates/gpu-null" } craft-gpu-providers = { path = "crates/gpu-providers" } craft-gpu-wgpu = { path = "crates/gpu-wgpu" } craft-i18n = { path = "crates/i18n" } +craft-i18n-build = { path = "crates/i18n-build" } craft-ipc = { path = "crates/ipc" } craft-idml = { path = "crates/idml" } craft-indd = { path = "crates/indd" } @@ -227,6 +229,7 @@ craft-testkit = { path = "crates/testkit" } craft-text = { path = "crates/text" } craft-tcraft = { path = "crates/tcraft" } craft-texture = { path = "crates/texture" } +craft-pbr = { path = "crates/pbr" } craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } craft-tiff = { path = "crates/tiff" } diff --git a/NOTICE b/NOTICE index c63edc0812..a2cbbb811e 100644 --- a/NOTICE +++ b/NOTICE @@ -229,6 +229,26 @@ The colour management module in crates/cms is extracted from: Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain (CC0-1.0); see ATTRIBUTION.md. +The image-based lighting in crates/pbr (craft-pbr) is adapted from: +- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc, + copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs. + https://github.com/storytold/texturecraft + Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors. +- MaterialCraft, crates/render/src/ibl.rs, revision 4ff5af9af7371613ee37b186e03caf49ee6dbd88, + whose differing parts are copied to crates/pbr/tests/it/reference/materialcraft.rs. + https://github.com/storytold/materialcraft + Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors. +The BRDF, environment BRDF and default environment in crates/pbr are adapted from: +- EffectCraft, crates/render/src/three_d/adv/shade.rs and adv/scene.rs, revision + 41da144555a1c8ddbbe94876a00259832322d00c, whose shading functions and default environment + are copied to crates/pbr/tests/it/reference/effectcraft.rs. + https://github.com/storytold/effectcraft + Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. +The WGSL text in crates/pbr/src/shade.wgsl is adapted from: +- EffectCraft, crates/gpu/src/shaders/advanced3d.wgsl, revision + f4d45dfef3a280d96aff1d4eb5f1950160adefc2 (above). +All four sources are licensed MIT OR Apache-2.0. crates/pbr/README.md lists the changes from them. + Optional PDF writer Krilla 0.8.2 (https://github.com/LaurenzV/krilla), MIT OR Apache-2.0. @@ -269,9 +289,10 @@ linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs, -src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names Joe Neeman as author, and -its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/linesweeper/README.craft.md and -vendor/linesweeper/SOURCE.json for provenance, the local patches and the files left out. +src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names +Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See +vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local +patches and the files left out. Platform lifecycle source provenance diff --git a/README.md b/README.md index 5cbfd01ab4..8dde0845f5 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from FilmCraft. +- [`craft-cdr`](crates/cdr/README.md): bounded reader and writer of `.cdr` drawings: versions 1 to + 27 and `.cmx` files read into one drawing model (pages, layers, groups, shapes, fills and + outlines), and version 15 `.cdr` files written. - [`craft-cfb`](crates/cfb/README.md): clean-room Compound File Binary ([MS-CFB], OLE structured storage) reader and writer: the container of legacy Office files, Outlook messages, encrypted OOXML packages and AAF. Bounded on hostile input; what the streams hold stays with each format. @@ -126,6 +129,10 @@ 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-ease`](crates/ease/README.md): easing curves, keyed tracks, constant-speed motion paths + and damped springs for animation: named eases, CSS `cubic-bezier()`, speed and influence, + editable custom and sampled curves, hold keys and a spring stepped by its exact solution. + From AniCraft and EffectCraft. No dependencies without the optional `serde` feature. - [`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)`), @@ -219,6 +226,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit lookup with fallback (`pt-br` → `pt` → English), plurals, language names, the system locale and a pseudo locale. The catalogs stay a fully optional build input; apps keep `tl!` and their language setting. +- [`craft-i18n-build`](crates/i18n-build/README.md): embeds the optional craft-i18n catalogs + from an app's `build.rs` (`CRAFT_I18N_DIR`, `CRAFT_I18N_REQUIRED`) as the table `craft-i18n` + reads, with each regional locale's parent and the app's own catalogs merged in. No + dependencies. - [`craft-raw`](crates/raw/README.md): camera raw files, the file-format layer, from LightCraft with what PhotoCraft's and FilmCraft's readers added: container parsing and decompression to a neutral raw image (samples, CFA, black and white levels, active area, crop, orientation, colour tags, @@ -291,7 +302,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`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 - (`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`) and + (`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`), Bink (`bink`) and MPEG-TS/PS (`mpegts`) demuxers, from FilmCraft, a Sierra VMD (`vmd`) demuxer, and an ISO BMFF box reader. Containers only; codecs are in `craft-audio`, and video codecs will go in a separate crate. - [`craft-lottie`](crates/lottie/README.md): Lottie (Bodymovin) JSON: the document model of @@ -402,8 +413,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test whose body runs past a limit, or whose condition does not hold in time; a variable the caller names replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged - copies of a valid input, and fails the test with the case that panicked or did not finish. Not - published. + copies of a valid input, and fails the test with the case that panicked or did not finish. Its `rng` + module holds two seeded generators for repeatable test input. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and diff --git a/crates/ai/Cargo.toml b/crates/ai/Cargo.toml index cca808c9c9..95fc39442f 100644 --- a/crates/ai/Cargo.toml +++ b/crates/ai/Cargo.toml @@ -19,10 +19,10 @@ dirs = "7" sysinfo = "0.39" ureq = { version = "3", features = ["json"] } sha2 = "0.11" -candle-core = { version = "0.9", optional = true } -candle-nn = { version = "0.9", optional = true } -candle-transformers = { version = "0.9", optional = true } -tokenizers = { version = "0.22", optional = true, default-features = false, features = ["onig"] } +candle-core = { version = "0.11.1", optional = true } +candle-nn = { version = "0.11.1", optional = true } +candle-transformers = { version = "0.11.1", optional = true } +tokenizers = { version = "0.23", optional = true, default-features = false, features = ["onig"] } [features] # Local GGUF inference on candle. Heavy dependency tree; apps opt in. diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index fce5926b91..ce6724bb8e 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -12,7 +12,8 @@ and contains no `unsafe` code. (compressor, expander and gate, limiter, maximizer, multiband and tube-modeled compressors), delays and reverbs (including convolution and surround), modulation, restoration (denoise, dehum, click remover, de-esser, de-reverb, speech enhancement), channel tools, distortion, - dither, a signal generator and a loudness meter. + dither, a signal generator, a loudness meter, and a pitch shifter for a live voice with 10 ms + of latency. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order @@ -76,6 +77,9 @@ The crate combines two crates from the ArtCraft apps, with changes: `648ed9db9a0e98cc55643babffac381521a556c8`: the tail length, offline mode, events, saved state and editor parts of the trait, the maximizer, dither, panning, the signal generator and the offline resampler. +- [storytold/soundcraft](https://github.com/storytold/soundcraft) `crates/dsp` at + `915481be1b49d7e0502e07b059d0c0198c61911a`: the two crossfaded read taps of the voice pitch + shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`). `NOTICE` keeps the copyright notices of both projects. diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 679b7c5f9a..42ec2261ce 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -17,6 +17,7 @@ pub(crate) mod special; mod stft; pub(crate) mod time; pub(crate) mod util; +pub(crate) mod voice; pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing}; pub(crate) use declick::ClickRemover; @@ -35,6 +36,7 @@ pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb}; pub use special::LoudnessMeterFx; pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer}; pub(crate) use time::{Delay, Reverb}; +pub use voice::VoicePitch; use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate}; @@ -124,6 +126,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("dehum", "DeHum", Restoration, DeHum), entry!("denoise", "DeNoise", Restoration, DeNoise), entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter), + entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch), entry!("deesser", "DeEsser", Restoration, DeEsser), entry!("dereverb", "DeReverb", Restoration, DeReverb), entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index 0b6f05a802..662046f75c 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -147,7 +147,7 @@ fn latency_is_where_the_impulse_lands() { // settings (FFT filter / convolution / existing STFT effects). The click remover repairs a // lone impulse in silence as a click, so its latency is checked on noise by // `neutral_settings_are_delayed_identity`. - for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)])] { + for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)]), ("voice_pitch", vec![])] { let mut e = fx(id, &p); let lat = e.latency(); assert!(lat > 0, "{id}"); @@ -976,6 +976,7 @@ fn direct_constructors_cap_the_channel_count() { channel::Amplify, filters::FullParametricEq, pitch::PitchShifter, + voice::VoicePitch, ); } diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs new file mode 100644 index 0000000000..af487cdbbb --- /dev/null +++ b/crates/audio-dsp/src/effects/voice.rs @@ -0,0 +1,575 @@ +//! Voice pitch shifter for live use: two read taps sweep through a short delay line and crossfade +//! (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms. +//! +//! The taps sit half a sweep apart and are centered on the latency, so the delay of each one +//! stays within `latency ± spacing`. A pitch tracker (YIN, on a copy of the input low-passed and +//! decimated to about 12 kHz, over the last 42.7 ms of history) sets the spacing to a whole number +//! of periods whenever one tap passes the center, so the two taps read the same point of a +//! period and a voiced sound crossfades without beating. A period longer than the room inside the +//! latency (below about 100 Hz), and unvoiced input, use the widest spacing that fits; below +//! 100 Hz each crossfade then steps the phase of the voice, which can move its pitch by a few +//! hertz (5 Hz for 85 Hz shifted up 5 semitones). At a shift +//! of 0 the effect crossfades over 20 ms to the input delayed by the latency, so a neutral setting +//! is a plain delay. + +use crate::biquad::{Biquad, Coeffs, FilterType}; +use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, flush32, param_plumbing}; +use std::f64::consts::PI; + +/// Latency, and the most a tap may read either side of it. +const LATENCY_MS: f32 = 10.0; +/// Lowest and highest fundamental the tracker reports. +const MIN_HZ: f32 = 70.0; +const MAX_HZ: f32 = 1000.0; +/// Rate the tracker analyzes at, before rounding to a whole decimation factor. +const TRACK_RATE: f32 = 12_000.0; +/// YIN's threshold on the cumulative mean normalized difference. +const THRESHOLD: f32 = 0.15; +/// Length of the crossfade to and from the plain delay at a shift of 0. +const BYPASS_MS: f32 = 20.0; +/// Samples kept between a tap and the newest sample, for the cubic interpolation. +const MARGIN: f64 = 2.0; +/// Largest step of the sweep phase per sample; one step never crosses two tap boundaries. +const MAX_STEP: f64 = 0.45; +/// Analysis input is clipped to this level, so a huge sample cannot overflow the tracker. +const TRACK_CLIP: f64 = 1.0e4; + +/// Fundamental period of the recent input, from YIN (de Cheveigné and Kawahara, 2002) run on a +/// low-passed, decimated copy. Every buffer is sized at creation. +/// +/// It keeps two copies: the mean of the channels, and the first channel alone. A frame whose +/// mean holds less than a quarter of the first channel's energy (channels of opposite polarity +/// cancel in the mean) is analyzed on the first channel. +#[derive(Clone, Debug)] +struct Tracker { + /// Input samples per analysis sample. + factor: usize, + count: usize, + coeffs: [Coeffs; 2], + feeds: [Feed; 2], + at: usize, + hop: usize, + since: usize, + frame: Vec, + diff: Vec, + min_tau: usize, + max_tau: usize, + /// Period in input samples, or `None` when the last frame was unvoiced. + period: Option, +} + +impl Tracker { + fn new(sample_rate: f32) -> Self { + let factor = (sample_rate / TRACK_RATE).round().max(1.0) as usize; + let rate = sample_rate / factor as f32; + let max_hz = MAX_HZ.min(rate / 4.0); + let min_tau = ((rate / max_hz).floor() as usize).max(2); + let max_tau = (rate / MIN_HZ).ceil() as usize + 1; + let len = (2 * max_tau + 2).next_power_of_two(); + // Fourth-order Butterworth low-pass at a quarter of the analysis rate. + let (sr, fc) = (sample_rate as f64, rate as f64 / 4.0); + let coeffs = [0.541_196_1, 1.306_563].map(|q| Coeffs::design(FilterType::LowPass, sr, fc, q, 0.0)); + Tracker { + factor, + count: 0, + coeffs, + feeds: [Feed::new(len), Feed::new(len)], + at: 0, + hop: len / 4, + since: 0, + frame: vec![0.0; len], + diff: vec![0.0; max_tau + 2], + min_tau, + max_tau, + period: None, + } + } + + fn reset(&mut self) { + self.count = 0; + self.feeds.iter_mut().for_each(Feed::reset); + self.at = 0; + self.since = 0; + self.period = None; + } + + /// Takes one input sample, as the mean of the channels and the first channel; runs an + /// analysis every `hop` analysis samples. + fn push(&mut self, mean: f32, first: f32) { + let clipped = [mean, first].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP)); + for (feed, x) in self.feeds.iter_mut().zip(clipped) { + feed.filter(&self.coeffs, x); + } + self.count += 1; + if self.count < self.factor { + return; + } + self.count = 0; + let mask = self.frame.len() - 1; + for feed in &mut self.feeds { + feed.ring[self.at] = feed.last as f32; + } + self.at = (self.at + 1) & mask; + self.since += 1; + if self.since >= self.hop { + self.since = 0; + self.analyze(); + } + } + + fn analyze(&mut self) { + let [mean, first] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::()); + let feed = if mean < 0.25 * first { &self.feeds[1] } else { &self.feeds[0] }; + let mask = self.frame.len() - 1; + for (i, v) in self.frame.iter_mut().enumerate() { + *v = feed.ring[(self.at + i) & mask]; + } + self.period = yin(&self.frame, &mut self.diff, self.min_tau, self.max_tau).map(|t| t * self.factor as f64); + } + + /// Tap spacing for the current period: the most whole periods that fit in `max`, or `max` + /// itself for unvoiced input and for a period longer than `max`. + fn spacing(&self, max: f64) -> f64 { + match self.period { + Some(t) if t <= max => (max / t).floor() * t, + _ => max, + } + } +} + +/// One low-passed, decimated copy of the input that the tracker can analyze. +#[derive(Clone, Debug)] +struct Feed { + lowpass: [Biquad; 2], + /// The newest low-passed sample, kept at every input sample. + last: f64, + ring: Vec, +} + +impl Feed { + fn new(len: usize) -> Self { + Feed { lowpass: [Biquad::new(), Biquad::new()], last: 0.0, ring: vec![0.0; len] } + } + + fn reset(&mut self) { + self.lowpass.iter_mut().for_each(Biquad::reset); + self.last = 0.0; + self.ring.iter_mut().for_each(|v| *v = 0.0); + } + + fn filter(&mut self, coeffs: &[Coeffs; 2], x: f64) { + let y = self.lowpass[0].tick(&coeffs[0], x); + self.last = self.lowpass[1].tick(&coeffs[1], y); + } +} + +/// YIN on `frame`: the lag in samples, with parabolic interpolation, or `None` when no lag in +/// `min_tau..max_tau` falls below the threshold. `diff` holds at least `max_tau + 1` values. +fn yin(frame: &[f32], diff: &mut [f32], min_tau: usize, max_tau: usize) -> Option { + let w = frame.len().checked_sub(max_tau)?; + if max_tau <= min_tau + 2 || diff.len() <= max_tau || w == 0 { + return None; + } + difference(frame, &mut diff[..=max_tau], w); + normalize(&mut diff[..=max_tau]); + pick(&diff[..=max_tau], min_tau) +} + +/// Squared difference of the frame with itself at every lag. +fn difference(frame: &[f32], diff: &mut [f32], w: usize) { + diff[0] = 0.0; + for (tau, d) in diff.iter_mut().enumerate().skip(1) { + *d = frame[..w].iter().zip(&frame[tau..tau + w]).map(|(a, b)| (a - b) * (a - b)).sum(); + } +} + +/// Cumulative mean normalized difference, in place. +fn normalize(diff: &mut [f32]) { + diff[0] = 1.0; + let mut running = 0.0f32; + for (tau, d) in diff.iter_mut().enumerate().skip(1) { + running += *d; + *d = if running > 0.0 { *d * tau as f32 / running } else { 1.0 }; + } +} + +/// The first dip below the threshold, walked to its local minimum and interpolated. +fn pick(cmnd: &[f32], min_tau: usize) -> Option { + let last = cmnd.len() - 1; + let mut tau = (min_tau..last).find(|&t| cmnd[t] < THRESHOLD)?; + while tau + 1 < last && cmnd[tau + 1] < cmnd[tau] { + tau += 1; + } + let (a, b, c) = (cmnd[tau - 1] as f64, cmnd[tau] as f64, cmnd[tau + 1] as f64); + let denom = a - 2.0 * b + c; + let shift = if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 }; + Some(tau as f64 + shift) +} + +/// Four-point cubic Hermite read of `line` at a fractional `delay` behind `pos`. `delay` is at +/// least 2 and leaves two samples in the line behind it. +#[inline] +fn read(line: &[f32], mask: usize, pos: usize, delay: f64) -> f64 { + let i = delay as usize; + let f = delay - i as f64; + let at = |k: usize| line[(pos + line.len() - k) & mask] as f64; + let (ym1, y0, y1, y2) = (at(i - 1), at(i), at(i + 1), at(i + 2)); + let c1 = 0.5 * (y1 - ym1); + let c2 = ym1 - 2.5 * y0 + 2.0 * y1 - 0.5 * y2; + let c3 = 0.5 * (y2 - ym1) + 1.5 * (y0 - y1); + ((c3 * f + c2) * f + c1) * f + y0 +} + +/// Read positions and gains of both taps for one sample. +#[derive(Clone, Copy, Debug)] +struct Taps { + wet: f64, + delay_a: f64, + gain_a: f64, + delay_b: f64, +} + +/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). +pub struct VoicePitch { + pv: ParamValues, + latency: usize, + /// Widest tap spacing that keeps both taps inside the line, in samples. + max_spacing: f64, + lines: Vec>, + mask: usize, + pos: usize, + tracker: Tracker, + ratio: f64, + /// Sweep phase in `[0, 1)`: tap A is at the latency when it is 0.5, tap B when it is 0. + phase: f64, + spacing: f64, + /// Share of the shifted signal against the plain delay. + wet: f64, + wet_step: f64, +} + +impl VoicePitch { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::new("semitones", "Pitch", -24.0, 24.0, 0.0, Unit::Semitones), + ParamSpec::new("cents", "Fine Tune (cents)", -100.0, 100.0, 0.0, Unit::None), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + let latency = ((sample_rate * LATENCY_MS / 1000.0).round() as usize).max(4); + let len = (2 * latency + 8).next_power_of_two(); + let mut s = VoicePitch { + pv: ParamValues::new(Self::PARAMS), + latency, + max_spacing: latency as f64 - MARGIN, + lines: vec![vec![0.0; len]; ch], + mask: len - 1, + pos: 0, + tracker: Tracker::new(sample_rate), + ratio: 1.0, + phase: 0.5, + spacing: latency as f64 - MARGIN, + wet: 0.0, + wet_step: 1.0 / (sample_rate * BYPASS_MS / 1000.0).max(1.0) as f64, + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, snap: bool) { + let shift = self.pv.v("semitones") as f64 + self.pv.v("cents") as f64 / 100.0; + self.ratio = 2f64.powf(shift / 12.0); + if snap { + self.wet = self.target_wet(); + } + } + + fn target_wet(&self) -> f64 { + if self.ratio == 1.0 { 0.0 } else { 1.0 } + } + + /// Moves the crossfade and the sweep by one sample and returns where the taps read. + fn advance(&mut self) -> Taps { + let target = self.target_wet(); + self.wet = if self.wet < target { (self.wet + self.wet_step).min(target) } else { (self.wet - self.wet_step).max(target) }; + if self.wet == 0.0 { + // Fully on the plain delay: the next shift starts with tap A at the latency. + self.phase = 0.5; + self.spacing = self.max_spacing; + } else { + self.sweep(); + } + let pb = if self.phase >= 0.5 { self.phase - 0.5 } else { self.phase + 0.5 }; + let (l, s) = (self.latency as f64, self.spacing); + Taps { wet: self.wet, delay_a: l + (self.phase - 0.5) * 2.0 * s, gain_a: (PI * self.phase).sin().powi(2), delay_b: l + (pb - 0.5) * 2.0 * s } + } + + /// Advances the sweep phase. A tap whose delay changes by `1 - ratio` per sample reads the + /// input `ratio` times as fast. + fn sweep(&mut self) { + let step = ((1.0 - self.ratio) / (2.0 * self.spacing)).clamp(-MAX_STEP, MAX_STEP); + let raw = self.phase + step; + let wrapped = !(0.0..1.0).contains(&raw); + let p = raw - raw.floor(); + if wrapped || (p >= 0.5) != (self.phase >= 0.5) { + self.regrain(p, wrapped); + } else { + self.phase = p; + } + } + + /// One tap has just passed the latency and the other is silent at the end of its sweep: + /// take the tracker's spacing, and scale the centered tap's small offset so its delay does + /// not jump. + fn regrain(&mut self, p: f64, wrapped: bool) { + let new = self.tracker.spacing(self.max_spacing); + let k = self.spacing / new; + self.spacing = new; + let phase = if wrapped { + // Tap B is centered; its offset from the center is `p` (just past 0) or `p - 1`. + let u = (if p < 0.5 { p } else { p - 1.0 }) * k; + let u = u.clamp(-MAX_STEP, MAX_STEP); + if u < 0.0 { u + 1.0 } else { u } + } else { + 0.5 + ((p - 0.5) * k).clamp(-MAX_STEP, MAX_STEP) + }; + self.phase = if phase < 1.0 { phase } else { 0.0 }; + } +} + +impl AudioEffect for VoicePitch { + param_plumbing!("voice_pitch"); + fn latency(&self) -> usize { + self.latency + } + fn tail_samples(&self) -> usize { + // A tap reads up to `latency + max_spacing` samples back and the cubic read two samples + // more, which is twice the latency in all. + self.latency + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|v| *v = 0.0)); + self.pos = 0; + self.tracker.reset(); + self.phase = 0.5; + self.spacing = self.max_spacing; + self.wet = self.target_wet(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + let ch = channels.len().min(self.lines.len()); + let dry_at = self.mask + 1 - self.latency; + for i in 0..len { + let mut sum = 0.0f32; + for (line, io) in self.lines.iter_mut().zip(channels.iter()) { + // A non-finite sample is stored as silence, so it never reaches the output. + let x = flush32(io[i]); + line[self.pos] = x; + sum += x; + } + let first = self.lines[0][self.pos]; + self.tracker.push(sum / ch as f32, first); + let t = self.advance(); + for (line, io) in self.lines.iter().zip(channels.iter_mut()) { + let dry = line[(self.pos + dry_at) & self.mask] as f64; + let y = if t.wet == 0.0 { + dry + } else { + let shifted = + t.gain_a * read(line, self.mask, self.pos, t.delay_a) + (1.0 - t.gain_a) * read(line, self.mask, self.pos, t.delay_b); + t.wet * shifted + (1.0 - t.wet) * dry + }; + io[i] = y.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + } + self.pos = (self.pos + 1) & self.mask; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn shifter(semitones: f32, cents: f32) -> VoicePitch { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("semitones", semitones) && p.set_param("cents", cents)); + p.reset(); + p + } + + fn run(p: &mut VoicePitch, x: &[f32]) -> Vec { + let (mut l, mut r) = (x.to_vec(), x.to_vec()); + p.process(&mut [&mut l, &mut r]); + assert_eq!(l, r, "both channels get the same shift"); + l + } + + /// One second of output after the first half second. + fn settled(y: &[f32]) -> &[f32] { + &y[SR as usize / 2..SR as usize * 3 / 2] + } + + /// Frequency of the strongest component between `lo` and `hi` Hz, to 0.01 Hz. + fn peak_hz(x: &[f32], lo: f64, hi: f64) -> f64 { + let best = |from: f64, to: f64, step: f64| { + let n = ((to - from) / step) as usize; + (0..=n) + .map(|i| from + i as f64 * step) + .max_by(|a, b| tone_amplitude(x, *a, SR as f64).total_cmp(&tone_amplitude(x, *b, SR as f64))) + .unwrap_or(from) + }; + let coarse = best(lo, hi, 0.25); + best(coarse - 0.25, coarse + 0.25, 0.01) + } + + fn cents(f: f64, want: f64) -> f64 { + 1200.0 * (f / want).log2() + } + + /// A voiced tone shifted by an octave either way, or by a fifth with a fine offset, lands on + /// the shifted frequency within 2 cents. + #[test] + fn a_shifted_tone_reads_the_shifted_frequency() { + for (f_in, semis, fine) in [(220.0, 12.0, 0.0), (220.0, -12.0, 0.0), (180.0, 7.0, 30.0), (110.0, -24.0, 0.0)] { + let mut p = shifter(semis, fine); + let y = run(&mut p, &sine(f_in, 0.5, SR as f64, SR as usize * 2, 0.0)); + let want = f_in * 2f64.powf((semis as f64 + fine as f64 / 100.0) / 12.0); + let got = peak_hz(settled(&y), want * 0.9, want * 1.1); + assert!(cents(got, want).abs() < 2.0, "{f_in} Hz {semis:+} st {fine:+} ct: {got} Hz, want {want}"); + } + } + + /// On a voiced tone the taps are spaced by whole periods, so the crossfades do not beat: + /// almost all the output is the shifted tone. + #[test] + fn a_voiced_tone_crossfades_without_beating() { + for (f_in, semis) in [(220.0, 7.0), (150.0, -5.0), (300.0, 12.0)] { + let mut p = shifter(semis, 0.0); + let y = run(&mut p, &sine(f_in, 0.5, SR as f64, SR as usize * 2, 0.0)); + let rest = beside_tone_db(&y, f_in * 2f64.powf(semis as f64 / 12.0)); + assert!(rest < -40.0, "{f_in} Hz {semis:+} st: {rest:.1} dB beside the tone"); + } + } + + /// A voice whose two channels have opposite polarity, which cancel in their mean, is still + /// tracked and crossfades without beating. + #[test] + fn opposite_polarity_channels_are_still_tracked() { + let mut p = shifter(7.0, 0.0); + let mut l = sine(220.0, 0.5, SR as f64, SR as usize * 2, 0.0); + let mut r: Vec = l.iter().map(|v| -v).collect(); + p.process(&mut [&mut l, &mut r]); + assert!(l.iter().zip(&r).all(|(a, b)| *a == -*b)); + let rest = beside_tone_db(&l, 220.0 * 2f64.powf(7.0 / 12.0)); + assert!(rest < -40.0, "{rest:.1} dB beside the tone"); + } + + /// Level of everything but the strongest component near `want`, against that component, in + /// the settled output. + fn beside_tone_db(y: &[f32], want: f64) -> f64 { + let tail = settled(y); + let tone = tone_amplitude(tail, peak_hz(tail, want * 0.98, want * 1.02), SR as f64) / std::f64::consts::SQRT_2; + db((rms(tail).powi(2) - tone * tone).max(0.0).sqrt() / tone) + } + + /// The output of a burst, shifted or not, comes from taps within the spacing of the latency: + /// nothing sounds earlier than `latency - tail` or later than `latency + tail` around it. + #[test] + fn a_shifted_burst_stays_within_the_spacing_of_the_latency() { + for semis in [0.0, -24.0, -3.0, 5.0, 24.0] { + let mut p = shifter(semis, 0.0); + let (n, at, len) = (8000, 1777, 1000); + let mut rng = Rng::new(7); + let mut x = vec![0.0f32; n]; + x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform()); + let y = run(&mut p, &x); + let reach = p.tail_samples(); + let (lo, hi) = (at + p.latency() - reach, at + len + p.latency() + reach); + assert!(y.iter().enumerate().all(|(i, v)| *v == 0.0 || (lo..hi).contains(&i)), "{semis}"); + assert!(y.iter().any(|v| v.abs() > 0.05), "{semis}: the burst is lost"); + } + } + + /// Over whole sweeps, the oldest sample either tap reads, interpolation included, lies within + /// the latency plus the tail, so a render that compensates the latency and runs the tail past + /// the end of the input keeps every sample the taps still hold. + #[test] + fn the_tail_covers_the_oldest_sample_a_tap_reads() { + for semis in [-24.0, -3.0, 5.0, 24.0] { + let mut p = shifter(semis, 0.0); + let oldest = (0..SR as usize).map(|_| p.advance()).map(|t| t.delay_a.max(t.delay_b) as usize + 2).max().unwrap_or(0); + assert!(oldest > p.latency(), "{semis}: the taps never sweep past the latency"); + assert!(oldest <= p.latency() + p.tail_samples(), "{semis}: a tap reads {oldest} samples back"); + } + } + + /// A gliding voiced tone with a shift change part way gives the same output however the + /// stream is cut into blocks, spacing changes included. + #[test] + fn output_does_not_depend_on_how_the_stream_is_cut() { + let n = 40_000; + let x: Vec = (0..n) + .map(|i| (0.4 * (2.0 * std::f64::consts::PI * (120.0 * i as f64 / 48_000.0 + 0.6 * (i as f64 / 48_000.0).powi(2) * 200.0)).sin()) as f32) + .collect(); + let change = 17_321; + let run_cut = |sizes: &mut dyn FnMut() -> usize| { + let mut p = shifter(4.0, -20.0); + let mut y = x.clone(); + let mut pos = 0; + while pos < n { + if pos == change { + p.set_param("semitones", -9.0); + } + let mut len = sizes().min(n - pos); + if pos < change { + len = len.min(change - pos); + } + p.process(&mut [&mut y[pos..pos + len]]); + pos += len; + } + y + }; + let whole = run_cut(&mut || usize::MAX); + let mut rng = Rng::new(11); + let cut = run_cut(&mut || (rng.next_u64() % 700) as usize); + assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits())); + } + + /// NaN, infinite and the largest finite samples in a shifted voice give finite output, and + /// the voice is still shifted afterwards. + #[test] + fn non_finite_and_huge_samples_give_finite_output() { + let mut p = shifter(-7.0, 0.0); + let mut x = sine(200.0, 0.5, SR as f64, SR as usize * 2, 0.0); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + x[3000 + i * 1500] = bad; + x[3001 + i * 1500] = bad; + } + let y = run(&mut p, &x); + assert!(y.iter().all(|v| v.is_finite())); + let want = 200.0 * 2f64.powf(-7.0 / 12.0); + let tail = settled(&y); + assert!(cents(peak_hz(tail, want * 0.9, want * 1.1), want).abs() < 2.0); + assert!(db(rms(tail) / (0.5 / std::f64::consts::SQRT_2)).abs() < 1.0, "level {}", rms(tail)); + } + + /// The tracker finds a voice's period down to 70 Hz and reports nothing for silence. + #[test] + fn the_tracker_reaches_70_hz() { + for f in [72.0, 110.0, 440.0, 950.0] { + let mut t = Tracker::new(SR); + for v in sine(f, 0.3, SR as f64, SR as usize / 4, 0.0) { + t.push(v, v); + } + let period = t.period.unwrap_or(0.0); + assert!((SR as f64 / period / f - 1.0).abs() < 0.005, "{f} Hz read as {} Hz", SR as f64 / period); + } + let mut t = Tracker::new(SR); + (0..SR as usize / 4).for_each(|_| t.push(0.0, 0.0)); + assert!(t.period.is_none()); + } +} diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 7981f3a013..100986d8b1 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -24,7 +24,7 @@ decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa- # 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`. +# All but Opus are also file formats of `encode` and `FileEncoder`; all are codecs of `PacketEncoder`. 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"] @@ -44,6 +44,8 @@ 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 = [] +# SMPTE ST 302M (AES3 audio in MPEG-2 transport streams): packet decoder and encoder. +s302m = [] # ADPCM (`adpcm`): IMA WAV, Microsoft, Yamaha and Flash (SWF) decoders and encoders. adpcm = ["craft-media/bitstream"] # QOA (Quite OK Audio) files: decoder and encoder in the `qoa` module, each on its own. @@ -54,6 +56,7 @@ qoa-encode = [] g722 = [] # ITU-T G.726 ADPCM speech codec (16/24/32/40 kbit/s). g726 = [] +# The Opus encoder (`opus::encoder`), and Opus through `PacketEncoder`. opus-encode = [] # GSM 06.10 full-rate speech: decoder and encoder in the `gsm` module, each on its own. gsm = ["gsm-decode", "gsm-encode"] diff --git a/crates/audio/README.md b/crates/audio/README.md index bd80b54069..75f5694f66 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -34,19 +34,20 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `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` | +| `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 and `PacketEncoder` for AAC | 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 | +| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A; `PacketEncoder` for ALAC | craft-media `isobmff` | +| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder`; with `opus-encode`, `PacketEncoder` for Opus | 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` | | `vorbis-decode` | `vorbis::decoder::Decoder` (packets), `vorbis::decoder::decode_ogg` (whole Ogg Vorbis files); native Vorbis I: floors 0 and 1, residues 0 to 2, channel coupling, both block sizes. `decode` still reads Vorbis files through symphonia | 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` | +| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams; `PacketEncoder` for them | craft-media `bitstream` | | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | | `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` | -| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` | +| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3; `PacketEncoder` for MP3 | craft-media `bitstream` | | `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` | | `adpcm` | `adpcm::{ima, ms, yamaha, swf}`: decoders and encoders for IMA WAV, Microsoft, Yamaha and Flash ADPCM | craft-media `bitstream` | +| `s302m` | `s302m::{decode, Encoder}`: SMPTE ST 302M packets (AES3 audio in MPEG-2 transport streams), 2 to 8 channels of 16, 20 or 24 bits | none | | `gsm-decode`, `gsm-encode` (`gsm`) | `gsm::Decoder`, `gsm::Encoder`, `gsm::decode`, `gsm::encode`: GSM 06.10 full-rate speech, bit-exact, raw `.gsm` and WAV (GSM 6.10) packings | none | | `vmd-decode` | `vmd::Decoder`: Sierra VMD sound (8-bit PCM and 16-bit DPCM), frame by frame from `craft_media::vmd` | none | | `peaks` | `peaks::Peaks` | none | @@ -214,9 +215,11 @@ packet. Opus with empty `extradata` and 1 or 2 channels (RTP, MPEG-TS) needs no To seek: position your demuxer at the packet that starts `preroll()` frames or more before the target, call `reset()`, decode from there, and drop the output before the target. -The codec modules are also usable on their own. `aac::Decoder` and `opus::Decoder` return the -codec's channel order; `aac::wav_order(channel_config)` and `opus::wav_order(channels)` map it to -WAV order. `ac3::Decoder` and `mpa::Decoder` output WAV order. +The codec modules are also usable on their own. `aac::Decoder`, `opus::Decoder` and +`vorbis::decoder::Decoder` return the codec's channel order; `aac::wav_order(channel_config)`, +`opus::wav_order(channels)` and `vorbis::wav_order(channels)` map it to WAV order, and +`vorbis::layout(channels)` gives the speakers of the result. `ac3::Decoder` and `mpa::Decoder` +output WAV order. ### Encode a file @@ -311,12 +314,76 @@ file needs that step before it is written again. An M4A's edit list skips the AAC encoder's priming (1024 frames) and ends at the last frame written, so the file decodes to the length that went in. An MP3, AC-3 or E-AC-3 stream has no -place for that (see [Limits](#limits)). For a container of your own, use the codec modules below. +place for that (see [Limits](#limits)). For a container of your own, use `PacketEncoder` below. + +### Encode packets for your own container + +`PacketEncoder` is the encode-side counterpart of `TrackDecoder`: one interface over the AAC-LC, +ALAC, MP3, AC-3, E-AC-3 and Opus encoders for an app that muxes the audio itself (a video export +to MP4, Matroska or MXF). It returns packets and writes no file; `FileEncoder` writes its coded +formats through it. + +```rust +use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder}; + +let opts = EncodeOptions::new(EncodeFormat::Aac).with_layout(info.layout).with_bitrate(384_000); +let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 6)?; +for block in blocks { // planar f32 in WAV order, any length + for p in enc.encode(&block.channels, block.frames())? { + mux.write(p.pts, p.duration, &p.data)?; // pts and duration in samples at the rate + } +} +for p in enc.finish()? { + mux.write(p.pts, p.duration, &p.data)?; +} +let params = enc.codec_params(); // codec, rate, channels, extradata: what TrackDecoder::new takes +let priming = enc.priming(); // decoded samples before the first input frame +let padding = enc.padding(); // decoded samples after the last one +``` + +It takes the `EncodeOptions` of `FileEncoder` and reads `rate_control`, `layout`, and for ALAC +`bit_depth` and `dither`; `format` is ignored, so `EncodeOptions::default()` with a bit rate will +do for any codec. Input is planar `f32` in WAV channel order. `layout` names the speakers, the +channels are reordered into the codec's order, and ALAC's samples are quantized to the bit depth. +`layout()` reports the speakers the stream carries, in WAV order: the codec's layout for the count +(AAC's 5.1 has side surrounds, ALAC's back surrounds), or the AC-3 coding mode the layout chose. + +| `CodecId` | Feature | Frames per packet | `extradata()` | `priming()` | +|---|---|---|---|---| +| `Aac` (LC) | `aac-encode` | 1024 | `AudioSpecificConfig` | 1024 | +| `Alac` | `alac-encode` | 4096, the last one shorter | `alac` box payload / CodecPrivate | 0 | +| `Mp3` | `mp3-encode` | 1152 (576 below 32 kHz), one frame per packet | empty | 1057 | +| `Ac3`, `Eac3` | `ac3-encode`, `eac3-encode` | 1536 | empty | 256 | +| `Opus` | `opus-encode` | 960 (20 ms) | `OpusHead` | the pre-skip | + +The sample rates, channel counts and layouts are those of the `EncodeFormat` of the same name; +Opus takes 48 kHz mono or stereo at a constant bit rate, 64 kbit/s per channel by default. A codec +with no encoder here, and one whose feature is off, are `Unsupported`; settings a codec cannot take +get the error `EncodeOptions::check` gives for the format. + +Timing: a packet's `pts` is where its decoded audio starts, counted from the first decoded sample, +so input frame `n` is at `n + priming()`. `finish` pads the end with silence until a decoder +returns every input frame, and the durations add up to `priming() + frames() + padding()`. With no +input there are no packets: the durations add up to 0 and `padding()` is 0, while `priming()` still +reports the codec's delay. A muxer +skips the priming (MP4: `TrackConfig::media_start` or an edit list; Matroska: `CodecDelay`; Opus: +the pre-skip, which `OpusHead` already holds) and trims the padding (the end of an MP4 edit, +Matroska's `DiscardPadding`). ALAC's `extradata` records the largest packet and the average bit +rate, so read it after `finish`. `bitrate()` is the constant rate used (`None` for ALAC and AAC by +quality); `bit_depth()` is ALAC's. + +`encode` refuses a block without one slice per channel, or with a slice shorter than `frames`, +and encodes nothing; the encoder stays usable, so the caller can correct the block and call again. +After `finish`, or after encoding itself failed (the block's packets are lost), every call returns +an error. +E-AC-3 7.1 is encoded as 7.1, and this crate's `TrackDecoder` plays its 5.1 substream (see +[Limits](#limits)). ### Encode AAC packets -For an `.m4a` file, use `EncodeFormat::Aac` above. `aac::Encoder` is the packet encoder behind it, -for muxing into a container of your own: +For an `.m4a` file, use `EncodeFormat::Aac` above, and for packets in WAV channel order, +`PacketEncoder`. `aac::Encoder` is the codec's own encoder behind both, with the settings +`EncodeOptions` does not have (bandwidth, TNS, M/S stereo, window shape, ADTS): ```rust use craft_audio::AudioError; @@ -573,7 +640,35 @@ Each codec module's rustdoc lists the coding tools it implements. | MP2 encoder (`mpa::encoder`) | ISO/IEC 11172-3 (§2.4, Annex B and C), 13818-3 | Layer II, constant bit rate, mono or stereo (no joint stereo), 32/44.1/48 kHz at the spec's rate/mode pairs and 16/22.05/24 kHz at 8–160 kbit/s; no CRC | our decoder and ffmpeg decode the frames; SNR of 20–37 dB on tone mixes, and the 481-sample filter delay matches | | MP3 decoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, MPEG-1/2/2.5, 8–48 kHz, every bit rate, CBR and VBR; mono, stereo, dual channel, joint stereo (mid/side and intensity); long, short and mixed blocks; bit reservoir; CRC read, not checked; Xing / Info / VBRI and LAME tags; no free format (read through symphonia) | ffmpeg's float decoder: 127–131 dB SNR on LAME streams of every sampling frequency (CBR, VBR, CRC, no reservoir, transients with short blocks) and on this crate's encoder's; intensity stereo and mixed blocks through LAME frames edited to use them (112–131 dB) | | MP3 encoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, constant bit rate: 32–320 kbit/s at 32/44.1/48 kHz, 8–160 kbit/s at 16/22.05/24 kHz; mono, stereo, joint stereo (mid/side); bit reservoir; long blocks only; no Xing/Info tag, VBR, CRC or free format | ffmpeg decodes every Huffman code as intended; full encodes at every sampling frequency checked with ffprobe and by SNR of ffmpeg's decode | -| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder, same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | +| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder (except 24- and 32-bit packets quiet enough to shift off fewer low bytes, such as silence), same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | + +### ALAC encoding + +Apple's reference encoder stores the low byte (24-bit) or low two bytes (32-bit) of every sample +uncompressed. This encoder shifts off fewer bytes, per element and per packet, when the samples +allow it: at 24 bits a packet that peaks below −54 dBFS keeps no uncompressed byte; at 32 bits one +below −54 dBFS keeps one, and a mono or LFE element below −102 dBFS none (a 32-bit pair always keeps +one). Other packets are the same as the reference's, and decoders need no change. + +Stream sizes in MB (10⁶ bytes) for 4 minutes at 48 kHz in 4096-frame packets. "Reference" is this +encoder with the reference's fixed shift; Apple's `afconvert` gives the same sizes for the 24-bit stereo rows. The +music is synthetic (decaying harmonic notes over a noise floor, peaking at −3 dBFS); a stem plays +5 or 10 seconds in every 20. + +| Material | Depth / ch | PCM | Reference | This encoder | Saved | +|---|---|---|---|---|---| +| Music throughout | 24 / 2 | 69.1 | 45.5 | 45.5 | 0% | +| Music, 2 s of digital silence at each end | 24 / 2 | 69.1 | 45.1 | 44.7 | 0.8% | +| Stem playing half the time, digital silence between | 24 / 2 | 69.1 | 34.3 | 22.8 | 33% | +| Stem playing a quarter of the time, digital silence between | 24 / 2 | 69.1 | 28.7 | 11.5 | 60% | +| The same, noise at −110 dBFS in place of silence | 24 / 2 | 69.1 | 32.6 | 25.1 | 23% | +| Quiet music, peaking at −60 dBFS | 24 / 2 | 69.1 | 27.7 | 20.1 | 27% | +| Digital silence | 24 / 2 | 69.1 | 23.1 | 0.09 | 99.6% | +| 5.1: music in front, surrounds a quarter of the time, silent LFE | 24 / 6 | 207.4 | 108.7 | 79.9 | 26% | +| Stem playing a quarter of the time, digital silence between | 32 / 1 | 46.1 | 25.9 | 8.7 | 66% | +| Stem playing a quarter of the time, digital silence between | 32 / 2 | 92.2 | 51.7 | 34.5 | 33% | +| Quiet music, peaking at −60 dBFS | 32 / 2 | 92.2 | 50.7 | 43.2 | 15% | +| Digital silence | 32 / 2 | 92.2 | 46.2 | 23.1 | 50% | ### MP3 encoding diff --git a/crates/audio/src/alac/encoder.rs b/crates/audio/src/alac/encoder.rs index 7fc842597b..e4211dc5b1 100644 --- a/crates/audio/src/alac/encoder.rs +++ b/crates/audio/src/alac/encoder.rs @@ -8,7 +8,11 @@ //! //! The search (stereo matrixing, 4 or 8 predictor coefficients) and the state kept across //! packets (coefficients, the last matrixing, and the buffers the trial runs read stale parts of) -//! follow the reference, so for the same input this writes the same packets as it. +//! follow the reference, so for the same input this writes the same packets as it, with one +//! exception: the shifted-off low bytes. The reference passes 1 (24-bit) or 2 (32-bit) low bytes +//! of every sample through uncompressed, even for silence. Here an element shifts off fewer bytes +//! in a packet whose samples fit well within the width the reference predicts (see +//! [`packet_shift`]), so silence and quiet passages are not padded with a byte or two per sample. use super::ag::{self, AgParams}; use super::bits::{BitCounter, BitSink, BitWriter}; @@ -100,6 +104,25 @@ fn bytes_shifted(bit_depth: u32) -> u32 { } } +/// The bytes an element shifts off in one packet: the fewest, down from the reference's +/// [`bytes_shifted`], that leave every sample at least one bit narrower than the width the +/// reference predicts (`bit_depth − 8 · bytes_shifted`). The predictor then works on values no +/// wider than in the reference, so its arithmetic stays in the same range; only fewer low bytes go +/// out uncompressed. The spare bit is there because at the full width, coding the low byte through +/// the predictor costs about as much as storing it, and for 24-bit mono measured 2% more. +/// A 32-bit pair keeps at least 1: with none, its prediction width (33 bits) exceeds the 32 the +/// format allows. +fn packet_shift(bit_depth: u32, channels: &[&[i32]]) -> u32 { + let reference = bytes_shifted(bit_depth); + let width = bit_depth - reference * 8 - 1; + let floor = u32::from(bit_depth == 32 && channels.len() == 2); + let fits = |bytes: u32| { + let (lo, hi) = (-(1i64 << (width - 1)), (1i64 << (width - 1)) - 1); + channels.iter().flat_map(|c| c.iter()).all(|&x| (lo..=hi).contains(&i64::from(x >> (bytes * 8)))) + }; + (floor..reference).find(|&b| fits(b)).unwrap_or(reference) +} + impl Encoder { /// An encoder for `cfg`. pub fn new(cfg: EncoderConfig) -> Result { @@ -191,11 +214,12 @@ impl Encoder { w.put(cpe_tag, 4); cpe_tag += 1; let (l, r) = (channels[index], channels[index + 1]); + let bs = packet_shift(self.bit_depth, &[l, r]); // as in the reference, fast mode applies to stereo streams only if self.cfg.fast && channels.len() == 2 { - self.encode_stereo_fast(&mut w, index, l, r)?; + self.encode_stereo_fast(&mut w, index, l, r, bs)?; } else { - self.encode_stereo(&mut w, index, l, r)?; + self.encode_stereo(&mut w, index, l, r, bs)?; } index += 2; } @@ -203,7 +227,8 @@ impl Encoder { let tag = if element == ID_LFE { &mut lfe_tag } else { &mut sce_tag }; w.put(*tag, 4); *tag += 1; - self.encode_mono(&mut w, index, channels[index])?; + let bs = packet_shift(self.bit_depth, &[channels[index]]); + self.encode_mono(&mut w, index, channels[index], bs)?; index += 1; } } @@ -231,10 +256,10 @@ impl Encoder { } /// `EncodeStereo`: a channel pair with the matrixing and coefficient search. - fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> { + /// `bs`: the bytes shifted off, from [`packet_shift`]. + fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = l.len(); - let bs = bytes_shifted(self.bit_depth); let chan_bits = self.bit_depth - bs * 8 + 1; let partial = self.partial(n); let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0); @@ -329,10 +354,9 @@ impl Encoder { } /// `EncodeStereoFast`: a channel pair without matrixing or search. - fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> { + fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = l.len(); - let bs = bytes_shifted(self.bit_depth); let chan_bits = self.bit_depth - bs * 8 + 1; let partial = self.partial(n); let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0); @@ -396,10 +420,9 @@ impl Encoder { } /// `EncodeMono`: one channel (SCE or LFE). - fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32]) -> Result<()> { + fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = input.len(); - let bs = bytes_shifted(self.bit_depth); let shift = bs * 8; let chan_bits = self.bit_depth - shift; let partial = self.partial(n); @@ -563,4 +586,84 @@ mod tests { let mut dec = Decoder::new(&enc.cookie()).unwrap(); assert_eq!(dec.decode(&p).unwrap(), vec![noise[..4096].to_vec()]); } + + /// One packet of `frames` frames per element, encoded and decoded back; its size in bytes. + fn packet_bytes(cfg: EncoderConfig, input: &[Vec]) -> usize { + let mut enc = Encoder::new(cfg).unwrap(); + let chunk: Vec<&[i32]> = input.iter().map(Vec::as_slice).collect(); + let p = enc.encode(&chunk).unwrap(); + let mut dec = Decoder::new(&enc.cookie()).unwrap(); + assert_eq!(dec.decode(&p).unwrap(), input, "{cfg:?}"); + p.len() + } + + /// The reference shifts 1 (24-bit) or 2 (32-bit) low bytes of every sample off and stores them + /// uncompressed, so a 4096-frame stereo packet of 24-bit silence was 8224 bytes (#1368). + #[test] + fn silence_is_a_few_bytes_at_every_depth() { + for bits in [16, 20, 24, 32] { + for ch in [1, 2, 6] { + for fast in [false, true] { + let cfg = EncoderConfig::new(48_000, ch, bits).with_fast(fast); + let bytes = packet_bytes(cfg, &vec![vec![0; 4096]; usize::from(ch)]); + // a 32-bit pair keeps one shifted byte per sample: the format allows no less + let floor = if bits == 32 { 4096 * 2 * (usize::from(ch) / 2) } else { 0 }; + assert!(bytes <= floor + 40 * usize::from(ch), "{bits} bits, {ch} ch, fast {fast}: {bytes} bytes"); + } + } + } + } + + /// Quiet audio (within 12 bits) at 24 and 32 bits shifts nothing off and comes within 10% of + /// the same audio at 16 bits (the wider prediction width makes the coder's escapes longer); + /// the reference stored a byte or two more per sample. Samples at the edges of each width and + /// loud audio decode exactly. + #[test] + fn quiet_packets_compress_like_16_bit_audio_and_loud_ones_round_trip() { + let quiet = signal(4096, 2, 12); + let at16 = packet_bytes(EncoderConfig::new(48_000, 2, 16), &quiet); + let at24 = packet_bytes(EncoderConfig::new(48_000, 2, 24), &quiet); + assert!(at24 * 10 <= at16 * 11, "24-bit {at24} bytes, 16-bit {at16}"); + let mono = vec![quiet[0].clone()]; + let at16 = packet_bytes(EncoderConfig::new(48_000, 1, 16), &mono); + let at32 = packet_bytes(EncoderConfig::new(48_000, 1, 32), &mono); + assert!(at32 * 10 <= at16 * 11, "32-bit mono {at32} bytes, 16-bit {at16}"); + // the samples just past each narrower width, and loud audio, decode exactly + for bits in [24u32, 32] { + for ch in [1u8, 2] { + let edge: Vec> = (0..ch) + .map(|c| { + (0..4096) + .map(|i| match (i + usize::from(c)) % 4 { + 0 => (16_384 << (bits - 24)) - 1, + 1 => -(16_384 << (bits - 24)), + 2 => 16_384 << (bits - 24), + _ => -(16_384 << (bits - 24)) - 1, + }) + .collect() + }) + .collect(); + packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &edge); + packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &signal(4096, usize::from(ch), bits)); + } + } + } + + #[test] + fn the_shift_is_the_fewest_bytes_that_keep_the_reference_width() { + let z = [0i32; 4]; + assert_eq!(packet_shift(16, &[&z]), 0); + assert_eq!(packet_shift(24, &[&z, &z]), 0); + assert_eq!(packet_shift(24, &[&[16_383, -16_384], &z]), 0); + assert_eq!(packet_shift(24, &[&[16_384], &z]), 1); + assert_eq!(packet_shift(24, &[&[-16_385]]), 1); + assert_eq!(packet_shift(24, &[&[32_767]]), 1); + assert_eq!(packet_shift(32, &[&z]), 0); + assert_eq!(packet_shift(32, &[&[16_383]]), 0); + assert_eq!(packet_shift(32, &[&z, &z]), 1); + assert_eq!(packet_shift(32, &[&[1 << 21]]), 1); + assert_eq!(packet_shift(32, &[&[1 << 22]]), 2); + assert_eq!(packet_shift(32, &[&[i32::MIN]]), 2); + assert_eq!(packet_shift(32, &[&[i32::MAX], &z]), 2); + } } diff --git a/crates/audio/src/alac/mod.rs b/crates/audio/src/alac/mod.rs index 14bbbf6c50..d580fd9c28 100644 --- a/crates/audio/src/alac/mod.rs +++ b/crates/audio/src/alac/mod.rs @@ -23,7 +23,9 @@ //! reference: hostile input returns errors instead of reading or writing out of bounds, integer //! arithmetic wraps where C would overflow, the 4- and 8-tap predictor loops are folded into the //! general one (same values), the sample-width variants of the matrix routines into one routine -//! over `i32`, and the encoder fills in the cookie's average bit rate. +//! over `i32`, the encoder fills in the cookie's average bit rate, and it shifts off fewer low +//! bytes in packets whose samples fit a narrower width (silence and quiet passages at 24 and 32 +//! bits), where the reference always passes them through uncompressed. // The bit I/O, coder, predictor and matrix modules serve both halves; with only one of // `alac-decode` and `alac-encode` built, the other half's routines are unused. diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 29054288ec..d57baa6b59 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -23,6 +23,9 @@ //! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`, //! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature //! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. +//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`, +//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC, +//! MP3, AC-3, E-AC-3 or Opus, with their timing and codec configuration, for an app's own muxer. //! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`], //! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF //! file bit for bit, and minimal files around such PCM, for essence embedded in other containers. @@ -32,7 +35,8 @@ //! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`] //! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder; //! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), [`adpcm`] -//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), +//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`s302m`] (`s302m`: SMPTE 302M packets), +//! [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), //! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`: //! Sierra VMD sound). //! @@ -64,6 +68,15 @@ pub mod mp3; pub mod mpa; #[cfg(any(feature = "opus-decode", feature = "opus-encode"))] pub mod opus; +#[cfg(any( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" +))] +mod packet; #[cfg(any( feature = "aac-decode", feature = "alac-decode", @@ -79,6 +92,8 @@ pub mod peaks; pub mod qoa; #[cfg(feature = "decode-native")] mod read; +#[cfg(feature = "s302m")] +pub mod s302m; #[cfg(feature = "sbc")] pub mod sbc; #[cfg(any( @@ -157,6 +172,15 @@ pub use buffer::AudioBuffer; pub use craft_media; pub use craft_media::{ByteSource, CodecId, CodecParams, Container, PcmFormat, ReadSeekSource}; pub use layout::{ChannelLayout, Speaker}; +#[cfg(any( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" +))] +pub use packet::{EncodedPacket, PacketEncoder}; #[cfg(feature = "decode-native")] pub use read::SharedSource; #[cfg(feature = "decode-native")] diff --git a/crates/audio/src/packet.rs b/crates/audio/src/packet.rs new file mode 100644 index 0000000000..2d1ab7d621 --- /dev/null +++ b/crates/audio/src/packet.rs @@ -0,0 +1,696 @@ +//! [`PacketEncoder`]: one interface over the AAC-LC, ALAC, MP3, AC-3, E-AC-3 and Opus encoders, for +//! a caller that puts the packets in its own container. It takes planar `f32` in WAV channel order, +//! maps the channels onto the codec's order, and returns packets with their timing; the coded +//! formats of [`FileEncoder`](crate::FileEncoder) are written through it. + +// Each codec is its own feature: with only some of them built, the other halves of the shared +// code are unused. +#![cfg_attr( + not(all( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" + )), + allow(dead_code, unused_imports, unused_variables, unused_mut) +)] + +use crate::layout::channel_map; +use crate::{AudioError, ChannelLayout, CodecId, CodecParams, EncodeFormat, EncodeOptions, RateControl, Result}; + +/// Maximum frames handed to a codec per internal call, bounding that call's input and output. +/// `PacketEncoder::encode` collects packets across all chunks, so its returned vector grows with +/// the caller's input block. Also the frames of an ALAC packet. +pub(crate) const CHUNK: usize = 4096; + +/// Bits per second per channel when no rate is asked for: AAC and Opus. +const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; +const OPUS_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; +/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per +/// full-bandwidth channel). +const DEFAULT_KBPS_PER_CHANNEL: u32 = 96; + +/// Opus's layouts by channel count: RFC 7845 mapping family 0 (mono, and stereo as L R). +const OPUS_LAYOUT_MASKS: [&[u32]; 2] = [&[0x4], &[0x3]]; + +/// One packet from a [`PacketEncoder`]. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncodedPacket { + /// The coded bytes: an AAC raw data block (no ADTS header), an ALAC packet, one MP3 frame, + /// one AC-3 syncframe or an E-AC-3 access unit, one Opus packet. + pub data: Vec, + /// Where the packet's decoded audio starts, in samples at the sample rate from the first + /// decoded sample of the stream. The encoder's [priming](PacketEncoder::priming) comes first, + /// so input frame `n` is at `n + priming`. + pub pts: u64, + /// The samples per channel the packet decodes to, the last packet's padding included. + pub duration: u32, +} + +/// Encodes audio to packets of one codec, for a muxer of the caller's own: the encode-side +/// counterpart of [`TrackDecoder`](crate::TrackDecoder). Built from a [`CodecId`] and the +/// [`EncodeOptions`] of [`FileEncoder`](crate::FileEncoder), of which it reads the rate control, +/// the layout, and for ALAC the bit depth and dither. +/// +/// Input is planar `f32` in WAV channel order, one slice per channel, at any block size; packets +/// come out as they are completed, and [`finish`](Self::finish) returns the rest. What a container +/// needs to describe the track is on the encoder: [`codec_params`](Self::codec_params) (codec, +/// rate, channels and [`extradata`](Self::extradata)), [`layout`](Self::layout), +/// [`priming`](Self::priming), and after `finish` [`padding`](Self::padding). +/// +/// | Codec | Feature | Packet | `extradata` | Priming | +/// |---|---|---|---|---| +/// | [`CodecId::Aac`] (LC) | `aac-encode` | 1024 frames | `AudioSpecificConfig` | 1024 | +/// | [`CodecId::Alac`] | `alac-encode` | 4096 frames | the `alac` box / CodecPrivate | 0 | +/// | [`CodecId::Mp3`] | `mp3-encode` | 1152 frames (576 below 32 kHz) | none | 1057 | +/// | [`CodecId::Ac3`], [`CodecId::Eac3`] | `ac3-encode`, `eac3-encode` | 1536 frames | none | 256 | +/// | [`CodecId::Opus`] | `opus-encode` | 960 frames (20 ms) | `OpusHead` | the pre-skip | +/// +/// ``` +/// # #[cfg(all(feature = "aac-encode", feature = "aac-decode"))] { +/// use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder, TrackDecoder}; +/// +/// let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128_000); +/// let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 2)?; +/// let block = [vec![0.25f32; 4800], vec![-0.25f32; 4800]]; // 0.1 s, one Vec per channel +/// let mut packets = enc.encode(&block, 4800)?; +/// packets.extend(enc.finish()?); +/// assert_eq!(enc.priming(), 1024); +/// assert_eq!(packets.iter().map(|p| u64::from(p.duration)).sum::(), 1024 + 4800 + enc.padding()); +/// +/// // The description a muxer writes is what a decoder reads. +/// let mut dec = TrackDecoder::new(&enc.codec_params(), &[])?; +/// assert_eq!(dec.decode(&packets[0].data)?.frames(), 1024); +/// # } +/// # Ok::<(), craft_audio::AudioError>(()) +/// ``` +pub struct PacketEncoder { + codec: CodecId, + inner: Inner, + sample_rate: u32, + /// The speakers of the channels encoded, in WAV order. + layout: ChannelLayout, + /// For each codec channel, the caller's channel that feeds it. + map: Vec, + bitrate: Option, + /// The integer depth of a lossless codec. + bit_depth: Option, + /// Where the next packet starts. + pts: u64, + /// Frames of input taken. + frames: u64, + finished: bool, + /// Set when a call failed: the packets of that block are lost, so the stream has a gap and + /// every later call is refused. + failed: bool, +} + +impl std::fmt::Debug for PacketEncoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PacketEncoder") + .field("codec", &self.codec) + .field("sample_rate", &self.sample_rate) + .field("layout", &self.layout) + .field("frames", &self.frames) + .finish_non_exhaustive() + } +} + +/// A packet encoder of one of the codecs, taking planar `f32` in its own channel order. +enum Inner { + #[cfg(feature = "aac-encode")] + Aac(Box), + #[cfg(feature = "alac-encode")] + Alac { + enc: Box, + quantizers: Vec, + /// Quantized samples of the packet being filled, per channel. + pending: Vec>, + }, + #[cfg(feature = "mp3-encode")] + Mp3 { + enc: Box, + /// Bytes the encoder returned that do not yet make a whole frame. + bytes: Vec, + }, + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Ac3 { + enc: Box, + /// The block with every sample finite and within ±1, as the encoder requires. + planes: Vec>, + }, + #[cfg(feature = "opus-encode")] + Opus { + enc: Box, + /// Interleaved samples of the frame being filled. + pending: Vec, + /// Frames of the decoded stream the packets so far cover. + coded: u64, + }, +} + +/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`. +fn labels(mask: u32) -> String { + ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::>().join(" ") +} + +/// The speakers of the caller's layout, for an error message. +fn given(layout: &ChannelLayout) -> String { + layout.mask().map_or_else(|| "without speaker assignment".into(), labels) +} + +/// [`channel_map`] for a codec with one layout per channel count (the first of `masks`), and +/// that layout; or why the audio does not fit. +fn fixed_map(masks: &[u32], name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<(Vec, ChannelLayout)> { + let Some(&mask) = masks.first() else { + return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels()))); + }; + let map = channel_map(mask, order, layout).ok_or_else(|| { + AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout))) + })?; + Ok((map, ChannelLayout::from_mask(mask))) +} + +/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for +/// 8 channels configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc. +#[cfg(feature = "aac-encode")] +pub(super) fn aac_order(channels: usize) -> Option<&'static [usize]> { + if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) } +} + +/// The lowest AAC bit rate used, per channel: 6 kbit/s, and a quarter of the sample rate (256 +/// bits a frame). The encoder accepts less, and from about half of this down codes silence; a +/// stream of silence is no answer to a low bit rate (or to kbit/s given as bit/s). +#[cfg(feature = "aac-encode")] +fn aac_floor_per_channel(sample_rate: u32) -> u32 { + (sample_rate / 4).max(6000) +} + +/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a +/// quality of 0–1 spans the encoder's VBR range. +#[cfg(feature = "aac-encode")] +pub(super) fn aac_mode(rate: Option, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode { + use crate::aac::BitrateMode; + let (lo, hi) = crate::aac::cbr_range(sample_rate, channels); + let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo)); + // An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone. + let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps }; + match rate { + None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))), + Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)), + // NaN stays NaN, which the encoder refuses. + Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)), + } +} + +/// The bit rate in bits per second for a codec with constant bit rates only. +fn constant_bps(name: &str, rate: Option, default: u32) -> Result { + match rate { + None => Ok(default), + Some(RateControl::Bitrate(bps)) => Ok(bps), + Some(RateControl::Quality(_)) => { + Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality"))) + } + } +} + +/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding +/// mode whose speakers the layout names, at the nearest bit rate the stream can carry. +#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] +pub(super) fn ac3_config( + codec: crate::ac3::encoder::Codec, + sample_rate: u32, + layout: &ChannelLayout, + rate: Option, +) -> Result<(crate::ac3::encoder::Config, Vec)> { + use crate::ac3::encoder::{Codec, CodingMode, Config}; + use CodingMode::*; + let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" }; + let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; + let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| { + // 7.1 is an E-AC-3 programme with an LFE; the encoder has no other. + if mode == Surround71 && (codec != Codec::Eac3 || !lfe) { + return None; + } + let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe }; + let map = channel_map(config.channel_layout().mask()?, None, layout)?; + Some((config, map)) + }); + let Some((mut config, map)) = found else { + return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout)))); + }; + let full = config.mode.channels() as u32; + let want = constant_bps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full * 1000)? / 1000; + // What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of + // the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold. + let least = if config.mode == Surround71 { 384 } else { 32 * full }; + config.bitrate_kbps = match codec { + Codec::Ac3 => { + let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least); + crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor) + } + Codec::Eac3 => { + let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 }; + want.clamp(least, most.max(least)) + } + }; + Ok((config, map)) +} + +/// The feature a codec's encoder is built with, or `None` for a codec with no encoder here. +fn feature(codec: CodecId) -> Option<&'static str> { + Some(match codec { + CodecId::Aac => "aac-encode", + CodecId::Alac => "alac-encode", + CodecId::Mp3 => "mp3-encode", + CodecId::Ac3 => "ac3-encode", + CodecId::Eac3 => "eac3-encode", + CodecId::Opus => "opus-encode", + _ => return None, + }) +} + +impl PacketEncoder { + /// An encoder of `codec` for `channels` channels at `sample_rate`. Of `opts` it reads + /// `rate_control` and `layout` (as [`FileEncoder`](crate::FileEncoder) does: the speakers of + /// the caller's channels, mapped onto the codec's layout), and for ALAC `bit_depth` and + /// `dither`; `format`, `bwf` and `force_rf64` are for files and ignored. + /// + /// Opus takes 48 kHz mono or stereo at a constant bit rate (64 kbit/s per channel when none + /// is asked for); the others take what their [`EncodeFormat`] lists. A codec this crate has + /// no encoder for, and one whose feature is not built, are [`AudioError::Unsupported`]. A + /// rate, channel count, layout or rate control the codec cannot take is refused with the error + /// [`EncodeOptions::check`] gives for the format (`Unsupported` for a layout or rate control). + pub fn new(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, channels: u16) -> Result { + let Some(feature) = feature(codec) else { + return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))); + }; + let built = [ + (CodecId::Aac, cfg!(feature = "aac-encode")), + (CodecId::Alac, cfg!(feature = "alac-encode")), + (CodecId::Mp3, cfg!(feature = "mp3-encode")), + (CodecId::Ac3, cfg!(feature = "ac3-encode")), + (CodecId::Eac3, cfg!(feature = "eac3-encode")), + (CodecId::Opus, cfg!(feature = "opus-encode")), + ]; + if !built.contains(&(codec, true)) { + return Err(AudioError::Unsupported(format!("encoding {} needs the `{feature}` feature", codec.name()))); + } + let n = usize::from(channels); + // As the file writers word it. + if channels == 0 { + return Err(AudioError::Encode("buffer has no channels".into())); + } + if sample_rate == 0 { + return Err(AudioError::Encode("sample rate is 0".into())); + } + if let Some(layout) = &opts.layout + && layout.channels() != channels + { + return Err(AudioError::Encode(format!("a {}-channel layout for {channels} channels", layout.channels()))); + } + let given = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels)); + let (inner, map, layout, bitrate, bit_depth) = match codec { + #[cfg(feature = "aac-encode")] + CodecId::Aac => { + let (map, layout) = fixed_map(EncodeFormat::Aac.layout_masks(channels), "AAC", aac_order(n), &given)?; + let mode = aac_mode(opts.rate_control, sample_rate, n); + let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, n, 0) }; + let bitrate = match mode { + crate::aac::BitrateMode::Cbr(bps) => Some(bps), + crate::aac::BitrateMode::Vbr(_) => None, + }; + (Inner::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, layout, bitrate, None) + } + #[cfg(feature = "alac-encode")] + CodecId::Alac => { + let count = u8::try_from(channels).unwrap_or(u8::MAX); + let (map, layout) = fixed_map(EncodeFormat::Alac.layout_masks(channels), "ALAC", crate::alac::alac_order(count), &given)?; + let bits = match opts.bit_depth { + crate::BitDepth::Int16 => 16, + crate::BitDepth::Int24 => 24, + crate::BitDepth::Int32 => 32, + crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())), + }; + let config = crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32); + let enc = crate::alac::Encoder::new(config)?; + let quantizers = crate::write::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, n); + (Inner::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); n] }, map, layout, None, Some(bits)) + } + #[cfg(feature = "mp3-encode")] + CodecId::Mp3 => { + let (map, layout) = fixed_map(EncodeFormat::Mp3.layout_masks(channels), "MP3", None, &given)?; + let want = constant_bps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * u32::from(channels) * 1000)? / 1000; + // A sample rate MP3 has not is the encoder's to refuse. + let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want); + let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, n, kbps))?; + (Inner::Mp3 { enc: Box::new(enc), bytes: Vec::new() }, map, layout, Some(kbps.saturating_mul(1000)), None) + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + CodecId::Ac3 | CodecId::Eac3 => { + let which = if codec == CodecId::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 }; + let (config, map) = ac3_config(which, sample_rate, &given, opts.rate_control)?; + let enc = crate::ac3::encoder::Encoder::new(config)?; + let layout = enc.channel_layout(); + let bitrate = Some(config.bitrate_kbps.saturating_mul(1000)); + (Inner::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); n] }, map, layout, bitrate, None) + } + #[cfg(feature = "opus-encode")] + CodecId::Opus => { + let masks = n.checked_sub(1).and_then(|i| OPUS_LAYOUT_MASKS.get(i)).copied().unwrap_or_default(); + let (map, layout) = fixed_map(masks, "Opus", None, &given)?; + if sample_rate != 48_000 { + return Err(AudioError::Unsupported(format!("Opus is encoded at 48000 Hz, not {sample_rate} Hz"))); + } + let bps = constant_bps("Opus", opts.rate_control, OPUS_DEFAULT_BPS_PER_CHANNEL * u32::from(channels))?; + let enc = crate::opus::encoder::Encoder::new(channels as u8, bps)?; + let bitrate = Some(enc.bitrate()); + (Inner::Opus { enc: Box::new(enc), pending: Vec::new(), coded: 0 }, map, layout, bitrate, None) + } + #[allow(unreachable_patterns)] + _ => return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))), + }; + Ok(PacketEncoder { codec, inner, sample_rate, layout, map, bitrate, bit_depth, pts: 0, frames: 0, finished: false, failed: false }) + } + + /// The codec of the packets. + pub fn codec(&self) -> CodecId { + self.codec + } + + /// The sample rate of the audio and of the packets' timing. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// The number of channels. + pub fn channels(&self) -> u16 { + self.layout.channels() + } + + /// The speakers of the channels encoded, in WAV order: the codec's layout for the channel + /// count (for AC-3 and E-AC-3, the coding mode's), which is what a decoder reports. Where the + /// codec has one surround pair, it is the codec's (AAC's 5.1 has side surrounds, ALAC's back + /// ones), whichever pair the caller's layout named. + pub fn layout(&self) -> ChannelLayout { + self.layout + } + + /// The constant bit rate in bits per second for all channels together, as + /// [`RateControl::Bitrate`] describes the rate the stream settles on; `None` for ALAC and + /// for AAC at a constant quality. + pub fn bitrate(&self) -> Option { + self.bitrate + } + + /// The bits per sample of a lossless codec (ALAC), `None` for the lossy ones. + pub fn bit_depth(&self) -> Option { + self.bit_depth + } + + /// The codec configuration a container stores: AAC's `AudioSpecificConfig` (MP4 `esds` + /// decoder-specific info, Matroska CodecPrivate), ALAC's configuration as MP4's `alac` box + /// and Matroska's CodecPrivate hold it, Opus's `OpusHead`; empty for MP3, AC-3 and E-AC-3. + /// ALAC's records the largest packet and the average bit rate so far, so read it after + /// [`finish`](Self::finish). + pub fn extradata(&self) -> Vec { + match &self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => enc.audio_specific_config(), + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, .. } => enc.cookie(), + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, .. } => enc.opus_head(), + #[allow(unreachable_patterns)] + _ => Vec::new(), + } + } + + /// The codec, sample rate, channels and [`extradata`](Self::extradata): the description + /// [`TrackDecoder::new`](crate::TrackDecoder::new) takes, and what a muxer's track needs. + pub fn codec_params(&self) -> CodecParams { + CodecParams::new(self.codec).with_sample_rate(self.sample_rate).with_channels(self.channels()).with_extradata(self.extradata()) + } + + /// Decoded samples before the first input frame: the encoder's delay, which a container + /// skips (an MP4 edit list's media time, Matroska's CodecDelay, Opus's pre-skip, which + /// `OpusHead` already holds). 0 for ALAC. + /// + /// This is the codec's delay and does not depend on the input. An encoder that is given no + /// input returns no packets, and this still reports the delay. + pub fn priming(&self) -> u32 { + match &self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => enc.priming_samples(), + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, .. } => enc.delay(), + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, .. } => enc.priming_samples(), + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, .. } => u32::from(enc.pre_skip()), + #[allow(unreachable_patterns)] + _ => 0, + } + } + + /// Frames of input taken so far. + pub fn frames(&self) -> u64 { + self.frames + } + + /// Decoded samples after the last input frame, which a container trims (the end of an MP4 + /// edit, Matroska's DiscardPadding): the packets' durations add up to + /// [`priming`](Self::priming) + [`frames`](Self::frames) + this. Complete after + /// [`finish`](Self::finish). + /// + /// The sum holds once there is input. With none, [`finish`](Self::finish) returns no packets, + /// so the durations add up to 0 and this is 0, while `priming` is still the codec's delay: a + /// muxer writes an empty track and has no priming to skip. + pub fn padding(&self) -> u64 { + self.pts.saturating_sub(u64::from(self.priming()).saturating_add(self.frames)) + } + + /// Encodes the first `frames` frames of `block`, one slice per channel in WAV order + /// (`&[Vec]`, `&[&[f32]]`, …), and returns the packets completed. Samples are full scale + /// at ±1; NaN is taken as 0, and what a codec cannot carry above full scale is clipped. + /// + /// Internal codec calls process at most 4096 frames at a time, but this method collects their + /// packets in one returned vector whose memory use grows with `frames`. For streaming with + /// bounded memory, pass bounded input blocks and consume each returned batch before encoding + /// the next block, as [`FileEncoder`](crate::FileEncoder) does for coded formats. + /// + /// `block` must have one slice per channel, each at least `frames` long; otherwise nothing is + /// encoded and the error is [`AudioError::Encode`]. A call after [`finish`](Self::finish) is + /// an error too. When encoding itself fails, the packets of the block are lost, and every + /// later call fails rather than return a stream with a gap. + pub fn encode>(&mut self, block: &[C], frames: usize) -> Result> { + self.usable()?; + let channels = usize::from(self.channels()); + if block.len() != channels { + return Err(AudioError::Encode(format!("a block of {} channels for a {channels}-channel stream", block.len()))); + } + if let Some(short) = block.iter().map(|c| c.as_ref().len()).filter(|&n| n < frames).min() { + return Err(AudioError::Encode(format!("{frames} frames asked for, but a channel holds {short}"))); + } + let mut out = Vec::new(); + for at in (0..frames).step_by(CHUNK) { + let end = frames.min(at + CHUNK); + let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect(); + if let Err(e) = self.push(&planes, &mut out) { + self.failed = true; + return Err(e); + } + self.frames = self.frames.saturating_add((end - at) as u64); + } + Ok(out) + } + + /// Encodes what the encoder still holds, padded with silence to whole packets and as far as + /// a decoder needs to return every input frame after the priming, and returns the last + /// packets. Later calls of [`encode`](Self::encode) and `finish` are errors; the description + /// ([`extradata`](Self::extradata), [`padding`](Self::padding)) stays readable. + pub fn finish(&mut self) -> Result> { + self.usable()?; + self.finished = true; + let mut out = Vec::new(); + let done = self.drain(&mut out); + if done.is_err() { + self.failed = true; + } + done.map(|()| out) + } + + fn usable(&self) -> Result<()> { + if self.failed { + Err(AudioError::Encode("the packet encoder already failed; its stream is incomplete".into())) + } else if self.finished { + Err(AudioError::Encode("the packet encoder is finished".into())) + } else { + Ok(()) + } + } + + /// Appends a packet of `duration` decoded samples at the current position. + fn emit(pts: &mut u64, out: &mut Vec, data: Vec, duration: u32) { + out.push(EncodedPacket { data, pts: *pts, duration }); + *pts = pts.saturating_add(u64::from(duration)); + } + + /// Encodes `planes` (one slice per codec channel, equally long, at most [`CHUNK`] frames) + /// and appends the packets completed. + fn push(&mut self, planes: &[&[f32]], out: &mut Vec) -> Result<()> { + let pts = &mut self.pts; + match &mut self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => { + for data in enc.encode(planes) { + Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32); + } + } + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, quantizers, pending } => { + let frames = planes.first().map_or(0, |p| p.len()); + let mut at = 0; + while at < frames { + let filled = pending.first().map_or(0, Vec::len); + let end = frames.min(at + CHUNK.saturating_sub(filled).max(1)); + for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) { + dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s))); + } + at = end; + if pending.first().is_some_and(|p| p.len() >= CHUNK) { + alac_packet(enc, pending, pts, out)?; + } + } + } + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, bytes } => { + bytes.extend(enc.encode(planes)); + mp3_frames(enc, bytes, pts, out)?; + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, planes: clean } => { + for (dst, src) in clean.iter_mut().zip(planes) { + dst.clear(); + dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })); + } + let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect(); + for p in enc.push(&refs)? { + Self::emit(pts, out, p.data, p.samples); + } + } + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, pending, coded } => { + let frames = planes.first().map_or(0, |p| p.len()); + for i in 0..frames { + pending.extend(planes.iter().map(|p| p.get(i).copied().map_or(0.0, |s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }))); + if pending.len() == crate::opus::encoder::Encoder::FRAME_SIZE * planes.len() { + opus_packet(enc, pending, coded, pts, out)?; + } + } + } + } + Ok(()) + } + + /// Encodes what the codec still holds and appends the last packets. + fn drain(&mut self, out: &mut Vec) -> Result<()> { + let pts = &mut self.pts; + match &mut self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => { + for data in enc.flush() { + Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32); + } + } + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, pending, .. } => { + if pending.first().is_some_and(|p| !p.is_empty()) { + alac_packet(enc, pending, pts, out)?; + } + } + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, bytes } => { + bytes.extend(enc.flush()); + mp3_frames(enc, bytes, pts, out)?; + if !bytes.is_empty() { + return Err(AudioError::Encode(format!("the MP3 encoder ended with {} bytes that are not a whole frame", bytes.len()))); + } + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, .. } => { + for p in enc.finish()?.packets { + Self::emit(pts, out, p.data, p.samples); + } + } + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, pending, coded } => { + // Every input frame decodes after the pre-skip: as many packets as that takes. + let size = crate::opus::encoder::Encoder::FRAME_SIZE as u64; + let needed = if self.frames == 0 { 0 } else { (self.frames + u64::from(enc.pre_skip())).div_ceil(size) * size }; + let width = usize::from(enc.channels()); + while *coded < needed { + pending.resize(crate::opus::encoder::Encoder::FRAME_SIZE * width, 0.0); + opus_packet(enc, pending, coded, pts, out)?; + } + } + } + Ok(()) + } +} + +/// Encodes the pending samples as one ALAC packet and empties them. +#[cfg(feature = "alac-encode")] +fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec], pts: &mut u64, out: &mut Vec) -> Result<()> { + let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect(); + let frames = refs.first().map_or(0, |p| p.len()) as u32; + let data = enc.encode(&refs)?; + pending.iter_mut().for_each(Vec::clear); + PacketEncoder::emit(pts, out, data, frames); + Ok(()) +} + +/// Encodes one full frame of pending interleaved samples as an Opus packet and empties them. +#[cfg(feature = "opus-encode")] +fn opus_packet( + enc: &mut crate::opus::encoder::Encoder, + pending: &mut Vec, + coded: &mut u64, + pts: &mut u64, + out: &mut Vec, +) -> Result<()> { + let data = enc.encode_float(pending)?; + pending.clear(); + let size = crate::opus::encoder::Encoder::FRAME_SIZE as u32; + *coded += u64::from(size); + PacketEncoder::emit(pts, out, data, size); + Ok(()) +} + +/// Splits the whole MP3 frames off the front of `bytes`. The encoder writes constant-rate frames +/// back to back, so each one's length follows from its header's padding bit. +#[cfg(feature = "mp3-encode")] +fn mp3_frames(enc: &crate::mp3::Encoder, bytes: &mut Vec, pts: &mut u64, out: &mut Vec) -> Result<()> { + let samples = enc.frame_samples(); + let config = enc.config(); + // Bytes per frame: samples / 8 × bit rate / sample rate, plus the padding slot. + let base = (samples as u64 / 8 * u64::from(config.bitrate_kbps) * 1000 / u64::from(config.sample_rate.max(1))) as usize; + let mut at = 0; + while let Some(header) = bytes.get(at..at + 4) { + if header[0] != 0xFF || header[1] & 0xE0 != 0xE0 { + return Err(AudioError::Encode("the MP3 encoder returned bytes that are not a frame".into())); + } + let len = base + usize::from((header[2] >> 1) & 1); + let Some(frame) = bytes.get(at..at + len).filter(|_| len > 4) else { break }; + PacketEncoder::emit(pts, out, frame.to_vec(), samples as u32); + at += len; + } + bytes.drain(..at); + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/audio/src/write/coded/tests.rs b/crates/audio/src/packet/tests.rs similarity index 90% rename from crates/audio/src/write/coded/tests.rs rename to crates/audio/src/packet/tests.rs index cbdbd3375b..0056a6b162 100644 --- a/crates/audio/src/write/coded/tests.rs +++ b/crates/audio/src/packet/tests.rs @@ -1,6 +1,6 @@ use super::*; -use crate::Speaker; +use crate::{CodecId, Speaker}; fn map(mask: u32, order: Option<&[usize]>, layout: u32) -> Option> { channel_map(mask, order, &ChannelLayout::from_mask(layout)) @@ -165,3 +165,25 @@ fn the_listed_sample_rates_are_the_encoders() { assert_eq!(EncodeFormat::Aac.sample_rates().unwrap(), sorted(&crate::aac::SAMPLE_RATES)); assert_eq!(EncodeFormat::Mp3.sample_rates().unwrap(), sorted(&crate::mp3::SAMPLE_RATES)); } + +/// A codec whose feature is not built is refused, as `EncodeOptions::check` refuses its format. +#[test] +fn unbuilt_codecs_are_unsupported() { + let built = [ + (CodecId::Aac, cfg!(feature = "aac-encode")), + (CodecId::Alac, cfg!(feature = "alac-encode")), + (CodecId::Mp3, cfg!(feature = "mp3-encode")), + (CodecId::Ac3, cfg!(feature = "ac3-encode")), + (CodecId::Eac3, cfg!(feature = "eac3-encode")), + (CodecId::Opus, cfg!(feature = "opus-encode")), + ]; + let opts = EncodeOptions::default().with_bit_depth(crate::BitDepth::Int16); + for (codec, built) in built { + let made = PacketEncoder::new(codec, &opts, 48_000, 2); + if built { + assert!(made.is_ok(), "{codec:?}: {made:?}"); + } else { + assert!(matches!(&made, Err(AudioError::Unsupported(m)) if m.contains("feature")), "{codec:?}: {made:?}"); + } + } +} diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs new file mode 100644 index 0000000000..205741c529 --- /dev/null +++ b/crates/audio/src/s302m.rs @@ -0,0 +1,257 @@ +//! SMPTE ST 302M: AES3 audio carried in MPEG-2 transport stream packets (feature `s302m`): a +//! packet decoder ([`decode`]) and encoder ([`Encoder`]) for the payload of one PES packet. +//! +//! A packet is a 4-byte header and the audio. The header is the size in bytes of the audio (16 bits, +//! big-endian), then 16 bits: the channel count code (2 bits; 0 to 3 for 2, 4, 6 or 8 channels), the +//! identification of the first channel (8 bits), the sample size code (2 bits; 0, 1 and 2 for 16, 20 +//! and 24 bits) and 4 alignment bits. The audio is, for every frame, one 40-, 48- or 56-bit group +//! per channel pair, the pairs in order: each pair is two AES3 subframes, the left channel then the +//! right one, each of the sample (least significant bit first) and four flag bits (V, U, C and a +//! frame-start flag set on the left subframe of each channel pair in the first frame of every block of 192 frames). The +//! bits go out in transmission order, so a byte holds them most significant bit first. +//! +//! Samples are signed `i32` in the stream's own range (16, 20 or 24 bits, not scaled). The +//! decoder reads the flags and ignores them; the encoder writes the validity, user and channel +//! status bits as zero and sets the frame-start flag. +//! +//! Written from the standard's description of the packet and the AES3 subframe. ffmpeg is only run +//! as a black-box oracle in the tests. + +/// The most audio bytes one packet can hold (the size field is 16 bits). +pub const MAX_AUDIO_BYTES: usize = 0xFFFF; + +/// What went wrong decoding or encoding. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The packet is damaged, truncated, or uses a reserved code. + #[error("malformed SMPTE 302M packet: {0}")] + Malformed(&'static str), + /// The settings or samples given to the encoder cannot be written. + #[error("SMPTE 302M cannot encode: {0}")] + InvalidInput(&'static str), +} + +/// `Result` of this module. +pub type Result = std::result::Result; + +/// The header of a packet. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Header { + /// 2, 4, 6 or 8. + pub channels: usize, + /// The identification of the first channel (as the stream gives it). + pub channel_id: u8, + /// 16, 20 or 24. + pub bits: u32, + /// The alignment bits as written. + pub alignment: u8, + /// Bytes of audio after the header. + pub audio_bytes: usize, +} + +impl Header { + /// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` are unsupported or overflow. + pub fn frame_bytes(&self) -> usize { + let pair_bytes = match self.bits { + 16 => 5, + 20 => 6, + 24 => 7, + _ => return 0, + }; + (self.channels / 2).checked_mul(pair_bytes).unwrap_or(0) + } +} + +/// Parse the 4-byte header at the start of `packet`. +pub fn parse_header(packet: &[u8]) -> Result
{ + let [a, b, c, d, ..] = *packet else { return Err(Error::Malformed("shorter than the header")) }; + let size = usize::from(u16::from_be_bytes([a, b])); + let word = u16::from_be_bytes([c, d]); + let channels = 2 * (usize::from(word >> 14) + 1); + let bits = match (word >> 4) & 3 { + 0 => 16, + 1 => 20, + 2 => 24, + _ => return Err(Error::Malformed("reserved sample size code")), + }; + Ok(Header { channels, channel_id: ((word >> 6) & 0xFF) as u8, bits, alignment: (word & 0xF) as u8, audio_bytes: size }) +} + +/// One decoded packet. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Decoded { + /// The packet header. + pub header: Header, + /// Interleaved samples, `header.channels` per frame. + pub samples: Vec, +} + +/// Bit `i` of a byte string in transmission order (the first bit sent is the least significant bit of the sample, held in the most significant bit of the byte). +fn bit(bytes: &[u8], i: usize) -> u32 { + bytes.get(i / 8).map_or(0, |b| u32::from((b >> (7 - i % 8)) & 1)) +} + +/// Decode the payload of one PES packet. +pub fn decode(packet: &[u8]) -> Result { + let header = parse_header(packet)?; + let audio = packet.get(4..).unwrap_or(&[]); + if audio.len() < header.audio_bytes { + return Err(Error::Malformed("the audio is shorter than the header says")); + } + let audio = audio.get(..header.audio_bytes).unwrap_or(&[]); + let frame_bytes = header.frame_bytes(); + if frame_bytes == 0 || audio.len() % frame_bytes != 0 { + return Err(Error::Malformed("the audio is not a whole number of frames")); + } + let n = header.bits as usize; + let mut samples = Vec::with_capacity(audio.len() / (n + 4) * 8 / 2); + for frame in audio.chunks_exact(frame_bytes) { + for pos in (0..header.channels).map(|c| c * (n + 4)) { + let mut v = 0u32; + for k in 0..n { + v |= bit(frame, pos + k) << k; + } + // sign-extend the n-bit sample + let shift = 32 - n as u32; + samples.push(((v << shift) as i32) >> shift); + } + } + Ok(Decoded { header, samples }) +} + +/// A packet encoder. It counts frames so that the frame-start flag falls on the first frame of +/// every block of 192. +#[derive(Debug, Clone)] +pub struct Encoder { + channels: usize, + bits: u32, + channel_id: u8, + frames: u64, +} + +impl Encoder { + /// An encoder for `channels` (2, 4, 6 or 8) channels of `bits` (16, 20 or 24) bits. + pub fn new(channels: usize, bits: u32) -> Result { + if !matches!(channels, 2 | 4 | 6 | 8) { + return Err(Error::InvalidInput("SMPTE 302M carries 2, 4, 6 or 8 channels")); + } + if !matches!(bits, 16 | 20 | 24) { + return Err(Error::InvalidInput("SMPTE 302M samples have 16, 20 or 24 bits")); + } + Ok(Encoder { channels, bits, channel_id: 0, frames: 0 }) + } + + /// Set the identification of the first channel written in the header (0 by default). + pub fn channel_id(mut self, id: u8) -> Encoder { + self.channel_id = id; + self + } + + /// The most frames one packet can hold. + pub fn max_frames(&self) -> usize { + MAX_AUDIO_BYTES / (self.channels / 2 * ((self.bits as usize + 4) * 2 / 8)) + } + + /// Encode interleaved samples (a whole number of frames, at most [`Encoder::max_frames`], each + /// within the sample size) as one packet payload. + pub fn encode(&mut self, samples: &[i32]) -> Result> { + if samples.is_empty() || !samples.len().is_multiple_of(self.channels) { + return Err(Error::InvalidInput("the samples are not a whole number of frames")); + } + let frames = samples.len() / self.channels; + if frames > self.max_frames() { + return Err(Error::InvalidInput("too many frames for one packet")); + } + let n = self.bits as usize; + let limit = 1i64 << (n - 1); + if samples.iter().any(|&s| i64::from(s) < -limit || i64::from(s) >= limit) { + return Err(Error::InvalidInput("a sample is outside the sample size")); + } + let frame_bytes = self.channels / 2 * ((n + 4) * 2 / 8); + let audio_bytes = frames * frame_bytes; + let code = match self.bits { + 16 => 0u16, + 20 => 1, + _ => 2, + }; + let word = (((self.channels / 2 - 1) as u16) << 14) | (u16::from(self.channel_id) << 6) | (code << 4); + let mut out = Vec::with_capacity(4 + audio_bytes); + out.extend((audio_bytes as u16).to_be_bytes()); + out.extend(word.to_be_bytes()); + out.resize(4 + audio_bytes, 0); + for (f, frame) in samples.chunks_exact(self.channels).enumerate() { + let start = (self.frames + f as u64).is_multiple_of(192); + let base = 4 + f * frame_bytes; + for (c, &s) in frame.iter().enumerate() { + let pos = c * (n + 4); + let v = (s as u32) & ((1u32 << n) - 1); + for k in 0..n { + set_bit(&mut out, base, pos + k, (v >> k) & 1); + } + // flags V, U, C, then the frame-start flag on the left subframe of each pair + if c % 2 == 0 && start { + set_bit(&mut out, base, pos + n + 3, 1); + } + } + } + self.frames += frames as u64; + Ok(out) + } +} + +fn set_bit(out: &mut [u8], base: usize, i: usize, v: u32) { + if v != 0 + && let Some(b) = out.get_mut(base + i / 8) + { + *b |= 0x80 >> (i % 8); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_packet() { + // stereo 16-bit, one frame: L = 0x1234, R = 0xFEFF, the first frame of a block + let packet = [0x00, 0x05, 0x00, 0x00, 0x2c, 0x48, 0x1f, 0xf7, 0xf0]; + let d = decode(&packet).unwrap(); + assert_eq!(d.samples, vec![0x1234, -257]); + assert_eq!((d.header.channels, d.header.bits), (2, 16)); + let mut e = Encoder::new(2, 16).unwrap(); + assert_eq!(e.encode(&[0x1234, -257]).unwrap(), packet); + } + + #[test] + fn settings_and_packets_are_checked() { + assert!(Encoder::new(1, 16).is_err()); + assert!(Encoder::new(2, 18).is_err()); + let mut e = Encoder::new(2, 16).unwrap(); + assert!(e.encode(&[]).is_err()); + assert!(e.encode(&[1]).is_err()); + assert!(e.encode(&[40_000, 0]).is_err()); + assert!(decode(&[0, 1]).is_err()); + assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err()); + assert!(decode(&[0, 5, 0, 0, 0, 0]).is_err()); + assert!(decode(&[0, 4, 0, 0, 0, 0, 0, 0]).is_err()); + } + + #[test] + fn header_frame_bytes_overflow_does_not_panic() { + let h = Header { channels: usize::MAX, channel_id: 0, bits: 24, alignment: 0, audio_bytes: 0 }; + assert_eq!(h.frame_bytes(), 0); + } + + #[test] + fn header_frame_bytes_rejects_unsupported_depth() { + let h_max = Header { channels: 2, channel_id: 0, bits: u32::MAX, alignment: 0, audio_bytes: 0 }; + assert_eq!(h_max.frame_bytes(), 0); + + let h_unsupported = Header { channels: 2, channel_id: 0, bits: 18, alignment: 0, audio_bytes: 0 }; + assert_eq!(h_unsupported.frame_bytes(), 0); + + let h_zero = Header { channels: 2, channel_id: 0, bits: 0, alignment: 0, audio_bytes: 0 }; + assert_eq!(h_zero.frame_bytes(), 0); + } +} diff --git a/crates/audio/src/vorbis/mod.rs b/crates/audio/src/vorbis/mod.rs index 15b81bb26d..bb2dbec062 100644 --- a/crates/audio/src/vorbis/mod.rs +++ b/crates/audio/src/vorbis/mod.rs @@ -1,7 +1,83 @@ //! Vorbis I: the pure-Rust [`decoder`] (feature `vorbis-decode`) and [`encoder`] (feature //! `vorbis-encode`). `craft_audio::decode` still reads Vorbis files through symphonia. +//! +//! Both work in Vorbis channel order (Vorbis I §4.3.9). [`wav_order`] maps decoded channels to the +//! WAV order the rest of craft-audio uses, and [`layout`] gives the speakers they then feed. + +use crate::ChannelLayout; #[cfg(feature = "vorbis-decode")] pub mod decoder; #[cfg(feature = "vorbis-encode")] pub mod encoder; + +/// Channel order for Vorbis surround (Vorbis I §4.3.9: L C R for three, L C R Ls Rs for five, +/// L C R Ls Rs LFE for 5.1, L C R Ls Rs Cb LFE for 6.1, L C R Ls Rs Lb Rb LFE for 7.1): output +/// channel → decoded channel, giving the WAV order (L R C LFE back… side…) of [`layout`]. `None` for +/// 1, 2 and 4 channels, which are already in WAV order, and for more than 8, whose order the +/// specification leaves to the application. +/// +/// ``` +/// let vorbis: Vec> = (0..6).map(|c| vec![c as f32]).collect(); // L C R Ls Rs LFE +/// let order = craft_audio::vorbis::wav_order(6).unwrap(); +/// let wav: Vec> = order.iter().map(|&c| vorbis[c].clone()).collect(); // L R C LFE Ls Rs +/// assert_eq!(wav[3], vec![5.0]); +/// ``` +pub fn wav_order(channels: usize) -> Option<&'static [usize]> { + Some(match channels { + 3 => &[0, 2, 1], + 5 => &[0, 2, 1, 3, 4], + 6 => &[0, 2, 1, 5, 3, 4], + 7 => &[0, 2, 1, 6, 5, 3, 4], + 8 => &[0, 2, 1, 7, 5, 6, 3, 4], + _ => return None, + }) +} + +/// The speakers of a Vorbis stream with `channels` channels, in WAV order (after [`wav_order`]): +/// mono, stereo, L R C, quad, 5.0, 5.1, 6.1 with a back center and side surrounds, and 7.1 with +/// backs and sides. Other counts are unordered. For 7 channels this differs from +/// [`ChannelLayout::default_for`], which puts the surrounds at the back. +pub fn layout(channels: u16) -> ChannelLayout { + match channels { + 1 => ChannelLayout::MONO, + 2 => ChannelLayout::STEREO, + 3 => ChannelLayout::SURROUND_3_0, + 4 => ChannelLayout::QUAD, + 5 => ChannelLayout::SURROUND_5_0, + 6 => ChannelLayout::SURROUND_5_1, + 7 => ChannelLayout::SURROUND_6_1, + 8 => ChannelLayout::SURROUND_7_1, + _ => ChannelLayout::unordered(channels), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Speaker::{self, *}; + + /// Vorbis I §4.3.9, one row per channel count, in the order a stream carries the channels. + const VORBIS_ORDER: [&[Speaker]; 8] = [ + &[FrontCenter], + &[FrontLeft, FrontRight], + &[FrontLeft, FrontCenter, FrontRight], + &[FrontLeft, FrontRight, BackLeft, BackRight], + &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight], + &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight, Lfe], + &[FrontLeft, FrontCenter, FrontRight, SideLeft, SideRight, BackCenter, Lfe], + &[FrontLeft, FrontCenter, FrontRight, SideLeft, SideRight, BackLeft, BackRight, Lfe], + ]; + + #[test] + fn reordered_channels_feed_the_layout_speakers() { + for (i, stream) in VORBIS_ORDER.iter().enumerate() { + let channels = i + 1; + let wav: Vec = match wav_order(channels) { + Some(order) => order.iter().map(|&c| stream[c]).collect(), + None => stream.to_vec(), + }; + assert_eq!(wav, layout(channels as u16).speakers(), "{channels} channels"); + } + } +} diff --git a/crates/audio/src/write/coded.rs b/crates/audio/src/write/coded.rs index 0d0dd626f4..040d590d0d 100644 --- a/crates/audio/src/write/coded.rs +++ b/crates/audio/src/write/coded.rs @@ -1,7 +1,7 @@ //! The coded formats of [`FileEncoder`](crate::FileEncoder): AAC-LC and ALAC in M4A (through -//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] maps the caller's -//! WAV-order channels onto the encoder's order, drives the packet encoder, and for M4A records the -//! encoder's priming and the exact length in the edit list. +//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] drives a +//! [`PacketEncoder`], which maps the caller's WAV-order channels onto the codec's order, and for +//! M4A records the encoder's priming and the exact length in the edit list. // Each codec is its own feature, and so are the two sinks: with only some of them built, the // other halves of the shared code are unused. @@ -11,271 +11,10 @@ )] use super::failed_write_error; -use super::pcm::validate_layout; -use crate::layout::channel_map; -use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, RateControl, Result}; +use crate::packet::{EncodedPacket, PacketEncoder}; +use crate::{AudioBuffer, AudioError, CodecId, EncodeFormat, EncodeOptions, Result}; use std::io::{Cursor, Seek, Write}; -/// Frames handed to the encoder at a time, so its buffers and the packets waiting to be written -/// stay small however long a block is. Also the frames of an ALAC packet. -const CHUNK: usize = 4096; - -/// Bits per second per channel when no rate is asked for: AAC. -const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; -/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per -/// full-bandwidth channel). -const DEFAULT_KBPS_PER_CHANNEL: u32 = 96; - -/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`. -fn labels(mask: u32) -> String { - ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::>().join(" ") -} - -/// [`channel_map`] for a format with one layout per channel count ([`EncodeFormat::layout_masks`]), -/// or why the audio does not fit. -fn fixed_map(format: EncodeFormat, name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result> { - let Some(&mask) = format.layout_masks(layout.channels()).first() else { - return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels()))); - }; - channel_map(mask, order, layout).ok_or_else(|| { - AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout))) - }) -} - -/// The speakers of the caller's layout, for an error message. -fn given(layout: &ChannelLayout) -> String { - layout.mask().map_or_else(|| "without speaker assignment".into(), labels) -} - -/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for 8 channels -/// configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc. -#[cfg(feature = "aac-encode")] -fn aac_order(channels: usize) -> Option<&'static [usize]> { - if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) } -} - -/// The lowest AAC bit rate the writer uses, per channel: 6 kbit/s, and a quarter of the sample -/// rate (256 bits a frame). The encoder accepts less, and from about half of this down codes -/// silence; a file of silence is no answer to a low bit rate (or to kbit/s given as bit/s). -#[cfg(feature = "aac-encode")] -fn aac_floor_per_channel(sample_rate: u32) -> u32 { - (sample_rate / 4).max(6000) -} - -/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a -/// quality of 0–1 spans the encoder's VBR range. -#[cfg(feature = "aac-encode")] -fn aac_mode(rate: Option, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode { - use crate::aac::BitrateMode; - let (lo, hi) = crate::aac::cbr_range(sample_rate, channels); - let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo)); - // An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone. - let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps }; - match rate { - None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))), - Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)), - // NaN stays NaN, which the encoder refuses. - Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)), - } -} - -/// The bit rate in kbit/s for a codec with constant bit rates only. -fn constant_kbps(name: &str, rate: Option, default: u32) -> Result { - match rate { - None => Ok(default), - Some(RateControl::Bitrate(bps)) => Ok(bps / 1000), - Some(RateControl::Quality(_)) => { - Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality"))) - } - } -} - -/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding -/// mode whose speakers the layout names, at the nearest bit rate the stream can carry. -#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] -fn ac3_config( - codec: crate::ac3::encoder::Codec, - sample_rate: u32, - layout: &ChannelLayout, - rate: Option, -) -> Result<(crate::ac3::encoder::Config, Vec)> { - use crate::ac3::encoder::{Codec, CodingMode, Config}; - use CodingMode::*; - let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" }; - let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; - let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| { - // 7.1 is an E-AC-3 programme with an LFE; the encoder has no other. - if mode == Surround71 && (codec != Codec::Eac3 || !lfe) { - return None; - } - let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe }; - let map = channel_map(config.channel_layout().mask()?, None, layout)?; - Some((config, map)) - }); - let Some((mut config, map)) = found else { - return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout)))); - }; - let full = config.mode.channels() as u32; - let want = constant_kbps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full)?; - // What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of - // the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold. - let least = if config.mode == Surround71 { 384 } else { 32 * full }; - config.bitrate_kbps = match codec { - Codec::Ac3 => { - let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least); - crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor) - } - Codec::Eac3 => { - let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 }; - want.clamp(least, most.max(least)) - } - }; - Ok((config, map)) -} - -/// One encoded packet and the frames it decodes to. -struct Packet { - data: Vec, - frames: u32, -} - -/// A packet encoder of any of the codecs, taking planar `f32` in its own channel order. -enum Codec { - #[cfg(feature = "aac-encode")] - Aac(Box), - #[cfg(feature = "alac-encode")] - Alac { - enc: Box, - quantizers: Vec, - /// Quantized samples of the packet being filled, per channel. - pending: Vec>, - }, - #[cfg(feature = "mp3-encode")] - Mp3(Box), - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Ac3 { - enc: Box, - /// The block with every sample finite and within ±1, as the encoder requires. - planes: Vec>, - }, -} - -impl Codec { - /// Encodes `planes` (one slice per encoder channel, equally long, at most [`CHUNK`] frames) - /// and appends the packets completed. - fn push(&mut self, planes: &[&[f32]], out: &mut Vec) -> Result<()> { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => out.extend(enc.encode(planes).into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, quantizers, pending } => { - let frames = planes.first().map_or(0, |p| p.len()); - let mut at = 0; - while at < frames { - let filled = pending.first().map_or(0, Vec::len); - let end = frames.min(at + CHUNK.saturating_sub(filled).max(1)); - for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) { - dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s))); - } - at = end; - if pending.first().is_some_and(|p| p.len() >= CHUNK) { - alac_packet(enc, pending, out)?; - } - } - } - #[cfg(feature = "mp3-encode")] - Codec::Mp3(enc) => { - let data = enc.encode(planes); - if !data.is_empty() { - out.push(Packet { data, frames: 0 }); - } - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Codec::Ac3 { enc, planes: clean } => { - for (dst, src) in clean.iter_mut().zip(planes) { - dst.clear(); - dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })); - } - let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect(); - out.extend(enc.push(&refs)?.into_iter().map(|p| Packet { data: p.data, frames: p.samples })); - } - } - Ok(()) - } - - /// Encodes what the encoder still holds and appends the last packets. - fn finish(&mut self, out: &mut Vec) -> Result<()> { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => out.extend(enc.flush().into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, pending, .. } => { - if pending.first().is_some_and(|p| !p.is_empty()) { - alac_packet(enc, pending, out)?; - } - } - #[cfg(feature = "mp3-encode")] - Codec::Mp3(enc) => { - let data = enc.flush(); - if !data.is_empty() { - out.push(Packet { data, frames: 0 }); - } - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Codec::Ac3 { enc, .. } => out.extend(enc.finish()?.packets.into_iter().map(|p| Packet { data: p.data, frames: p.samples })), - } - Ok(()) - } - - /// Decoded frames before the first frame of the audio. - fn priming(&self) -> u32 { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => enc.priming_samples(), - #[allow(unreachable_patterns)] - _ => 0, - } - } - - /// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` - /// frames in all): the configuration a decoder needs, with the average bit rate. - #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - fn sample_entry(&self, sample_rate: u32, channels: u32, bytes: u64, frames: u64) -> Option { - use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry}; - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => { - let mut entry = SampleEntry::aac(enc.audio_specific_config(), channels, sample_rate); - if let CodecConfig::Aac(config) = &mut entry.codec - && frames > 0 - { - let bps = u128::from(bytes) * 8 * u128::from(sample_rate) / u128::from(frames); - config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX); - } - Some(entry) - } - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, .. } => { - let bits = u16::from(enc.encoder_config().bit_depth); - Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.cookie() }, channels, f64::from(sample_rate), bits)) - } - #[allow(unreachable_patterns)] - _ => None, - } - } -} - -/// Encodes the pending samples as one ALAC packet and empties them. -#[cfg(feature = "alac-encode")] -fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec], out: &mut Vec) -> Result<()> { - let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect(); - let frames = refs.first().map_or(0, |p| p.len()) as u32; - let data = enc.encode(&refs)?; - pending.iter_mut().for_each(Vec::clear); - out.push(Packet { data, frames }); - Ok(()) -} - /// A muxer's error as this crate's: a failed write stays an I/O error. #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] fn mux_error(e: craft_media::isobmff::Error) -> AudioError { @@ -285,6 +24,31 @@ fn mux_error(e: craft_media::isobmff::Error) -> AudioError { } } +/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` frames in +/// all): the configuration a decoder needs, with the average bit rate. +#[cfg(any(feature = "aac-encode", feature = "alac-encode"))] +fn sample_entry(enc: &PacketEncoder, bytes: u64, frames: u64) -> Option { + use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry}; + let (rate, channels) = (enc.sample_rate(), u32::from(enc.channels())); + match enc.codec() { + CodecId::Aac => { + let mut entry = SampleEntry::aac(enc.extradata(), channels, rate); + if let CodecConfig::Aac(config) = &mut entry.codec + && frames > 0 + { + let bps = u128::from(bytes) * 8 * u128::from(rate) / u128::from(frames); + config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX); + } + Some(entry) + } + CodecId::Alac => { + let bits = u16::from(enc.bit_depth().unwrap_or(16)); + Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.extradata() }, channels, f64::from(rate), bits)) + } + _ => None, + } +} + /// An M4A file being written: one audio track whose samples are the packets. /// /// The last packet is held back until the length is known: its duration is cut to the audio's @@ -298,9 +62,8 @@ struct M4a { track: Option, entry: craft_media::isobmff::SampleEntry, sample_rate: u32, - channels: u32, priming: u32, - held: Option, + held: Option, /// Frames and bytes of the packets written, the held one not counted. frames: u64, bytes: u64, @@ -308,13 +71,14 @@ struct M4a { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] impl M4a { - fn new(out: W, codec: &Codec, sample_rate: u32, channels: u32) -> Result { + fn new(out: W, enc: &PacketEncoder) -> Result { use craft_media::isobmff::{Brand, Mp4Writer, WriterOptions}; - let entry = codec.sample_entry(sample_rate, channels, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?; + let entry = sample_entry(enc, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?; + let sample_rate = enc.sample_rate(); let mut options = WriterOptions::new(Brand::Mp4); options.movie_timescale = sample_rate; let mux = Mp4Writer::new(out, options).map_err(mux_error)?; - Ok(M4a { mux, track: None, entry, sample_rate, channels, priming: codec.priming(), held: None, frames: 0, bytes: 0 }) + Ok(M4a { mux, track: None, entry, sample_rate, priming: enc.priming(), held: None, frames: 0, bytes: 0 }) } fn track(&mut self, has_audio: bool) -> Result { @@ -333,7 +97,7 @@ impl M4a { Ok(track) } - fn sample(&mut self, packet: &Packet, duration: u32) -> Result<()> { + fn sample(&mut self, packet: &EncodedPacket, duration: u32) -> Result<()> { let track = self.track(true)?; let sample = craft_media::isobmff::WriteSample { data: &packet.data, duration, composition_offset: 0, is_sync: true }; self.mux.write_sample(track, sample).map_err(mux_error)?; @@ -342,22 +106,22 @@ impl M4a { Ok(()) } - fn write(&mut self, packet: Packet) -> Result<()> { + fn write(&mut self, packet: EncodedPacket) -> Result<()> { if let Some(held) = self.held.replace(packet) { - self.sample(&held, held.frames)?; + self.sample(&held, held.duration)?; } Ok(()) } - /// Writes the last packet, cut to the end of `audio_frames` frames of audio, and the `moov`. - fn finish(mut self, codec: &Codec, audio_frames: u64) -> Result { + /// Writes the last packet, cut to the end of the audio the encoder took, and the `moov`. + fn finish(mut self, enc: &PacketEncoder) -> Result { if let Some(held) = self.held.take() { - let rest = (u64::from(self.priming) + audio_frames).saturating_sub(self.frames); - self.sample(&held, rest.min(u64::from(held.frames)) as u32)?; + let rest = (u64::from(self.priming) + enc.frames()).saturating_sub(self.frames); + self.sample(&held, rest.min(u64::from(held.duration)) as u32)?; } let track = self.track(false)?; // The configuration is complete only now: the bit rate, and ALAC's largest packet. - if let Some(entry) = codec.sample_entry(self.sample_rate, self.channels, self.bytes, self.frames) { + if let Some(entry) = sample_entry(enc, self.bytes, self.frames) { self.mux.set_sample_entry(track, entry).map_err(mux_error)?; } self.mux.finish().map_err(mux_error) @@ -374,15 +138,8 @@ enum Sink { /// A file of one of the coded formats written block by block. pub(crate) struct Writer { - codec: Codec, + enc: PacketEncoder, sink: Sink, - /// For each encoder channel, the caller's channel that feeds it. - map: Vec, - /// The constant bit rate the encoder was set to, bits per second; `None` for ALAC and for - /// AAC at a constant quality. - bitrate: Option, - frames: u64, - packets: Vec, /// Set when a write has failed: the encoder and the sink no longer agree, so the writer /// refuses every later call. failed: bool, @@ -390,68 +147,23 @@ pub(crate) struct Writer { impl Writer { pub(crate) fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: usize) -> Result { - validate_layout(channels, sample_rate)?; - let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels as u16)); - let (codec, map, bitrate) = match opts.format { - #[cfg(feature = "aac-encode")] - EncodeFormat::Aac => { - let map = fixed_map(EncodeFormat::Aac, "AAC", aac_order(channels), &layout)?; - let mode = aac_mode(opts.rate_control, sample_rate, channels); - let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, channels, 0) }; - let bitrate = match mode { - crate::aac::BitrateMode::Cbr(bps) => Some(bps), - crate::aac::BitrateMode::Vbr(_) => None, - }; - (Codec::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, bitrate) - } - #[cfg(feature = "alac-encode")] - EncodeFormat::Alac => { - let count = u8::try_from(channels).unwrap_or(u8::MAX); - let map = fixed_map(EncodeFormat::Alac, "ALAC", crate::alac::alac_order(count), &layout)?; - let bits = match opts.bit_depth { - crate::BitDepth::Int16 => 16, - crate::BitDepth::Int24 => 24, - crate::BitDepth::Int32 => 32, - crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())), - }; - let enc = crate::alac::Encoder::new(crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32))?; - let quantizers = super::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, channels); - (Codec::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); channels] }, map, None) - } - #[cfg(feature = "mp3-encode")] - EncodeFormat::Mp3 => { - let map = fixed_map(EncodeFormat::Mp3, "MP3", None, &layout)?; - let want = constant_kbps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * channels as u32)?; - // A sample rate MP3 has not is the encoder's to refuse. - let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want); - let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, channels, kbps))?; - (Codec::Mp3(Box::new(enc)), map, Some(kbps.saturating_mul(1000))) - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - EncodeFormat::Ac3 | EncodeFormat::Eac3 => { - let codec = if opts.format == EncodeFormat::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 }; - let (config, map) = ac3_config(codec, sample_rate, &layout, opts.rate_control)?; - let enc = crate::ac3::encoder::Encoder::new(config)?; - (Codec::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); channels] }, map, Some(config.bitrate_kbps.saturating_mul(1000))) - } - #[allow(unreachable_patterns)] - f => return Err(AudioError::Unsupported(format!("writing {f:?}"))), - }; + let channels = u16::try_from(channels).map_err(|_| AudioError::Encode("too many channels".into()))?; + let enc = PacketEncoder::new(opts.format.codec(), opts, sample_rate, channels)?; let sink = match opts.format { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &codec, sample_rate, channels as u32)?)), + EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &enc)?)), _ => Sink::Raw(out), }; - Ok(Writer { codec, sink, map, bitrate, frames: 0, packets: Vec::new(), failed: false }) + Ok(Writer { enc, sink, failed: false }) } pub(crate) fn bitrate(&self) -> Option { - self.bitrate + self.enc.bitrate() } - /// Hands the packets waiting to the sink. - fn drain(&mut self) -> Result<()> { - for packet in self.packets.drain(..) { + /// Hands `packets` to the sink. + fn drain(&mut self, packets: Vec) -> Result<()> { + for packet in packets { match &mut self.sink { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] Sink::M4a(m4a) => m4a.write(packet)?, @@ -466,16 +178,16 @@ impl Writer { if self.failed { return Err(failed_write_error()); } - for at in (0..frames).step_by(CHUNK) { - let end = frames.min(at + CHUNK); - let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect(); - let written = self.codec.push(&planes, &mut self.packets).and_then(|()| self.drain()); + // A block at a time, so the packets waiting for the sink stay few however long it is. + for at in (0..frames).step_by(crate::packet::CHUNK) { + let end = frames.min(at + crate::packet::CHUNK); + let part: Vec<&[f32]> = block.iter().map(|c| c.as_ref().get(at..end).unwrap_or_default()).collect(); + let written = self.enc.encode(&part, end - at).and_then(|packets| self.drain(packets)); if let Err(e) = written { self.failed = true; return Err(e); } } - self.frames = self.frames.saturating_add(frames as u64); Ok(()) } @@ -483,11 +195,11 @@ impl Writer { if self.failed { return Err(failed_write_error()); } - self.codec.finish(&mut self.packets)?; - self.drain()?; + let last = self.enc.finish()?; + self.drain(last)?; match self.sink { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - Sink::M4a(m4a) => m4a.finish(&self.codec, self.frames), + Sink::M4a(m4a) => m4a.finish(&self.enc), Sink::Raw(mut out) => { out.flush()?; Ok(out) @@ -501,6 +213,3 @@ pub(crate) fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> w.write(&buf.channels, buf.frames())?; Ok(w.finish()?.into_inner()) } - -#[cfg(test)] -mod tests; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index bbb42601ec..18beab7872 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -8,7 +8,7 @@ mod aiff; mod coded; #[cfg(feature = "flac-encode")] pub(crate) mod flac; -mod pcm; +pub(crate) mod pcm; #[cfg(feature = "vorbis-encode")] mod vorbis; #[cfg(feature = "vorbis-encode")] diff --git a/crates/audio/tests/codecs/alac.rs b/crates/audio/tests/codecs/alac.rs index 2d52234e86..8038c3ceb9 100644 --- a/crates/audio/tests/codecs/alac.rs +++ b/crates/audio/tests/codecs/alac.rs @@ -153,3 +153,39 @@ fn ffmpeg_decodes_our_alac_exactly() { } } } + +/// Quiet and silent passages at 24 and 32 bits, which our encoder codes with fewer shifted-off +/// low bytes than Apple's reference (#1368), decode exactly in ffmpeg. The packets alternate +/// between silence, audio within 12 bits, audio at the narrower widths' edges and full scale, so +/// one stream changes its shift from packet to packet. +#[test] +fn ffmpeg_decodes_our_quiet_alac_exactly() { + let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return }; + for (channels, bits) in [(1, 24), (2, 24), (6, 24), (1, 32), (2, 32)] { + let full = input(channels, bits, 4 * 4096); + let wav: Vec> = full + .iter() + .map(|c| { + c.iter() + .enumerate() + .map(|(i, &x)| match i / 4096 { + 0 => 0, + 1 => x >> (bits - 12), + 2 => (x >> (bits - 15)) << (bits - 24), + _ => x, + }) + .collect() + }) + .collect(); + // ffmpeg does not decode escaped 32-bit stereo frames: keep the full-scale packet for 24 + let wav: Vec> = if bits == 32 { wav.iter().map(|c| c[..3 * 4096].to_vec()).collect() } else { wav }; + let m4a = our_m4a(&wav, bits, 4096); + let path = dir().join(format!("ours_quiet_{channels}ch_{bits}.m4a")); + std::fs::write(&path, &m4a).unwrap(); + let theirs = ffmpeg_decode(&ff, &path, channels, bits); + assert!(theirs == wav, "{channels} ch, {bits} bits: ffmpeg's decode differs from the input"); + if bits <= 24 { + assert!(our_decode(&m4a, bits) == wav, "{channels} ch, {bits} bits: our decode differs"); + } + } +} diff --git a/crates/audio/tests/codecs/main.rs b/crates/audio/tests/codecs/main.rs index 41829be5c9..4701426cd8 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -18,6 +18,7 @@ mod mp3_encoder_oracle; mod mpa_oracle; mod opus; mod opusenc; +mod packet_encoder; mod routing_oracle; mod track_decoder; #[cfg(feature = "vorbis-encode")] diff --git a/crates/audio/tests/codecs/opusenc/modes.rs b/crates/audio/tests/codecs/opusenc/modes.rs index a48ad2d444..723510a0f9 100644 --- a/crates/audio/tests/codecs/opusenc/modes.rs +++ b/crates/audio/tests/codecs/opusenc/modes.rs @@ -268,9 +268,7 @@ fn extreme_inputs_stay_decodable() { let (enc, packets) = encode(OpusEncoder::with_mode(c as u8, rate * c as u32, mode, bw).unwrap(), &planar); assert!(packets.iter().all(|p| p.len() >= 3 && p.len() <= 1276), "{name} {mode:?}: packet sizes"); let dec = decode(&enc.opus_head(), &packets); - let peak = dec.iter().flatten().fold(0f32, |m, v| m.max(v.abs())); - let snr = if name == "nan" { f64::NAN } else { snr_search(&planar[0], &dec[0], 2).0 }; - eprintln!("{name} {mode:?}/{bw:?} {c} ch: peak {peak:.2}, SNR {snr:.1} dB, {:.1} kb/s", bitrate(&packets) / 1000.0); + assert_eq!(dec.len(), c, "{name} {mode:?}/{bw:?} {c} ch: decoded channels"); assert!(dec.iter().all(|ch| ch.iter().all(|v| v.is_finite() && v.abs() <= 4.0)), "{name} {mode:?}/{bw:?} {c} ch: bad output"); } } diff --git a/crates/audio/tests/codecs/packet_encoder.rs b/crates/audio/tests/codecs/packet_encoder.rs new file mode 100644 index 0000000000..584255d152 --- /dev/null +++ b/crates/audio/tests/codecs/packet_encoder.rs @@ -0,0 +1,244 @@ +//! `PacketEncoder`: every codec round-trips through `TrackDecoder` from the description the +//! encoder gives, at the length that was encoded and with each channel on its speaker. + +use std::io::Cursor; + +use craft_audio::{ + AudioError, BitDepth, ChannelLayout, CodecId, EncodeFormat, EncodeOptions, EncodedPacket, FileEncoder, PacketEncoder, TrackDecoder, +}; + +/// `channels` channels of `frames` frames, each a tone of its own frequency low enough for an LFE. +fn tones(sample_rate: u32, channels: usize, frames: usize) -> Vec> { + (0..channels) + .map(|c| { + let step = (40.0 + 9.0 * c as f32) * std::f32::consts::TAU / sample_rate as f32; + (0..frames).map(|i| ((i as f32 * step).sin() * 0.4 * 32768.0).round() / 32768.0).collect() + }) + .collect() +} + +/// Normalised correlation of two signals over the samples both have. +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) { + let (x, y) = (f64::from(x), f64::from(y)); + ab += x * y; + aa += x * x; + bb += y * y; + } + ab / (aa * bb).sqrt().max(1e-30) +} + +/// Encodes `input` in uneven blocks and returns the packets. +fn encode(enc: &mut PacketEncoder, input: &[Vec]) -> Vec { + let frames = input[0].len(); + let mut packets = Vec::new(); + let mut at = 0; + for n in [1, 999, 4096, 10_000, 7, usize::MAX].into_iter().cycle() { + let n = n.min(frames - at); + let block: Vec<&[f32]> = input.iter().map(|c| &c[at..at + n]).collect(); + packets.extend(enc.encode(&block, n).unwrap()); + at += n; + if at == frames { + break; + } + } + packets.extend(enc.finish().unwrap()); + packets +} + +/// Encodes, checks the timing the packets carry, decodes them from the encoder's description, and +/// returns the decoded audio from the first input frame on, cut to the input's length, and the +/// layout the decoder reports. +fn decode_back(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec]) -> (PacketEncoder, Vec>, ChannelLayout) { + let frames = input[0].len(); + let mut enc = PacketEncoder::new(codec, opts, sample_rate, input.len() as u16).unwrap(); + let packets = encode(&mut enc, input); + assert_eq!(enc.frames(), frames as u64); + // The packets follow one another, and add up to the priming, the audio and the padding. + let mut pts = 0; + for p in &packets { + assert_eq!(p.pts, pts, "{codec:?}"); + pts += u64::from(p.duration); + } + assert_eq!(pts, u64::from(enc.priming()) + frames as u64 + enc.padding(), "{codec:?}"); + let last = packets.last().map_or(0, |p| u64::from(p.duration)); + assert!(enc.padding() < last, "{codec:?}: {} samples of padding after a packet of {last}", enc.padding()); + + let lookahead: Vec<&[u8]> = packets.iter().take(craft_audio::LOOKAHEAD_PACKETS).map(|p| p.data.as_slice()).collect(); + let mut dec = TrackDecoder::new(&enc.codec_params(), &lookahead).unwrap(); + assert_eq!((dec.codec(), dec.sample_rate()), (codec, sample_rate), "{codec:?}"); + let mut out = vec![Vec::new(); usize::from(dec.channels())]; + for p in &packets { + let block = dec.decode(&p.data).unwrap(); + assert_eq!(block.frames(), p.duration as usize, "{codec:?}: a packet's duration is what it decodes to"); + for (o, c) in out.iter_mut().zip(block.channels) { + o.extend(c); + } + } + let skip = enc.priming() as usize; + let out = out.into_iter().map(|c| c[skip..skip + frames].to_vec()).collect(); + (enc, out, dec.layout()) +} + +/// [`decode_back`] for a codec whose decoder returns every channel: on the speakers encoded. +fn round_trip(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec]) -> (PacketEncoder, Vec>) { + let (enc, out, layout) = decode_back(codec, opts, sample_rate, input); + assert_eq!(layout, enc.layout(), "{codec:?}"); + (enc, out) +} + +/// Each decoded channel is its input channel, in place: it matches that channel and no other. The +/// AC-3 encoders low-pass the LFE, which shifts its phase, so the match is by magnitude. +fn assert_in_place(codec: CodecId, input: &[Vec], output: &[Vec], least: f64) { + for (c, got) in output.iter().enumerate() { + let scores: Vec = input.iter().map(|want| correlation(want, got).abs()).collect(); + let least = if matches!(codec, CodecId::Ac3 | CodecId::Eac3) && c == 3 { 0.5 } else { least }; + assert!(scores[c] > least, "{codec:?} channel {c}: {scores:?}"); + for (other, &score) in scores.iter().enumerate().filter(|&(o, _)| o != c) { + assert!(score < scores[c] - 0.3, "{codec:?} channel {c} matches channel {other}: {scores:?}"); + } + } +} + +#[test] +fn aac_round_trips_in_place() { + let input = tones(48_000, 6, 30_001); + let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(384_000); + let (enc, out) = round_trip(CodecId::Aac, &opts, 48_000, &input); + assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (1024, ChannelLayout::SURROUND_5_1_SIDE, Some(384_000))); + assert_eq!(enc.extradata().len(), 2, "an AudioSpecificConfig for channel configuration 6"); + assert_in_place(CodecId::Aac, &input, &out, 0.95); +} + +/// 16-bit ALAC is lossless: the input comes back bit for bit. +#[test] +fn alac_round_trips_exactly() { + let input = tones(44_100, 6, 10_000); + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(ChannelLayout::SURROUND_5_1); + let (enc, out) = round_trip(CodecId::Alac, &opts, 44_100, &input); + assert_eq!((enc.priming(), enc.padding(), enc.bit_depth(), enc.layout()), (0, 0, Some(16), ChannelLayout::SURROUND_5_1)); + assert_eq!(out, input); +} + +#[test] +fn mp3_round_trips_in_place() { + for (rate, frame) in [(48_000, 1152), (44_100, 1152), (24_000, 576)] { + let input = tones(rate, 2, 20_000); + let opts = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(192_000); + let mut enc = PacketEncoder::new(CodecId::Mp3, &opts, rate, 2).unwrap(); + let packets = encode(&mut enc, &input); + assert!(packets.iter().all(|p| p.duration == frame && p.data[0] == 0xFF), "{rate} Hz"); + let (enc, out) = round_trip(CodecId::Mp3, &opts, rate, &input); + assert_eq!((enc.priming(), enc.extradata()), (1057, vec![])); + assert_in_place(CodecId::Mp3, &input, &out, 0.95); + } +} + +#[test] +fn ac3_round_trips_in_place() { + let input = tones(48_000, 6, 20_000); + let (enc, out) = round_trip(CodecId::Ac3, &EncodeOptions::new(EncodeFormat::Ac3), 48_000, &input); + assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (256, ChannelLayout::SURROUND_5_1_SIDE, Some(448_000))); + assert_in_place(CodecId::Ac3, &input, &out, 0.9); +} + +#[test] +fn eac3_round_trips_in_place() { + let input = tones(48_000, 6, 20_000); + let (enc, out) = round_trip(CodecId::Eac3, &EncodeOptions::new(EncodeFormat::Eac3), 48_000, &input); + assert_eq!((enc.priming(), enc.layout()), (256, ChannelLayout::SURROUND_5_1_SIDE)); + assert_in_place(CodecId::Eac3, &input, &out, 0.9); +} + +/// 7.1 E-AC-3 is encoded as 7.1; `TrackDecoder` plays its 5.1 independent substream (see the +/// README), at the same length. +#[test] +fn eac3_7_1_decodes_as_its_5_1_substream() { + let input = tones(48_000, 8, 20_000); + let opts = EncodeOptions::new(EncodeFormat::Eac3).with_layout(ChannelLayout::SURROUND_7_1); + let (enc, out, layout) = decode_back(CodecId::Eac3, &opts, 48_000, &input); + assert_eq!((enc.layout(), enc.channels(), layout), (ChannelLayout::SURROUND_7_1, 8, ChannelLayout::SURROUND_5_1_SIDE)); + assert!(out.iter().all(|c| c.len() == 20_000)); +} + +#[test] +fn opus_round_trips_in_place() { + for channels in [1, 2] { + let input = tones(48_000, channels, 20_000); + let opts = EncodeOptions::default().with_bitrate(128_000); + let (enc, out) = round_trip(CodecId::Opus, &opts, 48_000, &input); + let head = enc.extradata(); + assert_eq!((&head[..8], head[9], u32::from(u16::from_le_bytes([head[10], head[11]]))), (&b"OpusHead"[..], channels as u8, enc.priming())); + assert_in_place(CodecId::Opus, &input, &out, 0.9); + } +} + +/// The raw streams `FileEncoder` writes are the packets in a row. +#[test] +fn file_encoder_writes_the_packets() { + for (format, layout) in [(EncodeFormat::Mp3, ChannelLayout::STEREO), (EncodeFormat::Ac3, ChannelLayout::SURROUND_5_1)] { + let input = tones(48_000, usize::from(layout.channels()), 12_345); + let opts = EncodeOptions::new(format).with_layout(layout); + let mut file = FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, layout.channels()).unwrap(); + file.write(&input, 12_345).unwrap(); + let file = file.finish().unwrap().into_inner(); + let mut enc = PacketEncoder::new(format.codec(), &opts, 48_000, layout.channels()).unwrap(); + let packets: Vec = encode(&mut enc, &input).into_iter().flat_map(|p| p.data).collect(); + assert_eq!(file, packets, "{format:?}"); + } +} + +/// What a codec cannot take is refused, and as `EncodeOptions::check` refuses it for the format. +#[test] +fn unsupported_settings_are_refused() { + let unsupported = + |codec, opts: &EncodeOptions, rate, channels| matches!(PacketEncoder::new(codec, opts, rate, channels), Err(AudioError::Unsupported(_))); + let opts = EncodeOptions::default(); + assert!(unsupported(CodecId::Vorbis, &opts, 48_000, 2)); + assert!(unsupported(CodecId::Flac, &opts, 48_000, 2)); + assert!(unsupported(CodecId::Opus, &opts, 44_100, 2)); + assert!(unsupported(CodecId::Opus, &opts, 48_000, 3)); + assert!(unsupported(CodecId::Opus, &opts.clone().with_quality(0.5), 48_000, 2)); + for (codec, format, rate, channels) in [ + (CodecId::Mp3, EncodeFormat::Mp3, 96_000, 2), + (CodecId::Mp3, EncodeFormat::Mp3, 48_000, 0), + (CodecId::Mp3, EncodeFormat::Mp3, 48_000, 6), + (CodecId::Ac3, EncodeFormat::Ac3, 48_000, 8), + (CodecId::Aac, EncodeFormat::Aac, 44_000, 2), + ] { + let opts = EncodeOptions::new(format); + let (packets, file) = (PacketEncoder::new(codec, &opts, rate, channels).map(drop), opts.check(rate, channels)); + assert_eq!(format!("{packets:?}"), format!("{file:?}"), "{codec:?} {rate} {channels}"); + assert!(packets.is_err()); + } + assert!(unsupported(CodecId::Alac, &opts.clone().with_bit_depth(BitDepth::Float32), 48_000, 2)); + assert!(unsupported(CodecId::Ac3, &opts.clone().with_layout(ChannelLayout::unordered(2)), 48_000, 2)); + // A layout for another channel count is the caller's mistake. + assert!(matches!(PacketEncoder::new(CodecId::Aac, &opts.with_layout(ChannelLayout::STEREO), 48_000, 1), Err(AudioError::Encode(_)))); +} + +/// Blocks that do not fit, and calls after `finish`, are errors that leave the stream as it was. +#[test] +fn misuse_is_an_error() { + let mut enc = PacketEncoder::new(CodecId::Aac, &EncodeOptions::new(EncodeFormat::Aac), 48_000, 2).unwrap(); + let short = [vec![0.0f32; 10], vec![0.0; 5]]; + assert!(matches!(enc.encode(&short, 10), Err(AudioError::Encode(_)))); + assert!(matches!(enc.encode(&short[..1], 5), Err(AudioError::Encode(_)))); + assert_eq!(enc.frames(), 0); + assert!(enc.encode(&short, 5).unwrap().is_empty()); + assert_eq!(enc.finish().unwrap().len(), 2, "5 frames after 1024 of priming fit in two packets"); + assert!(matches!(enc.finish(), Err(AudioError::Encode(_)))); + assert!(matches!(enc.encode(&short, 5), Err(AudioError::Encode(_)))); + // An encoder given nothing returns nothing: no packets, no frames and no padding. `priming` + // is the codec's delay either way, so it equals that of an encoder that was given input. + for codec in [CodecId::Aac, CodecId::Alac, CodecId::Mp3, CodecId::Ac3, CodecId::Eac3, CodecId::Opus] { + let mut enc = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap(); + assert!(enc.finish().unwrap().is_empty(), "{codec:?}"); + assert_eq!((enc.frames(), enc.padding()), (0, 0), "{codec:?}"); + let mut fed = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap(); + fed.encode(&short, 5).unwrap(); + fed.finish().unwrap(); + assert_eq!(enc.priming(), fed.priming(), "{codec:?}"); + } +} diff --git a/crates/audio/tests/main.rs b/crates/audio/tests/main.rs index 5470dc5530..6e1461348b 100644 --- a/crates/audio/tests/main.rs +++ b/crates/audio/tests/main.rs @@ -36,6 +36,9 @@ mod mp2_encoder_oracle; #[cfg(feature = "qoa")] #[path = "qoa_oracle.rs"] mod qoa_oracle; +#[cfg(feature = "s302m")] +#[path = "s302m_oracle.rs"] +mod s302m_oracle; #[cfg(feature = "sbc")] #[path = "sbc_oracle.rs"] mod sbc_oracle; diff --git a/crates/audio/tests/s302m_oracle.rs b/crates/audio/tests/s302m_oracle.rs new file mode 100644 index 0000000000..1d1a0c60da --- /dev/null +++ b/crates/audio/tests/s302m_oracle.rs @@ -0,0 +1,240 @@ +//! SMPTE 302M (feature `s302m`) against ffmpeg (oracle; skipped when ffmpeg is absent, a failure +//! with `CRAFT_MEDIA_REQUIRE_ORACLES=1`): we decode the packets ffmpeg's encoder puts in a transport +//! stream to the samples ffmpeg decodes, our encoder writes the same bytes, and ffmpeg decodes +//! packets of ours (patched into a transport stream) to our samples. + +use craft_audio::s302m::{Encoder, decode, parse_header}; +use std::path::Path; +use std::process::Command; + +fn signal(channels: usize, frames: usize, seed: u32) -> Vec { + let mut x = seed | 1; + let mut out = Vec::with_capacity(frames * channels); + for i in 0..frames { + for c in 0..channels { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let tone = ((i as f64) * (0.03 + 0.011 * c as f64)).sin() * 0.6; + let noise = f64::from(x % 2000) / 2000.0 - 0.5; + out.push(((tone + 0.3 * noise) * f64::from(i32::MAX)) as i32); + } + } + out +} + +#[test] +fn round_trips_every_size_and_channel_count() { + for channels in [2usize, 4, 6, 8] { + for bits in [16u32, 20, 24] { + let max = 1i64 << (bits - 1); + let mut e = Encoder::new(channels, bits).expect("encoder"); + let frames = 500; + let samples: Vec = signal(channels, frames, 3).iter().map(|&v| (i64::from(v) * max / (1 << 31)) as i32).collect(); + let mut all = Vec::new(); + for chunk in samples.chunks(channels * 193) { + let p = e.encode(chunk).expect("encode"); + let d = decode(&p).expect("decode"); + assert_eq!((d.header.channels, d.header.bits), (channels, bits)); + all.extend(d.samples); + } + assert_eq!(all, samples, "{channels}ch {bits} bits"); + } + } + // the extremes + for bits in [16u32, 20, 24] { + let (lo, hi) = (-(1i32 << (bits - 1)), (1i32 << (bits - 1)) - 1); + let mut e = Encoder::new(2, bits).expect("encoder"); + assert_eq!(decode(&e.encode(&[lo, hi, hi, lo, 0, -1]).expect("encode")).expect("decode").samples, vec![lo, hi, hi, lo, 0, -1]); + assert!(e.encode(&[hi + 1, 0]).is_err()); + assert!(e.encode(&[lo - 1, 0]).is_err()); + } +} + +#[test] +fn the_packet_size_limit_and_headers_are_checked() { + let mut e = Encoder::new(2, 16).expect("encoder"); + let max = e.max_frames(); + assert!(e.encode(&vec![0; max * 2]).is_ok()); + assert!(e.encode(&vec![0; (max + 1) * 2]).is_err()); + let p = Encoder::new(8, 24).expect("encoder").channel_id(0x55).encode(&[0; 8]).expect("encode"); + let h = parse_header(&p).expect("header"); + assert_eq!((h.channels, h.channel_id, h.bits, h.audio_bytes), (8, 0x55, 24, 28)); + assert_eq!(h.frame_bytes(), 28); +} + +#[test] +fn damaged_packets_are_errors_never_panics() { + let mut e = Encoder::new(4, 24).expect("encoder"); + let p = e.encode(&signal(4, 40, 5).iter().map(|&v| v >> 8).collect::>()).expect("encode"); + for n in 0..p.len() { + let _ = decode(&p[..n]); + } + let mut x = 9u32; + for i in 0..p.len() { + let mut d = p.clone(); + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + d[i] ^= (x >> 8) as u8 | 1; + let _ = decode(&d); + } + assert!(decode(&[]).is_err()); + assert!(decode(&[0xFF, 0xFF, 0, 0, 1, 2, 3]).is_err()); + assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err(), "the reserved size code"); +} + +// ---- ffmpeg as the reference + +fn ffmpeg(ff: &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)); +} + +fn s(p: &Path) -> String { + p.to_str().expect("path").to_string() +} + +/// The elementary-stream bytes of every PES packet of PID 0x100 in a transport stream, each as +/// the list of (offset in the file, length) pieces it is spread over. +fn pes_pieces(ts: &[u8]) -> Vec> { + let mut out: Vec> = Vec::new(); + for (i, p) in ts.as_chunks::<188>().0.iter().enumerate() { + if p[0] != 0x47 || ((usize::from(p[1] & 0x1F) << 8) | usize::from(p[2])) != 0x100 { + continue; + } + let mut off = 4; + if p[3] & 0x20 != 0 { + off += 1 + usize::from(p[4]); + } + if p[3] & 0x10 == 0 || off >= 188 { + continue; + } + let mut start = off; + if p[1] & 0x40 != 0 { + // a new PES packet: skip its header (00 00 01 id, length, flags, flags, header length, header) + assert_eq!(&p[off..off + 3], &[0, 0, 1]); + start = off + 9 + usize::from(p[off + 8]); + out.push(Vec::new()); + } + if let Some(last) = out.last_mut() { + last.push((i * 188 + start, 188 - start)); + } + } + out +} + +fn gather(ts: &[u8], pieces: &[(usize, usize)]) -> Vec { + pieces.iter().flat_map(|&(o, n)| ts[o..o + n].iter().copied()).collect() +} + +fn pcm_bytes(samples: &[i32], wide: bool) -> Vec { + if wide { + samples.iter().flat_map(|v| v.to_le_bytes()).collect() + } else { + samples.iter().flat_map(|&v| ((v >> 16) as i16).to_le_bytes()).collect() + } +} + +fn decoded_by_ffmpeg(ff: &Path, ts: &Path, out: &Path, wide: bool) -> Vec { + ffmpeg(ff, &["-i", &s(ts), "-f", if wide { "s32le" } else { "s16le" }, "-acodec", if wide { "pcm_s32le" } else { "pcm_s16le" }, &s(out)]); + let bytes = std::fs::read(out).expect("read"); + if wide { + bytes.as_chunks::<4>().0.iter().map(|b| i32::from_le_bytes(*b)).collect() + } else { + bytes.as_chunks::<2>().0.iter().map(|b| i32::from(i16::from_le_bytes(*b))).collect() + } +} + +#[test] +fn we_decode_and_encode_what_ffmpeg_encodes_and_ffmpeg_decodes_ours() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("s302m"); + for (channels, bits) in [(2usize, 16u32), (2, 20), (2, 24), (4, 20), (4, 24), (6, 16), (6, 20), (8, 20), (8, 24)] { + let name = format!("{channels}ch{bits}"); + let frames = 6000; + let wide = bits > 16; + let pcm = signal(channels, frames, 17); + let raw = dir.join(format!("{name}.pcm")); + std::fs::write(&raw, pcm_bytes(&pcm, wide)).expect("write"); + let ts = dir.join(format!("{name}.ts")); + let ch_str = channels.to_string(); + let raw_str = s(&raw); + let ts_str = s(&ts); + let mut ff_args = vec![ + "-f", + if wide { "s32le" } else { "s16le" }, + "-ar", + "48000", + "-ac", + &ch_str, + "-i", + &raw_str, + "-af", + "asetnsamples=n=1024:p=0", + "-c:a", + "s302m", + "-strict", + "-2", + ]; + if bits == 20 { + ff_args.extend(["-bits_per_raw_sample", "20"]); + } + ff_args.extend(["-f", "mpegts", &ts_str]); + ffmpeg(&ff, &ff_args); + let bytes = std::fs::read(&ts).expect("read"); + let pieces = pes_pieces(&bytes); + assert!(pieces.len() >= 2, "{name}: {} packets", pieces.len()); + let theirs = decoded_by_ffmpeg(&ff, &ts, &dir.join(format!("{name}.out.pcm")), wide); + + let mut enc = Encoder::new(channels, bits).expect("encoder"); + let mut ours: Vec = Vec::new(); + let mut frames_seen = 0usize; + for pes in &pieces { + // the ES bytes of the packet: its own size field says how much of them is the packet + let es = gather(&bytes, pes); + let h = parse_header(&es).expect("header"); + let packet = &es[..4 + h.audio_bytes]; + let d = decode(packet).expect("decode"); + assert_eq!((d.header.channels, d.header.bits), (channels, bits), "{name}"); + // our encoder writes the same bytes ffmpeg's does + assert!(enc.encode(&d.samples).expect("encode") == packet, "{name}: our packet differs from ffmpeg's at frame {frames_seen}"); + frames_seen += d.samples.len() / channels; + // 20-bit and 24-bit samples are scaled to 32 bits by ffmpeg's decoder; 16-bit ones are not + ours.extend(d.samples.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) })); + } + let n = ours.len().min(theirs.len()); + assert!(n >= (frames - 1600) * channels, "{name}: {n} samples"); + assert!(ours[..n] == theirs[..n], "{name}: our decode differs from ffmpeg's"); + + // ffmpeg decodes our packets: patch them over the same-sized ones in the stream + let mine = signal(channels, frames, 23); + let mut patched = bytes.clone(); + let mut enc = Encoder::new(channels, bits).expect("encoder"); + let mut expect: Vec = Vec::new(); + for pes in &pieces { + let es = gather(&bytes, pes); + let h = parse_header(&es).expect("header"); + let n_frames = h.audio_bytes / h.frame_bytes(); + let at = expect.len(); + let src: Vec = mine[at..at + n_frames * channels].iter().map(|&v| v >> (32 - bits)).collect(); + let packet = enc.encode(&src).expect("encode"); + assert_eq!(packet.len(), 4 + h.audio_bytes); + expect.extend(src.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) })); + let mut k = 0; + for &(o, len) in pes { + let take = len.min(packet.len() - k); + patched[o..o + take].copy_from_slice(&packet[k..k + take]); + k += take; + } + assert!(k >= packet.len()); + } + let ours_ts = dir.join(format!("{name}.ours.ts")); + std::fs::write(&ours_ts, patched).expect("write"); + let theirs = decoded_by_ffmpeg(&ff, &ours_ts, &dir.join(format!("{name}.ours.pcm")), wide); + let n = expect.len().min(theirs.len()); + assert!(n >= (frames - 1600) * channels, "{name}: {n} samples"); + assert!(expect[..n] == theirs[..n], "{name}: ffmpeg decodes our packets differently"); + println!("{name}: {} PES packets, {n} samples identical both ways", pieces.len()); + } +} diff --git a/crates/behavior/src/dock/action.rs b/crates/behavior/src/dock/action.rs index 825e63292e..484b9f554f 100644 --- a/crates/behavior/src/dock/action.rs +++ b/crates/behavior/src/dock/action.rs @@ -340,6 +340,16 @@ pub enum Action

{ /// The destination. to: Target

, }, + /// Move one shown panel, without the rest of its group, to a recorded place, as reopening a closed panel + /// restores it: the split size, sibling subtree, group, column and accordion state of `location` come back + /// with it. Dock Panel returns a floating panel to the docked place it left this way. + #[non_exhaustive] + Restore { + /// The panel the action applies to. + panel: P, + /// Where the panel goes back. + location: Location

, + }, } impl

Location

{ @@ -489,6 +499,11 @@ impl

Action

{ pub fn move_panel(panel: P, to: Target

) -> Self { Self::MovePanel { panel, to } } + + /// Builds [`Action::Restore`]. + pub fn restore(panel: P, location: Location

) -> Self { + Self::Restore { panel, location } + } } impl

DockPlacement

{ diff --git a/crates/behavior/src/dock/apply.rs b/crates/behavior/src/dock/apply.rs index 0f0760a1b7..de4ccfc98a 100644 --- a/crates/behavior/src/dock/apply.rs +++ b/crates/behavior/src/dock/apply.rs @@ -78,6 +78,18 @@ impl Layout

{ return Err(DockError::NotAllowed); } } + Action::Restore { panel, location } => { + let policy = permissions(panel); + let allowed = policy.movable + && location + .anchor + .as_ref() + .is_none_or(|anchor| location.placement.allowed_by(permissions(anchor)) && (!floats(anchor) || policy.floatable)) + && (location.floating.is_none() || policy.floatable); + if !allowed { + return Err(DockError::NotAllowed); + } + } Action::MoveGroup { panel, to } | Action::MoveColumn { panel, to } | Action::MoveWindow { panel, to } => { let members = self.members(panel, unit_of(&action))?; if members.iter().any(|p| !permissions(p).movable) { diff --git a/crates/behavior/src/dock/inner.rs b/crates/behavior/src/dock/inner.rs index 93510d78a5..b213dd3177 100644 --- a/crates/behavior/src/dock/inner.rs +++ b/crates/behavior/src/dock/inner.rs @@ -145,6 +145,10 @@ impl Layout

{ self.insert_moving(Moving::taken(Group::new(vec![entry.panel], 0), source), to, canvas) } }, + Action::Restore { panel, location } => { + self.take(&panel).ok_or(DockError::MissingPanel)?; + self.restore(panel, &location) + } Action::CloseGroup { ref panel } | Action::CloseWindow { ref panel } => self.take_unit(panel, unit_of(&action)).map(|_| ()), Action::CloseOthers { panel } => { for other in self.members(&panel, Unit::Group)? { diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 14a752fe9e..442c65f8b0 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -41,8 +41,8 @@ pub struct Workspace

{ /// goes back. #[serde(default)] hidden: Vec<(P, Location

)>, - /// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the - /// workspace. + /// Floating panels, and closed panels that were floating, with the docked location each one left, so Dock Panel + /// can return it. A closed panel's record lives as long as its `hidden` record. Saved with the workspace. #[serde(default, skip_serializing_if = "Vec::is_empty")] floated: Vec<(P, Location

)>, /// Counts the replacements of this live workspace. Not saved, and not part of equality. @@ -105,7 +105,7 @@ impl

Workspace

{ &self.hidden } - /// The floating panels with the docked location each one left. + /// The floating panels, and the closed panels that were floating, with the docked location each one left. pub fn floated(&self) -> &[(P, Location

)] { &self.floated } @@ -409,11 +409,12 @@ impl Workspace

{ } } - /// Update the floated records after an action that turned `before` into the current layout: drop the records of - /// panels that no longer float, and record the docked place of each panel that floats now and did not before. + /// Update the floated records after an action that turned `before` into the current layout: drop the stale + /// records ([`Self::drop_stale_floated`]), and record the docked place of each panel that floats now and did not + /// before. fn track_floated(&mut self, before: &Layout

) { + self.drop_stale_floated(); let layout = &self.layout; - self.floated.retain(|(p, _)| floats(layout, p)); let fresh: Vec<(P, Location

)> = layout .panels() .into_iter() @@ -423,6 +424,13 @@ impl Workspace

{ self.floated.extend(fresh); } + /// Drop the floated records of panels that neither float nor are hidden: a panel that closed while floating keeps + /// its record as long as its hidden record, so it docks back to its place after it reopens floating. + fn drop_stale_floated(&mut self) { + let (layout, hidden) = (&self.layout, &self.hidden); + self.floated.retain(|(p, _)| floats(layout, p) || hidden.iter().any(|(q, _)| q == p)); + } + /// Restore `panel` where the chain of hidden anchors from its location ends, else at the /// nearest location before that end that restores. The hidden panels it passed then anchor /// on the panel before them in the chain, on the recorded side, so reopening them joins it @@ -492,7 +500,6 @@ impl Workspace

{ self.layout.take(panel); } self.hidden.extend(locations); - self.floated.retain(|(p, _)| registered(p)); let known: HashSet

= self.layout.panels().into_iter().chain(self.hidden.iter().map(|(p, _)| p)).cloned().collect(); let mut missing: Vec<(P, Location

)> = Vec::new(); for panel in default.layout.panels() { @@ -536,6 +543,7 @@ impl Workspace

{ !drop }); self.hidden.truncate(MAX_PANELS); + self.drop_stale_floated(); } } diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index 1d25354fdc..ba1ff28419 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -224,9 +224,10 @@ fn tabs_closed_together_reopen_together_and_a_tab_closed_alone_stays_closed() { assert_eq!(group_members(workspace.layout(), 2), [2, 3], "it reopens beside 2"); } -/// A panel that floats keeps its docked place until it docks or closes; floating again from the float keeps the first. +/// A panel that floats keeps its docked place until it docks; floating again from the float keeps the first, and a +/// float that closes keeps it while it is closed and after it reopens floating. #[test] -fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { +fn a_floated_panel_keeps_where_it_was_docked_until_it_docks() { let mut workspace = Workspace::new(docked()); let docked_at = workspace.layout().location(&2).unwrap(); workspace.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); @@ -235,10 +236,15 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { assert_eq!(workspace.floated(), [(2, docked_at)], "floating again from the float keeps the first record"); workspace.apply(Action::move_beside(2, 11, DockPlacement::tab(None)), false, allow).unwrap(); assert!(workspace.floated().is_empty(), "docking drops the record"); + let docked_at = workspace.layout().location(&3).unwrap(); workspace.apply(Action::float(3, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); - assert_eq!(workspace.floated().len(), 1); workspace.apply(Action::close(3), false, allow).unwrap(); - assert!(workspace.floated().is_empty(), "closing drops the record"); + assert_eq!(workspace.floated(), [(3, docked_at.clone())], "closing keeps the record"); + workspace.apply(Action::open(3, None), false, allow).unwrap(); + assert!(floats(workspace.layout(), 3), "it reopens floating"); + assert_eq!(workspace.floated(), [(3, docked_at.clone())], "reopening keeps the record"); + workspace.apply(Action::restore(3, docked_at), false, allow).unwrap(); + assert!(!floats(workspace.layout(), 3) && workspace.floated().is_empty(), "docking back drops the record"); } /// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6]. diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index 4a4e27520f..7259d7212d 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-captions" -description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML/IMSC1/DFXP readers and writers with exact time, and CEA-608/708 coding" +description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL, ASS, TTML/IMSC1/DFXP and the legacy text formats (MicroDVD, MPL2, SubViewer, VPlayer, SAMI) readers and writers with exact time, and CEA-608/708 coding" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/captions/README.md b/crates/captions/README.md index b2f6a195f0..4568526750 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -60,6 +60,11 @@ lists at most 20 characters per stream. | 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. | +| MicroDVD `.sub` | yes | yes | `{first}{last}text` with frame numbers; the `{1}{1}fps` line or 23.976 fps. `\|` breaks a line; `{y:i,b,u}` and `{c:$BBGGRR}` style a line (capital `Y` / `C`: the rest of the cue too); other controls are dropped. Writing always names the rate (`WriteOptions::rate`, 23.976 by default) and styles only a line that ``, `` or `` wraps whole. | +| MPL2 `.mpl` | yes | yes | `[start][end]text` in tenths of a second; `\|` breaks a line, a leading `/` makes it italic. | +| SubViewer 2 `.sbv` (also `.sub`) | yes | yes | `start,end` in hundredths of a second after the `[INFORMATION]` header; `[br]` breaks a line. Text only; no styles. | +| VPlayer `.vpl` (also `.txt`) | yes | yes | `HH:MM:SS[.cc]=text` (`:` or a space also separate); only start times, a caption lasts to the next line (empty text clears), four seconds for the last. Text only. | +| SAMI `.smi` | yes | yes | `` blocks, ` ` clears; `
`, ``, ``, ``, `` kept; first language class only. | 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/lib.rs b/crates/captions/src/lib.rs index 612aa6f137..e83b868ce2 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), [ASS/SSA](ass) (`.ass`, `.ssa`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a +//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`), the legacy text formats [MicroDVD](microdvd) (`.sub`), [MPL2](mpl2) (`.mpl`), [SubViewer 2](subviewer) (`.sub`), [VPlayer](vplayer) (`.vpl`) and [SAMI](sami) (`.smi`) 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, `` @@ -36,17 +36,22 @@ pub mod ass; pub mod cea608; pub mod jacosub; pub mod mcc; +pub mod microdvd; #[cfg(feature = "mov-text")] pub mod mov_text; +pub mod mpl2; pub mod pjs; pub mod realtext; +pub mod sami; pub mod scc; pub mod srt; pub mod stl; +pub mod subviewer; mod text; /// Exact time: `craft-timeline`'s ticks, frame rates and timecode fields. pub use craft_timeline::time; pub mod ttml; +pub mod vplayer; pub mod vtt; pub use text::{decode_entities, entity_at, plain_text}; @@ -77,6 +82,16 @@ pub enum Format { Dfxp, /// Advanced SubStation Alpha (also reads SubStation Alpha). Ass, + /// MicroDVD (frame-numbered text). + MicroDvd, + /// MPL2 (times in tenths of a second). + Mpl2, + /// SubViewer 2. + SubViewer, + /// VPlayer (start times only). + VPlayer, + /// SAMI (HTML-like). + Sami, /// Phoenix Japanimation Society (PJS) subtitles. Pjs, /// RealText streaming timed text markup. @@ -86,7 +101,7 @@ pub enum Format { } impl Format { - pub const ALL: [Format; 11] = [ + pub const ALL: [Format; 16] = [ Format::Srt, Format::WebVtt, Format::Scc, @@ -95,6 +110,11 @@ impl Format { Format::Ttml, Format::Dfxp, Format::Ass, + Format::MicroDvd, + Format::Mpl2, + Format::SubViewer, + Format::VPlayer, + Format::Sami, Format::Pjs, Format::RealText, Format::JacoSub, @@ -109,6 +129,11 @@ impl Format { Format::Ttml => "TTML (IMSC1)", Format::Dfxp => "DFXP (TTML1)", Format::Ass => "Advanced SubStation Alpha (ASS)", + Format::MicroDvd => "MicroDVD", + Format::Mpl2 => "MPL2", + Format::SubViewer => "SubViewer 2", + Format::VPlayer => "VPlayer", + Format::Sami => "SAMI", Format::Pjs => "PJS", Format::RealText => "RealText", Format::JacoSub => "JACOsub", @@ -124,6 +149,12 @@ impl Format { Format::Ttml => "ttml", Format::Dfxp => "dfxp", Format::Ass => "ass", + Format::MicroDvd => "sub", + Format::Mpl2 => "mpl", + // SubViewer files are `.sub` too, as MicroDVD ones are; `.sbv` tells the two apart. + Format::SubViewer => "sbv", + Format::VPlayer => "vpl", + Format::Sami => "smi", Format::Pjs => "pjs", Format::RealText => "rt", Format::JacoSub => "jss", @@ -139,6 +170,11 @@ impl Format { "ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml), "dfxp" => Some(Format::Dfxp), "ass" | "ssa" => Some(Format::Ass), + "sub" | "microdvd" => Some(Format::MicroDvd), + "mpl" | "mpl2" => Some(Format::Mpl2), + "subviewer" | "sbv" => Some(Format::SubViewer), + "vplayer" | "vpl" => Some(Format::VPlayer), + "smi" | "sami" => Some(Format::Sami), "pjs" => Some(Format::Pjs), "rt" | "realtext" => Some(Format::RealText), "jss" | "js" | "jacosub" => Some(Format::JacoSub), @@ -292,28 +328,51 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.starts_with("[Script Info]") { return Some(Format::Ass); } + if head.get(..5).is_some_and(|h| h.eq_ignore_ascii_case("' || b == b'/') + { + return Some(Format::Sami); + } + if subviewer::is_header(head) { + return Some(Format::SubViewer); + } if realtext::is_realtext(head) { return Some(Format::RealText); } + let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); + let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some()); let first_lines: Vec<&str> = head.lines().map(str::trim).filter(|l| !l.is_empty()).take(3).collect(); + if first_lines.first().is_some_and(|l| microdvd::is_cue(l)) { + return Some(Format::MicroDvd); + } + if first_lines.first().is_some_and(|l| mpl2::split_cue(l).is_some()) { + return Some(Format::Mpl2); + } + if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) { + return Some(Format::SubViewer); + } + if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) { + return Some(Format::VPlayer); + } if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { return Some(Format::Pjs); } if first_lines.iter().any(|l| jacosub::is_timed_line(l)) || (head.starts_with('#') && (head.contains("TimeRes") || head.contains("#T"))) { return Some(Format::JacoSub); } - 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")) { let legacy = head.contains("ttaf1") || head.contains("dfxp"); return Some(if ext.as_deref() == Some("dfxp") || (legacy && ext.as_deref() != Some("ttml")) { Format::Dfxp } else { Format::Ttml }); } - let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some()); 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" | "ass" | "ssa" | "pjs" | "rt" | "jss" | "js") => None, + Some( + "srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "sub" | "mpl" | "vpl" | "smi" | "sami" | "pjs" | "rt" + | "jss" | "js", + ) => None, _ if has_arrow_timing => Some(Format::Srt), _ => None, } @@ -348,6 +407,11 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result { Format::Mcc => mcc::parse(&text), Format::Ttml | Format::Dfxp => ttml::parse(&text), Format::Ass => ass::parse(&text), + Format::MicroDvd => microdvd::parse(&text), + Format::Mpl2 => mpl2::parse(&text), + Format::SubViewer => subviewer::parse(&text), + Format::VPlayer => vplayer::parse(&text), + Format::Sami => sami::parse(&text), Format::Pjs => pjs::parse(&text), Format::RealText => realtext::parse(&text), Format::JacoSub => jacosub::parse(&text), @@ -389,6 +453,11 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { 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(), + Format::MicroDvd => microdvd::write(doc, opts.rate).into_bytes(), + Format::Mpl2 => mpl2::write(doc).into_bytes(), + Format::SubViewer => subviewer::write(doc).into_bytes(), + Format::VPlayer => vplayer::write(doc).into_bytes(), + Format::Sami => sami::write(doc).into_bytes(), Format::Pjs => pjs::write(doc).into_bytes(), Format::RealText => realtext::write(doc).into_bytes(), Format::JacoSub => jacosub::write(doc).into_bytes(), diff --git a/crates/captions/src/microdvd.rs b/crates/captions/src/microdvd.rs new file mode 100644 index 0000000000..5816373712 --- /dev/null +++ b/crates/captions/src/microdvd.rs @@ -0,0 +1,241 @@ +//! MicroDVD (`.sub`): frame-numbered text. +//! +//! ```text +//! {1}{1}23.976 +//! {24}{72}First line|{y:i}second line in italics +//! ``` +//! +//! A line is `{first frame}{last frame}text`; `|` starts a new line. A first cue `{1}{1}` or `{0}{0}` +//! whose text is a number gives the frame rate; without it the rate is 23.976 fps (the rate other +//! readers assume). Control codes `{y:i}` / `{y:b}` / `{y:u}` (italic, bold, underline; `i,b` together) +//! and `{c:$BBGGRR}` (colour) style the line they start; the capital forms `{Y:…}` and `{C:…}` +//! style every later line of the cue too. Other controls (`{f:…}` font, `{s:…}` size, `{h:…}`, …) +//! are dropped. Writing always starts with the `{1}{1}` rate line and styles a line only when +//! ``, `` or `` wraps all of it; other tags are dropped, and `{`, `}` and `|` in the +//! text become the full-width `{`, `}` and `|`. + +use crate::text::{LineStyle, escape_markup, number, plain_text, whole_line_style, wrap_style}; +use crate::time::FrameRate; +use crate::{Cue, Document, Error, Result}; + +/// The frame rate of a file that does not name one. +pub const DEFAULT_RATE: FrameRate = FrameRate::FPS_23_976; + +/// `{a}{b}text` as its parts. +fn split_cue(line: &str) -> Option<(i64, i64, &str)> { + let rest = line.strip_prefix('{')?; + let (a, rest) = rest.split_once('}')?; + let rest = rest.strip_prefix('{')?; + let (b, text) = rest.split_once('}')?; + Some((number(a.trim())?, number(b.trim())?, text)) +} + +/// Whether `line` is a `{first}{last}text` cue line. +pub(crate) fn is_cue(line: &str) -> bool { + split_cue(line).is_some() +} + +/// The frame rate a header cue's text names. +fn header_rate(text: &str) -> Option { + let fps: f64 = text.trim().parse().ok()?; + (fps.is_finite() && (1.0..=1000.0).contains(&fps)).then(|| FrameRate::from_f64(fps)) +} + +/// A `$BBGGRR` colour as `#rrggbb`. +fn colour(value: &str) -> Option { + let hex = value.trim().strip_prefix('$')?; + if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let (b, rest) = hex.split_at(2); + let (g, r) = rest.split_at(2); + Some(format!("#{}{}{}", r.to_ascii_lowercase(), g.to_ascii_lowercase(), b.to_ascii_lowercase())) +} + +/// What the styling controls of a cue's lines set. +#[derive(Default)] +struct Sticky { + style: LineStyle, + colour: Option, +} + +/// The text of one line without its `{x:…}` controls, and the controls in order. +fn split_controls(line: &str) -> (String, Vec<(char, String)>) { + let mut text = String::new(); + let mut controls = Vec::new(); + let mut rest = line; + while let Some(open) = rest.find('{') { + text.push_str(rest.get(..open).unwrap_or("")); + let after = rest.get(open + 1..).unwrap_or(""); + // Check the fixed-size control prefix before scanning its body. Invalid opening + // braces must not repeatedly scan the same suffix for a closing brace. + let name = after.as_bytes().first().copied().filter(u8::is_ascii_alphabetic); + if let Some(name) = name.filter(|_| after.as_bytes().get(1) == Some(&b':')) { + if let Some((body, tail)) = after.get(2..).and_then(|s| s.split_once('}')) { + controls.push((char::from(name), body.to_string())); + rest = tail; + } else { + // No later control can close either: preserve the entire remaining text. + text.push('{'); + text.push_str(after); + rest = ""; + break; + } + } else { + text.push('{'); + rest = after; + } + } + text.push_str(rest); + (text, controls) +} + +fn apply_style(value: &str, style: &mut LineStyle) { + for flag in value.split([',', ' ', '/']) { + match flag.trim().to_ascii_lowercase().as_str() { + "i" => style.italic = true, + "b" => style.bold = true, + "u" => style.underline = true, + _ => {} + } + } +} + +fn cue_text(raw: &str) -> String { + let mut sticky = Sticky::default(); + let mut lines = Vec::new(); + for line in raw.split('|') { + let (text, controls) = split_controls(line); + let mut style = sticky.style; + let mut line_colour = sticky.colour.clone(); + for (name, value) in controls { + match name { + 'y' => apply_style(&value, &mut style), + 'Y' => { + apply_style(&value, &mut style); + apply_style(&value, &mut sticky.style); + } + 'c' => line_colour = colour(&value).or(line_colour), + 'C' => { + line_colour = colour(&value).or(line_colour); + sticky.colour = line_colour.clone(); + } + _ => {} + } + } + let text = text.trim(); + if text.is_empty() { + continue; + } + lines.push(wrap_style(style, line_colour.as_deref(), &escape_markup(text))); + } + lines.join("\n") +} + +pub fn parse(text: &str) -> Result { + let mut rows = Vec::new(); + let mut rate = DEFAULT_RATE; + let mut has_rate_line = false; + let mut doc = Document::default(); + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + match split_cue(line) { + Some((0, 0, t) | (1, 1, t)) if rows.is_empty() && !has_rate_line && header_rate(t).is_some() => { + rate = header_rate(t).unwrap_or(rate); + has_rate_line = true; + } + Some(row) => rows.push(row), + None => doc.warnings.push(format!("line {}: not a MicroDVD cue, skipped", n + 1)), + } + } + if rows.is_empty() && !has_rate_line && !text.trim().is_empty() { + return Err(Error::NotFormat("MicroDVD")); + } + for (first, last, raw) in rows { + let (start, end) = (rate.tick_of(first), rate.tick_of(last)); + let text = cue_text(raw); + if end <= start || text.is_empty() { + doc.warnings.push(format!("the cue at frame {first} is empty or ends at frame {last}; skipped")); + continue; + } + doc.cues.push(Cue { start, end, text, ..Default::default() }); + } + Ok(doc) +} + +/// Write `doc` with its frames counted at `rate` (None: [`DEFAULT_RATE`]). +pub fn write(doc: &Document, rate: Option) -> String { + let rate = rate.map_or(DEFAULT_RATE, FrameRate::sane); + let mut out = format!("{{1}}{{1}}{:.3}\n", rate.as_f64()); + let frame = |t| rate.frame_at(rate.snap_nearest(t)).max(0); + for c in &doc.cues { + let first = frame(c.start); + let last = frame(c.end).max(first.saturating_add(1)); + let mut lines = Vec::new(); + for line in c.text.lines() { + let (style, inner) = whole_line_style(line); + let text = plain_text(inner).trim().replace('{', "\u{ff5b}").replace('}', "\u{ff5d}").replace('|', "\u{ff5c}"); + if text.is_empty() { + continue; + } + let mut flags = Vec::new(); + for (on, f) in [(style.italic, "i"), (style.bold, "b"), (style.underline, "u")] { + if on { + flags.push(f); + } + } + lines.push(if flags.is_empty() { text } else { format!("{{y:{}}}{text}", flags.join(",")) }); + } + if lines.is_empty() { + continue; + } + out.push_str(&format!("{{{first}}}{{{last}}}{}\n", lines.join("|"))); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn controls_style_lines() { + assert_eq!(cue_text("{y:i,b}x|plain"), "x\nplain"); + assert_eq!(cue_text("{Y:i}a|b"), "a\nb"); + assert_eq!(cue_text("{c:$0000ff}red"), "red"); + assert_eq!(cue_text("{f:Arial}{s:20}a & b {x"), "a & b {x"); + } + + #[test] + fn malformed_controls_inside_valid_cues_are_preserved() { + for raw in ["{".repeat(32_768), "{y:".repeat(16_384)] { + let doc = parse(&format!("{{0}}{{25}}{raw}")).unwrap(); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].text, raw); + } + assert_eq!(cue_text("{{y:i}hello"), "{hello"); + assert_eq!(cue_text("{xx:no}{y:b}hello"), "{xx:no}hello"); + } + + #[test] + fn rate_header() { + let d = parse("{1}{1}25.000\n{25}{50}x\n").unwrap(); + assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25)); + let d = parse("{0}{0}25.000\n{25}{50}x\n{50}{75}29.97\n").unwrap(); + assert_eq!(d.cues.len(), 2); + assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25)); + assert_eq!(d.cues[1].start, FrameRate::FPS_25.tick_of(50)); + assert_eq!(d.cues[1].text, "29.97"); + let d = parse("{25}{50}x\n").unwrap(); + assert_eq!(d.cues[0].start, DEFAULT_RATE.tick_of(25)); + } + + #[test] + fn rejects_other_text() { + assert!(parse("hello\nworld\n").is_err()); + assert!(parse("").unwrap().cues.is_empty()); + } +} diff --git a/crates/captions/src/mpl2.rs b/crates/captions/src/mpl2.rs new file mode 100644 index 0000000000..b7613f073d --- /dev/null +++ b/crates/captions/src/mpl2.rs @@ -0,0 +1,114 @@ +//! MPL2 (`.txt`, `.mpl`): times in tenths of a second. +//! +//! ```text +//! [10][35]First line|/second line in italics +//! ``` +//! +//! A line is `[start][end]text` with times in deciseconds. `|` starts a new line; a `/` at the +//! start of a line makes it italic. Writing marks a line italic only when `` wraps all of it, +//! drops other tags, rounds times to a tenth of a second, writes `|` in text as `|`, and writes +//! a leading `/` in non-italic text as `/`. + +use crate::text::{escape_markup, ms_to_tick, number, plain_text, tick_to_ms, whole_line_style, wrap_style}; +use crate::{Cue, Document, Error, Result}; + +/// `[a][b]text` as its parts. +pub(crate) fn split_cue(line: &str) -> Option<(i64, i64, &str)> { + let rest = line.strip_prefix('[')?; + let (a, rest) = rest.split_once(']')?; + let rest = rest.strip_prefix('[')?; + let (b, text) = rest.split_once(']')?; + Some((number(a.trim())?, number(b.trim())?, text)) +} + +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut found = false; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let Some((a, b, raw)) = split_cue(line) else { + doc.warnings.push(format!("line {}: not an MPL2 cue, skipped", n + 1)); + continue; + }; + found = true; + let mut lines = Vec::new(); + for l in raw.split('|') { + let (italic, l) = match l.trim().strip_prefix('/') { + Some(r) => (true, r.trim().to_string()), + None => { + let t = l.trim(); + if let Some(rest) = t.strip_prefix('\u{ff0f}') { (false, format!("/{rest}")) } else { (false, t.to_string()) } + } + }; + if !l.is_empty() { + lines.push(wrap_style(crate::text::LineStyle { italic, ..Default::default() }, None, &escape_markup(&l))); + } + } + let (start, end) = (ms_to_tick(a.saturating_mul(100)), ms_to_tick(b.saturating_mul(100))); + if end <= start || lines.is_empty() { + doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1)); + continue; + } + doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() }); + } + if !found && !text.trim().is_empty() { + return Err(Error::NotFormat("MPL2")); + } + Ok(doc) +} + +pub fn write(doc: &Document) -> String { + let mut out = String::new(); + let ds = |t| (tick_to_ms(t) + 50) / 100; + for c in &doc.cues { + let start = ds(c.start); + let end = ds(c.end).max(start + 1); + let mut lines = Vec::new(); + for line in c.text.lines() { + let (style, inner) = whole_line_style(line); + let mut text = plain_text(inner).trim().replace('|', "\u{ff5c}"); + if !style.italic && text.starts_with('/') { + text.replace_range(..1, "\u{ff0f}"); + } + if !text.is_empty() { + lines.push(if style.italic { format!("/{text}") } else { text }); + } + } + if !lines.is_empty() { + out.push_str(&format!("[{start}][{end}]{}\n", lines.join("|"))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn italics_and_lines() { + let d = parse("[10][35]Hello|/italic\n").unwrap(); + assert_eq!(d.cues[0].text, "Hello\nitalic"); + assert_eq!(d.cues[0].end, ms_to_tick(3500)); + } + + #[test] + fn rejects_other_text() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err()); + } + + #[test] + fn non_italic_leading_slash_roundtrip() { + let doc = Document { + cues: vec![Cue { start: ms_to_tick(1000), end: ms_to_tick(2000), text: "/not italic\n/italic".into(), ..Default::default() }], + ..Default::default() + }; + let written = write(&doc); + assert_eq!(written, "[10][20]/not italic|//italic\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues[0].text, "/not italic\n/italic"); + } +} diff --git a/crates/captions/src/sami.rs b/crates/captions/src/sami.rs new file mode 100644 index 0000000000..29f8281dd9 --- /dev/null +++ b/crates/captions/src/sami.rs @@ -0,0 +1,323 @@ +//! SAMI (`.smi`, `.sami`): Microsoft's HTML-like captions. +//! +//! ```text +//! +//!

First line
second line +//!

  +//! +//! ``` +//! +//! A `` block shows its text from that millisecond until the next block; a block +//! holding only ` ` clears the screen. The last caption lasts four seconds if nothing clears +//! it. `
` starts a new line; ``, ``, `` and `` are kept, other tags +//! dropped; `&`, `<`, `>`, ` ` and numeric references are read. A file can hold +//! several language classes (`

`, `

`): the first one named is read and +//! the others skipped with a warning. Writing makes one `ENCC` class, an ` ` block where a +//! caption ends before the next starts, and rounds to milliseconds. + +use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, sequential, tick_to_ms}; +use crate::time::Tick; +use crate::{Cue, Document, Error, Result}; + +/// The value of attribute `name` in the tag text `tag` (quotes optional). +fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> { + let lower = tag.to_ascii_lowercase(); + let mut from = 0; + while let Some(i) = lower.get(from..).and_then(|r| r.find(name)) { + let at = from + i; + from = at + name.len(); + let before_ok = at == 0 || lower.as_bytes().get(at - 1).is_some_and(|b| !b.is_ascii_alphanumeric()); + let rest = tag.get(from..).unwrap_or("").trim_start(); + let Some(rest) = rest.strip_prefix('=').filter(|_| before_ok) else { continue }; + let rest = rest.trim_start(); + return Some(match rest.chars().next() { + Some(q @ ('"' | '\'')) => { + let inner = rest.get(1..).unwrap_or(""); + inner.split(q).next().unwrap_or("") + } + _ => rest.split(|c: char| c.is_whitespace() || c == '>').next().unwrap_or(""), + }); + } + None +} + +/// A numeric character reference body (`#65`, `#x41`) as its character. +fn numeric_reference(body: &str) -> Option { + let digits = body.strip_prefix('#')?; + let code = match digits.strip_prefix(['x', 'X']) { + Some(hex) => u32::from_str_radix(hex, 16).ok()?, + None => digits.parse().ok()?, + }; + char::from_u32(code).filter(|c| !c.is_control() || *c == '\n') +} + +/// HTML text as cue text: entities the cue model keeps stay, numeric ones are decoded, a stray +/// `&` is escaped, whitespace runs collapse. +fn text_run(s: &str) -> String { + let mut out = String::new(); + let mut rest = s; + let mut space = false; + while let Some(c) = rest.chars().next() { + let mut advance = c.len_utf8(); + if c.is_whitespace() && c != '\u{a0}' { + space = true; + rest = rest.get(advance..).unwrap_or(""); + continue; + } + if space { + out.push(' '); + } + space = false; + if c == '&' { + if let Some((_, len)) = crate::entity_at(rest) { + out.push_str(rest.get(..len).unwrap_or("")); + advance = len; + } else if let Some(body) = rest.get(1..).and_then(|r| { + // Numeric entities have at most eight body bytes. Never scan the + // unbounded remainder again for each malformed ampersand. + let end = r.bytes().take(9).position(|b| b == b';')?; + r.get(..end) + }) && let Some(ch) = numeric_reference(body) + { + out.push_str(&escape_markup(&ch.to_string())); + advance = body.len() + 2; + } else { + out.push_str("&"); + } + } else { + out.push_str(&escape_markup(&c.to_string())); + } + rest = rest.get(advance..).unwrap_or(""); + } + if space { + out.push(' '); + } + out +} + +/// One `` block's body as (class, cue text) segments, one per `

`. +fn segments(body: &str) -> Vec<(String, String)> { + let mut segs: Vec<(String, String)> = vec![(String::new(), String::new())]; + let mut open_fonts = 0usize; + let mut rest = body; + while !rest.is_empty() { + let Some(lt) = rest.find('<') else { + if let Some(last) = segs.last_mut() { + last.1.push_str(&text_run(rest)); + } + break; + }; + if let Some(last) = segs.last_mut() { + last.1.push_str(&text_run(rest.get(..lt).unwrap_or(""))); + } + let after = rest.get(lt + 1..).unwrap_or(""); + let Some(gt) = after.find('>') else { + if let Some(last) = segs.last_mut() { + last.1.push_str("<"); + last.1.push_str(&text_run(after)); + } + break; + }; + let tag = after.get(..gt).unwrap_or(""); + rest = after.get(gt + 1..).unwrap_or(""); + let closing = tag.starts_with('/'); + let name: String = tag.trim_start_matches('/').chars().take_while(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase(); + let Some(last) = segs.last_mut() else { continue }; + match (name.as_str(), closing) { + ("br", _) => last.1.push('\n'), + ("p", false) => segs.push((attribute(tag, "class").unwrap_or("").to_string(), String::new())), + ("i" | "b" | "u", false) => last.1.push_str(&format!("<{name}>")), + ("i" | "b" | "u", true) => last.1.push_str(&format!("")), + ("font", false) => { + if let Some(c) = attribute(tag, "color").filter(|c| c.len() <= 20 && c.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'#')) { + open_fonts += 1; + last.1.push_str(&format!("")); + } + } + ("font", true) if open_fonts > 0 => { + open_fonts -= 1; + last.1.push_str(""); + } + _ => {} + } + } + segs +} + +/// A caption text without the whitespace and non-breaking spaces round its lines. +fn tidy(text: &str) -> String { + let lines: Vec = text + .split('\n') + .map(|l| l.replace(" ", " ").trim().to_string()) + .filter(|l| !l.is_empty() && !crate::plain_text(l).trim().is_empty()) + .collect(); + lines.join("\n") +} + +pub fn parse(text: &str) -> Result { + let lower = text.to_ascii_lowercase(); + let mut starts: Vec = Vec::new(); + let mut from = 0; + while let Some(i) = lower.get(from..).and_then(|r| r.find(" = None; + let mut skipped_class = false; + let mut syncs: Vec<(Tick, String)> = Vec::new(); + for (k, &at) in starts.iter().enumerate() { + let stop = starts.get(k + 1).copied().unwrap_or(text.len()); + let chunk = text.get(at..stop).unwrap_or(""); + let chunk = match chunk.to_ascii_lowercase().find(" chunk.get(..i).unwrap_or(chunk), + None => chunk, + }; + let Some((tag, body)) = chunk.get(1..).and_then(|c| c.split_once('>')) else { continue }; + let Some(start) = attribute(tag, "start").and_then(|v| number(v.trim())) else { + doc.warnings.push("a without a Start time was skipped".to_string()); + continue; + }; + let mut shown = String::new(); + for (cls, seg) in segments(body) { + if class.is_none() && !cls.is_empty() { + class = Some(cls.to_ascii_lowercase()); + } + if class.as_deref().is_none_or(|c| c == cls.to_ascii_lowercase() || cls.is_empty()) { + shown.push_str(&seg); + } else { + skipped_class = true; + } + } + syncs.push((ms_to_tick(start), tidy(&shown))); + } + if skipped_class { + doc.warnings.push("the file has other language classes; only the first was read".to_string()); + } + syncs.sort_by_key(|(t, _)| *t); + for (i, (start, text)) in syncs.iter().enumerate() { + if text.is_empty() { + continue; + } + let end = syncs.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next); + if end <= *start { + doc.warnings.push("two captions start at the same time; the first was skipped".to_string()); + continue; + } + doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() }); + } + Ok(doc) +} + +pub fn write(doc: &Document) -> String { + let cues = sequential(doc); + let mut out = String::from( + "\n\n\n\n\n\n", + ); + let active_cues: Vec<(&Cue, Vec<&str>)> = cues + .iter() + .filter_map(|c| { + let lines: Vec<&str> = c.text.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + if lines.is_empty() { None } else { Some((c, lines)) } + }) + .collect(); + let mut resolved_cues: Vec<(i64, i64, &Vec<&str>)> = Vec::with_capacity(active_cues.len()); + let mut prev_end = 0i64; + for (c, lines) in &active_cues { + let start_ms = tick_to_ms(c.start).max(prev_end); + let end_ms = tick_to_ms(c.end).max(start_ms + 1); + prev_end = end_ms; + resolved_cues.push((start_ms, end_ms, lines)); + } + for (i, &(start_ms, end_ms, lines)) in resolved_cues.iter().enumerate() { + out.push_str(&format!("

{}\n", lines.join("
"))); + let next_start = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s); + if next_start != Some(end_ms) { + out.push_str(&format!("

 \n")); + } + } + out.push_str("\n\n"); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blocks_clear_and_style() { + let d = parse("\n

Hello
world & you\n

 \n

x A y\n").unwrap(); + assert_eq!(d.cues.len(), 2); + assert_eq!(d.cues[0].text, "Hello\nworld & you"); + assert_eq!(d.cues[0].end, ms_to_tick(3500)); + assert_eq!(d.cues[1].text, "x A y"); + assert_eq!(d.cues[1].end, last_cue_end(ms_to_tick(4000))); + } + + #[test] + fn malformed_entities_inside_valid_cues_are_bounded() { + let raw = "&".repeat(32_768); + let doc = parse(&format!("

{raw}

 ")).unwrap(); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].text, "&".repeat(32_768)); + assert_eq!(text_run("A A A &é;"), "A &#00000065; A &é;"); + } + + #[test] + fn only_the_first_class_is_read() { + let d = parse("

en

kr

 ").unwrap(); + assert_eq!(d.cues.len(), 1); + assert_eq!(d.cues[0].text, "en"); + assert_eq!(d.warnings.len(), 1); + } + + #[test] + fn rejects_other_text() { + assert!(parse("hello").is_err()); + } + + #[test] + fn short_duration_and_empty_cues() { + let doc = Document { + cues: vec![ + Cue { start: ms_to_tick(100), end: Tick(ms_to_tick(100).0 + 1), text: "Brief".into(), ..Default::default() }, + Cue { start: ms_to_tick(101), end: ms_to_tick(200), text: " ".into(), ..Default::default() }, + Cue { start: ms_to_tick(500), end: ms_to_tick(600), text: "After gap".into(), ..Default::default() }, + ], + ..Default::default() + }; + let written = write(&doc); + assert!(written.contains("

Brief\n

 \n")); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 2); + assert_eq!(parsed.cues[0].start, ms_to_tick(100)); + assert_eq!(parsed.cues[0].end, ms_to_tick(101)); + assert_eq!(parsed.cues[1].start, ms_to_tick(500)); + } + + #[test] + fn adjacent_short_cues_do_not_collide_after_rounding() { + let t100 = ms_to_tick(100); + let t100_1 = Tick(t100.0 + crate::TICKS_PER_MS / 10); + let t200 = ms_to_tick(200); + let doc = Document { + cues: vec![ + Cue { start: t100, end: t100_1, text: "First".into(), ..Default::default() }, + Cue { start: t100_1, end: t200, text: "Second".into(), ..Default::default() }, + ], + ..Default::default() + }; + let encoded = write(&doc); + let back = parse(&encoded).unwrap(); + assert_eq!(back.cues.len(), 2); + assert_eq!(back.cues[0].text, "First"); + assert_eq!(tick_to_ms(back.cues[0].start), 100); + assert_eq!(tick_to_ms(back.cues[0].end), 101); + assert_eq!(back.cues[1].text, "Second"); + assert_eq!(tick_to_ms(back.cues[1].start), 101); + assert_eq!(tick_to_ms(back.cues[1].end), 200); + } +} diff --git a/crates/captions/src/subviewer.rs b/crates/captions/src/subviewer.rs new file mode 100644 index 0000000000..96b97ef6d2 --- /dev/null +++ b/crates/captions/src/subviewer.rs @@ -0,0 +1,198 @@ +//! SubViewer 2 (`.sub`): hundredths of a second, with an information header. +//! +//! ```text +//! [INFORMATION] +//! [TITLE]… +//! [END INFORMATION] +//! [SUBTITLE] +//! 00:00:01.00,00:00:03.50 +//! First line[br]second line +//! +//! ``` +//! +//! Reading skips the bracketed header lines and takes every `start,end` time line as a cue whose +//! text runs to the next blank line; `[br]` starts a new line. Fractions of one to three digits +//! are accepted. Writing adds a minimal header, rounds times to a hundredth of a second, drops +//! tags, writes `[br]` inside text as `[br]`, and writes `,` in lines that match the timing +//! syntax as `,`. + +use crate::text::{escape_markup, plain_lines}; +use crate::time::{TICKS_PER_SECOND, Tick}; +use crate::{Cue, Document, Error, Result, parse_clock}; + +const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100; + +/// Returns true if `head` begins with a genuine SubViewer header structure. +pub(crate) fn is_header(head: &str) -> bool { + let mut lines = head.lines().map(str::trim).filter(|l| !l.is_empty()); + match lines.next() { + Some("[INFORMATION]") => lines.any(|l| { + l == "[SUBTITLE]" + || l == "[END INFORMATION]" + || l.starts_with("[TITLE") + || l.starts_with("[AUTHOR") + || l.starts_with("[SOURCE") + || l.starts_with("[FILEPATH") + || l.starts_with("[DELAY") + || l.starts_with("[CD TRACK") + || l.starts_with("[COMMENT") + || (l.starts_with('[') && l.contains(']')) + }), + Some("[SUBTITLE]") => true, + _ => false, + } +} + +/// `h:mm:ss.cc,h:mm:ss.cc` as its two times. +pub(crate) fn parse_timing(line: &str) -> Option<(Tick, Tick)> { + let (a, b) = line.trim().split_once(',')?; + let ok = |s: &str| s.contains(':') && s.contains('.'); + if !ok(a) || !ok(b) { + return None; + } + Some((parse_clock(a)?, parse_clock(b)?)) +} + +/// Split `s` at each `[br]`, whatever its case. +fn split_br(s: &str) -> Vec<&str> { + let lower = s.to_ascii_lowercase(); + let mut parts = Vec::new(); + let mut from = 0; + while let Some(i) = lower.get(from..).and_then(|r| r.find("[br]")) { + parts.push(s.get(from..from + i).unwrap_or("")); + from += i + 4; + } + parts.push(s.get(from..).unwrap_or("")); + parts +} + +pub fn parse(text: &str) -> Result { + let lines: Vec<&str> = text.lines().collect(); + let mut doc = Document::default(); + let mut found = false; + let mut i = 0; + while i < lines.len() { + let Some((start, end)) = lines.get(i).and_then(|l| parse_timing(l)) else { + i += 1; + continue; + }; + found = true; + i += 1; + let mut out: Vec = Vec::new(); + while let Some(l) = lines.get(i).filter(|l| !l.trim().is_empty()) { + if parse_timing(l).is_some() { + break; + } + out.extend(split_br(l).into_iter().map(str::trim).filter(|p| !p.is_empty()).map(escape_markup)); + i += 1; + } + if end <= start || out.is_empty() { + doc.warnings.push(format!("the cue at line {i} is empty or ends before it starts; skipped")); + continue; + } + doc.cues.push(Cue { start, end, text: out.join("\n"), ..Default::default() }); + } + let has_header = text.contains("[INFORMATION]") || text.contains("[SUBTITLE]"); + if !found && !has_header && !text.trim().is_empty() { + return Err(Error::NotFormat("SubViewer")); + } + Ok(doc) +} + +fn cs(t: Tick) -> u64 { + ((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as u64 +} + +fn clock(cs: u64) -> String { + format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100) +} + +pub fn write(doc: &Document) -> String { + let mut out = String::from( + "[INFORMATION]\n[TITLE]\n[AUTHOR]\n[SOURCE]\n[PRG]\n[FILEPATH]\n[DELAY]0\n[CD TRACK]0\n[COMMENT]\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]no,[SIZE]18,[FONT]Arial\n", + ); + for c in &doc.cues { + let lines = plain_lines(&c.text); + if lines.is_empty() { + continue; + } + let start_cs = cs(c.start); + let end_cs = cs(c.end).max(start_cs + 1); + out.push_str(&format!("{},{}\n", clock(start_cs), clock(end_cs))); + let lines: Vec = lines + .into_iter() + .map(|mut l| { + if parse_timing(&l).is_some() { + l = l.replacen(',', "\u{ff0c}", 1); + } + l.replace("[br]", "\u{ff3b}br\u{ff3d}") + .replace("[BR]", "\u{ff3b}BR\u{ff3d}") + .replace("[Br]", "\u{ff3b}Br\u{ff3d}") + .replace("[bR]", "\u{ff3b}bR\u{ff3d}") + }) + .collect(); + out.push_str(&lines.join("[br]")); + out.push_str("\n\n"); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn header_and_breaks() { + let d = parse("[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:03.50\nHello[BR]world\n\n").unwrap(); + assert_eq!(d.cues[0].text, "Hello\nworld"); + assert_eq!(d.cues[0].end, crate::text::ms_to_tick(3500)); + } + + #[test] + fn writer_escapes_every_case_of_literal_break_tokens() { + let doc = Document { + cues: vec![Cue { start: Tick(0), end: crate::text::ms_to_tick(1000), text: "a[br]b[BR]c[Br]d[bR]é".into(), ..Default::default() }], + ..Default::default() + }; + let decoded = parse(&write(&doc)).unwrap(); + assert_eq!(decoded.cues[0].text, "a[br]b[BR]c[Br]d[bR]é"); + } + + #[test] + fn rejects_other_text() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err()); + } + + #[test] + fn centisecond_rounding_without_double_rounding_error() { + // 1.0046s is 255_184_473_600 ticks (at 254_016_000_000 ticks/sec). + // Direct rounding to hundredths gives 100cs (00:00:01.00). + // Double-rounding through ms gives 1005ms -> 101cs (00:00:01.01). + let t = Tick(255_184_473_600); + assert_eq!(clock(cs(t)), "00:00:01.00"); + } + + #[test] + fn timing_shaped_text_escaped_and_roundtripped() { + let doc = Document { + cues: vec![ + Cue { start: Tick(TICKS_PER_SECOND), end: Tick(3 * TICKS_PER_SECOND), text: "00:00:01.00,00:00:02.00".into(), ..Default::default() }, + Cue { start: Tick(4 * TICKS_PER_SECOND), end: Tick(5 * TICKS_PER_SECOND), text: "Second cue".into(), ..Default::default() }, + ], + ..Default::default() + }; + let written = write(&doc); + assert!(written.contains("00:00:01.00,00:00:02.00")); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 2); + assert_eq!(parsed.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00"); + assert_eq!(parsed.cues[1].text, "Second cue"); + } + + #[test] + fn literal_fullwidth_comma_preserved_on_read() { + let raw = "[INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:02.00\n00:00:01.00\u{ff0c}00:00:02.00\n\n"; + let doc = parse(raw).unwrap(); + assert_eq!(doc.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00"); + } +} diff --git a/crates/captions/src/text.rs b/crates/captions/src/text.rs index 4f1d04f696..35cd23c0fc 100644 --- a/crates/captions/src/text.rs +++ b/crates/captions/src/text.rs @@ -85,8 +85,8 @@ pub fn plain_text(s: &str) -> String { out } -use crate::TICKS_PER_MS; use crate::time::{TICKS_PER_SECOND, Tick}; +use crate::{Cue, Document, TICKS_PER_MS}; /// How long the last cue of a format that gives only start times lasts: such a file says when a /// caption appears, and the next one ends it. @@ -131,6 +131,62 @@ pub(crate) fn plain_lines(text: &str) -> Vec { text.lines().map(plain_text).map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect() } +/// The style a whole line of cue text carries: ``, `` and `` around all of it. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub(crate) struct LineStyle { + pub italic: bool, + pub bold: bool, + pub underline: bool, +} + +/// The style that wraps the whole of `line`, and the line without it. `a b c` is not +/// italic as a whole. +pub(crate) fn whole_line_style(line: &str) -> (LineStyle, &str) { + let mut style = LineStyle::default(); + let mut rest = line.trim(); + loop { + let mut changed = false; + for (open, close, flag) in [("", "", 0), ("", "", 1), ("", "", 2)] { + if let Some(inner) = rest.strip_prefix(open).and_then(|r| r.strip_suffix(close)) + && !inner.contains(open) + && !inner.contains(close) + { + match flag { + 0 => style.italic = true, + 1 => style.bold = true, + _ => style.underline = true, + } + rest = inner.trim(); + changed = true; + } + } + if !changed { + return (style, rest); + } + } +} + +/// Cue text from a line's style and its (already escaped) text. +pub(crate) fn wrap_style(style: LineStyle, color: Option<&str>, text: &str) -> String { + let mut out = text.to_string(); + for (on, tag) in [(style.underline, "u"), (style.bold, "b"), (style.italic, "i")] { + if on { + out = format!("<{tag}>{out}"); + } + } + match color { + Some(c) => format!("{out}"), + None => out, + } +} + +/// The cues of `doc` in time order with no overlaps, for a format that holds one caption at a time. +pub(crate) fn sequential(doc: &Document) -> Vec { + let mut copy = Document { cues: doc.cues.clone(), ..Default::default() }; + copy.normalize(); + copy.cues +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/captions/src/vplayer.rs b/crates/captions/src/vplayer.rs new file mode 100644 index 0000000000..169e4f24a0 --- /dev/null +++ b/crates/captions/src/vplayer.rs @@ -0,0 +1,206 @@ +//! VPlayer (`.txt`, `.vpl`): one start time per caption. +//! +//! ```text +//! 00:00:01.00=First line|second line +//! 00:00:04.00= +//! ``` +//! +//! A line is `HH:MM:SS`, an optional `.cc` fraction, one of `:`, `=` or a space, and the text; `|` +//! starts a new line. The file gives only when each caption appears: it stays until the next +//! line, whose empty text clears it. The last caption lasts four seconds if no line ends it. +//! Writing puts a clearing line where a caption ends before the next one starts, drops tags, +//! rounds to a hundredth of a second and writes `|` in text as `|`. + +use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, plain_lines, sequential}; +use crate::time::{TICKS_PER_SECOND, Tick}; +use crate::{Cue, Document, Error, Result}; + +const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100; + +/// `HH:MM:SS[.cc]` then a separator and text: the time and the text. +pub(crate) fn split_line(line: &str) -> Option<(Tick, &str)> { + let mut parts = line.splitn(3, ':'); + let h = number(parts.next()?)?; + let m = number(parts.next()?)?; + let tail = parts.next()?; + let digits = tail.bytes().take_while(u8::is_ascii_digit).count(); + let s = number(tail.get(..digits)?)?; + let mut rest = tail.get(digits..)?; + let mut ms = 0; + if let Some(frac) = rest.strip_prefix('.') { + let n = frac.bytes().take_while(u8::is_ascii_digit).count().min(3); + let f = frac.get(..n).filter(|f| !f.is_empty())?; + ms = number(f)? * 10_i64.pow(3 - n as u32); + rest = frac.get(n..)?; + // further digits of a long fraction are below a millisecond + rest = rest.trim_start_matches(|c: char| c.is_ascii_digit()); + } + if m >= 60 || s >= 60 || h > 9999 { + return None; + } + let text = rest.strip_prefix([':', '=', ' '])?; + Some((ms_to_tick(((h * 60 + m) * 60 + s) * 1000 + ms), text)) +} + +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut starts: Vec<(Tick, String)> = Vec::new(); + for (n, line) in text.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + match split_line(line.trim()) { + Some((t, raw)) => { + let lines: Vec = raw.split('|').map(str::trim).filter(|l| !l.is_empty()).map(escape_markup).collect(); + starts.push((t, lines.join("\n"))); + } + None => doc.warnings.push(format!("line {}: not a VPlayer line, skipped", n + 1)), + } + } + if starts.is_empty() && !text.trim().is_empty() { + return Err(Error::NotFormat("VPlayer")); + } + for (i, (start, text)) in starts.iter().enumerate() { + if text.is_empty() { + continue; + } + let end = starts.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next); + if end <= *start { + doc.warnings.push("a caption is followed by a line at the same time; skipped".to_string()); + continue; + } + doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() }); + } + Ok(doc) +} + +fn cs(t: Tick) -> i64 { + ((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as i64 +} + +fn clock(cs: i64) -> String { + format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100) +} + +pub fn write(doc: &Document) -> String { + let cues = sequential(doc); + let mut out = String::new(); + let active_cues: Vec<(&Cue, Vec)> = cues + .iter() + .filter_map(|c| { + let lines = plain_lines(&c.text); + if lines.is_empty() { + None + } else { + let lines = lines.into_iter().map(|l| l.replace('|', "\u{ff5c}")).collect(); + Some((c, lines)) + } + }) + .collect(); + + let mut resolved_cues: Vec<(i64, i64, &Vec)> = Vec::with_capacity(active_cues.len()); + let mut prev_end = 0i64; + for (c, lines) in &active_cues { + let start_cs = cs(c.start).max(prev_end); + let end_cs = cs(c.end).max(start_cs + 1); + prev_end = end_cs; + resolved_cues.push((start_cs, end_cs, lines)); + } + + for (i, &(start_cs, end_cs, lines)) in resolved_cues.iter().enumerate() { + out.push_str(&format!("{}={}\n", clock(start_cs), lines.join("|"))); + let next_start_cs = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s); + if next_start_cs != Some(end_cs) { + out.push_str(&format!("{}=\n", clock(end_cs))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn short_duration_cue_preserves_positive_duration_on_write_and_read() { + let mut doc = Document::default(); + // A cue from 0 to 1 ms collapses to 00:00:00.00 under centisecond rounding. + doc.cues.push(Cue { start: ms_to_tick(0), end: ms_to_tick(1), text: "Short".to_string(), ..Default::default() }); + let written = write(&doc); + assert_eq!(written, "00:00:00.00=Short\n00:00:00.01=\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 1); + assert_eq!(parsed.cues[0].text, "Short"); + assert_eq!(parsed.cues[0].start, ms_to_tick(0)); + assert_eq!(parsed.cues[0].end, ms_to_tick(10)); + } + + #[test] + fn adjacent_short_cues_do_not_collide_after_rounding() { + let doc = Document { + cues: vec![ + Cue { start: ms_to_tick(1000), end: ms_to_tick(1001), text: "First".to_string(), ..Default::default() }, + Cue { start: ms_to_tick(1001), end: ms_to_tick(1020), text: "Second".to_string(), ..Default::default() }, + ], + ..Default::default() + }; + let written = write(&doc); + assert_eq!(written, "00:00:01.00=First\n00:00:01.01=Second\n00:00:01.02=\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 2); + assert_eq!(parsed.cues[0].text, "First"); + assert_eq!(parsed.cues[0].start, ms_to_tick(1000)); + assert_eq!(parsed.cues[0].end, ms_to_tick(1010)); + assert_eq!(parsed.cues[1].text, "Second"); + assert_eq!(parsed.cues[1].start, ms_to_tick(1010)); + assert_eq!(parsed.cues[1].end, ms_to_tick(1020)); + } + + #[test] + fn separators_and_ends() { + let d = parse("00:00:01:Hello|world\n00:00:04.50=\n00:00:05 later\n").unwrap(); + assert_eq!(d.cues.len(), 2); + assert_eq!(d.cues[0].text, "Hello\nworld"); + assert_eq!(d.cues[0].end, ms_to_tick(4500)); + assert_eq!(d.cues[1].end, ms_to_tick(9000)); + } + + #[test] + fn rejects_other_text() { + assert!(parse("hello\n").is_err()); + assert!(parse("00:00:01,000 --> 00:00:02,000\n").is_err()); + } + + #[test] + fn empty_cue_skipped_and_numerical_timestamp_order() { + let doc = Document { + cues: vec![ + Cue { + start: Tick(99 * 3600 * TICKS_PER_SECOND), + end: Tick(99 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND), + text: "At 99h".into(), + ..Default::default() + }, + Cue { + start: Tick(99 * 3600 * TICKS_PER_SECOND + 3 * TICKS_PER_SECOND), + end: Tick(99 * 3600 * TICKS_PER_SECOND + 4 * TICKS_PER_SECOND), + text: " ".into(), + ..Default::default() + }, + Cue { + start: Tick(100 * 3600 * TICKS_PER_SECOND), + end: Tick(100 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND), + text: "At 100h".into(), + ..Default::default() + }, + ], + ..Default::default() + }; + let written = write(&doc); + assert_eq!(written, "99:00:00.00=At 99h\n99:00:02.00=\n100:00:00.00=At 100h\n100:00:02.00=\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 2); + assert_eq!(parsed.cues[0].text, "At 99h"); + assert_eq!(parsed.cues[1].text, "At 100h"); + } +} diff --git a/crates/captions/tests/it/legacy_text.rs b/crates/captions/tests/it/legacy_text.rs new file mode 100644 index 0000000000..1bfe11bfea --- /dev/null +++ b/crates/captions/tests/it/legacy_text.rs @@ -0,0 +1,252 @@ +//! The legacy text formats (MicroDVD, MPL2, SubViewer 2, VPlayer, SAMI): reading, writing, and +//! ffmpeg as the reference (oracle; skipped when ffmpeg is absent, a failure with +//! `CRAFT_MEDIA_REQUIRE_ORACLES=1`). + +use craft_captions::time::FrameRate; +use craft_captions::{Cue, Document, Format, TICKS_PER_SECOND, Tick, WriteOptions, detect, parse, plain_text, write}; +use std::process::Command; + +const T: i64 = TICKS_PER_SECOND; +const MS: i64 = T / 1000; + +fn ms(v: i64) -> Tick { + Tick(v * MS) +} + +/// The five formats, with the ffmpeg format name each is read and written through. +const FORMATS: [(Format, &str, &str); 5] = [ + (Format::MicroDvd, "microdvd", "sub"), + (Format::Mpl2, "mpl2", "txt"), + (Format::SubViewer, "subviewer", "sbv"), + (Format::VPlayer, "vplayer", "txt"), + (Format::Sami, "sami", "smi"), +]; + +const MICRODVD: &str = "{1}{1}23.976\n{24}{72}Hello|{y:i}second bold\n{100}{150}{c:$0000ff}red\n{200}{250}a & b < c\n"; +const MPL2: &str = "[10][35]Hello|/italic\n[40][60]plain\n[70][90]/a|/b\n"; +const SUBVIEWER: &str = "[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]bd,[SIZE]18,[FONT]Arial\n00:00:01.00,00:00:03.50\nHello[br]world\n\n00:00:04.00,00:00:05.00\nplain\n"; +const VPLAYER: &str = "00:00:01.00=Hello|world\n00:00:04.00=\n00:00:05:plain\n00:00:09 later\n"; +const SAMI: &str = "\nx\n\n

Hello
world\n

 \n

plain & more\n

 \n\n\n"; + +fn samples() -> [(Format, &'static str); 5] { + [(Format::MicroDvd, MICRODVD), (Format::Mpl2, MPL2), (Format::SubViewer, SUBVIEWER), (Format::VPlayer, VPLAYER), (Format::Sami, SAMI)] +} + +fn 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)); +} + +/// What ffmpeg reads from `bytes` as `ffmpeg_format`, as cues. +fn ffmpeg_reads(ff: &std::path::Path, name: &str, ffmpeg_format: &str, ext: &str, bytes: &[u8]) -> Document { + let dir = craft_media_testkit::fixture_subdir("captions_legacy"); + let (input, out) = (dir.join(format!("{name}.{ext}")), dir.join(format!("{name}.srt"))); + std::fs::write(&input, bytes).expect("write"); + run(ff, &["-f", ffmpeg_format, "-i", input.to_str().expect("path"), out.to_str().expect("path")]); + parse(&std::fs::read(&out).expect("read"), Format::Srt).expect("parse ffmpeg's srt") +} + +/// The lines of a cue's text as plain text, tags and entities gone. +fn plain(c: &Cue) -> String { + c.text.lines().map(|l| plain_text(l).trim().to_string()).collect::>().join("\n") +} + +#[test] +fn we_read_what_ffmpeg_reads() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + for (format, text) in samples() { + let (_, name, ext) = FORMATS.iter().copied().find(|f| f.0 == format).expect("format"); + let ours = parse(text.as_bytes(), format).expect("parse"); + let theirs = ffmpeg_reads(&ff, &format!("read_{name}"), name, ext, text.as_bytes()); + assert_eq!(ours.cues.len(), theirs.cues.len(), "{format:?}: {:?} against {:?}", ours.cues, theirs.cues); + for (i, (o, t)) in ours.cues.iter().zip(&theirs.cues).enumerate() { + // ffmpeg gives a last caption of a start-only format no end (an enormous one). + let last = i + 1 == ours.cues.len(); + let open_ended = matches!(format, Format::VPlayer | Format::Sami) && last; + assert!((o.start.0 - t.start.0).abs() <= MS, "{format:?} start of {:?}: {:?} against {:?}", o.text, o.start, t.start); + if !open_ended { + assert!((o.end.0 - t.end.0).abs() <= MS, "{format:?} end of {:?}: {:?} against {:?}", o.text, o.end, t.end); + } + assert_eq!(plain(o), plain(t), "{format:?} text of the cue at {:?}", o.start); + } + } +} + +fn sample_document() -> Document { + let cue = |a: i64, b: i64, text: &str| Cue { start: ms(a), end: ms(b), text: text.into(), ..Default::default() }; + Document { + cues: vec![ + cue(1000, 3500, "Hello\nsecond line"), + cue(3500, 5000, "straight after, with & and <"), + cue(7000, 9000, "after a gap [br] { } |"), + cue(3_600_000, 3_601_500, "an hour in"), + ], + ..Default::default() + } +} + +#[test] +fn ffmpeg_reads_what_we_write() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + // ffmpeg's own readers mangle the look-alike characters a writer uses for what a format cannot hold, + // so the cue that has those is left out here (write_then_read covers it). + let mut doc = sample_document(); + doc.cues[2].text = "after a gap".into(); + for (format, name, ext) in FORMATS { + let bytes = write(&doc, format, WriteOptions::default()); + let theirs = ffmpeg_reads(&ff, &format!("write_{name}"), name, ext, &bytes); + assert_eq!(theirs.cues.len(), doc.cues.len(), "{format:?}: {:?}", String::from_utf8_lossy(&bytes)); + for (t, d) in theirs.cues.iter().zip(&doc.cues) { + let tolerance = if format == Format::MicroDvd { 45 * MS } else { 10 * MS }; + assert!((t.start.0 - d.start.0).abs() <= tolerance, "{format:?} start of {:?}: {:?}", d.text, t.start); + // the characters a format cannot hold are written as look-alikes: compare without them + let bare = |c: &Cue| { + plain(c) + .replace('\u{ff3b}', "[") + .replace('\u{ff3d}', "]") + .replace("[br]", "") + .replace(['{', '}', '|', '\u{ff5b}', '\u{ff5d}', '\u{ff5c}'], "") + .replace(" ", " ") + }; + assert_eq!(bare(t), bare(d), "{format:?}"); + } + } +} + +#[test] +fn write_then_read_keeps_times_and_text() { + let doc = sample_document(); + for (format, _, _) in FORMATS { + let bytes = write(&doc, format, WriteOptions::default()); + let back = parse(&bytes, format).unwrap_or_else(|e| panic!("{format:?}: {e}")); + assert_eq!(back.cues.len(), doc.cues.len(), "{format:?}"); + let tolerance = match format { + Format::MicroDvd => 25 * MS, + Format::Mpl2 => 50 * MS, + _ => 5 * MS, + }; + for (b, d) in back.cues.iter().zip(&doc.cues) { + assert!((b.start.0 - d.start.0).abs() <= tolerance, "{format:?} start {:?} against {:?}", b.start, d.start); + assert!((b.end.0 - d.end.0).abs() <= tolerance, "{format:?} end {:?} against {:?}", b.end, d.end); + } + assert_eq!(back.cues[0].text.lines().count(), 2, "{format:?} keeps the line break"); + assert_eq!(plain(&back.cues[1]), "straight after, with & and <", "{format:?}"); + } +} + +#[test] +fn styles_survive_where_the_format_has_them() { + let doc = Document { + cues: vec![Cue { start: ms(0), end: ms(2000), text: "plain\nslanted".into(), ..Default::default() }], + ..Default::default() + }; + for format in [Format::MicroDvd, Format::Mpl2] { + let back = parse(&write(&doc, format, WriteOptions::default()), format).expect("parse"); + assert_eq!(back.cues[0].text, "plain\nslanted", "{format:?}"); + } + // SAMI keeps inline tags too. + let doc = Document { + cues: vec![Cue { start: ms(0), end: ms(2000), text: "a bold and more".into(), ..Default::default() }], + ..Default::default() + }; + assert_eq!(parse(&write(&doc, Format::Sami, WriteOptions::default()), Format::Sami).expect("parse").cues[0].text, doc.cues[0].text); +} + +#[test] +fn microdvd_counts_frames_at_the_given_rate() { + let doc = Document { cues: vec![Cue { start: Tick(2 * T), end: Tick(4 * T), text: "x".into(), ..Default::default() }], ..Default::default() }; + let bytes = write(&doc, Format::MicroDvd, WriteOptions { rate: Some(FrameRate::FPS_25), ..Default::default() }); + assert_eq!(String::from_utf8(bytes.clone()).expect("utf8"), "{1}{1}25.000\n{50}{100}x\n"); + let back = parse(&bytes, Format::MicroDvd).expect("parse"); + assert_eq!((back.cues[0].start, back.cues[0].end), (Tick(2 * T), Tick(4 * T))); + + for header in ["{1}{1}25.000", "{0}{0}25.000"] { + let fixture = format!("{header}\n{{50}}{{100}}First cue\n{{100}}{{150}}23.976\n"); + let parsed = parse(fixture.as_bytes(), Format::MicroDvd).expect("parse rate header fixture"); + assert_eq!(parsed.cues.len(), 2, "{header}"); + assert_eq!((parsed.cues[0].start, parsed.cues[0].end), (Tick(2 * T), Tick(4 * T)), "{header}"); + assert_eq!((parsed.cues[1].start, parsed.cues[1].end), (Tick(4 * T), Tick(6 * T)), "{header}"); + assert_eq!(parsed.cues[1].text, "23.976", "{header}"); + } +} + +#[test] +fn detection_finds_each_format() { + for (format, text) in samples() { + assert_eq!(detect(text.as_bytes(), None), Some(format), "{format:?}"); + let ext = FORMATS.iter().find(|f| f.0 == format).map(|f| f.2); + assert_eq!(detect(text.as_bytes(), ext), Some(format), "{format:?} with its extension"); + } + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nx\n", None), Some(Format::Srt)); + // Cue text containing literal SubViewer markers must not hijack SRT detection + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nHere is a [SUBTITLE] tag\n", None), Some(Format::Srt)); + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n[INFORMATION] about movie\n", None), Some(Format::Srt)); + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", None), Some(Format::Srt)); + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", Some("srt")), Some(Format::Srt)); + // TTML with namespaced sami element is not SAMI + assert_ne!(detect(b"", None), Some(Format::Sami)); + // Genuine SubViewer with only [SUBTITLE] header + assert_eq!(detect(b"[SUBTITLE]\n00:00:01.00,00:00:02.00\nText\n", None), Some(Format::SubViewer)); + // Genuine SubViewer with long/truncated [TITLE] line + let truncated_sv = format!("[INFORMATION]\n[TITLE]{}", "A".repeat(5000)); + assert_eq!(detect(truncated_sv.as_bytes(), None), Some(Format::SubViewer)); + assert_eq!(detect(b"just some prose\n", Some("txt")), None); +} + +#[test] +fn other_text_is_not_one_of_these_formats() { + for (format, _, _) in FORMATS { + assert!(parse(b"hello there\nthis is not a subtitle file\n", format).is_err(), "{format:?}"); + assert!(parse(b"", format).expect("empty").cues.is_empty(), "{format:?}"); + } +} + +#[test] +fn hostile_input_is_an_error_or_a_warning_never_a_panic() { + let mut inputs: Vec> = vec![ + "{".repeat(10_000).into_bytes(), + "{1}{1}".repeat(2000).into_bytes(), + "{999999999}{999999999}x\n{1}{99999999999999999999}y\n{5}{3}z\n".into(), + "[999999999][999999999]x\n[1][2".into(), + "99999:99:99.99,99999:99:99.99\nx\n\n00:00:01.00,00:00:00.00\ny\n".into(), + "99999999:00:00=x\n00:60:00=y\n00:00:00.=z\n".into(), + "

xy<<<<&&&&�&#x;".into(), + format!("{}", "".repeat(10_000)).into_bytes(), + format!("{}", "<".repeat(10_000)).into_bytes(), + vec![0xff, 0xfe, 0x00, 0xd8, 0x00], + vec![0u8; 1000], + ]; + // deterministic noise + let mut x = 0x9e37_79b9u32; + for len in [10usize, 100, 1000] { + let alphabet = b"{}[]<>:=,. \n|&#;0123456789abSYNC"; + let noise: Vec = (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + alphabet[x as usize % alphabet.len()] + }) + .collect(); + inputs.push(noise); + } + for (format, _, _) in FORMATS { + for input in &inputs { + if let Ok(doc) = parse(input, format) { + // what was read writes and reads again + let again = write(&doc, format, WriteOptions::default()); + parse(&again, format).expect("a written file reads back"); + } + } + } +} + +#[test] +fn the_cue_limit_applies() { + let mut text = String::new(); + for i in 0..200 { + text.push_str(&format!("[{}][{}]x\n", i * 10, i * 10 + 5)); + } + assert_eq!(parse(text.as_bytes(), Format::Mpl2).expect("parse").cues.len(), 200); +} diff --git a/crates/captions/tests/it/main.rs b/crates/captions/tests/it/main.rs index 7d8070cad6..9cb0535be6 100644 --- a/crates/captions/tests/it/main.rs +++ b/crates/captions/tests/it/main.rs @@ -1,4 +1,5 @@ mod ass; +mod legacy_text; mod limits; mod literal_roundtrips; mod mcc_708_timing; diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml index edeb8d72e2..f208a7ef47 100644 --- a/crates/cdr/Cargo.toml +++ b/crates/cdr/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-cdr" -description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing" +description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings" version.workspace = true edition.workspace = true license.workspace = true @@ -11,7 +11,7 @@ repository.workspace = true workspace = true [features] -# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer. +# Synthetic-file builders for tests and fuzz seeds, of every version; `write` is the crate's writer. synth = [] [dependencies] diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 7c3ddadbb5..a7974a705d 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -1,7 +1,8 @@ # Where each layout comes from -The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and -`tests/it/provenance.rs` fails when a cited id has no row here. +The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15 +files by the same rows, with R64 to R73 for what only the writer needs. Code cites a row by its id +(`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here. Sources: @@ -18,8 +19,9 @@ Sources: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE), https://www.rfc-editor.org/rfc/rfc1951 - **F**: the magic database of the `file` utility (BSD-2-Clause), - https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and - https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images, + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff and + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/archive - **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0, https://pronom.nationalarchives.gov.uk/fmt/467.xml, https://pronom.nationalarchives.gov.uk/fmt/466.xml and @@ -119,7 +121,7 @@ file is committed. | R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | | R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec | | R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) | -| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | +| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | | R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | | R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | | R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | @@ -130,3 +132,13 @@ file is committed. | R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) | | R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) | | R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample | +| R64 | A package of versions 14 to 16 starts with a stored member `mimetype` holding `application/x-vnd.corel.draw.document+zip`; in versions 14 and 15 the RIFF file follows in `content/riffData.cdr` (R25) | F `archive` L1902-L1906 (a first member named `mimetype` at offset 30, stored, with no extra field), L2071-L2077 (the text at offsets 50 and 62); S: every file of LT `testset/15` | public-spec | +| R65 | A `trfd` record has a fourth header field, 0xFFFF, after where its offsets lie; in version 15 its offsets table starts at byte 16; each entry starts with the tag 1300 and a u32 before its type, and a matrix entry ends with 8 bytes after the six f64. The specification names the u32 `len_body`; every sample entry holds 0 there, and the writer writes 0 | KF L1079-L1106 (the 0xFFFF field), L1134-L1141 (the tag and `len_body`); S: every `trfd` record of the 15 files of LT `testset/15` without text (96 bytes, the offsets 24 and 96) | public-spec (the u32 after the tag and the 8 bytes at the end: sample) | +| R66 | A fill's property list from version 13 ends with an empty property (type 0, length 0), then two u16, the overprint flag (u32), an angle and a u32, inside the list's length; a uniform fill's record ends with 8 bytes after the list. The specification names 0, 45 degrees and 60 as the usual values of the first u16, the angle and the last u32, and lists 0, 1 and 13 for the flag | K L1100-L1121 (the 8 bytes), L1122-L1186 (the list and its end); S: the uniform fills of LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr`, whose lists hold 0 in the flag, 45 degrees and 60 there | public-spec | +| R67 | Byte 2 of an object's `flgs` holds 0x08 when the object carries argument 8000 and 0x10 when it is a clipping container (argument 8005); the group of `LIST clpt` that a container clips has 0x80 there | S: LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr` (0x08), `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (0x10 on the container, 0x80 on the clipped group) and `square_blackfill_nooutline_cdr15.cdr` (0 on a plain object) | sample (the reader does not use these bits) | +| R68 | Bit 2 of a point's type byte marks a node that can be edited. In most of the specification's samples it is set on move points and on line and curve ends and clear on control points and on the end that closes a subpath, with exceptions in a few samples of versions 13 and 14; the writer uses that common pattern. A closed subpath ends with an explicit line or curve end at its move point's coordinates, carrying bit 3 | K L2747-L2789 (`can_modify`, `is_closing_path`, from the specification's notes on its sample files) | public-spec (the reader does not use bit 2) | +| R69 | In a version 1300 uniform transparency record (R47), the u32 at byte 105 is a fill id, followed by 8 bytes. The sample's record also holds 261 as a u32 at byte 0, 0xFFFFFFFF at byte 57, 100.0 as an f64 at byte 69 and 2 at byte 81, and 0 in every other byte outside the fields R47 names | KF L707-L745 (`fill_id`); S: the record of LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr` names fill 1, a uniform fill of RGB 255, 255, 255 | public-spec (the field), sample (the white fill and the other values, which the writer writes as the sample holds them; the reader does not use them) | +| R70 | Argument 40050 of a layer is a 16-byte id, different for each layer. The other pages hold an entry for each of the master page's guides, desktop and grid layers: a layer with byte 2 of its flags set and the master layer's object type, name and id, holding nothing; the guides and desktop entries come before the page's own layers and the grid entry after them. The master page holds a guides, a desktop and a grid layer, the grid hidden and locked | K L873-L883 (the id, and the master page's layers named from the other pages by the same id); S: LT `square_blackfill_nooutline_cdr15.cdr` (the master page's three layers, and the entries on its page, in that order, with the master layers' ids) | public-spec (the id), sample (the entries and their order; the reader does not use the id, and leaves the entries out as empty layers that are not drawing layers) | +| R71 | An `outl` chunk from version 13 holds records up to the one of id 1, whose length the specification's samples give as the bytes left in the chunk less 8. In the version 15 samples the id 1 record holds 130 bytes, 8 bytes follow it, and its body holds an f64 1 at bytes 16 and 48, 45 degrees at byte 84 and 60 at byte 88; the writer writes that layout and those values. A record of id 2 holds a color property list that ends at its empty property, without the fields R66 names after a fill's list | KF L1158-L1244 (the records, type 2 a color property list, and the id 1 length in its samples); S: the 18 `outl` chunks of the LT `testset/15` files without text (each 237 bytes, the id 1 record 130 bytes long with those values and 8 bytes of 0 after it, the id 2 record 43 bytes long) | public-spec (the record types and the length), sample (the values; the reader does not use them) | +| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) | +| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 7a842a3abc..37a3424e2e 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -1,10 +1,12 @@ # craft-cdr -A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates). +A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates), and a +writer of version 15 drawings. It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its compressed lists, the ZIP packages that versions 14 and later save (with the data streams of versions 16 and later) and the records listed below, and hands the engine a drawing in points, -with each object's transform. It does not write `.cdr` files. +with each object's transform. `write` writes a drawing back out as a `.cdr` file of version 15 +(see [Writing](#writing)). ## What is read @@ -95,9 +97,68 @@ arrowheads and lenses are not read; the drawing's `warnings` name each kind it h path is left out and the objects it clips are read without it. Files in big-endian byte order and files with 16-bit coordinates are refused. +## Writing + +`write` writes a drawing as a `.cdr` file of version 15: a ZIP package whose first member, +`mimetype`, names the format and whose member `content/riffData.cdr` holds the RIFF file. Each +record is laid out as the reader reads it, by the `PROVENANCE.md` rows it cites. The reader reads +the written file back as the drawing it was written from, to the precision the file stores +(1/254000 inch for coordinates, 1/255 for color components), with the changes listed below the +table. + +| In the drawing | Written as | +|---|---| +| Pages and their sizes; the drawing's page size | pages with a page size argument; `mcfg` | +| The master page's layers and the drawing's guidelines | the master page, with a guides, a desktop and a grid layer | +| Layers: name, kind, hidden and locked | layers with their flags and their kind as the object type | +| Guidelines of a layer | guideline objects in that layer | +| Groups, and clipping containers with the objects they clip | `LIST grp ` lists; containers naming groups of the document's `LIST clpt` | +| Paths, rectangles with each corner's radius, ellipses | curves, rectangles of the version 15 layout, ellipses | +| Uniform fills and outlines (width, color, caps, joins, dashes, behind the fill, scaled with the shape) | fill and outline records, one for each different fill or outline | +| RGB, CMYK, gray, registration and spot colors | color models 5, 3, 9 and 20; a spot color as its look with its tint and its name | +| The nonzero fill rule, opacity and blend modes | the winding argument and the uniform transparency argument | + +Opacity is written as the reader reads argument 8000 (R47), and the fill rule as the reader reads +argument 14001 (R52). The uniform transparency of every public sample R47 cites is 50%, and the +specifications R52 cites do not say which fill rule each winding value means, so the direction of +the opacity value and the value written for nonzero rest on the reader's own reading. Each layer +gets an id (argument 40050), and every other page names the master page's guides, desktop and grid +layers by those ids (R70); the master page's drawing layers are not named from the other pages. + +The drawing's version and warnings are not written. A group that holds no shape or container is +left out, a clipping container whose objects hold none is written as a plain shape, a subpath +without segments is left out, as the reader leaves it out, and a drawing without pages gets one +empty page. A closed subpath whose last segment ends away from its start gets a closing line to +its start, as the file closes subpaths with an explicit point. A drawing without a page size of +its own is written without `mcfg`. Guidelines on the master page's layers read back as the +drawing's guidelines. An empty layer of a page other than a drawing layer, and an empty layer of +the master page, are written and read back left out, as the reader leaves out such layers in any +file. A guideline on a hidden layer reads back hidden, and a guideline angle past the field's +range is written as the same angle within one turn. Hidden groups and objects carry the same hide +bit as hidden layers (R19); the specification's notes date that bit on groups and objects to a +later program release than version 15 files, so a program of that version may show them. A spot +color without a look is written with a black look. Dash lengths are written to whole outline +widths and spot color tints to whole percent, as the file stores them. + +Writing refuses a drawing that the reader would not read whole within the same `Limits` +(objects, coordinates, dashes, arguments, chunks, clipped chunks, nesting depth, clip nesting, +members and sizes), and groups nested deeper than the nesting depth, groups that hold nothing +included. It also refuses what the file cannot hold or the reader would read back otherwise +changed: a coordinate past 32 bits of 1/254000 inch, a number that is not finite, a page width or +height that rounds to less than one coordinate unit, a negative outline width or a positive one +that rounds to 0, a corner radius below 0 or more than a billionth past half the rectangle's +shorter side (a radius within that is written as half), a color value, tint or opacity outside 0 +to 1, more than 10 dash lengths, a negative one or one that rounds past 65,535, a pattern whose +lengths all round to 0, a name longer than 256 UTF-16 units or holding a NUL, a spot color without +a name, at a tint that rounds to 0 percent or at a tint too low for its look to read back within +one step of 1/255, objects on the master page's grid layer, and a guideline at the edge of the +coordinate range with no room for a second point on it whose rounded coordinates lie within 1 +degree of its angle. + ## Provenance -`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status. +`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writer +needs, with their public sources and status. Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row. The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the `synth` feature); no third-party file is committed. diff --git a/crates/cdr/src/cmx.rs b/crates/cdr/src/cmx.rs index 4960c4b8df..9dee077b26 100644 --- a/crates/cdr/src/cmx.rs +++ b/crates/cdr/src/cmx.rs @@ -4,6 +4,8 @@ //! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses //! are left out with a warning. +use std::collections::BTreeSet; + use crate::bytes::{Rd, u32_at}; use crate::geometry::path_of; use crate::layout::{self, Profile}; @@ -19,6 +21,16 @@ const FORM: [u8; 4] = *b"CMX1"; const DEFAULT_UNIT: f64 = 1e-7; /// How far past a chunk that runs short the next chunk id is looked for (R53). const RESYNC: usize = 64; +/// How many steps (a chunk, or a jump over stray bytes) the reader walks on from a position it +/// could resume at, to compare it with the first chunk id found (R53). +const LOOKAHEAD: usize = 16; +/// The work counted for one step of a walk ([`walk`]) against [`PROBE_FLOOR`] (R53). +const STEP_COST: usize = 64; +/// The least work one read may spend on recoveries after stray bytes (R53), counted as +/// [`STEP_COST`] for each step of a walk and as the length of each page body judged. A read may +/// spend four times the length of the RIFF form, cut at the file's length, when that is more. Past it, the reader resumes at the +/// first chunk id found. +const PROBE_FLOOR: usize = 1 << 20; /// The chunks the reader uses (R53 to R60). const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"]; /// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them. @@ -52,6 +64,15 @@ struct Chunk<'a> { id: [u8; 4], body: &'a [u8], start: usize, + /// Only a recovery after stray bytes reads the chunk ([`inner_page`]): the header or a table + /// is taken from it only when no other chunk of its id is read, and a page is kept only when it + /// reads with objects and without damage in its instructions. + recovered: bool, +} + +/// The first chunk of id `id` that is not recovered, or else the first recovered one. +fn first_of<'c, 'a>(chunks: &'c [Chunk<'a>], id: &[u8; 4]) -> Option<&'c Chunk<'a>> { + chunks.iter().find(|c| c.id == *id && !c.recovered).or_else(|| chunks.iter().find(|c| c.id == *id)) } /// The tables that page instructions refer to by 1-based index (R55 to R59). @@ -66,9 +87,35 @@ struct Tables { /// Line type, screen, color, arrowheads, pen and dashes. outlines: Vec>, arrowheads: Vec<(u16, u16)>, + /// Missing entries are not reported as damage: a page is read only to judge its instructions + /// ([`page_reads`]). + quiet: bool, } +/// The drawing in `bytes` (R53 to R63). When the chunks that only a recovery after stray bytes +/// reads make the read stop at a limit, the file is read again without the recovery, with the +/// warning for limits. pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result { + let fresh = budget.clone(); + match read_drawing(bytes, budget, true) { + Err(Error::Limit(_)) => { + *budget = fresh; + let mut d = read_drawing(bytes, budget, false)?; + push(&mut d.warnings, Warning::TooDeep); + Ok(d) + } + read => read, + } +} + +/// The drawing as the reader reads it when it resumes after stray bytes only at the first chunk +/// id found, never at a page inside that chunk (R53). +#[cfg(any(test, feature = "synth"))] +pub(crate) fn drawing_without_recovery(bytes: &[u8], budget: &mut Budget) -> Result { + read_drawing(bytes, budget, false) +} + +fn read_drawing(bytes: &[u8], budget: &mut Budget, recover: bool) -> Result { if !is_cmx(bytes) { return Err(Error::NotCmx); } @@ -76,8 +123,8 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result {} Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")), @@ -86,15 +133,38 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT); let unit = meters / 0.0254 * 72.0; let tables = Tables::read(&chunks, unit, budget, &mut warn)?; + // The pages read without the recovery go first, so that recovered pages spend only what the + // limits leave after them; the pages keep the order of the file. let mut pages = Vec::new(); - for c in chunks.iter().filter(|c| c.id == *b"page") { - pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?); + for c in chunks.iter().filter(|c| c.id == *b"page" && !c.recovered) { + pages.push((c.start, PageRead::new(&tables, unit, budget, &mut warn).read(c)?)); } + for c in chunks.iter().filter(|c| c.id == *b"page" && c.recovered) { + // A recovered page is judged however much the recoveries spent. One that a limit stops, + // or leaves without objects, is left out with the warning that says so; one the limits + // cut short is read as far as they allow, as the other pages are. + let read = match judgement(c, budget) { + Ok((true, false, _)) => PageRead::new(&tables, unit, budget, &mut warn).read(c), + Ok((_, _, true)) | Err(Error::Limit(_)) => { + push(&mut warn, Warning::TooDeep); + continue; + } + _ => continue, + }; + match read { + Ok(page) => pages.push((c.start, page)), + Err(Error::Limit(_)) => push(&mut warn, Warning::TooDeep), + Err(e) => return Err(e), + } + } + pages.sort_by_key(|(start, _)| *start); + let pages = pages.into_iter().map(|(_, page)| page).collect(); Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) } -/// The chunks of the file in order, those inside `LIST` chunks in place (R53). -fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Result>, Error> { +/// The chunks of the file in order, those inside `LIST` chunks in place (R53). With `recover`, the +/// reader may resume after stray bytes at a page inside the first chunk id found ([`inner_page`]). +fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec, recover: bool) -> Result>, Error> { let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len()); if declared > b.len() { // The file was cut short of the size its header gives. @@ -102,15 +172,23 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Resu } let end = declared.min(b.len()); let mut out = Vec::new(); - // (position, end, depth) of the lists still to walk; a list's children go before the rest of - // the list that holds it. - let mut stack = vec![(12usize, end, 0usize)]; - while let Some((mut pos, end, depth)) = stack.pop() { + // Where the chunks start that only a recovery reads ([`rejoins`]). + let mut extra = BTreeSet::new(); + // The work the recoveries may still spend ([`PROBE_FLOOR`]). + let mut left = end.saturating_mul(4).max(PROBE_FLOOR); + // (position, end, depth, recovered) of the lists still to walk; a list's children go before + // the rest of the list that holds it. + let mut stack = vec![(12usize, end, 0usize, false)]; + while let Some((mut pos, end, depth, in_recovered)) = stack.pop() { while pos.saturating_add(8) <= end { let Some(id) = Rd::at(b, pos).fourcc() else { break }; if !is_id(&id) { - match resync(b, pos, end) { - Some(next) => { + match resync(b, pos, end, depth, recover.then_some(&*budget), &mut left) { + Some((next, damaged, found)) => { + if damaged { + push(warn, Warning::Damaged); + } + extra.extend(found); pos = next; continue; } @@ -126,30 +204,38 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Resu let stop = start.saturating_add(size); if stop > end { // Stray bytes that happen to start with four letters give a length past the list: - // look for the next chunk id after them. A chunk the reader uses is kept, cut at - // the end of the list. - if !READ_IDS.contains(&id) - && let Some(next) = resync(b, pos, end) - { + // look for the next chunk id after them, and report the damage. A chunk the reader + // uses is kept, cut at the end of the list, unless it is a page that holds a page + // the reader resumes at. + push(warn, Warning::Damaged); + let resume = if !READ_IDS.contains(&id) { + resync(b, pos, end, depth, recover.then_some(&*budget), &mut left).map(|(next, _, found)| (next, found)) + } else if recover && id == *b"page" { + inner_page(b, pos, end, depth, budget, &mut left) + } else { + None + }; + if let Some((next, found)) = resume { + extra.extend(found); pos = next; continue; } - push(warn, Warning::Damaged); } let stop = stop.min(end); let next = stop.saturating_add(size & 1); + let recovered = in_recovered || extra.contains(&pos); if id == LIST { if depth >= budget.limits.depth { push(warn, Warning::TooDeep); pos = next; continue; } - stack.push((next, end, depth)); - stack.push((start + 4, stop, depth + 1)); + stack.push((next, end, depth, in_recovered)); + stack.push((start + 4, stop, depth + 1, recovered)); break; } if let Some(body) = b.get(start..stop) { - out.push(Chunk { id, body, start }); + out.push(Chunk { id, body, start, recovered }); } pos = next; } @@ -162,15 +248,199 @@ fn is_id(t: &[u8]) -> bool { matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' ')) } -/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`] -/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list -/// that ends at `end` (R53). -fn resync(b: &[u8], pos: usize, end: usize) -> Option { - let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end); - let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p))); +/// The chunk id at `p`, when the four bytes there read as one. +fn id_at(b: &[u8], p: usize) -> Option<[u8; 4]> { + Rd::at(b, p).fourcc().filter(|id| is_id(id)) +} + +/// Where the body of the chunk at `p` ends by its length, before its pad byte. +fn chunk_stop(b: &[u8], p: usize) -> Option { + u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)) +} + +/// The first chunk id after `pos`, at an even distance of 2 to [`RESYNC`] bytes, that names a +/// chunk the reader uses or another chunk whose length keeps it inside the list that ends at `end` +/// (R53). +fn first_chunk(b: &[u8], pos: usize, end: usize) -> Option { + let fits = |p: usize| chunk_stop(b, p).is_some_and(|stop| stop <= end); + let chunk_at = |p: usize| id_at(b, p).is_some_and(|id| READ_IDS.contains(&id) || fits(p)); (pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p)) } +/// Where the next chunk after stray bytes at `pos` lies, whether the bytes passed over are +/// reported as damage, and where the chunks start that only the recovery reads (R53). It is +/// [`first_chunk`], or, with `judge` (the read's budget), a page inside that chunk ([`inner_page`]), +/// found with at most `left` work ([`PROBE_FLOOR`]). The flag is set when the reader resumes at an +/// inner page, or at a chunk it passes over that is not followed by another chunk id or by the end +/// of the list. `depth` is how many lists hold the one that ends at `end`. +fn resync(b: &[u8], pos: usize, end: usize, depth: usize, judge: Option<&Budget>, left: &mut usize) -> Option<(usize, bool, Vec)> { + let p = first_chunk(b, pos, end)?; + if let Some((k, found)) = judge.and_then(|budget| inner_page(b, p, end, depth, budget, left)) { + return Some((k, true, found)); + } + let known = id_at(b, p).is_some_and(|id| READ_IDS.contains(&id)); + let followed = chunk_stop(b, p).filter(|stop| *stop <= end).is_some_and(|stop| { + let n = stop.saturating_add((stop - p - 8) & 1); + n >= end || (n.saturating_add(8) <= end && id_at(b, n).is_some()) + }); + Some((p, !known && !followed, Vec::new())) +} + +/// A page the reader resumes at instead of the chunk at `p`, the first chunk id after stray bytes +/// or letters spelling `page` whose length runs past the list (R53). It is a page id at an even +/// distance of 8 to [`RESYNC`] bytes after `p`, inside the body of that chunk, whose length is not +/// 0, keeps it inside the list and, when the chunk at `p` ends inside the list, reaches the end of +/// that chunk. A `LIST`, the header and the tables at `p` are always kept. Walking on from `p` and +/// from the page by the reader's rule without this recovery must meet ([`rejoins`]). The first page +/// that meets is taken, with the chunks only the walk from it reads. The walks and the pages judged +/// spend `left` ([`PROBE_FLOOR`]); when it runs out, no page is taken. `depth` is how many lists +/// hold the one that ends at `end`. +fn inner_page(b: &[u8], p: usize, end: usize, depth: usize, budget: &Budget, left: &mut usize) -> Option<(usize, Vec)> { + let id = id_at(b, p)?; + if READ_IDS.contains(&id) && id != *b"page" { + return None; + } + let stop = chunk_stop(b, p).filter(|stop| *stop <= end); + let body_end = stop.unwrap_or(end); + // The chunk at `k` ends, with its pad byte, at or past the end of the chunk at `p`. + let reaches = + |k: usize| chunk_stop(b, k).is_some_and(|s| s > k + 8 && s <= end && stop.is_none_or(|stop| s.saturating_add((s - k - 8) & 1) >= stop)); + let mut found = (p + 8..=p.saturating_add(RESYNC).min(end.saturating_sub(8))) + .step_by(2) + .filter(|&k| k < body_end && id_at(b, k) == Some(*b"page") && reaches(k)) + .peekable(); + found.peek()?; + let lists = budget.limits.depth.saturating_sub(depth); + let first = walk(b, p, end, lists, left)?; + found.find_map(|k| { + let alt = walk(b, k, end, lists, left)?; + rejoins(b, &first, &alt, budget, left).map(|extra| (k, extra)) + }) +} + +/// Positions a walk through a list passes and the chunks it reads, for at most [`LOOKAHEAD`] +/// steps. +struct Walk { + /// Where the walk starts, and its place after each step: the position, and for each `LIST` + /// chunk it is inside, where that list's body ends and where the reader goes on after it. + at: Vec<(usize, Vec<(usize, usize)>)>, + /// Where each chunk the walk read starts, and where its body ends, cut at the end of the list + /// that holds it; a `LIST` chunk it enters counts by the chunks inside. + read: Vec<(usize, usize)>, + /// The walk left the list it started in: at its end, or at stray bytes with no chunk id after + /// them, where [`chunks`] stops reading that list too. + ended: bool, +} + +/// Walk the list that ends at `end` from `from` as [`chunks`] does without recovery, entering at +/// most `lists` nested `LIST` chunks as it does, and spending [`STEP_COST`] of `left` for each step; +/// `None` when `left` runs out first. +fn walk(b: &[u8], from: usize, end: usize, lists: usize, left: &mut usize) -> Option { + let mut w = Walk { at: vec![(from, Vec::new())], read: Vec::new(), ended: false }; + let mut pos = from; + let mut inside: Vec<(usize, usize)> = Vec::new(); + for _ in 0..LOOKAHEAD { + *left = left.checked_sub(STEP_COST)?; + let list_end = inside.last().map_or(end, |&(stop, _)| stop); + match step(b, pos, list_end) { + Some((next, Some(chunk))) if id_at(b, chunk) == Some(LIST) && inside.len() < lists => { + // [`chunks`] reads the list's children before the rest of the list that holds it. + let stop = chunk_stop(b, chunk).map_or(list_end, |stop| stop.min(list_end)); + inside.push((stop, next)); + pos = chunk + 12; + } + Some((next, chunk)) => { + w.read.extend(chunk.map(|c| (c, chunk_stop(b, c).map_or(list_end, |stop| stop.min(list_end))))); + pos = next; + } + None => match inside.pop() { + Some((_, after)) => pos = after, + None => { + w.ended = true; + break; + } + }, + } + w.at.push((pos, inside.clone())); + } + Some(w) +} + +/// One step of [`chunks`] without recovery at `pos`: the position after it, and where the chunk +/// it read starts when it read one; `None` when the walk ends there. +fn step(b: &[u8], pos: usize, end: usize) -> Option<(usize, Option)> { + if pos.saturating_add(8) > end { + return None; + } + let id = Rd::at(b, pos).fourcc()?; + if !is_id(&id) { + return first_chunk(b, pos, end).map(|next| (next, None)); + } + let size = u32_at(b, pos + 4).map_or(0, |s| s as usize); + let stop = (pos + 8).saturating_add(size); + if stop > end + && !READ_IDS.contains(&id) + && let Some(next) = first_chunk(b, pos, end) + { + return Some((next, None)); + } + Some((stop.min(end).saturating_add(size & 1), Some(pos))) +} + +/// Where the chunks start that the walk from an inner page `alt` reads and the walk from the first +/// chunk id `first` does not read with the same body, when the two walks meet at a place both pass (a position inside the +/// same lists) or both end, and `alt` reads at least what `first` reads until then (R53). The page +/// `alt` starts at reads with objects and without damage in its instructions. Each chunk the reader +/// uses that `first` reads before that point, `alt` reads too, with the same body, unless it is a +/// page that reads without objects. The pages judged spend `left`; when it runs out, or when the +/// read of a page judged stops, the walks do not meet. +fn rejoins(b: &[u8], first: &Walk, alt: &Walk, budget: &Budget, left: &mut usize) -> Option> { + let meet = first.at.iter().find(|q| alt.at.contains(q)).map(|(q, _)| *q).or((first.ended && alt.ended).then_some(usize::MAX))?; + let uses = |q: usize| q < meet && id_at(b, q).is_some_and(|id| READ_IDS.contains(&id)); + let used = |w: &Walk| -> Vec<(usize, usize)> { w.read.iter().copied().filter(|&(q, _)| uses(q)).collect() }; + let (kept, taken) = (used(first), used(alt)); + let (start, stop) = *alt.read.first()?; + if page_reads(b, start, stop, budget, left)? != (true, false) { + return None; + } + for &(q, stop) in kept.iter().filter(|q| !taken.contains(q)) { + // A page that reads without objects is the only chunk the walk from `alt` may leave out, + // or read with a body cut shorter by a list. + if id_at(b, q) != Some(*b"page") || page_reads(b, q, stop, budget, left)?.0 { + return None; + } + } + Some(taken.into_iter().filter(|q| !kept.contains(q)).map(|(q, _)| q).collect()) +} + +/// Whether the page chunk at `at` reads with objects, and whether its instructions read with +/// damage ([`judge_page`]); `None` when `left` does not cover its body or the read stops. +fn page_reads(b: &[u8], at: usize, end: usize, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> { + let stop = chunk_stop(b, at).map_or(end, |stop| stop.min(end)); + let Some(body) = b.get(at + 8..stop) else { return Some((false, true)) }; + judge_page(&Chunk { id: *b"page", body, start: at + 8, recovered: true }, budget, left) +} + +/// Whether page `c` reads with objects, and whether its instructions read with damage. It is read +/// with empty tables whose missing entries are not reported, and with a copy of `budget` so that the +/// read's own budget is not spent. The length of its body is taken from `left` first; `None` when +/// `left` holds less, or when the read stops. +fn judge_page(c: &Chunk, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> { + *left = left.checked_sub(c.body.len())?; + judgement(c, budget).ok().map(|(objects, damaged, _)| (objects, damaged)) +} + +/// Whether page `c` reads with objects, whether its instructions read with damage, and whether +/// the read left something out at one of the limits, read as [`judge_page`] reads it; the error +/// when the read stops. +fn judgement(c: &Chunk, budget: &Budget) -> Result<(bool, bool, bool), Error> { + let tables = Tables { quiet: true, ..Tables::default() }; + let mut scratch = budget.clone(); + let mut warn = Vec::new(); + let page = PageRead::new(&tables, 1.0, &mut scratch, &mut warn).read(c)?; + Ok((!page.layers.is_empty(), warn.contains(&Warning::Damaged), warn.contains(&Warning::TooDeep))) +} + /// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs /// past it (R55). fn list_end(b: &[u8], mut pos: usize) -> usize { @@ -224,7 +494,7 @@ fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result, Error> impl Tables { /// The first chunk of each table; a table that is missing is empty. fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec) -> Result { - let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body); + let first = |id: &[u8; 4]| first_of(chunks, id).map_or(&[][..], |c| c.body); // A color record of field 10 holds a property list as a `.cdr` fill does (R56). let record = layout::for_version(1300); let mut t = Tables::default(); @@ -265,26 +535,26 @@ impl Tables { } /// Entry `index` (1-based) of `list`, or `None` with a warning when there is none. - fn get(list: &[Option], index: u16, warn: &mut Vec) -> Option { + fn get(&self, list: &[Option], index: u16, warn: &mut Vec) -> Option { let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten(); - if found.is_none() { + if found.is_none() && !self.quiet { push(warn, Warning::Damaged); } found } fn color(&self, index: u16, warn: &mut Vec) -> Color { - Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) + self.get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) } /// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58). fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec) -> Option { - let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?; - let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0)); + let [line, _screen, color, arrows, pen, dash] = self.get(&self.outlines, index, warn)?; + let (flags, caps_join) = self.get(&self.line_types, line, warn).unwrap_or((2, 0)); if flags & 1 != 0 { return None; } - let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0); + let width = self.get(&self.pens, pen, warn).unwrap_or(0.0); let mut dashes = Vec::new(); if flags & 4 != 0 { let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i)); diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 8eb2d48125..5c358d2f04 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -8,7 +8,10 @@ //! //! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source //! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not -//! panic. Nothing here writes `.cdr` or `.cmx` files. +//! panic. +//! +//! [`write()`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the +//! reader reads it. Nothing here writes `.cmx` files. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -32,11 +35,13 @@ pub mod synth; #[cfg(any(test, feature = "synth"))] pub mod synth_cmx; mod wl; +mod write; mod zip; pub use limits::Limits; pub use model::{Drawing, Warning}; pub use preview::{Preview, PreviewFormat, preview}; +pub use write::{WRITTEN_VERSION, WriteError, write}; /// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file /// of version 1 or 2 whose header offsets fit the file? diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs index bb9804557f..5ceceea8ec 100644 --- a/crates/cdr/src/limits.rs +++ b/crates/cdr/src/limits.rs @@ -74,7 +74,7 @@ impl Default for Limits { } /// The running counters of one read against its [`Limits`]. -#[derive(Debug)] +#[derive(Clone, Debug)] pub(crate) struct Budget { pub(crate) limits: Limits, inflated: usize, diff --git a/crates/cdr/src/synth_cmx.rs b/crates/cdr/src/synth_cmx.rs index c70fd8545c..309840e57f 100644 --- a/crates/cdr/src/synth_cmx.rs +++ b/crates/cdr/src/synth_cmx.rs @@ -285,3 +285,12 @@ pub fn sample() -> Vec { children.extend(tables()); riff(&children) } + +/// Read `bytes` as [`crate::read_cmx`] does, except that after stray bytes the reader resumes only +/// at the first chunk id found, never at a page inside that chunk (R53). Tests compare the two. +pub fn read_cmx_without_recovery(bytes: &[u8], limits: crate::Limits) -> Result { + if bytes.len() > limits.input { + return Err(crate::Error::Limit("input size")); + } + crate::cmx::drawing_without_recovery(bytes, &mut crate::limits::Budget::new(limits)) +} diff --git a/crates/cdr/src/write.rs b/crates/cdr/src/write.rs new file mode 100644 index 0000000000..99c834a25d --- /dev/null +++ b/crates/cdr/src/write.rs @@ -0,0 +1,1486 @@ +//! Writer of `.cdr` drawings of version 15: a ZIP package (R24, R25, R64) whose member +//! `content/riffData.cdr` is the RIFF file. Each record is laid out as the reader in this crate +//! reads it, by the `PROVENANCE.md` rows the code cites, so a written file reads back as the +//! drawing it was written from. Records the reader does not read are not written. +//! +//! Writing is bounded by [`Limits`]: a drawing the reader would not read whole within the same +//! limits is refused. It never recurses and does not panic. + +use std::cell::Cell; +use std::collections::HashMap; +use std::io::Write as _; +use std::rc::Rc; + +use self::WriteError as Error; +use crate::Limits; +use crate::model::{ + Blend, Cap, Color, Drawing, Flags, Geometry, Guideline, Join, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, +}; + +/// Why a drawing can't be written. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WriteError { + /// The reader would not read the file whole within the [`Limits`] it was written for. + Limit(&'static str), + /// What the file can't hold, or what the reader would read back changed. + Unwritable(&'static str), +} + +impl std::fmt::Display for WriteError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + WriteError::Limit(what) => write!(f, "past the {what} limit"), + WriteError::Unwritable(what) => write!(f, "{what} can't be written"), + } + } +} + +impl std::error::Error for WriteError {} + +/// The version written, in hundreds, as its `vrsn` chunk names it (R2). +pub const WRITTEN_VERSION: u16 = 1500; +/// The form type of version 15: `CDR` and the letter `F` (R1). +const FORM: [u8; 4] = *b"CDRF"; +/// The package member that holds the RIFF file (R25). +const MEMBER: &[u8] = b"content/riffData.cdr"; +/// The package's first member and what it holds (R64). +const MIMETYPE_NAME: &[u8] = b"mimetype"; +const MIMETYPE: &[u8] = b"application/x-vnd.corel.draw.document+zip"; +/// Coordinate units (1/254000 inch) in a point (R5). +const UNITS_PER_PT: f64 = 254_000.0 / 72.0; +/// The tag of the record layout from version 13 (R11, R12, R47). +const TAG_1300: u32 = 1300; + +/// Object types (R6, R23). +const RECTANGLE: u32 = 1; +const ELLIPSE: u32 = 2; +const CURVE: u32 = 3; +const GUIDELINE: u32 = 0x16; +/// Argument types (R6, R20, R21, R23, R46, R47, R52, R70). +const ARG_OUTLINE: u32 = 10; +const ARG_FILL: u32 = 20; +const ARG_COORDS: u32 = 30; +const ARG_NAME: u32 = 1000; +const ARG_TRANSPARENCY: u32 = 8000; +const ARG_CONTAINER: u32 = 8005; +const ARG_WINDING: u32 = 14001; +const ARG_GUIDE: u32 = 16000; +const ARG_PAGE_SIZE: u32 = 19130; +const ARG_LAYER_ID: u32 = 40050; + +/// The most clipped groups the reader reads one inside another (`build.rs`). +const MAX_CLIP_DEPTH: usize = 64; +/// Chunks the reader counts for one object list of a clipped group, as [`Writer::shape`] lays it +/// out: the list itself, then its searches (`build.rs`, `find_own`) for its `loda` (`flgs`, `lgob`, +/// `loda`), its `flgs` (`flgs`) and its `trfd` (`flgs`, `lgob`, `loda`, `trfl`, `trfd`). +const OBJECT_WALK: usize = 1 + 3 + 1 + 5; +/// Dash and gap lengths an outline record has room for: the arrowhead ids follow 20 bytes after +/// the first dash (R12). +const MAX_DASHES: usize = 10; +/// The most UTF-16 units of a name the reader keeps whole (`records.rs`). +const MAX_NAME: usize = 256; +/// Where a guideline's second point lies along it, in points: the writer's own value. +const GUIDE_REACH: f64 = 100.0; +/// How far, in degrees, the line through a guideline's two points, once rounded, may turn from +/// its stored angle: the writer's own value. +const GUIDE_TURN: f64 = 1.0; +/// How many units along the longer axis a guideline's second point is looked for in when no +/// farther point lies along its angle: past 82 units, a rounded point turns less than +/// `GUIDE_TURN`. +const GUIDE_STEPS: i32 = 128; + +/// The `.cdr` file of `drawing`, version 15, within `limits`. +/// +/// Pages, the master page's layers and the drawing's guidelines, layers with their kinds, names +/// and flags, groups, clipping containers with the objects they clip, curves, rectangles with +/// their corners, ellipses, uniform fills, outlines, the nonzero fill rule and uniform +/// transparency with its blend mode are written. Every other page names the master page's guides, +/// desktop and grid layers by their layer ids, and not its drawing layers. The drawing's `version` +/// and `warnings` are not written, and the written file reads back with these changes: +/// +/// - Groups that hold no shape or container are left out, and a container whose objects hold none +/// is written as a plain shape. A subpath without segments is left out. A drawing without pages +/// gets one empty page. +/// - A closed subpath whose last segment ends away from its start gets a closing line to its +/// start, as the file closes subpaths with an explicit point. +/// - Guidelines on the master page's layers read back as the drawing's guidelines. An empty layer +/// of the master page, and an empty layer of a page other than a drawing layer, read back left +/// out, as the reader leaves out such layers in any file. +/// - A guideline on a hidden layer reads back hidden, as the reader marks every guideline of a +/// hidden layer. A guideline angle past the field's range is written as the same angle within +/// one turn. +/// - Dash lengths are rounded to whole outline widths and spot color tints to whole percent, as +/// the file stores them. A spot color without a look is written with a black look. +/// +/// Hidden groups and objects carry the same hide bit as hidden layers (R19). The specification's +/// notes date that bit on groups and objects to a later program release than version 15 files, so +/// a program of that version may show them. +/// +/// Fails with [`WriteError::Limit`] when the reader would not read the file whole within `limits` +/// or groups nest deeper than its nesting depth, groups that hold nothing included, and with +/// [`WriteError::Unwritable`] for what the file can't hold or the reader would read back otherwise +/// changed: a coordinate past 32 bits of 1/254000 inch; a size, matrix or angle that is +/// not finite; a page width or height that rounds to less than one coordinate unit; a negative +/// outline width, or a positive one that rounds to 0; a corner radius below 0 or more than a billionth past half the rectangle's +/// shorter side (a radius within that is written as half); a color value, tint or opacity outside +/// 0 to 1; more than 10 dash lengths, one that is negative, not finite or rounds past 65,535, or a +/// pattern whose lengths all round to 0; a name longer than 256 UTF-16 units or holding a NUL; a +/// spot color without a name, at a tint that rounds to 0 percent or at a tint too low for its look +/// to read back within one step of 1/255; objects on the master page's grid layer; a guideline at +/// the edge of the coordinate range with no room for a second point on it whose rounded +/// coordinates lie within 1 degree of its angle. +pub fn write(drawing: &Drawing, limits: Limits) -> Result, Error> { + // Every package holds two members (R64). + if limits.members < 2 { + return Err(Error::Limit("package member count")); + } + let mut w = Writer::new(limits); + // The chunks the `doc` list always holds count from the start: `vrsn`, `doc `, `filt` and + // `otlt`, and `mcfg` with a page size. + w.counted.set(4 + usize::from(drawing.page_size.is_some())); + let mut pages = Out::new(0, limits, w.total.clone(), w.counted.clone()); + w.master_page(&mut pages, drawing)?; + if drawing.pages.is_empty() { + // A drawing has at least one page, with one layer. + pages.open(b"page")?; + pages.chunk(b"flgs", &PAGE_FLAGS)?; + pages.open(b"gobj")?; + w.master_refs(&mut pages, false)?; + let id = w.layer_id()?; + w.layer(&mut pages, &LayerParts { name: "Layer 1", kind: LayerKind::Drawing, flags: Flags::default(), master: false, id }, &[], [&[], &[]])?; + w.master_refs(&mut pages, true)?; + pages.close()?; + pages.close()?; + } + for page in &drawing.pages { + w.page(&mut pages, page)?; + } + let clips = w.clipped_groups()?; + // The bytes of each layer id after its count come from hashes of what is written, so + // different drawings get different ids and the same drawing the same ones (R70). + // A CRC-32 and a 64-bit FNV-1a hash of the same bytes. + let config = drawing.page_size.map(mcfg).transpose()?; + let (mut crc, mut fnv) = (crc32fast::Hasher::new(), 0xcbf2_9ce4_8422_2325_u64); + let mut hash = |part: &[u8]| { + crc.update(part); + for b in part { + fnv = (fnv ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3); + } + }; + for part in [&pages.buf[..], clips.as_ref().map_or(&[][..], |c| &c.buf), config.as_deref().unwrap_or_default()] { + hash(part); + } + // Each record as its chunk holds it: the id, then the body. + for (id, body) in w.fills.bodies.iter().chain(&w.outlines.bodies) { + hash(&id.to_le_bytes()); + hash(body); + } + let mut salt = [0u8; 12]; + for (slot, b) in salt.iter_mut().zip(crc.finalize().to_le_bytes().into_iter().chain(fnv.to_le_bytes())) { + *slot = b; + } + for &at in &w.id_at { + if let Some(slot) = pages.buf.get_mut(at + 4..at + 16) { + slot.copy_from_slice(&salt); + } + } + // The `doc` list's count starts with the RIFF header and the pages, which follow it. + // Its chunk count starts with the chunks of the pages and the clipped groups. + let streams = pages.chunks.saturating_add(clips.as_ref().map_or(0, |c| c.chunks)); + let mut doc = Out::new(0, limits, Rc::new(Cell::new(pages.buf.len().saturating_add(12))), Rc::new(Cell::new(streams))); + // The version chunk comes first (R2). + doc.chunk(b"vrsn", &WRITTEN_VERSION.to_le_bytes())?; + doc.open(b"doc ")?; + if let Some(config) = &config { + doc.chunk(b"mcfg", config)?; + } + // Each fill record in a `LIST filc` of its own (R72). + doc.open(b"filt")?; + for (id, body) in &w.fills.bodies { + doc.open(b"filc")?; + doc.chunk_of(b"fild", &[&id.to_le_bytes(), body])?; + doc.close()?; + } + doc.close()?; + doc.open(b"otlt")?; + for (id, body) in &w.outlines.bodies { + doc.chunk_of(b"outl", &[&id.to_le_bytes(), body])?; + } + doc.close()?; + // The clipped groups end the `doc` list; their bytes follow its stream in the file. + let clipped = clips.as_ref().map_or(&[][..], |c| &c.buf); + if clips.is_some() { + doc.tail(b"clpt", clipped.len())?; + } + doc.close()?; + // The reader takes the RIFF file within the input size too, once it is out of the package. + let len = 12usize.saturating_add(doc.buf.len()).saturating_add(clipped.len()).saturating_add(pages.buf.len()); + fits_stream(&limits, len)?; + let mut head = b"RIFF".to_vec(); + head.extend(len32(len - 8)?.to_le_bytes()); + head.extend(FORM); + let file = package(&[&head, &doc.buf, clipped, &pages.buf])?; + if file.len() > limits.input { + return Err(Error::Limit("input size")); + } + Ok(file) +} + +/// Checks that `n` bytes of the RIFF file fit what a read takes: it takes the file as input, as an +/// inflated package member and within the inflated bytes of the whole file. The error names the +/// smallest of those limits. +fn fits_stream(limits: &Limits, n: usize) -> Result<(), Error> { + let (max, what) = [(limits.input, "input size"), (limits.member, "member size"), (limits.inflated, "inflated size")] + .into_iter() + .min_by_key(|(max, _)| *max) + .unwrap_or((0, "input size")); + if n > max { Err(Error::Limit(what)) } else { Ok(()) } +} + +/// A u32 length field, or the size limit. +fn len32(n: usize) -> Result { + u32::try_from(n).map_err(|_| Error::Limit("output size")) +} + +/// A chunk stream being written: chunks and lists, with each list's size filled in when it closes +/// (R4). +struct Out { + buf: Vec, + /// Where each open list's size field lies. + open: Vec, + /// Lists around this stream's own in the file. + base: usize, + /// Chunks written, lists included. + chunks: usize, + limits: Limits, + /// Bytes of the RIFF file written so far, by every stream that shares the count. + total: Rc>, + /// Chunks of the RIFF file counted so far, lists included, by every stream that shares the + /// count. + counted: Rc>, + /// Bytes that follow the stream in the file and belong to its open lists (see `tail`). + after: usize, +} + +impl Out { + fn new(base: usize, limits: Limits, total: Rc>, counted: Rc>) -> Out { + Out { buf: Vec::new(), open: Vec::new(), base, chunks: 0, limits, total, counted, after: 0 } + } + + fn count(&mut self) -> Result<(), Error> { + self.chunks = self.chunks.saturating_add(1); + self.counted.set(self.counted.get().saturating_add(1)); + self.room_for_chunks(0) + } + + fn room_for_chunks(&self, more: usize) -> Result<(), Error> { + if self.counted.get().saturating_add(more) > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) } + } + + /// Checks that `lists` more lists nested in the open ones and `chunks` more chunks, lists + /// included, fit what a read takes, before anything is written. + fn fits(&self, lists: usize, chunks: usize) -> Result<(), Error> { + if self.base + self.open.len() + lists > self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + self.room_for_chunks(chunks) + } + + /// Checks that `n` more bytes keep the file within what a read takes. + fn room(&self, n: usize) -> Result<(), Error> { + fits_stream(&self.limits, self.total.get().saturating_add(n)) + } + + fn put(&mut self, bytes: &[u8]) { + self.buf.extend(bytes); + self.total.set(self.total.get().saturating_add(bytes.len())); + } + + fn chunk(&mut self, id: &[u8; 4], body: &[u8]) -> Result<(), Error> { + self.chunk_of(id, &[body]) + } + + /// A chunk whose body is `parts`, one after another. + fn chunk_of(&mut self, id: &[u8; 4], parts: &[&[u8]]) -> Result<(), Error> { + let len = parts.iter().fold(0usize, |n, p| n.saturating_add(p.len())); + self.count()?; + self.room(len.saturating_add(8 + len % 2))?; + self.put(id); + self.put(&len32(len)?.to_le_bytes()); + for p in parts { + self.put(p); + } + if len % 2 == 1 { + self.put(&[0]); + } + Ok(()) + } + + /// A `loda` chunk of a record of object type `kind` (R6): length, argument count, where the + /// offsets and the types lie, the type; the arguments; the offsets with one more for the end; + /// the types in reverse. The arguments are copied straight into the stream. + fn loda(&mut self, kind: u32, args: &[(u32, Vec)]) -> Result<(), Error> { + const HEAD: usize = 20; + let body = args.iter().fold(0usize, |n, (_, a)| n.saturating_add(a.len())); + let offsets_at = HEAD.saturating_add(body); + let types_at = offsets_at.saturating_add((args.len() + 1).saturating_mul(4)); + let len = types_at.saturating_add(args.len().saturating_mul(4)); + self.count()?; + self.room(len.saturating_add(8 + len % 2))?; + self.put(b"loda"); + self.put(&len32(len)?.to_le_bytes()); + for v in [len, args.len(), offsets_at, types_at] { + self.put(&len32(v)?.to_le_bytes()); + } + self.put(&kind.to_le_bytes()); + for (_, a) in args { + self.put(a); + } + let mut at = HEAD; + for (_, a) in args { + self.put(&len32(at)?.to_le_bytes()); + at += a.len(); + } + self.put(&len32(at)?.to_le_bytes()); + for (t, _) in args.iter().rev() { + self.put(&t.to_le_bytes()); + } + if len % 2 == 1 { + self.put(&[0]); + } + Ok(()) + } + + /// Opens a list of `form`. The reader reads the chunks of a list nested at most `depth` deep. + fn open(&mut self, form: &[u8; 4]) -> Result<(), Error> { + self.count()?; + if self.base + self.open.len() + 1 > self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + self.room(12)?; + self.put(b"LIST"); + self.open.push(self.buf.len()); + self.put(&[0; 4]); + self.put(form); + Ok(()) + } + + fn close(&mut self) -> Result<(), Error> { + let at = self.open.pop().ok_or(Error::Limit("output size"))?; + let len = (self.buf.len() + self.after) - at - 4; + let field = len32(len)?.to_le_bytes(); + if let Some(slot) = self.buf.get_mut(at..at + 4) { + slot.copy_from_slice(&field); + } + if len % 2 == 1 { + // A pad byte would go after the bytes kept outside the stream. + if self.after > 0 { + return Err(Error::Limit("output size")); + } + self.put(&[0]); + } + Ok(()) + } + + /// Opens a list of `form` whose chunks, `len` bytes already laid out, follow the stream in + /// the file instead of being copied into it. Nothing more is written to the stream; only the + /// lists open around it close. + fn tail(&mut self, form: &[u8; 4], len: usize) -> Result<(), Error> { + self.open(form)?; + self.room(len)?; + self.after = len; + self.total.set(self.total.get().saturating_add(len)); + self.close() + } +} + +/// Fill or outline records by their body, numbered as they are first used. +#[derive(Default)] +struct Records { + ids: HashMap, u32>, + /// Each record's id and body, in the order they were numbered; the chunk holds the id, then + /// the body. + bodies: Vec<(u32, Rc<[u8]>)>, +} + +/// What the read of the written file will count, against the limits. +struct Writer<'d> { + limits: Limits, + /// Bytes of the RIFF file written so far: the pages, the clipped groups and the fill and + /// outline tables, held together to what a read takes. + total: Rc>, + /// Chunks of the RIFF file counted so far, held to the chunk limit: the `doc` list's own, the + /// pages', the clipped groups' and the records'. + counted: Rc>, + fills: Records, + outlines: Records, + /// The next fill or outline id. + next_id: u32, + /// The objects each container clips, by the id of its `LIST clpt` group (R46), with how many + /// clipped groups the reader has open when it reads them. + clips: Vec<(u32, &'d [Object], usize)>, + /// The clipped groups open around the objects being written. + clip_depth: usize, + objects: usize, + coordinates: usize, + dashes: usize, + /// Chunks the reader steps through inside clipped groups: each group's `spnd` and flags, each + /// object or group list, each nested group's flags, and the chunks it looks at to find each + /// object's `loda`, `flgs` and `trfd`. + clip_walked: usize, + /// Layer ids given out so far, and where each layer's id lies in the pages' stream. + layer_ids: u32, + id_at: Vec, + /// The master page's guides, desktop and grid layers, which the other pages name (R70). + master_refs: Vec<(&'d str, LayerKind, Flags, [u8; 16])>, +} + +/// What a layer list carries besides its objects and guidelines. +struct LayerParts<'a> { + name: &'a str, + kind: LayerKind, + flags: Flags, + /// On the master page, or an entry that names one of its layers. + master: bool, + /// The layer id (R70). + id: [u8; 16], +} + +/// A layer of the master page as it is written. +struct MasterLayer<'a> { + name: &'a str, + kind: LayerKind, + flags: Flags, + objects: &'a [Object], + guides: [&'a [Guideline]; 2], +} + +/// A layer id before its last 12 bytes are set for the drawing: the first four count the layers +/// (R70). +const LAYER_ID: [u8; 16] = [0; 16]; + +/// The flags of a page other than the master page (R19). +const PAGE_FLAGS: [u8; 4] = [0, 0, 0, 0x90]; + +impl<'d> Writer<'d> { + fn new(limits: Limits) -> Self { + Writer { + limits, + total: Rc::new(Cell::new(0)), + counted: Rc::new(Cell::new(0)), + fills: Records::default(), + outlines: Records::default(), + next_id: 1, + clips: Vec::new(), + clip_depth: 0, + objects: 0, + coordinates: 0, + dashes: 0, + clip_walked: 0, + layer_ids: 0, + id_at: Vec::new(), + master_refs: Vec::new(), + } + } + + /// A new layer id (R70), different from every other id in the file. + fn layer_id(&mut self) -> Result<[u8; 16], Error> { + self.layer_ids = self.layer_ids.checked_add(1).ok_or(Error::Limit("output size"))?; + let mut id = LAYER_ID; + for (slot, b) in id.iter_mut().zip(self.layer_ids.to_le_bytes()) { + *slot = b; + } + Ok(id) + } + + /// The entries that name the master page's guides, desktop and grid layers on another page + /// (R70): the grid layers' when `grids`, the others' otherwise. + fn master_refs(&mut self, out: &mut Out, grids: bool) -> Result<(), Error> { + let refs: Vec<_> = self.master_refs.iter().filter(|r| (r.1 == LayerKind::Grid) == grids).copied().collect(); + for (name, kind, flags, id) in refs { + self.layer(out, &LayerParts { name, kind, flags, master: true, id }, &[], [&[], &[]])?; + } + Ok(()) + } + + /// A `loda` record, within the arguments a read takes from one. + fn loda(&self, out: &mut Out, kind: u32, args: &[(u32, Vec)]) -> Result<(), Error> { + if args.len() > self.limits.arguments { + return Err(Error::Limit("argument count")); + } + out.loda(kind, args) + } + + /// `n` more chunks the reader steps through, counted against the clipped chunks while inside + /// a clipped group. + fn walk(&mut self, n: usize) -> Result<(), Error> { + if self.clip_depth == 0 { + return Ok(()); + } + self.clip_walked = self.clip_walked.saturating_add(n); + if self.clip_walked > self.limits.clipped_chunks { Err(Error::Limit("clipped chunk count")) } else { Ok(()) } + } + + fn take_object(&mut self) -> Result<(), Error> { + self.objects += 1; + if self.objects > self.limits.objects { Err(Error::Limit("object count")) } else { Ok(()) } + } + + /// The master page (R19, R70). + fn master_page(&mut self, out: &mut Out, drawing: &'d Drawing) -> Result<(), Error> { + out.open(b"page")?; + // Byte 2 marks the master page (R19). + out.chunk(b"flgs", &[0, 0, 1, 0x90])?; + out.open(b"gobj")?; + // The reader leaves out the master page's grid layers. + for l in drawing.master.iter().filter(|l| l.kind == LayerKind::Grid) { + if draws(&l.objects, &self.limits)? { + return Err(Error::Unwritable("objects on the master page's grid layer")); + } + } + // The drawing's master layers, with a guides, a desktop and a grid layer when they have + // none. The drawing's guidelines go in the first guides layer that is shown and unlocked, + // and in a guides layer of their own when there is none. + let made = |name, kind, flags, guides| MasterLayer { name, kind, flags, objects: &[], guides: [guides, &[]] }; + let first_guides = drawing.master.iter().position(|l| l.kind == LayerKind::Guides && l.flags == Flags::default()); + let has_guides = drawing.master.iter().any(|l| l.kind == LayerKind::Guides); + let own_guides = first_guides.is_none() && (!has_guides || !drawing.guides.is_empty()); + let guides_layer = own_guides.then(|| made("Guides", LayerKind::Guides, Flags::default(), &drawing.guides[..])); + let layers = drawing.master.iter().enumerate().map(|(i, l)| MasterLayer { + name: &l.name, + kind: l.kind, + flags: l.flags, + objects: &l.objects, + guides: [&l.guides, if Some(i) == first_guides { &drawing.guides } else { &[] }], + }); + let has_desktop = drawing.master.iter().any(|l| l.kind == LayerKind::Desktop); + let desktop = (!has_desktop).then(|| made("Desktop", LayerKind::Desktop, Flags::default(), &[])); + // A grid layer, hidden and locked as sample files hold it, when they have none; the reader + // leaves out the master page's grid layers (R70). + let has_grid = drawing.master.iter().any(|l| l.kind == LayerKind::Grid); + let grid = (!has_grid).then(|| made("Grid", LayerKind::Grid, Flags { hidden: true, locked: true }, &[])); + for l in guides_layer.into_iter().chain(layers).chain(desktop).chain(grid) { + let id = self.layer_id()?; + if l.kind != LayerKind::Drawing { + self.master_refs.push((l.name, l.kind, l.flags, id)); + } + self.layer(out, &LayerParts { name: l.name, kind: l.kind, flags: l.flags, master: true, id }, l.objects, l.guides)?; + } + out.close()?; + out.close() + } + + /// A page (R19, R21, R22): its flags, its size in its own `loda`, then its layers in a `gobj` + /// list. + fn page(&mut self, out: &mut Out, page: &'d Page) -> Result<(), Error> { + out.open(b"page")?; + out.chunk(b"flgs", &PAGE_FLAGS)?; + if let Some(size) = page.size { + let size = page_size(size)?; + out.open(b"lgob")?; + self.loda(out, 0, &[(ARG_PAGE_SIZE, size)])?; + out.close()?; + } + out.open(b"gobj")?; + // The entries for the master page's layers go around the page's own, as sample files + // place them (R70). + self.master_refs(out, false)?; + for l in &page.layers { + let id = self.layer_id()?; + self.layer(out, &LayerParts { name: &l.name, kind: l.kind, flags: l.flags, master: false, id }, &l.objects, [&l.guides, &[]])?; + } + self.master_refs(out, true)?; + out.close()?; + out.close() + } + + /// A layer (R19, R9): flags, its `loda` with its kind as the object type and its name, then + /// its objects and guidelines. + fn layer(&mut self, out: &mut Out, layer: &LayerParts, objects: &'d [Object], guides: [&[Guideline]; 2]) -> Result<(), Error> { + // The kind's low bits; bit 0x10, which also marks a grid, is the lock bit here, and the + // object type names the kind. + let (kind, byte0) = match layer.kind { + LayerKind::Drawing => (0, 0), + LayerKind::Grid => (11, 0x0a), + LayerKind::Guides => (12, 0x0a), + LayerKind::Desktop => (17, 0x08), + }; + out.open(b"layr")?; + // Byte 2 is set on the master page's layers and on the entries that name them. + out.chunk(b"flgs", &flags(layer.flags, byte0, u8::from(layer.master), 0x98))?; + out.open(b"lgob")?; + // The id is the first argument: after the chunk's header and the record's 20 bytes. + self.id_at.push(out.buf.len() + 8 + 20); + self.loda(out, kind, &[(ARG_LAYER_ID, layer.id.to_vec()), (ARG_NAME, name(layer.name)?)])?; + out.close()?; + self.objects(out, objects)?; + for g in guides.into_iter().flatten() { + self.guideline(out, g)?; + } + out.close() + } + + /// A guideline object (R23). + fn guideline(&mut self, out: &mut Out, g: &Guideline) -> Result<(), Error> { + self.take_object()?; + // The points lie along the angle as stored. + let stored = angle(g.angle)?; + let (s, c) = (f64::from(i32::from_le_bytes(stored)) / 1_000_000.0).to_radians().sin_cos(); + let along = |k: f64| -> Result, Error> { Ok([coord(g.at.x + k * c)?, coord(g.at.y + k * s)?].concat()) }; + let first = along(0.0)?; + // Whether a rounded second point lies apart from the first along the stored angle, on + // either side, within `GUIDE_TURN`. + let units = |p: &[u8], i: usize| p.get(4 * i..4 * i + 4).and_then(|b| b.try_into().ok()).map_or(0.0, |b| f64::from(i32::from_le_bytes(b))); + let along_angle = |p: &Vec| { + let (dx, dy) = (units(p, 0) - units(&first, 0), units(p, 1) - units(&first, 1)); + // With room for the floating-point error of a turn of exactly `GUIDE_TURN`. + (dx != 0.0 || dy != 0.0) && (dx * s - dy * c).abs().atan2((dx * c + dy * s).abs()) <= GUIDE_TURN.to_radians() + 1e-12 + }; + // A second point on the line: the point at the full reach, on the positive side first. + // When neither side has one in the file's range, the farthest point on each side whose + // coordinates round within the range, and of the two the one farther away. Rounding moves + // monotonically along the line, so the points that round within the range form one span + // around the first point; halving the step finds its end to the last representable + // value. Short of a farthest point along the angle, which only happens within + // `GUIDE_STEPS` units of the range's edge, the farthest rounded point of the line within + // that distance that lies along the angle, on either side. + let full = [GUIDE_REACH, -GUIDE_REACH].into_iter().find_map(|k| along(k).ok().filter(along_angle)); + let stepped = || { + // Each side's run of rounded points, walked outward from the start with `along` + // itself: a step of one unit's length at a time, and a halving search for where the + // rounded point changes, so every rounded point the line passes through is reached. + let reach = f64::from(GUIDE_STEPS) / (UNITS_PER_PT * c.abs().max(s.abs())); + let unit = 1.0 / UNITS_PER_PT; + let mut best: Option<(f64, Vec)> = None; + for side in [1.0, -1.0] { + let (mut k, mut current) = (0.0, first.clone()); + loop { + let next = |k: f64| side * (k.abs() + unit).min(reach); + let mut far = next(k); + while along(far).ok().as_ref() == Some(¤t) && far.abs() < reach { + k = far; + far = next(k); + } + if along(far).ok().as_ref() == Some(¤t) { + break; + } + let (mut same, mut changed) = (k, far); + loop { + let mid = same + (changed - same) / 2.0; + if mid == same || mid == changed { + break; + } + if along(mid).ok().as_ref() == Some(¤t) { same = mid } else { changed = mid } + } + let Ok(p) = along(changed) else { break }; + if along_angle(&p) && best.as_ref().is_none_or(|b| changed.abs() > b.0.abs()) { + best = Some((changed, p.clone())); + } + (k, current) = (changed, p); + } + } + best.map(|(_, p)| p) + }; + let farthest = |end: f64| -> Option<(f64, Vec)> { + let (mut ok, mut bad) = (0.0, end); + loop { + let mid = ok + (bad - ok) / 2.0; + if mid == ok || mid == bad { + break; + } + if along(mid).is_ok() { ok = mid } else { bad = mid } + } + along(ok).ok().map(|p| (ok, p)) + }; + let second = full + .or_else(|| { + [farthest(GUIDE_REACH), farthest(-GUIDE_REACH)] + .into_iter() + .flatten() + .filter(|(_, p)| along_angle(p)) + .reduce(|a, b| if b.0.abs() > a.0.abs() { b } else { a }) + .map(|(_, p)| p) + }) + .or_else(stepped) + .ok_or(Error::Unwritable("guidelines with no room for a second point along their angle"))?; + let mut arg = vec![0; 12]; + arg.extend(stored); + arg.extend(&first); + arg.extend(second); + arg.extend(first); + out.open(b"obj ")?; + out.chunk(b"flgs", &flags(Flags { hidden: g.hidden, locked: false }, 0, 0, 0x08))?; + out.open(b"lgob")?; + self.loda(out, GUIDELINE, &[(ARG_GUIDE, arg)])?; + out.close()?; + out.close() + } + + /// `objects`, front to back, groups nested, without recursion. + fn objects(&mut self, out: &mut Out, objects: &'d [Object]) -> Result<(), Error> { + // The objects left at each level, the layer's and then each group's, with the group's + // flags. The reader leaves out a group that holds no shape or container, so a group's list + // is written only when the first one is reached: the first `written` levels have theirs. + let mut levels = vec![(objects.iter(), Flags::default())]; + let mut written = 1; + loop { + let Some((level, _)) = levels.last_mut() else { return Ok(()) }; + let Some(object) = level.next() else { + levels.pop(); + if levels.is_empty() { + return Ok(()); + } + if written > levels.len() { + written = levels.len(); + // The reader counts a group once its objects are read. + self.take_object()?; + out.close()?; + } + continue; + }; + if let Object::Group { objects, flags } = object { + // Groups nested past the depth are refused even when they hold nothing, so the + // walk holds no more levels than that. This group is `levels.len()` deep. + if levels.len() > self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + if !objects.is_empty() { + levels.push((objects.iter(), *flags)); + } + continue; + } + for (_, f) in levels.get(written..).unwrap_or_default() { + self.walk(2)?; + out.open(b"grp ")?; + out.chunk(b"flgs", &flags(*f, 0, 0, 0x10))?; + } + written = levels.len(); + match object { + Object::Shape(s) => { + self.walk(OBJECT_WALK)?; + self.shape(out, s, None)?; + } + Object::Group { .. } => {} + Object::Clip { container, objects } => { + self.walk(OBJECT_WALK)?; + // The reader reads a container whose objects hold no shape as a plain shape. + if !draws(objects, &self.limits)? { + self.shape(out, container, None)?; + continue; + } + let depth = self.clip_depth + 1; + if depth > MAX_CLIP_DEPTH { + return Err(Error::Limit("clip nesting")); + } + // Ids 1, 2, 3 ..., the same in the container and its group's `spnd` (R46, R73). + let id = len32(self.clips.len() + 1)?; + if self.clips.is_empty() { + // The `doc` list's `LIST clpt`, which holds the clipped groups. + self.counted.set(self.counted.get().saturating_add(1)); + } + self.clips.push((id, objects, depth)); + self.shape(out, container, Some(id))?; + } + } + } + } + + /// The `LIST clpt` body: one group for each container, holding the objects it clips (R46); + /// `None` without containers. The groups' own objects may name more groups. + fn clipped_groups(&mut self) -> Result, Error> { + if self.clips.is_empty() { + return Ok(None); + } + // `doc` and `clpt` are around the groups. + let mut out = Out::new(2, self.limits, self.total.clone(), self.counted.clone()); + let mut i = 0; + // The reader steps through a clipped group's `spnd` and flags, then the lists of its + // objects, each time a container names the group; each container names its own. + while let Some(&(id, objects, depth)) = self.clips.get(i) { + i += 1; + self.clip_depth = depth; + self.walk(2)?; + out.open(b"grp ")?; + out.chunk(b"spnd", &id.to_le_bytes())?; + // Byte 2 marks the group a container clips (R67). + out.chunk(b"flgs", &flags(Flags::default(), 0, 0x80, 0x10))?; + self.objects(&mut out, objects)?; + out.close()?; + } + Ok(Some(out)) + } + + /// One shape's object list (R19, R22): flags, then its `loda` and its transform in a `lgob` + /// list. `clip` names the group it clips. + fn shape(&mut self, out: &mut Out, s: &Shape, clip: Option) -> Result<(), Error> { + self.take_object()?; + // The arguments the shape's `loda` takes, counted before its points are encoded: the + // outline, the fill and the coordinates, and the winding, transparency and container + // arguments it carries. + let opacity = share(s.opacity)?; + let seen_through = opacity < 1.0 || s.blend != Blend::Normal; + let arguments = 3 + usize::from(s.nonzero) + usize::from(seen_through) + usize::from(clip.is_some()); + if arguments > self.limits.arguments { + return Err(Error::Limit("argument count")); + } + // The fill and outline records the shape names, added before its points are encoded so + // that they count toward the limits first. + let outline = self.outline(s.outline.as_ref())?; + let fill = self.fill(s.fill.as_ref())?; + // The transparency record names a white uniform fill as the sample files do (R69). + let white = if seen_through { Some(self.fill(Some(&Color::Rgb([1.0; 3])))?) } else { None }; + // The object's lists, `obj `, `lgob` and `trfl`, and its chunks, those three with `flgs`, + // `loda` and `trfd`. + out.fits(3, 6)?; + let (kind, coords) = self.geometry(&s.geometry, &s.matrix)?; + let mut args = vec![(ARG_OUTLINE, outline.to_le_bytes().to_vec()), (ARG_FILL, fill.to_le_bytes().to_vec()), (ARG_COORDS, coords)]; + if s.nonzero { + args.push((ARG_WINDING, vec![1, 0, 0, 0])); + } + // Byte 2 of the flags marks an object seen through (0x08) and a clipping container (0x10) + // (R67). + let mut byte2 = 0; + if let Some(white) = white { + args.push((ARG_TRANSPARENCY, transparency(opacity, s.blend, white))); + byte2 |= 0x08; + } + if clip.is_some() { + byte2 |= 0x10; + } + if let Some(id) = clip { + // As sample files lay it out (R46). + args.push((ARG_CONTAINER, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect())); + } + out.open(b"obj ")?; + out.chunk(b"flgs", &flags(s.flags, 0, byte2, 0x08))?; + out.open(b"lgob")?; + self.loda(out, kind, &args)?; + out.open(b"trfl")?; + out.chunk(b"trfd", &trfd(&s.matrix)?)?; + out.close()?; + out.close()?; + out.close() + } + + /// The object type and coordinates argument of `g`, drawn through `m`. + fn geometry(&mut self, g: &Geometry, m: &Matrix) -> Result<(u32, Vec), Error> { + Ok(match g { + Geometry::Rect { w, h, radii } => (RECTANGLE, rect(*w, *h, radii, m)?), + Geometry::Ellipse { w, h } => { + // Equal start and end angles: a whole ellipse (R17). + let mut b = [coord(*w)?, coord(*h)?].concat(); + b.extend([0; 12]); + (ELLIPSE, b) + } + Geometry::Path(p) => (CURVE, self.points(p)?), + }) + } + + /// A curve's point list (R16): the count, the points, then their type bytes. + fn points(&mut self, path: &Path) -> Result, Error> { + // A subpath without segments draws nothing, and the reader leaves it out. + let drawn = || path.subpaths.iter().filter(|s| !s.segments.is_empty()); + // A closed subpath ends with a point at its start (R68): a closing line is added when its + // last segment ends elsewhere. + let adds_close = |sp: &SubPath| -> Result { + let end = match sp.segments.last() { + Some(Segment::Line(p) | Segment::Cubic(_, _, p)) => *p, + None => return Ok(false), + }; + Ok(sp.closed && [coord(end.x)?, coord(end.y)?] != [coord(sp.start.x)?, coord(sp.start.y)?]) + }; + // `n` points within the coordinate count and, at two coordinates and a type byte each, on + // top of what the file holds so far, within its size. + let fits = |n: usize| -> Result<(), Error> { + if self.coordinates.saturating_add(n) > self.limits.coordinates { + return Err(Error::Limit("coordinate count")); + } + fits_stream(&self.limits, self.total.get().saturating_add(n.saturating_mul(9)).saturating_add(4)) + }; + // A subpath takes at least a point for its start and one for each segment, so a path past + // either limit stops before its segments are looked at one by one, and the count stops + // at the segment that takes it past. + let mut n = 0usize; + for sp in drawn() { + fits(n.saturating_add(sp.segments.len()).saturating_add(1))?; + n = n.saturating_add(1); + for s in &sp.segments { + n = n.saturating_add(if matches!(s, Segment::Line(_)) { 1 } else { 3 }); + fits(n)?; + } + n = n.saturating_add(usize::from(adds_close(sp)?)); + fits(n)?; + } + fits(n)?; + self.coordinates = self.coordinates.saturating_add(n); + // The record: the count, the points, then the type bytes, which go in their own buffer. + let mut b = Vec::with_capacity(4 + n * 9); + b.extend(len32(n)?.to_le_bytes()); + let mut types: Vec = Vec::with_capacity(n); + let mut put = |p: Pt, t: u8| -> Result<(), Error> { + b.extend(coord(p.x)?); + b.extend(coord(p.y)?); + types.push(t); + Ok(()) + }; + for sp in drawn() { + let added = adds_close(sp)?; + put(sp.start, EDITABLE | if sp.closed { CLOSES } else { 0 })?; + let last = sp.segments.len().saturating_sub(1); + for (i, seg) in sp.segments.iter().enumerate() { + // The end that closes the subpath is not editable; every other end is (R68). + let end = if sp.closed && !added && i == last { CLOSES } else { EDITABLE }; + match *seg { + Segment::Line(p) => put(p, LINE | end)?, + Segment::Cubic(c1, c2, p) => { + put(c1, CONTROL)?; + put(c2, CONTROL)?; + put(p, CURVE_END | end)?; + } + } + } + if added { + put(sp.start, LINE | CLOSES)?; + } + } + b.extend(types); + Ok(b) + } + + /// The id of the fill record of `color` (R11): a uniform fill, or a fill of type 0 for none. + fn fill(&mut self, color: Option<&Color>) -> Result { + let mut body = Vec::new(); + match color { + None => body.extend(0u16.to_le_bytes()), + Some(c) => { + let props = properties(c, true)?; + body.extend(1u16.to_le_bytes()); + body.extend(TAG_1300.to_le_bytes()); + body.extend(len32(props.len())?.to_le_bytes()); + body.extend(props); + // The 8 bytes that end a uniform fill (R66). + body.extend([0; 8]); + } + } + let mut record = TAG_1300.to_le_bytes().to_vec(); + record.extend(len32(body.len())?.to_le_bytes()); + record.extend(body); + // Each fill record sits in a `LIST filc` of its own (R72). + Self::record(&mut self.fills, &mut self.next_id, record, true, &self.limits, [&self.total, &self.counted]) + } + + /// The id of the outline record of `outline` (R12, R13, R48, R49, R50); without one, an + /// outline whose line type says none. + fn outline(&mut self, outline: Option<&Outline>) -> Result { + let none = Outline { + width: 0.0, + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let o = outline.unwrap_or(&none); + // Dash and gap lengths in whole outline widths, as u16, in the room before the arrowhead + // ids (R12). + if o.dashes.len() > MAX_DASHES { + return Err(Error::Unwritable("dash patterns of more than 10 lengths")); + } + if o.dashes.iter().any(|d| !(d.is_finite() && *d >= 0.0)) { + return Err(Error::Unwritable("dash lengths that are negative or not finite")); + } + if o.dashes.iter().any(|d| d.round() > f64::from(u16::MAX)) { + return Err(Error::Unwritable("dash lengths past 65,535 outline widths")); + } + let dashes: Vec = o.dashes.iter().map(|d| d.round() as u16).collect(); + let dashed = outline.is_some() && dashes.iter().any(|d| *d > 0); + // A pattern whose lengths all round to 0 reads back as a solid line, without its lengths + // (R48). + if outline.is_some() && !dashed && !o.dashes.is_empty() { + return Err(Error::Unwritable("dash patterns whose lengths all round to 0 outline widths")); + } + if dashed { + // The reader counts an outline's dashes for every shape that uses it. + self.dashes = self.dashes.saturating_add(dashes.len()); + if self.dashes > self.limits.dashes { + return Err(Error::Limit("dash count")); + } + } + // Bit 0 no outline (R13), 1 as in the plain outlines of sample files (R49), 2 dashed (R48), + // 4 behind the fill (R49), 5 scaled with the shape (R50). + let line_type: u16 = match outline { + None => 1, + Some(o) => 0x02 | if dashed { 0x04 } else { 0 } | if o.behind_fill { 0x10 } else { 0 } | if o.scale_with { 0x20 } else { 0 }, + }; + let color = color_record(&o.color)?; + let mut body = Vec::new(); + // A library color is named in a record of type 2 (R12). + if matches!(o.color, Color::Spot { .. }) { + // An outline's list ends at its empty property (R71). + let props = properties(&o.color, false)?; + body.extend(2u32.to_le_bytes()); + body.extend(len32(props.len())?.to_le_bytes()); + body.extend(props); + } + let mut fields = Vec::new(); + for v in [line_type, cap(o.cap), join(o.join)] { + fields.extend(v.to_le_bytes()); + } + if o.width < 0.0 { + return Err(Error::Unwritable("negative outline widths")); + } + let width = coord(o.width)?; + // A width of 0 reads back as no width, which a positive width must not become. + if o.width > 0.0 && width == [0; 4] { + return Err(Error::Unwritable("outline widths that round to 0")); + } + fields.extend(width); + // The stretch, 100 percent, and 2 bytes; the nib angle and 46 bytes. + fields.extend(100u16.to_le_bytes()); + fields.extend([0; 2]); + fields.extend(angle(0.0)?); + fields.extend([0; 46]); + fields.extend(color); + fields.extend([0; 16]); + fields.extend((dashes.len() as u16).to_le_bytes()); + let mut slots = [0u8; 2 * MAX_DASHES]; + for (slot, b) in slots.iter_mut().zip(dashes.iter().flat_map(|d| d.to_le_bytes())) { + *slot = b; + } + fields.extend(slots); + // The start and end arrowhead ids (none), and the rest of the record. + fields.extend([0; 16]); + // As sample files hold them (R71): an f64 1 at bytes 16 and 48, and 45 degrees and 60 at + // bytes 84 and 88. + let one = 1f64.to_le_bytes(); + let patches: [(usize, &[u8]); 4] = [(16, &one), (48, &one), (84, &45_000_000i32.to_le_bytes()), (88, &60u32.to_le_bytes())]; + for (at, bytes) in patches { + for (slot, b) in fields.iter_mut().skip(at).zip(bytes) { + *slot = *b; + } + } + body.extend(1u32.to_le_bytes()); + body.extend(len32(fields.len())?.to_le_bytes()); + body.extend(fields); + // 8 bytes follow the record (R71). + body.extend([0; 8]); + Self::record(&mut self.outlines, &mut self.next_id, body, false, &self.limits, [&self.total, &self.counted]) + } + + /// The id of the record with `body`, adding it when it is new. Its chunk, with its header, + /// its id and its pad byte, and the list around it when `wrapped`, count toward the file's + /// bytes and chunks. + fn record( + records: &mut Records, + next_id: &mut u32, + body: Vec, + wrapped: bool, + limits: &Limits, + spent: [&Cell; 2], + ) -> Result { + if let Some(id) = records.ids.get(body.as_slice()) { + return Ok(*id); + } + let [total, counted] = spent; + let chunk = body.len().saturating_add(4); + let n = total.get().saturating_add(8).saturating_add(chunk).saturating_add(chunk % 2).saturating_add(if wrapped { 12 } else { 0 }); + fits_stream(limits, n)?; + let chunks = counted.get().saturating_add(1 + usize::from(wrapped)); + if chunks > limits.chunks { + return Err(Error::Limit("chunk count")); + } + total.set(n); + counted.set(chunks); + let id = *next_id; + *next_id = next_id.checked_add(1).ok_or(Error::Limit("output size"))?; + let body: Rc<[u8]> = body.into(); + records.bodies.push((id, body.clone())); + records.ids.insert(body, id); + Ok(id) + } +} + +/// Whether `objects` hold a shape or a container. Groups that hold only empty groups draw nothing, +/// and the reader leaves them out. Groups nested past the depth are refused, as +/// [`Writer::objects`] refuses them. +fn draws(objects: &[Object], limits: &Limits) -> Result { + let mut open = vec![objects.iter()]; + while let Some(level) = open.last_mut() { + match level.next() { + None => { + open.pop(); + } + Some(Object::Group { objects, .. }) => { + if open.len() > limits.depth { + return Err(Error::Limit("nesting depth")); + } + open.push(objects.iter()); + } + Some(_) => return Ok(true), + } + } + Ok(false) +} + +/// Point type bytes (R16): a line end, a control point, a curve end, and bit 3, which closes the +/// subpath; bit 2 marks a node that can be edited (R68). +const LINE: u8 = 0x40; +const CONTROL: u8 = 0xC0; +const CURVE_END: u8 = 0x80; +const CLOSES: u8 = 0x08; +const EDITABLE: u8 = 0x04; + +/// A `flgs` chunk (R19): bit 0x10 of byte 0 locks, bit 0x01 of byte 1 hides; byte 3 the record +/// type. +fn flags(f: Flags, byte0: u8, byte2: u8, kind: u8) -> [u8; 4] { + [byte0 | if f.locked { 0x10 } else { 0 }, u8::from(f.hidden), byte2, kind] +} + +/// A length in points as an i32 coordinate (R5). +fn coord(pt: f64) -> Result<[u8; 4], Error> { + let units = (pt * UNITS_PER_PT).round(); + if !(units.is_finite() && (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&units)) { + return Err(Error::Unwritable("coordinates past the file's range")); + } + Ok((units as i32).to_le_bytes()) +} + +/// A page's width and height as coordinates (R10, R21); the reader takes a size only when both +/// are above 0. +fn page_size((w, h): (f64, f64)) -> Result, Error> { + if !((w * UNITS_PER_PT).round() >= 1.0 && (h * UNITS_PER_PT).round() >= 1.0) { + return Err(Error::Unwritable("page sizes that are not above 0")); + } + Ok([coord(w)?, coord(h)?].concat()) +} + +/// An angle in degrees as i32 millionths (R7). +fn angle(deg: f64) -> Result<[u8; 4], Error> { + let fits = |v: f64| (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&v); + let v = (deg * 1_000_000.0).round(); + // An angle past the field's range is written as the same angle within one turn. + let v = if fits(v) { v } else { (deg.rem_euclid(360.0) * 1_000_000.0).round() }; + if !v.is_finite() { + return Err(Error::Unwritable("angles that are not finite")); + } + Ok((v as i32).to_le_bytes()) +} + +/// A finite f64, or [`WriteError::Unwritable`]. +fn finite(v: f64, what: &'static str) -> Result<[u8; 8], Error> { + if v.is_finite() { Ok(v.to_le_bytes()) } else { Err(Error::Unwritable(what)) } +} + +/// The `mcfg` chunk (R10, R72): the tag 1300, the length of the rest and 4 bytes, the page width +/// and height, then 16 bytes. +fn mcfg(size: (f64, f64)) -> Result, Error> { + let mut b = TAG_1300.to_le_bytes().to_vec(); + b.extend([0; 8]); + b.extend(page_size(size)?); + b.extend([0; 16]); + let rest = len32(b.len() - 8)?.to_le_bytes(); + if let Some(slot) = b.get_mut(4..8) { + slot.copy_from_slice(&rest); + } + Ok(b) +} + +/// A `trfd` record of one matrix (R8, R51, R65): length, count, where the offsets lie and 0xFFFF; +/// the offsets with one more for the end; then the entry: the tag 1300 and a u32 0, type 8, 6 +/// bytes, `a c tx b d ty` as f64 with the offsets in coordinate units, and 8 bytes. +fn trfd(m: &Matrix) -> Result, Error> { + const ENTRY_AT: u32 = 24; + const ENTRY_LEN: u32 = 8 + 2 + 6 + 48 + 8; + let [a, b, c, d, e, f] = m.0; + let mut out = Vec::with_capacity((ENTRY_AT + ENTRY_LEN) as usize); + for v in [ENTRY_AT + ENTRY_LEN, 1, 16, 0xFFFF, ENTRY_AT, ENTRY_AT + ENTRY_LEN] { + out.extend(v.to_le_bytes()); + } + out.extend(TAG_1300.to_le_bytes()); + out.extend([0; 4]); + out.extend(8u16.to_le_bytes()); + out.extend([0; 6]); + for v in [a, c, e * UNITS_PER_PT, b, d, f * UNITS_PER_PT] { + out.extend(finite(v, "transforms that are not finite")?); + } + out.extend([0; 8]); + Ok(out) +} + +/// Rectangle coordinates (R29): width and height in coordinate units as f64, the scale factors +/// 1 and 1, the scale-with flag clear and 7 bytes, then each corner's radius as a share of half the +/// shorter side, 16 bytes apart. +fn rect(w: f64, h: f64, radii: &[f64; 4], m: &Matrix) -> Result, Error> { + // The reader takes sizes within the range of 32-bit coordinates, as stored. + // Within half a unit of the range is the range, as conversion rounding can carry a size the + // reader gave just past it. + let max = f64::from(i32::MAX); + let stored = |v: f64| -> Result { + let u = v * UNITS_PER_PT; + if !(u.is_finite() && u.abs() <= max + 0.5) { + return Err(Error::Unwritable("coordinates past the file's range")); + } + Ok(u.clamp(-max, max)) + }; + let (wu, hu) = (stored(w)?, stored(h)?); + let half = w.abs().min(h.abs()) / 2.0; + // The reader holds a corner to half the shorter side. + if radii.iter().any(|r| !(r.is_finite() && *r >= 0.0 && *r <= half * (1.0 + 1e-9))) { + return Err(Error::Unwritable("corner radii below 0 or past half the shorter side")); + } + // The scale fields repeat the transform's scale (R29): the lengths its x and y axes take, the + // writer's own reading for a transform that also turns or skews. + let [a, b, c, d, ..] = m.0; + let (sx, sy) = (a.hypot(b), c.hypot(d)); + if !(sx.is_finite() && sy.is_finite()) { + return Err(Error::Unwritable("transforms that are not finite")); + } + let mut out = Vec::with_capacity(32 + 8 + 4 * 8 + 3 * 16); + for v in [wu, hu, sx, sy] { + out.extend(v.to_le_bytes()); + } + out.extend([0; 8]); + for (k, r) in radii.iter().enumerate() { + if k > 0 { + out.extend([0; 16]); + } + let share = if half > 0.0 { (r / half).min(1.0) } else { 0.0 }; + out.extend(share.to_le_bytes()); + } + Ok(out) +} + +/// A value from 0 to 1 as a byte from 0 to 255. +fn byte(v: f32) -> Result { + Ok((share(v)? * 255.0).round() as u8) +} + +/// `v` when it is from 0 to 1, as colors, tints and opacity are. +fn share(v: f32) -> Result { + if (0.0..=1.0).contains(&v) { Ok(v) } else { Err(Error::Unwritable("color values, tints or opacity outside 0 to 1")) } +} + +/// A 12-byte color record (R14): model, palette, 4 bytes, four value bytes. RGB is model 5 (blue, +/// green, red), CMYK model 3 (0 to 255), gray model 9, registration model 20; a library color is +/// model 21, its full-strength look mixed toward white by its tint and the tint in percent last. +/// A library color without a look is written black. +fn color_record(c: &Color) -> Result<[u8; 12], Error> { + let (model, v): (u16, [u8; 4]) = match c { + Color::Rgb([r, g, b]) => (5, [byte(*b)?, byte(*g)?, byte(*r)?, 0]), + Color::Cmyk([c, m, y, k]) => (3, [byte(*c)?, byte(*m)?, byte(*y)?, byte(*k)?]), + Color::Gray(ink) => (9, [byte(1.0 - share(*ink)?)?, 0, 0, 0]), + Color::Registration => (20, [0; 4]), + Color::Spot { tint, look, .. } => { + // The tint is stored in whole percent; at 0 the stored color is white whatever the + // look, which the reader can't take off again. + let percent = (share(*tint)? * 100.0).round(); + if percent < 1.0 { + return Err(Error::Unwritable("spot colors at a tint below 0.5 percent")); + } + let t = percent / 100.0; + let [r, g, b] = look.unwrap_or([0.0; 3]); + // The reader takes the tint off again (`records::untinted`); a low tint leaves too few + // steps of the stored byte for the look to come back within one step. + // The nearest byte to the tinted value is written, or the other byte around it when + // only that one reads back within the step. + let tinted = |v: f32| -> Result { + let ideal = (1.0 - (1.0 - share(v)?) * t) * 255.0; + let reads_back = |s: &f32| ((1.0 - (1.0 - s / 255.0) / t).clamp(0.0, 1.0) - v).abs() <= 1.0 / 255.0 + 1e-6; + match [ideal.round(), ideal.floor(), ideal.ceil()].into_iter().find(reads_back) { + Some(s) => Ok(s.clamp(0.0, 255.0) as u8), + None => Err(Error::Unwritable("spot colors at a tint too low to keep their look")), + } + }; + (21, [tinted(b)?, tinted(g)?, tinted(r)?, percent as u8]) + } + }; + let mut out = [0; 12]; + for (slot, b) in out.iter_mut().zip(model.to_le_bytes().into_iter().chain([0; 6]).chain(v)) { + *slot = b; + } + Ok(out) +} + +/// A property list (R11, R12): the color, and for a library color its name in a property of type 8 +/// (16 bytes, then the count of UTF-16 units and the units); an empty property ends it. With +/// `tail`, the fields a fill's list has after that follow (R66). +fn properties(c: &Color, tail: bool) -> Result, Error> { + let mut out = vec![1]; + out.extend(12u32.to_le_bytes()); + out.extend(color_record(c)?); + if let Color::Spot { name, .. } = c { + // A color without a name reads back as a process color. + if name.is_empty() { + return Err(Error::Unwritable("spot colors without a name")); + } + let units = units(name)?; + let mut body = vec![0; 16]; + body.extend(len32(units.len())?.to_le_bytes()); + body.extend(units.iter().flat_map(|u| u.to_le_bytes())); + out.push(8); + out.extend(len32(body.len())?.to_le_bytes()); + out.extend(body); + } + out.extend([0; 5]); + if tail { + // After a fill's list (R66): two u16, the overprint flag (u32), an angle and a u32. The + // first u16, the angle and the last u32 hold the values the specification names as usual + // (0, 45 degrees and 60); the second u16 and the flag hold 0, a value sample files hold + // there. + out.extend([0; 8]); + out.extend(45_000_000i32.to_le_bytes()); + out.extend(60u32.to_le_bytes()); + } + Ok(out) +} + +/// A name argument (R9): UTF-16LE and a closing NUL. +fn name(s: &str) -> Result, Error> { + Ok(units(s)?.into_iter().chain([0]).flat_map(u16::to_le_bytes).collect()) +} + +/// The UTF-16 units of a name the reader reads back whole: at most [`MAX_NAME`] of them, without +/// a NUL, where a name ends. +fn units(s: &str) -> Result, Error> { + let units: Vec = s.encode_utf16().take(MAX_NAME + 1).collect(); + if units.len() > MAX_NAME || units.contains(&0) { + return Err(Error::Unwritable("names longer than 256 UTF-16 units or holding a NUL")); + } + Ok(units) +} + +fn cap(c: Cap) -> u16 { + match c { + Cap::Butt => 0, + Cap::Round => 1, + Cap::Square => 2, + } +} + +fn join(j: Join) -> u16 { + match j { + Join::Miter => 0, + Join::Round => 1, + Join::Bevel => 2, + } +} + +/// Argument 8000 of a uniform transparency (R47): a record tagged 1300 whose 117-byte body holds +/// the transparency in percent (f64) at byte 61, the merge mode at byte 77 and the id of `fill` at +/// byte 105 (R69), with the other fields as the sample files hold them (R69). +fn transparency(opacity: f32, blend: Blend, fill: u32) -> Vec { + let mut body = [0u8; 117]; + let percent = (1.0 - f64::from(opacity)) * 100.0; + let fields: [(usize, &[u8]); 6] = [ + (0, &261u32.to_le_bytes()), + (57, &u32::MAX.to_le_bytes()), + (61, &percent.to_le_bytes()), + (69, &100f64.to_le_bytes()), + (77, &[merge(blend), 0, 0, 0, 2]), + (105, &fill.to_le_bytes()), + ]; + for (at, bytes) in fields { + for (slot, b) in body.iter_mut().skip(at).zip(bytes) { + *slot = *b; + } + } + let mut out = TAG_1300.to_le_bytes().to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// The merge mode byte of `blend` (R47). +fn merge(blend: Blend) -> u8 { + match blend { + Blend::Normal => 0, + Blend::Multiply => 9, + Blend::Lighten => 11, + Blend::Darken => 12, + Blend::Color => 14, + Blend::Hue => 15, + Blend::Saturation => 16, + Blend::Luminosity => 17, + Blend::Difference => 24, + Blend::Screen => 28, + Blend::Overlay => 29, + Blend::SoftLight => 30, + Blend::HardLight => 31, + Blend::ColorDodge => 33, + Blend::ColorBurn => 34, + Blend::Exclusion => 36, + } +} + +/// A ZIP archive (R24) dated 1980-01-01: the stored `mimetype` member (R64), then the RIFF file +/// made of `riff`'s parts, deflated (R25). The parts are compressed as they are, without being +/// joined first, straight into the archive after the member's header. `craft_zip::Writer` streams +/// an entry only with ZIP64 size fields, which `zip.rs` refuses, and otherwise takes one slice. +fn package(riff: &[&[u8]]) -> Result, Error> { + let size = riff.iter().map(|p| p.len()).fold(0usize, usize::saturating_add); + let mut out = Vec::new(); + let mut dir = Vec::with_capacity(160); + let at = header(&mut out, MIMETYPE_NAME, 0, crc32fast::hash(MIMETYPE), MIMETYPE.len(), MIMETYPE.len())?; + out.extend(MIMETYPE); + entry(&mut dir, &out, at, MIMETYPE_NAME)?; + // The RIFF file's CRC-32 and packed size go in its header once it is compressed. + let at = header(&mut out, MEMBER, 8, 0, 0, size)?; + let start = out.len(); + let mut crc = crc32fast::Hasher::new(); + let mut e = flate2::write::DeflateEncoder::new(out, flate2::Compression::default()); + for part in riff { + crc.update(part); + e.write_all(part).map_err(|_| Error::Limit("output size"))?; + } + let mut out = e.finish().map_err(|_| Error::Limit("output size"))?; + let fields = [crc.finalize(), len32(out.len() - start)?].map(u32::to_le_bytes).concat(); + if let Some(slot) = out.get_mut(at + 14..at + 22) { + slot.copy_from_slice(&fields); + } + entry(&mut dir, &out, at, MEMBER)?; + let dir_at = len32(out.len())?; + let dir_len = len32(dir.len())?; + out.extend(dir); + out.extend(0x0605_4b50u32.to_le_bytes()); + out.extend([0; 4]); + out.extend(2u16.to_le_bytes()); + out.extend(2u16.to_le_bytes()); + out.extend(dir_len.to_le_bytes()); + out.extend(dir_at.to_le_bytes()); + out.extend(0u16.to_le_bytes()); + Ok(out) +} + +/// A member's local header into `out`, stored (`method` 0) or deflated (8), with the CRC-32, the +/// packed size and the full size of its bytes; where the header starts. +fn header(out: &mut Vec, name: &[u8], method: u16, crc: u32, packed: usize, size: usize) -> Result { + let at = out.len(); + out.extend(0x0403_4b50u32.to_le_bytes()); + // Version needed, flags, method, time, date, CRC-32, packed and full sizes, name length. + for v in [20, 0, method, 0, 0x21] { + out.extend(v.to_le_bytes()); + } + for v in [crc, len32(packed)?, len32(size)?] { + out.extend(v.to_le_bytes()); + } + out.extend((name.len() as u16).to_le_bytes()); + // No extra field. + out.extend(0u16.to_le_bytes()); + out.extend(name); + Ok(at) +} + +/// The central directory entry into `dir` of the member whose local header is at `at` in `out`. +fn entry(dir: &mut Vec, out: &[u8], at: usize, name: &[u8]) -> Result<(), Error> { + dir.extend(0x0201_4b50u32.to_le_bytes()); + // Made by version 2.0, then the local header's fields from the version needed to the name + // length. + dir.extend(20u16.to_le_bytes()); + dir.extend(out.get(at + 4..at + 28).ok_or(Error::Limit("output size"))?); + // Extra and comment lengths, disk, internal and external attributes, then the header's offset. + dir.extend([0; 12]); + dir.extend(len32(at)?.to_le_bytes()); + dir.extend(name); + Ok(()) +} diff --git a/crates/cdr/tests/it/cmx.rs b/crates/cdr/tests/it/cmx.rs index 0067d981b7..dab5ddd08e 100644 --- a/crates/cdr/tests/it/cmx.rs +++ b/crates/cdr/tests/it/cmx.rs @@ -1,11 +1,39 @@ //! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and //! hostile ones. -use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape}; +use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Page, Shape}; use craft_cdr::synth_cmx::*; -use craft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; +use craft_cdr::{Drawing, Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; use proptest::prelude::*; +/// Read `bytes`, and check that the reader never reads less than it does when it resumes after +/// stray bytes only at the first chunk id found (R53): when that read succeeds, this one does too, +/// and every page that read holds with objects is read here unchanged and in the same order. +fn read_checked(bytes: &[u8], limits: Limits) -> Result { + read_compared(bytes, limits, |p, q| p == q) +} + +/// As [`read_checked`], except that a page only has to keep its layers and the number of objects +/// on each: a header or a table that only the recovery reads may change their colors and sizes +/// (R53). +fn read_kept(bytes: &[u8], limits: Limits) -> Result { + read_compared(bytes, limits, |p, q| { + p.layers.len() == q.layers.len() && p.layers.iter().zip(&q.layers).all(|(a, b)| a.name == b.name && a.objects.len() == b.objects.len()) + }) +} + +fn read_compared(bytes: &[u8], limits: Limits, same: fn(&Page, &Page) -> bool) -> Result { + let d = read_cmx(bytes, limits); + if let Ok(first) = read_cmx_without_recovery(bytes, limits) { + let Ok(read) = &d else { panic!("{d:?} where the first chunk id gives {first:?}") }; + let mut rest = read.pages.iter(); + for p in first.pages.iter().filter(|p| !p.layers.is_empty()) { + assert!(rest.any(|q| same(q, p)), "{p:?} is not read"); + } + } + d +} + fn shape(o: &Object) -> &Shape { match o { Object::Shape(s) => s, @@ -52,7 +80,7 @@ fn a_cmx_file_is_told_from_a_cdr_drawing() { #[test] fn pages_layers_groups_and_curves() { - let d = read_cmx(&sample(), Limits::default()).unwrap(); + let d = read_checked(&sample(), Limits::default()).unwrap(); assert_eq!(d.version, 0); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); @@ -107,7 +135,7 @@ fn layer_names_and_layers_without_objects() { end_layer(), end_page(), ]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); let page = &d.pages[0]; assert_eq!(page.size, None); // The empty layer is left out, and the UTF-16 name wins over the 8-bit one. @@ -118,7 +146,7 @@ fn layer_names_and_layers_without_objects() { #[test] fn objects_before_any_layer_get_one() { let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.pages[0].layers.len(), 1); // The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place. assert_eq!(d.pages[0].layers[0].name, ""); @@ -134,7 +162,7 @@ fn a_page_without_a_size_takes_the_drawings_bounds() { end_layer(), end_page(), ]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); let page = &d.pages[0]; let side = 100.0 / 25.4 * 72.0; let (w, h) = page.size.unwrap(); @@ -150,7 +178,7 @@ fn curves_and_open_groups() { curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]); // A group the layer leaves open closes with it. let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); let objects = &d.pages[0].layers[0].objects; let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") }; let s = shape(&kids[0]); @@ -164,7 +192,7 @@ fn curves_and_open_groups() { #[test] fn a_curve_without_its_points_is_reported() { let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); } @@ -174,7 +202,7 @@ fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() { d.extend(b"Art"); let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])])); let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.pages[0].layers[0].name, "Art"); } @@ -192,7 +220,7 @@ fn what_is_not_read_is_reported() { square(&attrs(Some(1), None, true), 0, 0, 1000), end_layer(), ]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] { assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings); } @@ -213,7 +241,7 @@ fn colors_of_other_models_and_missing_entries() { square(&attrs(Some(2), None, false), 0, 0, 1000), ])); children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); let objects = &d.pages[0].layers[0].objects; assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0]))); @@ -231,7 +259,7 @@ fn gray_cmy_and_rgb_colors_of_the_older_fields() { square(&attrs(Some(3), None, false), 0, 0, 1000), ])); children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); let objects = &d.pages[0].layers[0].objects; // The model holds objects front to back: the RGB square, the CMY one, then the gray one. @@ -251,7 +279,7 @@ fn outline_arrowheads_are_reported() { children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota"))); children.push(arrowheads(&[(0, 2)])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert_eq!(d.warnings, vec![Warning::Arrowheads]); } @@ -275,7 +303,7 @@ fn a_long_instruction_and_a_jump_over_image_bytes() { .concat(); let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); // The images jumped over are not read, and the warning says so. assert_eq!(d.warnings, [Warning::UnsupportedObjects]); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -286,7 +314,7 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() { let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff]; let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -295,12 +323,12 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() { fn other_byte_orders_and_coordinate_sizes_are_refused() { let mut f = sample(); f[..4].copy_from_slice(b"RIFX"); - assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); + assert_eq!(read_checked(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); let mut children = vec![cont(b'2', 1e-3)]; children.extend(tables()); - assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); - assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); - assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_checked(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); + assert_eq!(read_checked(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_checked(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); } #[test] @@ -308,7 +336,7 @@ fn a_header_without_a_usable_unit_reads_0_1_micrometers() { for meters in [0.0, -1.0, f64::NAN, 2.0] { let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); let (w, _) = d.pages[0].size.unwrap(); assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}"); } @@ -325,7 +353,7 @@ fn groups_past_the_depth_limit_are_left_out() { ins.push(end_group()); } ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); - let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); + let d = read_checked(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); assert!(d.warnings.contains(&Warning::TooDeep)); // The square after the groups is still read, beside the three groups kept. let objects = &d.pages[0].layers[0].objects; @@ -346,18 +374,18 @@ fn groups_past_the_depth_limit_are_left_out() { fn counts_past_the_limits_are_bounded() { let ins: Vec> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect(); let f = file(&[page(&ins)]); - let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); + let d = read_checked(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); assert_eq!(d.pages[0].layers[0].objects.len(), 10); assert!(d.warnings.contains(&Warning::TooDeep)); - let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); + let d = read_checked(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); assert_eq!(d.pages[0].layers[0].objects.len(), 2); - assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); - assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); + assert_eq!(read_checked(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read_checked(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); let dashed = |n: u16| { let mut children = vec![cont(b'4', 1e-7)]; children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)])); children.extend(tables()); - read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() + read_checked(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() }; let d = dashed(3); let o: Vec = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect(); @@ -372,7 +400,7 @@ fn a_curve_cut_short_keeps_the_points_it_holds() { let at = c.windows(2).position(|w| w == [3, 0]).unwrap(); c[at] = 9; let p = page(&[begin_page(None), c]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged)); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -387,7 +415,7 @@ fn a_curve_that_lost_type_bytes_keeps_its_first_points() { } g.extend([0x0c, 0x44]); let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)])); - let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); + let d = read_checked(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() }; let side = 100.0 / 25.4 * 72.0; @@ -403,14 +431,14 @@ fn a_file_cut_short_of_its_declared_size_is_reported() { let mut f = file(&[]); let declared = (f.len() as u32 - 8 + 100).to_le_bytes(); f[4..8].copy_from_slice(&declared); - let d = read_cmx(&f, Limits::default()).unwrap(); + let d = read_checked(&f, Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); } #[test] fn a_page_that_ends_inside_an_instruction_is_reported() { let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -420,7 +448,7 @@ fn a_chunk_64_bytes_past_stray_bytes_is_found() { let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -432,7 +460,687 @@ fn stray_letters_with_a_length_past_the_file_are_passed_over() { let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +/// Stray bytes, then letters whose length covers exactly the page chunk after them, then the page. +fn page_inside_stray_letters(stray: &[u8]) -> Vec { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = stray.to_vec(); + b.extend(b"abcd"); + b.extend((p.len() as u32).to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + riff(&children) +} + +#[test] +fn after_stray_letters_the_page_is_preferred_to_letters_that_hold_it() { + let mut stray = b"wxyz".to_vec(); + stray.extend(0xFFFF_FF00u32.to_le_bytes()); + let d = read_checked(&page_inside_stray_letters(&stray), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_the_page_is_preferred_to_letters_that_hold_it() { + let d = read_checked(&page_inside_stray_letters(&[1, 1]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn letters_64_bytes_past_stray_bytes_do_not_hide_the_page_they_hold() { + let d = read_checked(&page_inside_stray_letters(&[1; 64]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_after_three_page_headers_that_do_not_read_inside_letters_is_read() { + // Stray bytes, then letters whose length covers three page headers that reach its end and + // whose instructions do not fit, then the page. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let len = 24 + p.len(); + let mut body = Vec::new(); + for k in 0..3 { + body.extend(b"page"); + body.extend(((len - 8 * k - 8) as u32).to_le_bytes()); + } + body.extend(p); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((body.len() as u32).to_le_bytes()); + b.extend(body); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_recoveries_stop_once_a_read_has_spent_its_allowance() { + // Many copies of stray bytes followed by a chunk the reader passes over that holds a page: + // the first pages are read, and once the checks have spent the read's allowance the reader + // resumes at the chunk that holds each page, as it does without the recovery. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut unit = vec![1u8; 2]; + unit.extend(chunk(b"inf1", &p)); + let copies = 2000; + let mut children = vec![cont(b'4', 1e-7), unit.repeat(copies)]; + children.extend(tables()); + let f = riff(&children); + let d = read_checked(&f, Limits::default()).unwrap(); + assert!(!d.pages.is_empty() && d.pages.len() < copies, "{} of {copies} pages", d.pages.len()); + assert!(read_cmx_without_recovery(&f, Limits::default()).unwrap().pages.is_empty()); +} + +#[test] +fn after_stray_bytes_a_page_past_a_limit_is_left_out_with_a_warning() { + let f = page_inside_stray_letters(&[1, 1]); + let all = read_cmx(&f, Limits::default()).unwrap().pages.len(); + assert_eq!(all, 1); + let mut cut = 0; + for chunks in 1..200 { + let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) else { continue }; + if d.pages.len() < all { + cut += 1; + assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings); + } + } + assert!(cut > 0); +} + +#[test] +fn a_recovered_page_spends_only_what_the_limits_leave_after_the_other_pages() { + // Stray bytes, letters whose length covers a page, the page, then another page: with room for + // one object, the last page keeps it and the warning tells of the page left out; with room for + // both, the recovered page reads first. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((p.len() as u32).to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b, q]; + children.extend(tables()); + let f = riff(&children); + let d = read_checked(&f, Limits { objects: 1, ..Limits::default() }).unwrap(); + assert_eq!(d.pages.len(), 1, "{:?}", d.pages); + let last = d.pages.last().unwrap(); + assert_eq!((last.layers[0].name.as_str(), last.layers[0].objects.len()), ("M", 1)); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); + let d = read_checked(&f, Limits::default()).unwrap(); + assert_eq!(d.pages.iter().map(|p| p.layers[0].name.as_str()).collect::>(), ["L", "M"]); +} + +#[test] +fn chunks_only_a_recovery_reads_do_not_stop_a_read_that_fits_without_them() { + // A page, then letters spelling `page` whose length runs past the file and that hold another + // page and an empty chunk: at every chunk limit at which the file opens without the recovery, + // it opens with it, and where the recovered page does not fit, the warning tells of it. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = b"page".to_vec(); + b.extend(0xFFFF_FF00u32.to_le_bytes()); + b.extend(q); + b.extend(chunk(b"junk", &[])); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(p); + children.push(b); + let f = riff(&children); + let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::>(); + assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["L", "M"]); + let mut cut = 0; + for chunks in 1..200 { + let limits = Limits { chunks, ..Limits::default() }; + if read_cmx_without_recovery(&f, limits).is_err() { + continue; + } + let d = read_checked(&f, limits).unwrap(); + if names(&d) != ["L", "M"] { + cut += 1; + assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings); + } + } + assert!(cut > 0); +} + +#[test] +fn after_stray_bytes_a_page_is_read_when_the_chunk_found_lands_inside_a_list() { + // Stray bytes, then letters whose length ends on the header of an empty page at the end of the + // page after them. That empty page's length ends on the first page inside the list that + // follows. Walking on from the page reads the same page inside the list, so the page is read. + let (name, q) = ["Q", "Qa"] + .iter() + .map(|n| { + let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat()); + (*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat()) + }) + .find(|(_, body)| body.len() % 2 == 0) + .unwrap(); + let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32).to_le_bytes()); + b.extend(chunk(b"page", &q)); + b.extend(list(b"pgls", &[r])); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect(); + assert_eq!(names, [name, "R"]); +} + +#[test] +fn after_stray_bytes_a_page_is_not_read_when_a_list_cuts_short_the_page_both_walks_reach() { + // As above, except that the list ends after the header of the page inside it, so walking on + // from the inner page reads that page without its body. Walking on from the letters reads the + // whole page, so the reader resumes at the letters and the page keeps its square. + let (name, q) = ["Q", "Qa"] + .iter() + .map(|n| { + let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat()); + (*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat()) + }) + .find(|(_, body)| body.len() % 2 == 0) + .unwrap(); + let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32).to_le_bytes()); + b.extend(chunk(b"page", &q)); + b.extend(b"LIST"); + b.extend(12u32.to_le_bytes()); + b.extend(b"pgls"); + b.extend(r); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect(); + assert!(!names.contains(&name), "{names:?}"); + assert_eq!(names, ["R"]); + assert_eq!(d.pages.last().unwrap().layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_a_list_cuts_short_only_without_the_recovery_is_judged_as_recovered() { + // Stray bytes, then letters whose length ends on the header of a list at the end of the page + // after them. The list ends after the header of the next page, so the walk from the letters + // reads that page without its body, and the walk from the page inside the letters reads the + // whole page. Only the recovery reads that whole page, and it ends inside an instruction, so the + // reader leaves it out. + let (name, q) = ["Q", "Qa"] + .iter() + .map(|n| { + let carried = long_instr(-1, &[b"LIST".as_slice(), &12u32.to_le_bytes(), b"pgls"].concat()); + (*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat()) + }) + .find(|(_, body)| body.len() % 2 == 0) + .unwrap(); + let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), vec![1, 0]]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32 - 4).to_le_bytes()); + b.extend(chunk(b"page", &q)); + b.extend(r); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect(); + assert_eq!(names, [name]); +} + +#[test] +fn after_stray_bytes_a_page_whose_check_stops_at_a_limit_is_not_replaced_by_a_page_inside_it() { + // Stray bytes, then letters whose body holds the start of a page of one square. That page's last + // instruction carries the page of thirty squares that follows the letters, and ends where it + // ends. At a chunk limit that stops the check of the page of thirty squares while the check of + // the page inside the letters fits, the page inside the letters never takes its place. + let squares = (1..=30).map(|i| square(&attrs(Some(1), None, false), 0, 0, 100 * i)); + let p = page(&[begin_page(None), begin_layer("P", None)].into_iter().chain(squares).chain([end_layer()]).collect::>()); + let carried = long_instr(-1, &p); + let head = &carried[..carried.len() - p.len()]; + let q = ["Q", "Qa"] + .iter() + .map(|n| [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), head.to_vec()].concat()) + .find(|body| body.len() % 2 == 0) + .unwrap(); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32 + 8).to_le_bytes()); + b.extend(b"page"); + b.extend(((q.len() + p.len()) as u32).to_le_bytes()); + b.extend(q); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let f = riff(&children); + let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::>(); + assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["P"]); + for chunks in 1..200 { + if let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) { + assert_eq!(names(&d), ["P"], "{chunks}: {:?}", d.warnings); + } + } +} + +/// A page that fills with color 1, then, inside a list, letters spelling `page` whose length runs +/// past the list and that hold another page and a color table of one red entry, then `after`. +fn page_and_recovered_red(after: &[Vec]) -> Vec { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = b"page".to_vec(); + b.extend(0xFFFF_FF00u32.to_le_bytes()); + b.extend(q); + b.extend(table(b"rclr", &[color(5, &[255, 0, 0])])); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr"))); + children.push(p); + children.push(list(b"pgls", &[b])); + children.extend(after.iter().cloned()); + riff(&children) +} + +/// The fill of the first object of each page. +fn fills(d: &Drawing) -> Vec> { + d.pages.iter().map(|p| shape(&p.layers[0].objects[0]).fill.clone()).collect() +} + +#[test] +fn a_color_table_only_the_recovery_reads_colors_every_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); + let red = fills(&read_checked(&file(&[p]), Limits::default()).unwrap())[0].clone(); + assert!(red.is_some()); + let d = read_kept(&page_and_recovered_red(&[]), Limits::default()).unwrap(); + assert_eq!(fills(&d), [red.clone(), red]); +} + +#[test] +fn a_color_table_read_without_the_recovery_wins_over_one_only_the_recovery_reads() { + let green = table(b"rclr", &[color(5, &[0, 255, 0])]); + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr"))); + children.push(green.clone()); + let green_fill = fills(&read_checked(&riff(&children), Limits::default()).unwrap())[0].clone(); + let d = read_checked(&page_and_recovered_red(&[green]), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 2); + assert_eq!(fills(&d), [green_fill.clone(), green_fill]); +} + +#[test] +fn after_stray_bytes_a_page_inside_a_chunk_with_more_after_it_is_not_read() { + // Stray bytes, a chunk the reader passes over that holds a page followed by another chunk, + // then the page: only the last page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat())); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); +} + +#[test] +fn a_list_between_stray_bytes_is_read_as_a_list() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let b = [vec![1u8; 2], list(b"pgls", &[p.clone(), p]), vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 2); +} + +#[test] +fn after_stray_bytes_an_empty_page_header_inside_another_chunk_is_not_a_page() { + // Stray bytes, a chunk the reader passes over that holds only an empty page header, then the + // page: only the page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[]))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_an_empty_page_is_kept_before_the_next_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"page", &[])); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 2); + assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); + assert_eq!(d.pages[1].layers[0].objects.len(), 1); +} + +#[test] +fn a_page_between_stray_bytes_is_preferred_to_letters_that_end_inside_it() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend(8u32.to_le_bytes()); + b.extend(p); + b.extend([1u8; 2]); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_is_preferred_to_page_letters_that_end_inside_it() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"page"); + b.extend(8u32.to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_page_between_stray_bytes_is_kept() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let b = [vec![1u8; 2], p, vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_header_that_ends_inside_another_chunk_is_not_a_page() { + // Stray bytes, a chunk the reader passes over whose body starts with a short page chunk, more + // stray bytes, then the page: only the last page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut inner = b"page".to_vec(); + inner.extend(4u32.to_le_bytes()); + inner.extend([0; 10]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + // The chunk passed over is followed by more stray bytes, and the warning says so. + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_header_too_short_to_read_inside_another_chunk_is_passed_over() { + // Stray bytes, then a chunk the reader passes over that holds a one-byte header, then the + // header: the drawing opens with the header after it. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0]))].concat(); + let mut children = vec![first, cont(b'4', 1e-7), p]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_letters_ending_on_a_layer_name_do_not_hide_the_page() { + // Stray bytes, then letters whose length ends on the letters of a layer name inside the page + // after them, then the page. + let names = ["Background", "aBackground"]; + let (p, at) = names + .iter() + .map(|n| page(&[begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()])) + .find_map(|p| p.windows(4).position(|w| w == b"Back").filter(|at| at % 2 == 0).map(|at| (p, at))) + .unwrap(); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((at as u32).to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_followed_by_a_chunk_inside_another_chunk_is_not_read_before_more_stray_bytes() { + // Stray bytes, a chunk the reader passes over that holds a page and another chunk, more stray + // bytes, then the page: only the last page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat())); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); +} + +#[test] +fn after_stray_bytes_a_header_without_a_coordinate_size_inside_another_chunk_is_passed_over() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0; 60]))].concat(); + let mut children = vec![first, cont(b'4', 1e-7), p]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_table_inside_another_chunk_that_ends_inside_the_next_page_is_passed_over() { + // Stray bytes, a chunk the reader passes over that holds the start of a color table whose + // length ends inside the page after more stray bytes: the page is read. + let sq = square(&attrs(Some(1), None, false), 0, 0, 1000); + let p = page(&[begin_page(None), begin_layer("L", None), sq.clone(), sq.clone(), sq, end_layer()]); + let mut inner = b"rclr".to_vec(); + inner.extend(14u32.to_le_bytes()); + inner.extend([0; 2]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 3); +} + +#[test] +fn a_page_between_stray_bytes_is_kept_when_its_body_holds_chunk_letters() { + // A layer name near the start of the page holds a color table chunk and another chunk id. + let mut tail = b"rclr".to_vec(); + tail.extend([4, 0, 0, 0, 0, 0, 0, 0]); + tail.extend(b"junk"); + tail.extend([0; 4]); + let tail = String::from_utf8(tail).unwrap(); + let (p, at) = ["", "x"] + .iter() + .map(|pre| { + page(&[begin_page(None), begin_layer(&format!("{pre}{tail}"), None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]) + }) + .find_map(|p| p.windows(4).position(|w| w == b"rclr").filter(|at| at % 2 == 0).map(|at| (p, at))) + .unwrap(); + assert!((8..=64).contains(&at), "{at}"); + let b = [vec![1u8; 2], p, vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_too_short_for_an_instruction_inside_another_chunk_is_not_a_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[0; 2]))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_short_page_is_not_hidden_by_a_table_inside_the_chunk_before_it() { + // Stray bytes, a chunk the reader passes over that holds the start of a color table whose + // length ends inside the short page after more stray bytes: the page is read. + let p = page(&[begin_page(None)]); + let mut inner = b"rclr".to_vec(); + inner.extend(10u32.to_le_bytes()); + inner.extend([0; 2]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); +} + +#[test] +fn a_last_page_before_stray_bytes_at_the_end_of_the_file_is_preferred_to_letters_that_end_inside_it() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend(8u32.to_le_bytes()); + b.extend(p); + b.extend([1u8; 2]); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_page_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() { + // Bytes the page's long instruction carries hold a color table whose length reaches the end + // of the page. + let sq = square(&attrs(Some(1), None, false), 0, 0, 1000); + let mut table = b"rclr".to_vec(); + let rest = [begin_layer("L", None), sq, end_layer()].concat(); + // The table's body: the rest of the long instruction (2 bytes), then the instructions after it. + table.extend(((2 + rest.len()) as u32).to_le_bytes()); + table.extend([0; 2]); + let carried = long_instr(-1, &table); + let p = page(&[begin_page(None), carried, rest]); + let at = p.windows(4).position(|w| w == b"rclr").unwrap(); + assert!(at % 2 == 0 && (8..=64).contains(&at), "{at}"); + let b = [vec![1u8; 2], p, vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_whose_first_instruction_is_empty_inside_another_chunk_is_not_a_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[0; 4]))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_header_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut c = cont(b'4', 1e-7); + let inner = (c.len() - 24) as u32; + c[16..20].copy_from_slice(b"rclr"); + c[20..24].copy_from_slice(&inner.to_le_bytes()); + let mut children = vec![[vec![1u8; 2], c, vec![1u8; 2]].concat(), p]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_table_whose_entries_do_not_fit_inside_another_chunk_is_passed_over() { + // Stray bytes, then a chunk the reader passes over that holds a color table of one entry with + // no bytes for it, then the real tables: the colors come from the real tables. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let read = |junk: &[u8]| { + let mut children = vec![cont(b'4', 1e-7), junk.to_vec()]; + children.extend(tables()); + children.push(p.clone()); + read_checked(&riff(&children), Limits::default()).unwrap() + }; + let junk = [vec![1u8; 2], chunk(b"inf1", &chunk(b"rclr", &[1, 0]))].concat(); + let d = read(&junk); + let clean = read(&[]); + assert_eq!(format!("{:?}", d.pages), format!("{:?}", clean.pages)); +} + +#[test] +fn after_stray_bytes_a_page_whose_second_instruction_is_empty_inside_another_chunk_is_not_a_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[instr(-1, &[]), vec![0; 4]].concat()))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_page_letters_with_a_length_past_the_list_do_not_hide_the_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"page"); + b.extend(0xFFFF_FF00u32.to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -444,7 +1152,7 @@ fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() { children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl"))); children.push(table(b"rdot", &[dashes(&[0, 0])])); children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap(); assert!(o.dashes.is_empty(), "{:?}", o.dashes); @@ -462,7 +1170,7 @@ fn a_curve_field_that_lost_points_is_left_out() { g.extend(1_000_000i32.to_le_bytes()); g.extend([0x40, 0x42]); let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)])); - let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); + let d = read_checked(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); } @@ -476,7 +1184,7 @@ fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() { b.extend(p); let mut children = vec![cont(b'4', 1e-7), b]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -493,7 +1201,7 @@ fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() { b.extend(p); let mut children = vec![cont(b'4', 1e-7), b]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -513,7 +1221,7 @@ fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() { b.extend(p); let mut children = vec![cont(b'4', 1e-7), b]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -525,7 +1233,7 @@ fn a_canvas_or_a_container_is_reported() { let mut a = attrs(Some(1), None, false); a[0] |= bit; let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}"); assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some()); } @@ -536,7 +1244,7 @@ fn a_library_color_with_its_name_reads_as_a_spot_color() { let mut children = vec![cont(b'4', 1e-7)]; children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); match shape(&d.pages[0].layers[0].objects[0]).fill.clone() { Some(Color::Spot { name, tint, look }) => { assert_eq!((name.as_str(), tint), ("Brick 12", 1.0)); @@ -553,7 +1261,7 @@ proptest! { fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { let mut b = b"RIFF\0\0\0\0CMX1".to_vec(); b.extend(bytes); - let _ = read_cmx(&b, Limits::default()); + let _ = read_kept(&b, Limits::default()); } #[test] @@ -563,6 +1271,6 @@ proptest! { for (at, v) in edits { b[at % n] = v; } - let _ = read_cmx(&b, Limits::default()); + let _ = read_kept(&b, Limits::default()); } } diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs index 4fc7dcbdc9..23419e0936 100644 --- a/crates/cdr/tests/it/main.rs +++ b/crates/cdr/tests/it/main.rs @@ -6,3 +6,4 @@ mod bench; mod cmx; mod provenance; mod read; +mod write; diff --git a/crates/cdr/tests/it/write.rs b/crates/cdr/tests/it/write.rs new file mode 100644 index 0000000000..6112e035f8 --- /dev/null +++ b/crates/cdr/tests/it/write.rs @@ -0,0 +1,976 @@ +//! Writing drawings and reading them back. + +use std::io::Read as _; + +use craft_cdr::WriteError as Error; +use craft_cdr::model::{ + Blend, Cap, Color, Drawing, Flags, Geometry, Guideline, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, +}; +use craft_cdr::{Limits, WRITTEN_VERSION, is_cdr, read, write}; +use proptest::prelude::*; + +/// `n` coordinate units (1/254000 inch) in points, which the file stores exactly. +fn u(n: i32) -> f64 { + f64::from(n) * (72.0 / 254_000.0) +} + +fn pt(x: i32, y: i32) -> Pt { + Pt { x: u(x), y: u(y) } +} + +/// A byte value as a color component, which the file stores exactly. +fn c(v: u8) -> f32 { + f32::from(v) / 255.0 +} + +fn moved(x: f64, y: f64) -> Matrix { + Matrix([1.0, 0.0, 0.0, 1.0, x, y]) +} + +fn layer(name: &str, objects: Vec) -> Layer { + Layer { name: name.into(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() } +} + +fn rect(w: i32, h: i32, fill: Option) -> Object { + Object::Shape(Box::new(Shape::new(Geometry::Rect { w: u(w), h: u(h), radii: [0.0; 4] }, moved(10.0, -20.0), fill, None))) +} + +/// A drawing of one page and one layer holding `objects`. +fn one_layer(objects: Vec) -> Drawing { + Drawing { + version: WRITTEN_VERSION, + page_size: None, + pages: vec![Page { size: None, layers: vec![layer("A", objects)] }], + master: Vec::new(), + guides: Vec::new(), + warnings: Vec::new(), + } +} + +/// A drawing with every kind of thing the writer writes. +fn everything() -> Drawing { + let black = Outline { + width: u(5080), + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let dashed = Outline { + width: u(2540), + color: Color::Cmyk([c(0), c(128), c(255), c(13)]), + cap: Cap::Round, + join: Join::Bevel, + dashes: vec![3.0, 1.0], + behind_fill: true, + scale_with: true, + }; + let curve = Path { + subpaths: vec![ + SubPath { + start: pt(0, 0), + segments: vec![Segment::Line(pt(254_000, 0)), Segment::Cubic(pt(254_000, 50_000), pt(100_000, 254_000), pt(0, 254_000))], + closed: true, + }, + SubPath { start: pt(-1000, -1000), segments: vec![Segment::Line(pt(-5000, -9000))], closed: false }, + ], + }; + let mut path = + Shape::new(Geometry::Path(curve), Matrix([0.5, 0.25, -0.25, 2.0, 100.0, -40.0]), Some(Color::Rgb([c(255), c(64), c(0)])), Some(dashed)); + path.nonzero = true; + path.opacity = 0.75; + path.blend = Blend::Multiply; + let mut rounded = Shape::new( + Geometry::Rect { w: u(200_000), h: u(-100_000), radii: [u(10_000), u(0), u(25_000), u(50_000)] }, + moved(0.0, 0.0), + Some(Color::Registration), + Some(black.clone()), + ); + rounded.flags = Flags { hidden: true, locked: true }; + let spot = Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([0.0, c(255), 0.0]) }; + let ellipse = Shape::new( + Geometry::Ellipse { w: u(80_000), h: u(40_000) }, + moved(-30.0, 30.0), + Some(spot.clone()), + Some(Outline { color: spot, ..black.clone() }), + ); + let container = Shape::new(Geometry::Rect { w: u(100_000), h: u(100_000), radii: [0.0; 4] }, moved(0.0, 0.0), None, Some(black.clone())); + let inner = Object::Clip { container: Box::new(container.clone()), objects: vec![rect(10_000, 10_000, Some(Color::Gray(c(128))))] }; + let clip = Object::Clip { container: Box::new(container), objects: vec![rect(20_000, 30_000, None), inner] }; + let group = Object::Group { + objects: vec![Object::Shape(Box::new(ellipse)), rect(1000, 2000, Some(Color::Gray(0.0)))], + flags: Flags { hidden: true, locked: false }, + }; + let mut art = layer("Art", vec![Object::Shape(Box::new(path)), Object::Shape(Box::new(rounded)), group, clip]); + art.guides.push(Guideline { at: pt(0, 254_000), angle: -45.0, hidden: false }); + let mut back = layer("Back ünïcode", vec![rect(5000, 5000, Some(Color::Rgb([c(1), c(2), c(3)])))]); + back.flags = Flags { hidden: true, locked: true }; + let mut desktop = layer("Desktop", vec![rect(3000, 3000, None)]); + desktop.kind = LayerKind::Desktop; + Drawing { + version: WRITTEN_VERSION, + page_size: Some((u(2_159_000), u(2_794_000))), + pages: vec![ + Page { size: Some((u(2_159_000), u(2_794_000))), layers: vec![art, back] }, + Page { size: Some((u(1_000_000), u(500_000))), layers: vec![layer("Second", vec![rect(7000, 8000, None)])] }, + ], + master: vec![desktop], + guides: vec![Guideline { at: pt(254_000, 0), angle: 90.0, hidden: false }], + warnings: Vec::new(), + } +} + +/// Rounds every number of `d` past the precision a round trip keeps. +fn rounded(mut d: Drawing) -> Drawing { + fn r(v: &mut f64) { + *v = (*v * 1e4).round() / 1e4 + 0.0; + } + fn rc(c: &mut Color) { + let f = |v: &mut f32| *v = (*v * 1e3).round() / 1e3 + 0.0; + match c { + Color::Rgb(v) => v.iter_mut().for_each(f), + Color::Cmyk(v) => v.iter_mut().for_each(f), + Color::Gray(v) => f(v), + Color::Registration => {} + Color::Spot { tint, look, .. } => { + f(tint); + if let Some(l) = look { + l.iter_mut().for_each(f); + } + } + } + } + fn rp(p: &mut Pt) { + r(&mut p.x); + r(&mut p.y); + } + fn rs(s: &mut Shape) { + s.matrix.0.iter_mut().for_each(r); + match &mut s.geometry { + Geometry::Rect { w, h, radii } => { + r(w); + r(h); + radii.iter_mut().for_each(r); + } + Geometry::Ellipse { w, h } => { + r(w); + r(h); + } + Geometry::Path(p) => { + for sp in &mut p.subpaths { + rp(&mut sp.start); + for seg in &mut sp.segments { + match seg { + Segment::Line(a) => rp(a), + Segment::Cubic(a, b, e) => [a, b, e].into_iter().for_each(rp), + } + } + } + } + } + s.fill.iter_mut().for_each(rc); + if let Some(o) = &mut s.outline { + r(&mut o.width); + rc(&mut o.color); + } + s.opacity = (s.opacity * 1e3).round() / 1e3; + } + let mut stack: Vec<&mut Object> = Vec::new(); + for l in d.pages.iter_mut().flat_map(|p| p.layers.iter_mut()).chain(d.master.iter_mut()) { + for g in &mut l.guides { + rp(&mut g.at); + } + stack.extend(l.objects.iter_mut()); + } + while let Some(o) = stack.pop() { + match o { + Object::Shape(s) => rs(s), + Object::Group { objects, .. } => stack.extend(objects.iter_mut()), + Object::Clip { container, objects } => { + rs(container); + stack.extend(objects.iter_mut()); + } + } + } + for g in &mut d.guides { + rp(&mut g.at); + } + for (w, h) in d.pages.iter_mut().filter_map(|p| p.size.as_mut()).chain(d.page_size.as_mut()) { + r(w); + r(h); + } + d +} + +/// `d` as it reads back once written: rounded, and each closed subpath whose last segment ends away +/// from its start given a closing line to its start. +fn as_read(d: Drawing) -> Drawing { + let mut d = rounded(d); + let mut stack: Vec<&mut Object> = d.pages.iter_mut().flat_map(|p| p.layers.iter_mut()).flat_map(|l| l.objects.iter_mut()).collect(); + stack.extend(d.master.iter_mut().flat_map(|l| l.objects.iter_mut())); + while let Some(o) = stack.pop() { + let shape = match o { + Object::Shape(s) => s, + Object::Group { objects, .. } => { + stack.extend(objects.iter_mut()); + continue; + } + Object::Clip { container, objects } => { + stack.extend(objects.iter_mut()); + container + } + }; + let Geometry::Path(p) = &mut shape.geometry else { continue }; + for sp in &mut p.subpaths { + let end = sp.segments.last().map(|s| match s { + Segment::Line(e) | Segment::Cubic(_, _, e) => *e, + }); + if sp.closed && end.is_some_and(|e| e != sp.start) { + sp.segments.push(Segment::Line(sp.start)); + } + } + } + d +} + +/// The RIFF file inside a written package. +fn riff_of(file: &[u8]) -> Vec { + // The second member, after the stored `mimetype`. + let (name, data) = member(file, 0); + assert_eq!((name, data), (&b"mimetype"[..], &b"application/x-vnd.corel.draw.document+zip"[..])); + let next = 30 + name.len() + data.len(); + let (name, data) = member(file, next); + assert_eq!(name, b"content/riffData.cdr"); + let mut out = Vec::new(); + flate2::read::DeflateDecoder::new(data).read_to_end(&mut out).unwrap(); + out +} + +/// The name and packed bytes of the member whose local header is at `at`. +fn member(file: &[u8], at: usize) -> (&[u8], &[u8]) { + let le16 = |i: usize| usize::from(u16::from_le_bytes([file[at + i], file[at + i + 1]])); + let packed = u32::from_le_bytes(file[at + 18..at + 22].try_into().unwrap()) as usize; + let name = &file[at + 30..at + 30 + le16(26)]; + let start = at + 30 + le16(26) + le16(28); + (name, &file[start..start + packed]) +} + +fn count(hay: &[u8], needle: &[u8]) -> usize { + hay.windows(needle.len()).filter(|w| *w == needle).count() +} + +#[test] +fn a_written_drawing_reads_back_as_written() { + let d = everything(); + let file = write(&d, Limits::default()).unwrap(); + let back = read(&file, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(rounded(back), as_read(d)); +} + +#[test] +fn a_written_file_is_a_version_15_package_and_the_same_each_time() { + let file = write(&everything(), Limits::default()).unwrap(); + assert!(is_cdr(&file) && file.starts_with(b"PK\x03\x04")); + let riff = riff_of(&file); + assert_eq!(&riff[8..12], b"CDRF"); + assert_eq!(&riff[12..18], b"vrsn\x02\0"); + assert_eq!(read(&file, Limits::default()).unwrap().version, 1500); + assert_eq!(file, write(&everything(), Limits::default()).unwrap()); + // `mcfg` starts with the tag 1300 and the length of the rest (R72). + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let mcfg = riff.windows(4).position(|w| w == b"mcfg").unwrap(); + assert_eq!((le32(mcfg + 8), le32(mcfg + 12)), (1300, le32(mcfg + 4) - 8)); + // Every child of `LIST filt` is a `LIST filc` that holds one `fild` and nothing else (R72). + let padded = |size: usize| 8 + size + (size & 1); + let filt = riff.windows(12).position(|w| &w[..4] == b"LIST" && &w[8..] == b"filt").unwrap(); + let (mut at, end) = (filt + 12, filt + 8 + le32(filt + 4)); + let mut lists = 0; + while at < end { + assert_eq!((&riff[at..at + 4], &riff[at + 8..at + 12], &riff[at + 12..at + 16]), (&b"LIST"[..], &b"filc"[..], &b"fild"[..])); + assert_eq!(at + 12 + padded(le32(at + 16)), at + padded(le32(at + 4))); + at += padded(le32(at + 4)); + lists += 1; + } + assert_eq!((at, lists), (end, count(&riff, b"fild"))); + assert!(lists > 0); +} + +#[test] +fn each_container_names_its_own_clipped_group_by_the_stored_id() { + let riff = riff_of(&write(&everything(), Limits::default()).unwrap()); + let ids: Vec = + (0..riff.len() - 12).filter(|&p| &riff[p..p + 4] == b"spnd").map(|p| u32::from_le_bytes(riff[p + 8..p + 12].try_into().unwrap())).collect(); + let mut distinct = ids.clone(); + distinct.sort_unstable(); + distinct.dedup(); + assert!(ids.len() > 1 && distinct.len() == ids.len(), "{ids:?}"); + // The first u32 of each container argument (8005), from every `loda` record: a `loda` chunk's + // body starts with its own length. + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let mut named: Vec = (0..riff.len() - 28) + .filter(|&p| &riff[p..p + 4] == b"loda" && le32(p + 4) == le32(p + 8)) + .flat_map(|p| { + let loda = p + 8; + let (n, offsets, types) = (le32(loda + 4), loda + le32(loda + 8), loda + le32(loda + 12)); + (0..n).filter(move |i| le32(types + 4 * (n - 1 - i)) == 8005).map(move |i| le32(loda + le32(offsets + 4 * i)) as u32) + }) + .collect(); + named.sort_unstable(); + // Each container names its group by the group's `spnd` id unchanged, and no two name one group. + assert_eq!(named, distinct); +} + +#[test] +fn shapes_with_the_same_fill_and_outline_share_one_record_of_each() { + let fill = || Some(Color::Rgb([c(10), c(20), c(30)])); + let records = |d: &Drawing| { + let riff = riff_of(&write(d, Limits::default()).unwrap()); + (count(&riff, b"fild"), count(&riff, b"outl")) + }; + assert_eq!(records(&one_layer((0..50).map(|i| rect(1000 + i, 1000, fill())).collect())), records(&one_layer(vec![rect(1000, 1000, fill())]))); +} + +#[test] +fn a_closed_subpath_ends_at_its_start_and_its_other_nodes_can_be_edited() { + let start = pt(1234, 5678); + let open_end = SubPath { start, segments: vec![Segment::Line(pt(90_000, 5678)), Segment::Line(pt(1234, 90_000))], closed: true }; + let triangle = + |sp: SubPath| one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(Path { subpaths: vec![sp] }), Matrix::IDENTITY, None, None)))]); + let riff = riff_of(&write(&triangle(open_end.clone()), Limits::default()).unwrap()); + // The closing point at the start, then the type bytes: an editable closed move, two editable + // line ends and the closing line end, which is not editable. + let tail: Vec = [1234i32, 5678].iter().flat_map(|v| v.to_le_bytes()).chain([0x0C, 0x44, 0x44, 0x48]).collect(); + assert_eq!(count(&riff, &tail), 1); + // A subpath that already ends at its start is written as it is. + let mut ends_at_start = open_end; + ends_at_start.segments.push(Segment::Line(start)); + assert_eq!(riff_of(&write(&triangle(ends_at_start), Limits::default()).unwrap()), riff); +} + +#[test] +fn every_page_names_the_master_pages_guides_desktop_and_grid_by_their_ids() { + let mut d = everything(); + // A drawing layer of the master page, which the other pages do not name. The drawing has no + // grid layer of its own, as a read drawing has none. + d.master.push(layer("Master art", vec![rect(100, 100, None)])); + let riff = riff_of(&write(&d, Limits::default()).unwrap()); + let layers = layer_entries(&riff); + // Each page names the master page's guides, desktop and grid layers (object types 12, 17 and + // 11) once each, by kind, name and id: the guides and desktop before the page's own layers, + // the grid after them. + let named = |page: usize, kinds: &[usize]| { + let kept = |l: &&Entry| l.0 == page && l.1 == 1 && kinds.contains(&l.2); + let mut v: Vec<_> = layers.iter().filter(kept).map(|l| (l.2, &l.3, &l.4)).collect(); + v.sort(); + v + }; + assert_eq!(named(0, &[11, 12, 17]).len(), 3); + for page in 1..=d.pages.len() { + assert_eq!(named(page, &[11, 12, 17, 0]), named(0, &[11, 12, 17])); + let kinds: Vec = layers.iter().filter(|l| l.0 == page).map(|l| if l.1 == 0 { 0 } else { l.2 }).collect(); + let own = kinds.iter().position(|k| *k == 0).unwrap(); + assert!(kinds[..own].iter().all(|k| [12, 17].contains(k)) && kinds[own..].iter().filter(|k| **k != 0).all(|k| *k == 11), "{kinds:?}"); + assert!(kinds.ends_with(&[11]), "{kinds:?}"); + } + // The master page's layers and the pages' own layers each have their own 16-byte id. + let mut own: Vec<&[u8]> = layers.iter().filter(|l| l.0 == 0 || l.1 == 0).map(|l| &l.4[..]).collect(); + assert!(own.iter().all(|id| id.len() == 16)); + let count = own.len(); + own.sort(); + own.dedup(); + assert_eq!(own.len(), count); + // The guides layer, the first layer written, gets another id in a drawing that differs only in + // a fill color. + // A guides layer of the drawing's own master page takes the drawing's guidelines too, and is + // the only guides layer there; a hidden or locked one keeps them off it. + let guide = |x: i32| Guideline { at: pt(x, 0), angle: 90.0, hidden: false }; + let with_guides = |flags: Flags, drawing_guides: Vec| { + let mut guides = layer("Guides", Vec::new()); + guides.kind = LayerKind::Guides; + guides.flags = flags; + guides.guides = vec![guide(100)]; + Drawing { master: vec![guides], guides: drawing_guides, ..one_layer(Vec::new()) } + }; + for (flags, drawing_guides, layers) in [ + (Flags::default(), vec![guide(200)], 1), + (Flags { hidden: true, locked: false }, Vec::new(), 1), + (Flags { hidden: true, locked: false }, vec![guide(200)], 2), + (Flags { hidden: false, locked: true }, vec![guide(200)], 2), + ] { + let d = with_guides(flags, drawing_guides.clone()); + let file = write(&d, Limits::default()).unwrap(); + let entries = layer_entries(&riff_of(&file)); + assert_eq!(entries.iter().filter(|l| l.0 == 0 && l.2 == 12).count(), layers, "{flags:?}"); + // Each guideline once, the drawing's in a layer that is shown and unlocked: each guideline + // object's x (in units), and bytes 0 and 1 of the flags of the layer it is in. + let riff = riff_of(&file); + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let mut placed: Vec<(i32, u8, u8)> = (0..riff.len() - 28) + .filter(|&p| &riff[p..p + 4] == b"loda" && le32(p + 8 + 16) == 0x16) + .map(|p| { + let arg = p + 8 + le32(p + 8 + le32(p + 8 + 8)); + let layr = riff[..p].windows(8).rposition(|w| w == b"layrflgs").unwrap(); + (i32::from_le_bytes(riff[arg + 16..arg + 20].try_into().unwrap()), riff[layr + 12], riff[layr + 13]) + }) + .collect(); + placed.sort(); + let xs: Vec = placed.iter().map(|g| g.0).collect(); + assert_eq!(xs, if drawing_guides.is_empty() { vec![100] } else { vec![100, 200] }, "{flags:?}"); + assert!(placed.iter().filter(|g| g.0 == 200).all(|g| g.1 & 0x10 == 0 && g.2 == 0), "{flags:?}"); + } + let first = |c: Color| layer_entries(&riff_of(&write(&one_layer(vec![rect(100, 100, Some(c))]), Limits::default()).unwrap()))[0].4.clone(); + assert_ne!(first(Color::Gray(0.0)), first(Color::Gray(1.0))); +} + +/// A layer list of a written file: its page (0 the master page), byte 2 of its flags, its object +/// type, and its name and id arguments. +type Entry = (usize, u8, usize, Vec, Vec); + +/// The layer lists of `riff`, each `layr` with its `flgs` chunk, then `LIST lgob` with its `loda`. +fn layer_entries(riff: &[u8]) -> Vec { + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let pages: Vec = riff.windows(12).enumerate().filter(|(_, w)| &w[..4] == b"LIST" && &w[8..] == b"page").map(|(p, _)| p).collect(); + riff.windows(8) + .enumerate() + .filter(|(_, w)| w == b"layrflgs") + .map(|(p, _)| { + let page = pages.iter().filter(|&&at| at < p).count() - 1; + let loda = p + 36; + let (n, offsets, types) = (le32(loda + 4), loda + le32(loda + 8), loda + le32(loda + 12)); + let arg = |t: usize| { + let i = (0..n).find(|i| le32(types + 4 * (n - 1 - i)) == t).unwrap(); + riff[loda + le32(offsets + 4 * i)..loda + le32(offsets + 4 * i + 4)].to_vec() + }; + (page, riff[p + 14], le32(loda + 16), arg(1000), arg(40050)) + }) + .collect() +} + +#[test] +fn a_guideline_runs_along_the_angle_it_stores() { + // Starts `by` units inside a corner of the coordinate range. + let near = |by: f64| Pt { x: u(i32::MAX) - by * u(1), y: u(i32::MAX) - by * u(1) }; + let guide = |at: Pt, angle: f64| Drawing { guides: vec![Guideline { at, angle, hidden: false }], ..one_layer(Vec::new()) }; + // A quarter of a unit past the corner, on the corner itself, and less than half a unit inside + // it, the start rounds onto the corner, and no other point of the line rounds within the range + // along it. The last line runs almost level, so every point of it in the range rounds onto the + // corner too, as does the line that starts on the corner and half a unit past it. + let on_corner = Pt { x: 608_735.521_984_251_9, y: 608_735.521_984_251_9 }; + let level = [(near(-0.49), -0.9), (Pt { x: 608_735.521_984_252, y: 608_735.522_125_984_2 }, -0.00004)]; + for (at, angle) in [near(-0.25), on_corner, near(0.1), near(0.01), near(0.00025)].map(|at| (at, -45.0)).into_iter().chain(level) { + assert!(matches!(write(&guide(at, angle), Limits::default()), Err(Error::Unwritable(_))), "{at:?}"); + } + let inside = [(pt(1000, 2000), 30.0), (pt(1000, 2000), -45.0), (pt(1000, 2000), 1e20)]; + // A unit or more inside the corner, a point a whole unit or more away on each axis fits; + // at 1.25 units the farthest points in the range round off the angle and a nearer one does not. + // At -44 degrees the only point along the line turns from it by exactly a degree. At -18 + // degrees the one point along the line lies between whole units on both axes. + let between = Pt { x: u(i32::MAX) - 2.0 * u(1), y: u(i32::MAX) - 1.48 * u(1) }; + // A start a unit and a half and half a unit inside the corner lies on the edges of rounding. + let edges = Pt { x: 608_735.521_559_055_1, y: 608_735.521_842_519_8 }; + let near_corner = [(near(1000.0), -45.0), (near(1.25), -45.0), (near(1.0), -45.0), (near(1.0), -44.0), (between, -18.0), (edges, -45.0)]; + for (at, angle) in inside.into_iter().chain(near_corner) { + let corner = at.x > u(1_000_000); + let d = Drawing { guides: vec![Guideline { at, angle, hidden: false }], ..one_layer(Vec::new()) }; + let riff = riff_of(&write(&d, Limits::default()).unwrap_or_else(|e| panic!("{at:?} {angle}: {e}"))); + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let i32_at = |at: usize| f64::from(i32::from_le_bytes(riff[at..at + 4].try_into().unwrap())); + // The guideline object's `loda` (object type 0x16) and its first argument: 12 bytes, the + // angle in millionths of a degree, then the point and a second point on the line. + let loda = riff.windows(4).enumerate().map(|(p, _)| p).find(|&p| &riff[p..p + 4] == b"loda" && le32(p + 8 + 16) == 0x16).unwrap() + 8; + let arg = loda + le32(loda + le32(loda + 8)); + let a = (i32_at(arg + 12) / 1e6).to_radians(); + let (dx, dy) = (i32_at(arg + 24) - i32_at(arg + 16), i32_at(arg + 28) - i32_at(arg + 20)); + assert!(dx.hypot(dy) > if corner { 0.0 } else { 1000.0 }); + // Off the stored direction by no more than the coordinates' rounding, and, on either + // side, by no more than a degree. + assert!((dx * a.sin() - dy * a.cos()).abs() <= 1.5, "{angle}: {dx} {dy}"); + let turn = (dx * a.sin() - dy * a.cos()).abs().atan2((dx * a.cos() + dy * a.sin()).abs()); + assert!(turn <= 1f64.to_radians() + 1e-12, "{angle}: {dx} {dy}"); + } +} + +#[test] +fn an_outline_record_ends_8_bytes_before_its_chunk_and_its_color_list_at_its_empty_property() { + let spot = Color::Spot { name: "Ink".into(), tint: 1.0, look: Some([0.0; 3]) }; + let o = Outline { width: u(2540), color: spot, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false }; + let outlined = one_layer(vec![Object::Shape(Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o))))]); + let riff = riff_of(&write(&outlined, Limits::default()).unwrap()); + let le32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + let at = riff.windows(4).position(|w| w == b"outl").unwrap(); + let chunk = &riff[at + 8..at + 8 + le32(&riff, at + 4)]; + // The outline's id, then records (type, length, body) up to the one of type 1. + let mut p = 4; + let mut types = Vec::new(); + loop { + let (kind, len) = (le32(chunk, p), le32(chunk, p + 4)); + types.push(kind); + if kind == 1 { + assert_eq!(len, chunk.len() - p - 8 - 8); + // The body as sample files lay it out (R71): 130 bytes, an f64 1 at bytes 16 and 48, + // 45 degrees at byte 84 and 60 at byte 88. + let body = &chunk[p + 8..p + 8 + len]; + let f64_at = |at: usize| f64::from_le_bytes(body[at..at + 8].try_into().unwrap()); + assert_eq!((len, f64_at(16), f64_at(48), le32(body, 84), le32(body, 88)), (130, 1.0, 1.0, 45_000_000, 60)); + break; + } + // The color property list (type byte, length, body) ends at its first empty property. + if kind == 2 { + let mut q = p + 8; + while chunk[q] != 0 { + q += 5 + le32(chunk, q + 1); + } + assert_eq!((q + 5, le32(chunk, q + 1)), (p + 8 + len, 0)); + } + p += 8 + len; + } + assert_eq!(types, [2, 1]); +} + +#[test] +fn a_transparency_names_a_white_fill_record_of_the_file() { + let mut s = Shape::new(rect_geometry(), Matrix::IDENTITY, Some(Color::Gray(1.0)), None); + s.opacity = 0.5; + let riff = riff_of(&write(&one_layer(vec![Object::Shape(Box::new(s))]), Limits::default()).unwrap()); + let head: Vec = [1300u32, 117].iter().flat_map(|v| v.to_le_bytes()).collect(); + let at = riff.windows(head.len()).position(|w| w == head).unwrap() + head.len(); + let id = &riff[at + 105..at + 109]; + // The `fild` chunk of that id (chunk id, size, record id) holds the RGB color record of white. + let fild = riff.windows(12).position(|w| &w[..4] == b"fild" && &w[8..] == id).unwrap(); + let size = u32::from_le_bytes(riff[fild + 4..fild + 8].try_into().unwrap()) as usize; + let white = [5, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0]; + assert_eq!(count(&riff[fild + 8..fild + 8 + size], &white), 1); +} + +#[test] +fn empty_groups_are_left_out_and_a_container_without_objects_is_a_shape() { + let container = Shape::new(Geometry::Ellipse { w: u(10_000), h: u(10_000) }, Matrix::IDENTITY, None, None); + let objects = vec![ + Object::Group { objects: Vec::new(), flags: Flags::default() }, + Object::Clip { container: Box::new(container.clone()), objects: Vec::new() }, + ]; + let back = read(&write(&one_layer(objects), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers[0].objects, vec![Object::Shape(Box::new(container.clone()))]); + assert!(back.warnings.is_empty()); + // A container whose objects are groups that draw nothing is written as the plain shape is. + let hollow = Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() }; + let clips_hollow = one_layer(vec![Object::Clip { container: Box::new(container.clone()), objects: vec![hollow] }]); + let file = write(&clips_hollow, Limits::default()).unwrap(); + assert_eq!(file, write(&one_layer(vec![Object::Shape(Box::new(container))]), Limits::default()).unwrap()); + // A group that holds only groups that draw nothing is written as no group at all. + assert_eq!(write(&one_layer(vec![hollow_group()]), Limits::default()).unwrap(), write(&one_layer(Vec::new()), Limits::default()).unwrap()); +} + +fn hollow_group() -> Object { + Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() } +} + +#[test] +fn a_drawing_without_pages_is_written_with_one_empty_page() { + let d = Drawing { pages: Vec::new(), ..one_layer(Vec::new()) }; + let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(back.pages.len(), 1); + assert!(back.pages[0].layers.iter().all(|l| l.objects.is_empty())); + // Without a page size of its own, the drawing reads back without one. + assert_eq!(back.page_size, None); +} + +/// At the smallest value of a limit at which the reader reads `d`'s file whole, the writer writes +/// it; one below, the writer refuses it. +fn writes_at_the_readers_limit(d: &Drawing, set: fn(&mut Limits, usize)) -> usize { + let limits = |n| { + let mut l = Limits::default(); + set(&mut l, n); + l + }; + let file = write(d, Limits::default()).unwrap(); + let whole = |n| read(&file, limits(n)).is_ok_and(|b| b.warnings.is_empty()); + // The smallest value that reads whole: a read that fits a limit fits every larger one. + let (mut n, mut above) = (0, 100_000); + while n < above { + let mid = (n + above) / 2; + if whole(mid) { above = mid } else { n = mid + 1 } + } + assert!(whole(n), "{n}"); + assert_eq!(write(d, limits(n)).as_ref(), Ok(&file), "{n}"); + assert!(n > 0 && matches!(write(d, limits(n - 1)), Err(Error::Limit(_))), "{n}"); + n +} + +#[test] +fn every_limit_a_read_applies_is_applied_when_writing() { + let d = everything(); + let set: [fn(&mut Limits, usize); 10] = [ + |l, n| l.input = n, + |l, n| l.inflated = n, + |l, n| l.arguments = n, + |l, n| l.clipped_chunks = n, + |l, n| l.chunks = n, + |l, n| l.member = n, + |l, n| l.dashes = n, + |l, n| l.objects = n, + |l, n| l.coordinates = n, + |l, n| l.members = n, + ]; + for set in set { + writes_at_the_readers_limit(&d, set); + } + // Without clipped groups the outline table ends the file: an empty drawing, and one whose + // last record is an outline. + let o = Outline { + width: u(2540), + color: Color::Gray(0.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let outlined = one_layer(vec![Object::Shape(Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o))))]); + let bytes: [fn(&mut Limits, usize); 3] = [|l, n| l.input = n, |l, n| l.inflated = n, |l, n| l.member = n]; + for d in [one_layer(Vec::new()), outlined] { + for set in bytes { + writes_at_the_readers_limit(&d, set); + } + } + // A group that holds only an empty group is left out, and takes nothing of the object count. + let hollow = + one_layer(vec![Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() }]); + assert!(write(&hollow, Limits { objects: 0, ..Limits::default() }).is_ok()); +} + +#[test] +fn a_path_past_the_coordinate_count_stops_before_its_points_are_written() { + // The closing point's coordinates are past the file's range; the count is refused first. + let mut segments: Vec = (1..10).map(|i| Segment::Line(pt(i * 100, 0))).collect(); + segments.push(Segment::Line(Pt { x: 1e30, y: 0.0 })); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: true }] }; + let d = one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]); + assert!(matches!(write(&d, Limits::default()), Err(Error::Unwritable(_)))); + assert!(matches!(write(&d, Limits { coordinates: 5, ..Limits::default() }), Err(Error::Limit(_)))); + // A shape takes at least three arguments, counted before its points. + assert_eq!(write(&d, Limits { arguments: 2, ..Limits::default() }), Err(Error::Limit("argument count"))); + // So is the file's size, from the segment count: a long path refused at half its bytes. + let long = |end: Pt| { + let mut segments: Vec = (1..1000).map(|i| Segment::Line(pt(i * 100, i % 2 * 100))).collect(); + segments.push(Segment::Line(end)); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: true }] }; + one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]) + }; + let member = riff_of(&write(&long(pt(0, 100)), Limits::default()).unwrap()).len() - 1000 * 9 / 2; + assert!(matches!(write(&long(Pt { x: 1e30, y: 0.0 }), Limits::default()), Err(Error::Unwritable(_)))); + assert!(matches!(write(&long(Pt { x: 1e30, y: 0.0 }), Limits { member, ..Limits::default() }), Err(Error::Limit(_)))); + // So are the shape's nested lists: one level short of what a rectangle in its place takes. + let fits = |n| write(&one_layer(vec![rect(100, 100, None)]), Limits { depth: n, ..Limits::default() }).is_ok(); + let depth = (1..64).find(|&n| fits(n)).unwrap(); + assert_eq!(write(&d, Limits { depth: depth - 1, ..Limits::default() }), Err(Error::Limit("nesting depth"))); + // In a clipped group, every other chunk of the file counts too: one chunk short of what the + // drawing takes with a path in range, the clipped path is refused before its points. + let clipped = |path: Path| { + let container = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None); + // A fill of its own, whose record counts as well. + let shape = Shape::new(Geometry::Path(path), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + one_layer(vec![Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(shape))] }]) + }; + let Some(Object::Shape(s)) = d.pages[0].layers[0].objects.first() else { panic!("no path") }; + let Geometry::Path(past) = s.geometry.clone() else { panic!("no path") }; + let mut within = past.clone(); + within.subpaths[0].segments.pop(); + let chunks = (1..1000).find(|&n| write(&clipped(within.clone()), Limits { chunks: n, ..Limits::default() }).is_ok()).unwrap(); + assert!(matches!(write(&clipped(past.clone()), Limits::default()), Err(Error::Unwritable(_)))); + assert_eq!(write(&clipped(past), Limits { chunks: chunks - 1, ..Limits::default() }), Err(Error::Limit("chunk count"))); +} + +#[test] +fn a_rectangle_repeats_the_scale_of_its_transform() { + // Scaled by 2 and 3, then turned a quarter turn: the scale fields hold 2 and 3 (R29). + for m in [Matrix([2.0, 0.0, 0.0, 3.0, 5.0, 7.0]), Matrix([0.0, 2.0, -3.0, 0.0, 5.0, 7.0])] { + let shape = Shape::new(Geometry::Rect { w: u(1000), h: u(2000), radii: [0.0; 4] }, m, None, None); + let riff = riff_of(&write(&one_layer(vec![Object::Shape(Box::new(shape))]), Limits::default()).unwrap()); + // The record's width and height in coordinate units, then the two scale fields. + let units = |v: f64| (v * (254_000.0 / 72.0)).to_le_bytes(); + let fields = [units(u(1000)), units(u(2000)), 2.0f64.to_le_bytes(), 3.0f64.to_le_bytes()].concat(); + assert_eq!(count(&riff, &fields), 1, "{m:?}"); + } +} + +#[test] +fn the_pages_clipped_groups_and_records_share_the_byte_limit() { + // A long path on the page and another in a clipped group each fit the limit; together they do + // not, and writing stops at the second before it reaches the unwritable shape after it. + let long = || { + let segments = (1..4000).map(|i| Segment::Line(pt(i * 100, (i % 7) * 100))).collect(); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: false }] }; + Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None))) + }; + let container = || Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, None)); + let fits = one_layer(vec![long(), Object::Clip { container: container(), objects: vec![long()] }]); + let past = Shape::new(Geometry::Rect { w: 1e30, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None); + let stops = one_layer(vec![long(), Object::Clip { container: container(), objects: vec![long(), Object::Shape(Box::new(past))] }]); + assert!(matches!(write(&stops, Limits::default()), Err(Error::Unwritable(_)))); + let member = riff_of(&write(&fits, Limits::default()).unwrap()).len() - 4000 * 9 / 2; + assert!(matches!(write(&stops, Limits { member, ..Limits::default() }), Err(Error::Limit(_)))); + // Shapes whose fills all differ: the page fits the limit, and the fill table takes it past + // before the writer reaches the unwritable shape at the end of the page. + let shapes = || (0..=255u8).map(|v| rect(1000, 1000, Some(Color::Gray(c(v))))).collect::>(); + let riff = riff_of(&write(&one_layer(shapes()), Limits::default()).unwrap()); + let filt = riff.windows(12).position(|w| &w[..4] == b"LIST" && &w[8..] == b"filt").unwrap(); + let table = u32::from_le_bytes(riff[filt + 4..filt + 8].try_into().unwrap()) as usize; + let member = riff.len() - table / 2; + let past = Shape::new(Geometry::Rect { w: 1e30, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None); + let stops = one_layer(shapes().into_iter().chain([Object::Shape(Box::new(past))]).collect()); + assert!(matches!(write(&stops, Limits::default()), Err(Error::Unwritable(_)))); + assert!(matches!(write(&stops, Limits { member, ..Limits::default() }), Err(Error::Limit(_)))); +} + +#[test] +fn clips_nest_as_deep_as_a_read_takes() { + let nested = |depth: usize| { + let mut o = rect(100, 100, None); + for _ in 0..depth { + let container = Shape::new(Geometry::Ellipse { w: u(1000), h: u(1000) }, Matrix::IDENTITY, None, None); + o = Object::Clip { container: Box::new(container), objects: vec![o] }; + } + one_layer(vec![o]) + }; + let back = read(&write(&nested(64), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(rounded(back), as_read(nested(64))); + assert_eq!(write(&nested(65), Limits::default()), Err(Error::Limit("clip nesting"))); +} + +#[test] +fn ten_dashes_fit_before_the_arrowheads_and_eleven_do_not() { + let dashed = |n: usize| { + let o = Outline { + width: u(2540), + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: (1..=n).map(|d| d as f64).collect(), + behind_fill: false, + scale_with: false, + }; + one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Ellipse { w: u(1000), h: u(1000) }, Matrix::IDENTITY, None, Some(o))))]) + }; + let back = read(&write(&dashed(10), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(rounded(back), as_read(dashed(10))); + assert!(matches!(write(&dashed(11), Limits::default()), Err(Error::Unwritable(_)))); +} + +#[test] +fn names_and_values_the_reader_would_change_are_refused() { + let named = |name: String| Drawing { pages: vec![Page { size: None, layers: vec![layer(&name, Vec::new())] }], ..one_layer(Vec::new()) }; + let back = read(&write(&named("é".repeat(256)), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers[0].name, "é".repeat(256)); + assert!(back.warnings.is_empty()); + for name in ["é".repeat(257), "A\0B".to_string()] { + assert!(matches!(write(&named(name), Limits::default()), Err(Error::Unwritable(_)))); + } + let filled = |c: Color| one_layer(vec![rect(100, 100, Some(c))]); + // At a 10% tint, the stored byte nearest a black look reads back a step off, and the next one + // reads back black. + let black_tint = Color::Spot { name: "Ink".into(), tint: 0.1, look: Some([0.0; 3]) }; + let back = read(&write(&filled(black_tint.clone()), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(rounded(back), rounded(filled(black_tint))); + for c in [ + Color::Rgb([f32::NAN, 0.0, 0.0]), + Color::Gray(1.5), + Color::Spot { name: String::new(), tint: 1.0, look: None }, + Color::Spot { name: "Red".into(), tint: 0.0, look: Some([1.0, 0.0, 0.0]) }, + Color::Spot { name: "Gray".into(), tint: 0.01, look: Some([0.5, 0.5, 0.5]) }, + ] { + assert!(matches!(write(&filled(c), Limits::default()), Err(Error::Unwritable(_)))); + } + // A corner past half the shorter side, a page of no width, a dash past what a u16 holds. + let corner = Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [9.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, None, None); + assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(corner))]), Limits::default()), Err(Error::Unwritable(_)))); + let flat = Drawing { page_size: Some((0.0, 10.0)), ..one_layer(Vec::new()) }; + assert!(matches!(write(&flat, Limits::default()), Err(Error::Unwritable(_)))); + let long = Outline { + width: 1.0, + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: vec![100_000.0], + behind_fill: false, + scale_with: false, + }; + let fine = Outline { dashes: vec![0.4, 0.4], ..long.clone() }; + for o in [long, fine] { + let dashed = Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o)); + assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(dashed))]), Limits::default()), Err(Error::Unwritable(_)))); + } + let mut see_through = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None); + see_through.opacity = f32::NAN; + assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(see_through))]), Limits::default()), Err(Error::Unwritable(_)))); + let mut grid = layer("Grid", vec![rect(100, 100, None)]); + grid.kind = LayerKind::Grid; + assert!(matches!(write(&Drawing { master: vec![grid], ..one_layer(Vec::new()) }, Limits::default()), Err(Error::Unwritable(_)))); +} + +fn rect_geometry() -> Geometry { + Geometry::Rect { w: u(1000), h: u(1000), radii: [0.0; 4] } +} + +#[test] +fn a_grid_layer_keeps_its_lock_state() { + for locked in [false, true] { + let mut grid = layer("Grid", vec![rect(100, 100, None)]); + grid.kind = LayerKind::Grid; + grid.flags.locked = locked; + let d = Drawing { pages: vec![Page { size: None, layers: vec![grid] }], ..one_layer(Vec::new()) }; + let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!((back.pages[0].layers[0].kind, back.pages[0].layers[0].flags.locked), (LayerKind::Grid, locked)); + } +} + +/// A drawing at a limit is written and read whole; one past it is refused. +#[test] +fn drawings_past_what_a_read_takes_are_refused() { + let flat = |n: i32| one_layer((0..n).map(|i| rect(100 + i, 100, None)).collect()); + let limits = Limits { objects: 10, ..Limits::default() }; + let back = read(&write(&flat(10), limits).unwrap(), limits).unwrap(); + assert!(back.warnings.is_empty()); + assert_eq!(write(&flat(11), limits), Err(Error::Limit("object count"))); + // Groups nested in groups: each one takes a list. + let nested = |depth: usize| { + let mut o = rect(100, 100, None); + for _ in 0..depth { + o = Object::Group { objects: vec![o], flags: Flags::default() }; + } + one_layer(vec![o]) + }; + // The smallest depth a read of eight nested groups takes whole is the smallest the writer + // takes, and a ninth group is refused at it. + let depth = writes_at_the_readers_limit(&nested(8), |l, n| l.depth = n); + assert_eq!(write(&nested(9), Limits { depth, ..Limits::default() }), Err(Error::Limit("nesting depth"))); + let limits = Limits { depth: 12, ..Limits::default() }; + // Groups that hold nothing are refused past the depth too, in a layer and in a clip. + let hollow = |depth: usize| { + let mut o = Object::Group { objects: Vec::new(), flags: Flags::default() }; + for _ in 0..depth { + o = Object::Group { objects: vec![o], flags: Flags::default() }; + } + o + }; + // `hollow(n)` is n + 1 groups deep. + let clip = |o| Object::Clip { container: Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, None)), objects: vec![o] }; + for wrap in [|o| o, clip] { + assert!(write(&one_layer(vec![wrap(hollow(11))]), limits).is_ok()); + assert_eq!(write(&one_layer(vec![wrap(hollow(12))]), limits), Err(Error::Limit("nesting depth"))); + } + let limits = Limits { coordinates: 3, ..Limits::default() }; + let line = |n: i32| { + let segments = (1..n).map(|i| Segment::Line(pt(i, i))).collect(); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: false }] }; + one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]) + }; + assert!(read(&write(&line(3), limits).unwrap(), limits).unwrap().warnings.is_empty()); + assert_eq!(write(&line(4), limits), Err(Error::Limit("coordinate count"))); +} + +#[test] +fn numbers_the_file_cant_hold_are_refused() { + let with = |s: Shape| one_layer(vec![Object::Shape(Box::new(s))]); + let far = Shape::new(Geometry::Ellipse { w: 1e9, h: 1.0 }, Matrix::IDENTITY, None, None); + assert!(matches!(write(&with(far), Limits::default()), Err(Error::Unwritable(_)))); + let nan = Shape::new(Geometry::Rect { w: f64::NAN, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None); + assert!(matches!(write(&with(nan), Limits::default()), Err(Error::Unwritable(_)))); + let inf = Shape::new(Geometry::Ellipse { w: 1.0, h: 1.0 }, Matrix([f64::INFINITY, 0.0, 0.0, 1.0, 0.0, 0.0]), None, None); + assert!(matches!(write(&with(inf), Limits::default()), Err(Error::Unwritable(_)))); +} + +#[test] +fn values_outside_their_range_are_refused() { + let with = |s: Shape| one_layer(vec![Object::Shape(Box::new(s))]); + let outlined = |width: f64| Outline { + width, + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let mut opaque = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None); + opaque.opacity = 1.5; + let far = Path { subpaths: vec![SubPath { start: Pt { x: 1e9, y: 0.0 }, segments: vec![Segment::Line(pt(0, 0))], closed: false }] }; + let cases = [ + ("negative outline width", with(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(outlined(-1.0))))), + // A width of 0 reads back as no width. + ("positive outline width that rounds to 0", with(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(outlined(u(1) / 4.0))))), + ("negative corner radius", with(Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [-1.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, None, None))), + ("opacity past 1", with(opaque)), + ("tint past 1", one_layer(vec![rect(100, 100, Some(Color::Spot { name: "Red".into(), tint: 1.5, look: Some([1.0, 1.0, 1.0]) }))])), + ("path point past 32 bits", with(Shape::new(Geometry::Path(far), Matrix::IDENTITY, None, None))), + ("page size past 32 bits", Drawing { page_size: Some((1e9, 10.0)), ..one_layer(Vec::new()) }), + ]; + let written: Vec<_> = + cases.iter().filter(|(_, d)| !matches!(write(d, Limits::default()), Err(Error::Unwritable(_)))).map(|(what, _)| *what).collect(); + assert!(written.is_empty(), "{written:?}"); +} + +fn arb_color() -> impl Strategy { + prop_oneof![ + any::<[u8; 3]>().prop_map(|v| Color::Rgb(v.map(c))), + any::<[u8; 4]>().prop_map(|v| Color::Cmyk(v.map(c))), + any::().prop_map(|v| Color::Gray(c(v))), + Just(Color::Registration), + ] +} + +fn arb_shape() -> impl Strategy { + let size = || (-1_000_000i32..1_000_000, -1_000_000i32..1_000_000); + let geometry = prop_oneof![ + size().prop_map(|(w, h)| Geometry::Rect { w: u(w), h: u(h), radii: [0.0; 4] }), + size().prop_map(|(w, h)| Geometry::Ellipse { w: u(w), h: u(h) }), + (prop::collection::vec(size(), 1..20), any::()).prop_map(|(pts, closed)| { + let segments = pts.iter().map(|&(x, y)| Segment::Line(pt(x, y))).collect(); + Geometry::Path(Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed }] }) + }), + ]; + (geometry, prop::option::of(arb_color()), any::(), -500i32..500) + .prop_map(|(g, fill, nonzero, x)| Shape { nonzero, ..Shape::new(g, moved(f64::from(x), -f64::from(x)), fill, None) }) +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })] + + #[test] + fn random_drawings_read_back_as_written(shapes in prop::collection::vec(arb_shape(), 0..30), grouped in 0usize..30) { + let mut objects: Vec = shapes.into_iter().map(|s| Object::Shape(Box::new(s))).collect(); + let tail = objects.split_off(grouped.min(objects.len())); + if !tail.is_empty() { + objects.push(Object::Group { objects: tail, flags: Flags::default() }); + } + let d = Drawing { page_size: Some((u(1_000_000), u(1_000_000))), ..one_layer(objects) }; + let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap(); + prop_assert!(back.warnings.is_empty()); + prop_assert_eq!(rounded(back), as_read(d)); + } + + #[test] + fn writing_never_panics( + w in prop_oneof![-1e4..1e4f64, any::()], + h in prop_oneof![-1e4..1e4f64, any::()], + m in prop_oneof![prop::array::uniform6(-1e3..1e3f64), any::<[f64; 6]>()], + dashes in prop::collection::vec(prop_oneof![-1.0..20.0f64, any::()], 0..12), + opacity in prop_oneof![-0.5..1.5f32, any::()], + ) { + let outline = + Outline { width: w, color: Color::Gray(opacity), cap: Cap::Square, join: Join::Round, dashes, behind_fill: false, scale_with: false }; + // Corners within half the shorter side, so a rectangle of a size the file holds is written. + let r = w.abs().min(h.abs()) / 4.0; + let mut s = Shape::new(Geometry::Rect { w, h, radii: [r, 0.0, r, 0.0] }, Matrix(m), Some(Color::Rgb([opacity; 3])), Some(outline)); + s.opacity = opacity; + let d = Drawing { pages: vec![Page { size: Some((w, h)), layers: vec![layer("A", vec![Object::Shape(Box::new(s))])] }], ..everything() }; + if let Ok(file) = write(&d, Limits::default()) { + prop_assert!(read(&file, Limits::default()).is_ok()); + } + } +} diff --git a/crates/cloud-local/README.md b/crates/cloud-local/README.md index a5006c2ca3..a3c8d53c9e 100644 --- a/crates/cloud-local/README.md +++ b/crates/cloud-local/README.md @@ -37,3 +37,16 @@ write never truncates its target in place. It writes a new sibling file and rena over the target, so the target's directory entry is replaced rather than its bytes being overwritten. A rename only ever changes one name; it does not reach through to any other name, inside the root or out, that happens to point at the same inode. + +## Concurrent saves + +A `Job::Write` checks the file's etag again just before the rename, and holds one lock for this +process from that check until the rename is done. Within one process, when two saves are made +from the same etag, the second gets `Fault::Conflict`, unless the first save left the file with an +unchanged etag (see the next paragraph). A second process writing the same folder does not take +that lock, so its save can still land between the check and the rename. A deployment that needs +the guarantee across processes needs a backend whose provider offers a conditional write. + +The etag is the file's length and modification time. On a filesystem whose timestamps are coarser +than the time between two saves, two saves of the same length can leave the same etag, and the +second save is then not refused. diff --git a/crates/cloud-local/src/lib.rs b/crates/cloud-local/src/lib.rs index 715a870842..5fca54f9b7 100644 --- a/crates/cloud-local/src/lib.rs +++ b/crates/cloud-local/src/lib.rs @@ -62,6 +62,7 @@ use std::ffi::OsStr; use std::fs; use std::io::{Read as _, Write as _}; use std::path::{Component, Path, PathBuf}; +use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use cap_std::fs::{Dir, OpenOptions}; @@ -208,8 +209,9 @@ fn is_windows_reserved_name(name: &str) -> bool { /// outright first, because a Unix build's [`Component`] parser does not /// treat either as a separator and would wave a Windows drive letter or UNC /// prefix (`C:`, `\\server\share`) straight through as one ordinary name. A -/// Windows reserved device name is refused the same way. None of this costs -/// anything here, unlike applying it to a name `list` merely discovered. +/// Windows reserved device name is refused the same way, and so is a name +/// [`is_temp_name`] matches, which [`list`] would leave out. None of this +/// costs anything here, unlike applying it to a name `list` merely discovered. fn confine_name(name: &str) -> Result<&str, Fault> { if name.contains('\\') || name.contains(':') { return Err(Fault::Refused(format!("{name} is not a plain file name"))); @@ -217,6 +219,9 @@ fn confine_name(name: &str) -> Result<&str, Fault> { if is_windows_reserved_name(name) { return Err(Fault::Refused(format!("{name} is a reserved device name on Windows"))); } + if is_temp_name(name) { + return Err(Fault::Refused(format!("{name} is a name this backend uses for its temporary files"))); + } confine_segment(name) } @@ -252,6 +257,13 @@ fn io_fault(error: &std::io::Error) -> Fault { } } +/// Lists the files and folders in `path`. +/// +/// A regular file whose name [`is_temp_name`] matches is left out before its +/// metadata is read. Such a file is a save in progress, or one that was +/// stopped between its create and its rename, and it is not a document. +/// [`confine_name`] refuses these names for a new file. A folder or a link +/// with such a name is listed. fn list(root: &Path, path: &str) -> Result, Fault> { let rel = relative(path)?; let dir = open_root(root)?; @@ -260,8 +272,11 @@ fn list(root: &Path, path: &str) -> Result, Fault> { let mut entries = Vec::new(); for item in read { let item = item.map_err(|error| io_fault(&error))?; - let meta = item.metadata().map_err(|error| io_fault(&error))?; let name = item.file_name().to_string_lossy().into_owned(); + if is_temp_name(&name) && item.file_type().is_ok_and(|kind| kind.is_file()) { + continue; + } + let meta = item.metadata().map_err(|error| io_fault(&error))?; let id = child_path(path, &name); entries.push(Entry { room: format!("local:{id}"), @@ -322,64 +337,154 @@ fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec), Fault> { /// so a hard link sharing the target's inode keeps its own, unmodified copy: /// the rename replaces `entry.id`'s directory entry, and never reaches /// through to any other name pointing at the same inode. +/// +/// The etag is checked once before any bytes are written, and again under +/// [`WRITE_LOCK`] just before the rename. Two saves made from the same etag +/// at once otherwise both pass the check before either renames, both report +/// success, and the later rename replaces the first save without a +/// [`Fault::Conflict`]. fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result { let rel = relative(&entry.id)?; let dir = open_root(root)?; - match dir.symlink_metadata(&rel) { - Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())), - Ok(meta) => { - if Some(etag_of(&meta)) != entry.etag { - return Err(Fault::Conflict); - } - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(io_fault(&error)), - } + check_unchanged(&dir, &rel, entry)?; if let Some(parent) = rel.parent() { dir.create_dir_all(parent).map_err(|error| io_fault(&error))?; } - write_replacing(&dir, &rel, bytes)?; - let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; + let meta = write_replacing(&dir, &rel, bytes, || check_unchanged(&dir, &rel, entry))?; Ok(Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() }) } +/// Refuses a link at `rel`, and a file whose etag is no longer `entry.etag`. +/// A file that does not exist passes. +fn check_unchanged(dir: &Dir, rel: &Path, entry: &Entry) -> Result<(), Fault> { + match dir.symlink_metadata(rel) { + Ok(meta) if meta.is_symlink() => Err(Fault::Refused("that path is a link, not a plain file".to_owned())), + Ok(meta) if Some(etag_of(&meta)) != entry.etag => Err(Fault::Conflict), + Ok(_) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(io_fault(&error)), + } +} + +/// Held by [`write_replacing`] from its last check until the rename is done +/// and the new file's metadata is read, and by [`create_in_place`] from the +/// moment it creates its file until the file is complete or removed. No other +/// save in this process can change the file between a save's check and its +/// rename, a save cannot replace a file that `create_in_place` is still +/// writing, and `create_in_place` cannot remove a replacement when its own +/// write fails. The temporary file is written and synced before the lock is +/// taken, so a slow save does not hold up the others. Another process writing +/// the same folder is not covered. +static WRITE_LOCK: Mutex<()> = Mutex::new(()); + /// The next in a run of sibling temporary names, unique within this process. /// Not meant to resist a second process picking the same name; the create -/// this writes with is exclusive (`create_new`), so a collision there is -/// just retried under a new counter value rather than silently overwritten. +/// [`open_temp`] does is exclusive (`create_new`), so a collision there is +/// retried under a new counter value rather than silently overwritten. static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); +/// How many temporary names [`open_temp`] tries before it gives up. +const TEMP_ATTEMPTS: usize = 16; + +/// The start of every name [`temp_name`] makes. +const TEMP_PREFIX: &str = ".craft-save-"; + +/// The end of every name [`temp_name`] makes. +const TEMP_SUFFIX: &str = ".tmp"; + +/// The temporary name for process `pid`, clock part `started` and sequence +/// value `n`. [`is_temp_name`] matches every name this returns. +fn temp_name(pid: u32, started: u128, n: u64) -> String { + format!("{TEMP_PREFIX}{pid}-{started:x}-{n}{TEMP_SUFFIX}") +} + +/// Whether [`temp_name`] returns exactly `name` for some process id, clock +/// part and sequence value. The three parts are read back from `name` and +/// passed to `temp_name`, so a name the two would format differently (a +/// leading zero, an uppercase hexadecimal digit, a sign) does not match. +/// [`list`] leaves these names out. A name with only the same prefix and +/// suffix, such as `.craft-save-notes.tmp`, does not match and is listed. +fn is_temp_name(name: &str) -> bool { + let Some(middle) = name.strip_prefix(TEMP_PREFIX).and_then(|rest| rest.strip_suffix(TEMP_SUFFIX)) else { + return false; + }; + let mut parts = middle.split('-'); + let (Some(pid), Some(started), Some(n), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { + return false; + }; + match (pid.parse::(), u128::from_str_radix(started, 16), n.parse::()) { + (Ok(pid), Ok(started), Ok(n)) => temp_name(pid, started, n) == name, + _ => false, + } +} + +/// Creates a new hidden temporary file beside `rel`, named from +/// [`TEMP_SEQUENCE`], and returns its path and handle. A name that already +/// exists (a file another process or an earlier run left) is skipped for the +/// next one, and never opened or removed. The name does not include `rel`'s +/// file name, so a file name near the filesystem's length limit still gets a +/// temporary name that fits. +fn open_temp(dir: &Dir, rel: &Path) -> Result<(PathBuf, cap_std::fs::File), Fault> { + if rel.file_name().is_none() { + return Err(Fault::Refused("that path names no file".to_owned())); + } + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + // The clock part keeps a stale file from an earlier run with the same + // process id from matching a run of names, so needing all the attempts + // takes 16 files made for this exact moment. + let started = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_nanos()); + #[cfg(test)] + let started = if tests::FIXED_TEMP_CLOCK.with(std::cell::Cell::get) { 0 } else { started }; + let mut last = None; + for _ in 0..TEMP_ATTEMPTS { + let temp_name = temp_name(std::process::id(), started, TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed)); + let temp_rel = match rel.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name), + _ => PathBuf::from(&temp_name), + }; + match dir.open_with(&temp_rel, &options) { + Ok(handle) => return Ok((temp_rel, handle)), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => last = Some(error), + Err(error) => return Err(io_fault(&error)), + } + } + Err(last.map_or_else(|| Fault::Unreachable("no temporary name was free".to_owned()), |error| io_fault(&error))) +} + /// Writes `bytes` to a new sibling of `rel` inside `dir`, then renames that /// sibling over `rel`. See the module docs for why: a direct write would /// truncate whatever `rel` currently names in place, and if that happens to /// be a hard link to a file outside `root`, the outside copy would be /// corrupted along with it. A rename only ever replaces `rel`'s own /// directory entry. -fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> { - let name = rel.file_name().ok_or_else(|| Fault::Refused("that path names no file".to_owned()))?; - let mut temp_name = OsStr::new(".").to_os_string(); - temp_name.push(name); - temp_name.push(format!(".tmp-{}-{}", std::process::id(), TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed))); - let temp_rel = match rel.parent() { - Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name), - _ => PathBuf::from(&temp_name), - }; - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - let written = (|| -> Result<(), Fault> { - let mut handle = dir.open_with(&temp_rel, &options).map_err(|error| io_fault(&error))?; - handle.write_all(bytes).map_err(|error| io_fault(&error))?; - handle.sync_all().map_err(|error| io_fault(&error)) - })(); +/// +/// `check` runs under [`WRITE_LOCK`] right before the rename; when it fails, +/// the temporary file is removed and `rel` is left as it was. Returns the +/// metadata of the file just published. +fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8], check: impl FnOnce() -> Result<(), Fault>) -> Result { + let (temp_rel, mut handle) = open_temp(dir, rel)?; + let written = handle.write_all(bytes).map_err(|error| io_fault(&error)).and_then(|()| handle.sync_all().map_err(|error| io_fault(&error))); + drop(handle); if let Err(fault) = written { let _ = dir.remove_file(&temp_rel); return Err(fault); } - if let Err(error) = dir.rename(&temp_rel, dir, rel) { + #[cfg(test)] + tests::before_lock(); + let published = { + let _serialized = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + check().and_then(|()| { + #[cfg(test)] + tests::after_check(); + dir.rename(&temp_rel, dir, rel).map_err(|error| io_fault(&error))?; + dir.metadata(rel).map_err(|error| io_fault(&error)) + }) + }; + if published.is_err() { let _ = dir.remove_file(&temp_rel); - return Err(io_fault(&error)); } - Ok(()) + published } fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result { @@ -397,24 +502,46 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result handle, - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - return Err(Fault::Refused(format!("{name} already exists"))); - } + // A taken name is refused before any bytes are written. The hard link + // below is still the check that settles a race. + match dir.symlink_metadata(&rel) { + Ok(_) => return Err(Fault::Refused(format!("{name} already exists"))), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(io_fault(&error)), - }; - handle.write_all(bytes).map_err(|error| io_fault(&error))?; + } + // The bytes go to a sibling temporary file first. A write that fails part + // way (a full disk, a lost share) leaves only that file, which is removed, + // so the name stays free for the next Save As instead of holding a partial + // file that makes it fail with "already exists". + let (temp_rel, mut handle) = open_temp(&dir, &rel)?; + let written = write_new(&mut handle, bytes).and_then(|()| sync_new(&handle)); drop(handle); + if let Err(fault) = written { + let _ = dir.remove_file(&temp_rel); + return Err(fault); + } + // The finished file takes `name` with a hard link, not an `exists` check + // ahead of a rename: two creates of the same name racing both see "not + // there yet" otherwise, and the second silently replaces the first. A link + // fails when the name is taken, so the loser gets an error instead of a + // chance to overwrite the winner. It also fails when `name` already exists + // as a symlink, dangling or not. + #[cfg(not(test))] + let linked = dir.hard_link(&temp_rel, &dir, &rel); + #[cfg(test)] + let linked = if tests::NO_HARD_LINKS.with(std::cell::Cell::get) { + Err(std::io::Error::other("no hard links")) + } else { + dir.hard_link(&temp_rel, &dir, &rel) + }; + let _ = dir.remove_file(&temp_rel); + match linked { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Err(Fault::Refused(format!("{name} already exists"))), + // A filesystem without hard links (FAT, some network shares): the + // temporary copy is gone by now, and the file is created in place. + Err(_) => create_in_place(&dir, &rel, name, bytes)?, + } let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; let id = child_path(folder, name); Ok(Entry { @@ -432,9 +559,314 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result Result<(), Fault> { + let _writing = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut create_options = OpenOptions::new(); + create_options.write(true).create_new(true); + let mut handle = match dir.open_with(rel, &create_options) { + Ok(handle) => handle, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Err(Fault::Refused(format!("{name} already exists"))), + Err(error) => return Err(io_fault(&error)), + }; + let written = write_new(&mut handle, bytes).and_then(|()| sync_new(&handle)); + drop(handle); + #[cfg(test)] + tests::in_place_finished(); + if written.is_err() { + let _ = dir.remove_file(rel); + } + written +} + +/// Syncs a file [`create`] is making. +fn sync_new(handle: &cap_std::fs::File) -> Result<(), Fault> { + #[cfg(test)] + if tests::FAIL_CREATE_SYNC.with(|countdown| { + let left = countdown.get(); + countdown.set(left.saturating_sub(1)); + left == 1 + }) { + return Err(Fault::Unreachable("no space left on device".to_owned())); + } + handle.sync_all().map_err(|error| io_fault(&error)) +} + +/// Writes the bytes of a file [`create`] is making. +fn write_new(handle: &mut cap_std::fs::File, bytes: &[u8]) -> Result<(), Fault> { + #[cfg(test)] + if tests::FAIL_CREATE_WRITE.with(|countdown| { + let left = countdown.get(); + countdown.set(left.saturating_sub(1)); + left == 1 + }) { + let half = bytes.get(..bytes.len() / 2).unwrap_or_default(); + handle.write_all(half).map_err(|error| io_fault(&error))?; + return Err(Fault::Unreachable("no space left on device".to_owned())); + } + handle.write_all(bytes).map_err(|error| io_fault(&error)) +} + #[cfg(test)] mod tests { use super::*; + use std::sync::mpsc; + + /// Run once by the next [`write`] to pass its etag check, then cleared. + type Hook = Box; + static AFTER_CHECK: Mutex> = Mutex::new(None); + + pub(super) fn after_check() { + let hook = AFTER_CHECK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + + /// Run once by the next [`write_replacing`] to finish its temporary file, + /// before it takes [`WRITE_LOCK`], then cleared. + static BEFORE_LOCK: Mutex> = Mutex::new(None); + + pub(super) fn before_lock() { + let hook = BEFORE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + + fn entry_for(id: &str) -> Entry { + Entry { + room: format!("local:{id}"), + name: id.trim_start_matches('/').to_owned(), + kind: EntryKind::File, + size: None, + modified: None, + mime: None, + etag: None, + writable: true, + shared_by: None, + path: id.to_owned(), + id: id.to_owned(), + } + } + + #[test] + fn two_saves_from_one_etag_cannot_both_pass_the_check() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("Note.txt"), b"original").unwrap(); + let (read_entry, _) = read(root.path(), &entry_for("/Note.txt")).unwrap(); + + let (checked_tx, checked_rx) = mpsc::channel::<()>(); + let (go_tx, go_rx) = mpsc::channel::<()>(); + *AFTER_CHECK.lock().unwrap() = Some(Box::new(move || { + checked_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + })); + + let first = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"first save")) + }; + checked_rx.recv().unwrap(); + // The first save has passed its check and not yet renamed. A second + // save must not be able to reach its own check in between. + assert!(WRITE_LOCK.try_lock().is_err(), "the check and the rename must run under one lock"); + // The second save passes its early check and writes its temporary + // file before the first one renames, so only the recheck under the + // lock can refuse it. + let (ready_tx, ready_rx) = mpsc::channel::<()>(); + *BEFORE_LOCK.lock().unwrap() = Some(Box::new(move || ready_tx.send(()).unwrap())); + let second = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"second save")) + }; + ready_rx.recv().unwrap(); + go_tx.send(()).unwrap(); + + assert!(first.join().unwrap().is_ok()); + assert!(matches!(second.join().unwrap(), Err(Fault::Conflict)), "the second save started from a stale etag"); + assert_eq!(std::fs::read(root.path().join("Note.txt")).unwrap(), b"first save"); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Note.txt"], "the refused save's temporary file is removed"); + } + + thread_local! { + /// When set to n, the nth [`write_new`] call on this thread from now + /// writes half its bytes and fails. 0 turns it off. + pub(super) static FAIL_CREATE_WRITE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Makes [`create`] on this thread take the path for a filesystem + /// without hard links. + pub(super) static NO_HARD_LINKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Makes [`open_temp`] on this thread use 0 for its clock part. + pub(super) static FIXED_TEMP_CLOCK: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// When set to n, the nth [`sync_new`] call on this thread from now + /// fails. 0 turns it off. + pub(super) static FAIL_CREATE_SYNC: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Run once by [`create_in_place`] on this thread after its write and + /// sync, before it removes a failed file. + static IN_PLACE_FINISHED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + } + + pub(super) fn in_place_finished() { + if let Some(hook) = IN_PLACE_FINISHED.with(|hook| hook.borrow_mut().take()) { + hook(); + } + } + + #[test] + fn without_hard_links_a_failed_sync_leaves_no_file_and_keeps_a_concurrent_save() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + let path = root.path().to_path_buf(); + let held = std::rc::Rc::new(std::cell::Cell::new(false)); + let saver = std::rc::Rc::new(std::cell::RefCell::new(None)); + let (seen_held, seen_saver) = (held.clone(), saver.clone()); + IN_PLACE_FINISHED.with(|hook| { + *hook.borrow_mut() = Some(Box::new(move || { + seen_held.set(WRITE_LOCK.try_lock().is_err()); + // A save of the same name starts while the failed file is + // still there. It must not land before that file is removed. + *seen_saver.borrow_mut() = Some(std::thread::spawn(move || { + let dir = open_root(&path).unwrap(); + write_replacing(&dir, Path::new("Minutes.txt"), b"saved meanwhile", || Ok(())) + })); + })); + }); + NO_HARD_LINKS.with(|off| off.set(true)); + // The temporary copy syncs, then the in-place file's sync fails. + FAIL_CREATE_SYNC.with(|fail| fail.set(2)); + let failed = create(root.path(), "", "Minutes.txt", b"the whole document"); + FAIL_CREATE_SYNC.with(|fail| fail.set(0)); + NO_HARD_LINKS.with(|off| off.set(false)); + + assert!(matches!(failed, Err(Fault::Unreachable(_))), "a failed sync is a failed create: {failed:?}"); + assert!(held.get(), "the in-place file is written and removed under the write lock"); + let saver = saver.borrow_mut().take().unwrap(); + saver.join().unwrap().unwrap(); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Minutes.txt"]); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"saved meanwhile", "the removal took only the failed file"); + } + + /// Held by the tests that make temporary files, so the next value of + /// [`TEMP_SEQUENCE`] is known to the test that reads it. + static TEMP_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + #[test] + fn a_stale_temporary_file_is_skipped_and_kept() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + let next = TEMP_SEQUENCE.load(Ordering::Relaxed); + let stale: Vec<_> = (next..next + 3).map(|n| temp_name(std::process::id(), 0, n)).collect(); + for name in &stale { + std::fs::write(root.path().join(name), b"left by an earlier run").unwrap(); + } + FIXED_TEMP_CLOCK.with(|fixed| fixed.set(true)); + let made = create(root.path(), "", "Minutes.txt", b"minutes"); + FIXED_TEMP_CLOCK.with(|fixed| fixed.set(false)); + made.unwrap(); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"minutes"); + for name in &stale { + assert_eq!(std::fs::read(root.path().join(name)).unwrap(), b"left by an earlier run", "{name} is not this call's file"); + } + } + + #[test] + fn a_listing_leaves_out_a_temporary_file_a_stopped_save_left() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + std::fs::create_dir(root.path().join("Archive")).unwrap(); + std::fs::write(root.path().join("Minutes.txt"), b"minutes").unwrap(); + std::fs::write(root.path().join(".craft-save-notes.tmp"), b"a person's own file").unwrap(); + let folder = temp_name(1, 2, 3); + std::fs::create_dir(root.path().join(&folder)).unwrap(); + let dir = open_root(root.path()).unwrap(); + // A save stopped after its create and before its rename leaves the + // temporary file, at the root and inside a folder. + let (at_root, handle) = open_temp(&dir, Path::new("Minutes.txt")).unwrap(); + drop(handle); + let (in_folder, handle) = open_temp(&dir, &Path::new("Archive").join("Agenda.txt")).unwrap(); + drop(handle); + assert!(root.path().join(&at_root).exists() && root.path().join(&in_folder).exists()); + + let names: Vec<_> = list(root.path(), "").unwrap().into_iter().map(|entry| entry.name).collect(); + assert_eq!(names, [".craft-save-1-2-3.tmp", "Archive", ".craft-save-notes.tmp", "Minutes.txt"], "a folder with the pattern stays listed"); + assert!(list(root.path(), "/Archive").unwrap().is_empty()); + } + + #[test] + fn a_create_refuses_a_name_a_listing_would_leave_out() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + let name = temp_name(1, 2, 3); + assert!(matches!(create(root.path(), "", &name, b"bytes"), Err(Fault::Refused(_)))); + assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0); + create(root.path(), "", ".craft-save-notes.tmp", b"bytes").unwrap(); + } + + #[test] + fn is_temp_name_matches_only_the_names_temp_name_makes() { + assert!(is_temp_name(&temp_name(4242, 0x1a2b, 7))); + assert!(is_temp_name(&temp_name(u32::MAX, u128::MAX, u64::MAX))); + for other in [ + ".craft-save-notes.tmp", + ".craft-save-1-2.tmp", + ".craft-save-1-2-3-4.tmp", + ".craft-save--2-3.tmp", + ".craft-save-1-xy-3.tmp", + "craft-save-1-2-3.tmp", + ".craft-save-1-2-3.tmp.txt", + ".craft-save-01-2-3.tmp", + ".craft-save-1-2A-3.tmp", + ".craft-save-+1-2-3.tmp", + ] { + assert!(!is_temp_name(other), "{other} is not a temporary name"); + } + } + + #[test] + fn without_hard_links_a_create_still_refuses_a_taken_name_and_cleans_up() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + NO_HARD_LINKS.with(|off| off.set(true)); + let made = create(root.path(), "", "Minutes.txt", b"first"); + let taken = create(root.path(), "", "Minutes.txt", b"second"); + // The temporary copy is written, then the in-place write fails. + FAIL_CREATE_WRITE.with(|fail| fail.set(2)); + let failed = create(root.path(), "", "Agenda.txt", b"the whole agenda"); + FAIL_CREATE_WRITE.with(|fail| fail.set(0)); + NO_HARD_LINKS.with(|off| off.set(false)); + + assert_eq!(made.unwrap().size, Some(5)); + assert!(matches!(taken, Err(Fault::Refused(_)))); + assert!(matches!(failed, Err(Fault::Unreachable(_)))); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Minutes.txt"], "only the finished file is left"); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"first"); + } + + #[test] + fn a_create_whose_write_fails_leaves_no_file_behind() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + FAIL_CREATE_WRITE.with(|fail| fail.set(1)); + let failed = create(root.path(), "", "Minutes.txt", b"the whole document"); + FAIL_CREATE_WRITE.with(|fail| fail.set(0)); + assert!(matches!(failed, Err(Fault::Unreachable(_)))); + assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0, "no partial or temporary file is left"); + + let retried = create(root.path(), "", "Minutes.txt", b"the whole document").unwrap(); + assert_eq!(retried.size, Some(18)); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"the whole document"); + } #[test] fn a_parent_segment_cannot_walk_out_of_root() { diff --git a/crates/cloud-ui/src/cloud/backend.rs b/crates/cloud-ui/src/cloud/backend.rs index f92328cef2..d5479f3397 100644 --- a/crates/cloud-ui/src/cloud/backend.rs +++ b/crates/cloud-ui/src/cloud/backend.rs @@ -70,6 +70,9 @@ pub enum Event { }, } +/// An answer with the account generation its job was issued in. +pub(crate) type Stamped = (u64, Event); + /// Where a worker's answers go. /// /// Handed to [`CloudBackend::submit`] with the job it belongs to. A worker is @@ -77,7 +80,10 @@ pub enum Event { /// sign-in reports the URL it wants a browser pointed at and then reports that /// the user finished there. A send after the window closed is not a failure. pub struct Post { - tx: Sender, + /// Each event goes with the generation its job was issued in, so + /// [`super::pump`] can drop one that waited in the channel across a + /// sign-out or a new sign-in. + tx: Sender, /// The window's account generation as of the moment the job this answers /// was issued, beside a handle to what it is now. A sign-out or a new /// sign-in bumps the live value; a reply that arrives after is for a @@ -87,7 +93,7 @@ pub struct Post { } impl Post { - pub(crate) fn new(tx: Sender, generation: Arc) -> Post { + pub(crate) fn new(tx: Sender, generation: Arc) -> Post { let issued = generation.load(Ordering::Relaxed); Post { tx, generation, issued } } @@ -99,16 +105,19 @@ impl Post { Post { tx: self.tx.clone(), generation: self.generation.clone(), issued: self.issued } } - /// Delivers the event, unless the window has signed out or signed in - /// again since the job this answers was issued. Silently dropping it - /// there, rather than delivering it, is what keeps a late reply from - /// restoring the previous session's account, files or busy state on top - /// of whatever replaced it. + /// Queues the event with the generation its job was issued in. + /// + /// [`super::pump`] holds the check that keeps a late reply from restoring + /// the previous session's account, files or busy state on top of whatever + /// replaced it: it drops every event whose generation is not the current + /// one, including an event sent here just before a sign-out or a new + /// sign-in. This method only skips the send when the generation has + /// already moved on, so an answer that `pump` would drop is not queued. pub fn send(&self, event: Event) { if self.generation.load(Ordering::Relaxed) != self.issued { return; } - let _ = self.tx.send(event); + let _ = self.tx.send((self.issued, event)); } } diff --git a/crates/cloud-ui/src/cloud/conflict_tests.rs b/crates/cloud-ui/src/cloud/conflict_tests.rs index 1e22e815fe..8a1426be37 100644 --- a/crates/cloud-ui/src/cloud/conflict_tests.rs +++ b/crates/cloud-ui/src/cloud/conflict_tests.rs @@ -214,6 +214,53 @@ fn sign_out_recovers_save_after_a_backend_job_never_replies() { assert!(saved.is_ok(), "after sign-out and sign-in, Save is still refused: {saved:?}; busy={:?}", app.cloud.busy.as_ref().map(Busy::text)); } +/// While a sign-in waits on the browser, the previous account may still be the one the service +/// answers for. No folder is listed until the sign-in answers, and then both are listed again, +/// so a listing from before the sign-in does not stay on screen as the new account's files. +#[test] +fn folders_are_listed_again_only_after_a_sign_in_answers() { + let (mut app, held, _log) = two_tabs(); + let ctx = egui::Context::default(); + start(&mut app); + held.take(|j| matches!(j, Job::Account)).unwrap().1.send(Event::Account(Ok(account("Ada")))); + held.take(|j| matches!(j, Job::List(_))).unwrap().1.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Ada.note", "a1")]) }); + drain(&mut app, &ctx); + assert!(app.cloud.mine.loaded); + + sign_in(&mut app); + start(&mut app); + drain(&mut app, &ctx); + assert!(held.take(|j| matches!(j, Job::List(_))).is_none(), "a folder is listed before the sign-in says who is signed in"); + assert!(report(&app)["entries"].as_array().is_some_and(Vec::is_empty), "the previous account's files stay on screen during sign-in"); + + held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Grace")))); + drain(&mut app, &ctx); + assert!(!app.cloud.mine.loading && !app.cloud.mine.loaded && !app.cloud.shared.loading && !app.cloud.shared.loaded); + start(&mut app); + let (_, list_post) = held.take(|j| matches!(j, Job::List(_))).expect("the root folder is listed again once the sign-in answers"); + list_post.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Grace.note", "g1")]) }); + drain(&mut app, &ctx); + assert_eq!(report(&app)["entries"], serde_json::json!(["Grace.note"])); +} + +/// A sign-in empties the folder the Save As page was showing. Until it answers, a save would go +/// to the root rather than the folder the user picked, so Save As refuses. +#[test] +fn save_as_waits_for_a_sign_in_to_answer() { + let (mut app, held, _log) = two_tabs(); + browse(&mut app, "/Projects"); + sign_in(&mut app); + let folder = app.cloud.mine.path.clone(); + let refused = save_as(&mut app, &folder, "B"); + assert!(refused.is_err(), "Save As went ahead during sign-in: {refused:?}"); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none()); + + held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Ada")))); + drain(&mut app, &egui::Context::default()); + assert!(save_as(&mut app, "", "B").is_ok()); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_some()); +} + /// An account and a listing answer a job issued before sign-out. Landing after it, they must /// not put the previous session's account and file names on screen with nobody signed in. #[test] diff --git a/crates/cloud-ui/src/cloud/mod.rs b/crates/cloud-ui/src/cloud/mod.rs index b1013a8ad4..fb3f0a5541 100644 --- a/crates/cloud-ui/src/cloud/mod.rs +++ b/crates/cloud-ui/src/cloud/mod.rs @@ -178,7 +178,8 @@ pub struct Guest { /// exists. pub struct CloudFiles { backend: Option>, - events: (Sender, Receiver), + /// Each answer with the account generation its job was issued in. + events: (Sender, Receiver), /// The badge and its menu. Signing in is the only way into any of this. /// The badge is the only control that offers it. It lives here. An /// application declares no field for it. @@ -215,9 +216,14 @@ pub struct CloudFiles { /// stay set after a failed sign-in. sign_in_from_menu: bool, /// Bumped on sign-out and on a new sign-in. Stamped onto every [`Post`] - /// handed out by [`submit`] so a reply to a job issued before the bump is - /// dropped rather than applied to the session that replaced it. + /// handed out by [`submit`] and onto every answer it queues. [`pump`] + /// drops an answer to a job issued before the bump rather than applying + /// it to the session that replaced it. account_generation: Arc, + /// Set by [`sign_in`] and cleared by the account answer that follows it. + /// While it is set both folders read as loading, so no listing is asked + /// for before the service says who is now signed in. + relist_after_sign_in: bool, /// The document Save As must act on, when it is not the active one. /// /// Set only by the conflict modal's "Save as a copy", so the copy it asks @@ -256,6 +262,7 @@ impl CloudFiles { guest: None, sign_in_from_menu: false, account_generation: Arc::new(AtomicU64::new(0)), + relist_after_sign_in: false, save_as_target: None, } } @@ -371,11 +378,17 @@ pub fn sign_in(app: &mut A) { cloud.link = None; cloud.status = Some(working); // A new session. A job the previous one left outstanding may never - // answer, and if it does, that answer is not about this account: see - // `Post::send`. Busy goes with it, or a stuck read from before this + // answer, and if it does, that answer is not about this account: `pump` + // drops it. Busy goes with it, or a stuck read from before this // sign-in would leave Save refused for a session that never asked for it. + // A folder listing that was outstanding is dropped the same way. Both + // folders wait for the account answer, which empties them so the next + // frame lists them for the account that is now signed in. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.mine = Folder { loading: true, ..Folder::default() }; + cloud.shared = Folder { loading: true, ..Folder::default() }; + cloud.relist_after_sign_in = true; submit(app, Job::SignIn); } @@ -396,26 +409,32 @@ pub fn sign_out(app: &mut A) { cloud.status = Some(signed_out); // The session this window had ends here. A job it started may never // answer, and a reply that does arrive late must not land on whatever - // comes next: see `Post::send`. Busy goes with it, so an open or a save + // comes next: `pump` drops it. Busy goes with it, so an open or a save // that never heard back does not refuse every one after it forever. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.relist_after_sign_in = false; cloud.save_as_target = None; submit(app, Job::SignOut); } /// Lists one folder. An empty path is the user's root. +/// +/// Nothing is sent while a sign-in waits for its answer. A listing sent then +/// can answer after the account does, and its files may be the previous +/// account's; the answer empties the folder so it is listed again. pub fn browse(app: &mut A, path: &str) { - if !available(app) { + if !available(app) || app.cloud().relist_after_sign_in { return; } app.cloud_mut().mine.begin(path); submit(app, Job::List(path.to_owned())); } -/// Lists what other people have shared with this user. +/// Lists what other people have shared with this user. Like [`browse`], it +/// sends nothing while a sign-in waits for its answer. pub fn load_shared(app: &mut A) { - if !available(app) { + if !available(app) || app.cloud().relist_after_sign_in { return; } app.cloud_mut().shared.begin(""); @@ -608,6 +627,9 @@ pub fn save_as(app: &mut A, folder: &str, name: &str) -> Result(app: &mut A, ctx: &egui::Context) { while let Ok(event) = app.cloud().events.1.try_recv() { arrived.push(event); } - for event in arrived { + for (issued, event) in arrived { + // A worker that sent just before a sign-out or a new sign-in passed + // `Post::send`'s check, and its answer waited here while the session + // changed. It is about the session that is gone. + if issued != app.cloud().account_generation.load(Ordering::Relaxed) { + continue; + } apply(app, event); } poll_link(app); @@ -649,6 +677,15 @@ pub fn pump(app: &mut A, ctx: &egui::Context) { fn apply(app: &mut A, event: Event) { let noun = app.kind().noun; + if matches!(event, Event::Account(_)) && app.cloud().relist_after_sign_in { + // The sign-in has answered, whether or not it succeeded. Both folders + // are emptied and not loading, so `start` and the Open page list them + // again for whoever is signed in now. + let cloud = app.cloud_mut(); + cloud.relist_after_sign_in = false; + cloud.mine = Folder::default(); + cloud.shared = Folder::default(); + } match event { Event::Account(Ok(account)) => { let linked = account.provider_linked; diff --git a/crates/cloud-ui/src/cloud/pages.rs b/crates/cloud-ui/src/cloud/pages.rs index 86e71d1c88..e969ecc28c 100644 --- a/crates/cloud-ui/src/cloud/pages.rs +++ b/crates/cloud-ui/src/cloud/pages.rs @@ -422,7 +422,9 @@ pub fn save_page(app: &mut A, ui: &mut Ui) -> bool { asked = typing.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); }); ui.add_space(10.0); - let ready = app.cloud().busy.is_none() && !document_name(&app.cloud().save_name, kind).is_empty(); + // A sign-in in progress has emptied the folder, so the destination is not + // the one the user picked until the folders are listed again. + let ready = app.cloud().busy.is_none() && !app.cloud().relist_after_sign_in && !document_name(&app.cloud().save_name, kind).is_empty(); if ui.add_enabled(ready, egui::Button::new(save_label)).clicked() { asked = true; } diff --git a/crates/cloud-ui/src/cloud/tests.rs b/crates/cloud-ui/src/cloud/tests.rs index 875612144f..82f818db01 100644 --- a/crates/cloud-ui/src/cloud/tests.rs +++ b/crates/cloud-ui/src/cloud/tests.rs @@ -197,6 +197,12 @@ fn pumped(app: &mut Notebook, ctx: &egui::Context) { ctx.end_pass().textures_delta.clear(); } +/// Puts an answer in the channel as a worker for the current session would. +fn deliver(app: &Notebook, event: Event) { + let issued = app.cloud.account_generation.load(Ordering::Relaxed); + app.cloud.events.0.send((issued, event)).unwrap(); +} + fn wired() -> (Notebook, Arc>>, egui::Context) { let mut app = Notebook::new(); let jobs = Arc::new(Mutex::new(Vec::new())); @@ -339,7 +345,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() { pumped(&mut app, &ctx); jobs.lock().unwrap().clear(); // What a service answers when somebody else saved first. - app.cloud.events.0.send(Event::Saved { uid: 1, entry: Err(Fault::Conflict) }).unwrap(); + deliver(&app, Event::Saved { uid: 1, entry: Err(Fault::Conflict) }); pumped(&mut app, &ctx); assert_eq!(report(&app)["conflict"]["name"], "Minutes.note", "the user is told, and asked what to do"); assert_eq!(app.did().dropped, vec![1], "the version that did not land is forgotten"); @@ -349,7 +355,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() { #[test] fn no_account_yet_is_an_offer_to_link_and_never_an_error() { let (mut app, _jobs, ctx) = wired(); - app.cloud.events.0.send(Event::Account(Err(Fault::NotLinked))).unwrap(); + deliver(&app, Event::Account(Err(Fault::NotLinked))); pumped(&mut app, &ctx); assert_eq!(report(&app)["link"], "offered"); assert_eq!(report(&app)["accountError"], serde_json::Value::Null, "not having linked an account yet is not a failure"); @@ -359,7 +365,7 @@ fn no_account_yet_is_an_offer_to_link_and_never_an_error() { #[test] fn a_browser_round_trip_is_polled_until_the_user_is_done() { let (mut app, jobs, ctx) = wired(); - app.cloud.events.0.send(Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }).unwrap(); + deliver(&app, Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }); pumped(&mut app, &ctx); assert_eq!(app.did().urls, vec!["https://cloud.example/link/abc".to_owned()], "the browser is opened for them"); assert_eq!(report(&app)["link"]["waiting"], "https://cloud.example/link/abc"); @@ -403,11 +409,10 @@ fn working_together_needs_somewhere_for_the_room_to_be_keyed_on() { #[test] fn a_conversation_uses_the_hosts_chat_opener() { let (mut app, _, ctx) = wired(); - app.cloud - .events - .0 - .send(Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() }))) - .unwrap(); + deliver( + &app, + Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() })), + ); pumped(&mut app, &ctx); @@ -430,6 +435,75 @@ fn signing_out_forgets_everything_this_window_knew() { assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too"); } +#[test] +fn an_answer_queued_before_the_session_changed_is_dropped() { + let (mut app, _jobs, ctx) = wired(); + let old = Account { display: "Ada Lovelace".to_owned(), capabilities: vec![Capability::Files], provider_linked: true }; + + // A worker answers, and the answers wait in the channel while the user + // signs out in the same frame. + let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone()); + post.send(Event::Account(Ok(old))); + post.dup().send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Minutes.note")]) }); + sign_out(&mut app); + pumped(&mut app, &ctx); + let state = report(&app); + assert_eq!(state["account"], serde_json::Value::Null, "the previous session's account must not come back"); + assert_eq!(state["entries"], serde_json::json!([]), "nor its files"); + + // The same across a new sign-in. + let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone()); + post.send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Stale.note")]) }); + sign_in(&mut app); + pumped(&mut app, &ctx); + assert_eq!(report(&app)["entries"], serde_json::json!([]), "a listing for the signed-out session is not shown to the new one"); +} + +#[test] +fn a_sign_in_that_drops_a_listing_leaves_no_folder_loading() { + let (mut app, _jobs, ctx) = wired(); + + // Both listings are asked for, and the answer to the first waits in the + // channel while the user signs in again. The shared one never answers. + browse(&mut app, ""); + load_shared(&mut app); + sign_in(&mut app); + pumped(&mut app, &ctx); + assert!(!app.cloud.mine.loading, "a dropped listing must not leave the folder loading forever"); + assert!(!app.cloud.shared.loading, "nor the shared one, which would then never be asked for again"); + + // A listing the new session asks for still completes. + browse(&mut app, ""); + pumped(&mut app, &ctx); + assert!(app.cloud.mine.loaded); + assert_eq!(report(&app)["entries"], serde_json::json!(["Minutes.note", "Archive"])); +} + +#[test] +fn a_listing_asked_for_before_the_sign_in_answers_is_not_sent() { + let (mut app, jobs, ctx) = wired(); + sign_in(&mut app); + jobs.lock().unwrap().clear(); + + // Asked for after the sign-in and before its answer. A listing sent now + // could answer after the account does, and its files may be the previous + // account's. + browse(&mut app, ""); + load_shared(&mut app); + assert!( + !jobs.lock().unwrap().iter().any(|j| matches!(j, Job::List(_) | Job::SharedWithMe)), + "no listing goes out while the sign-in is outstanding" + ); + pumped(&mut app, &ctx); + assert!(!app.cloud.mine.loaded && !app.cloud.mine.loading, "the folder waits to be listed for the new account"); + assert!(!app.cloud.shared.loaded && !app.cloud.shared.loading, "and so does the shared one"); + + // Once the sign-in has answered, a listing goes through. + browse(&mut app, ""); + pumped(&mut app, &ctx); + assert!(app.cloud.mine.loaded); +} + #[test] fn bytes_are_said_the_way_a_person_reads_them() { assert_eq!(size_text(None), ""); diff --git a/crates/cloud-ui/src/share/mod.rs b/crates/cloud-ui/src/share/mod.rs index e380674119..b4739909fc 100644 --- a/crates/cloud-ui/src/share/mod.rs +++ b/crates/cloud-ui/src/share/mod.rs @@ -675,14 +675,17 @@ impl ShareDialog { } } Answer::Granted { shared, failed } => { - // A link was asked for in order to be handed out, so it goes - // to the clipboard without a second click. - if let Some(url) = shared.iter().find_map(|s| s.url.clone()) { - ctx.copy_text(url); - } if let Some(sheet) = &mut self.open && sheet.granting == Some(seq) { + // A link was asked for in order to be handed out, so it + // goes to the clipboard without a second click. Only for + // the sheet that asked: a grant answered after the sheet + // closed or moved to another document leaves the + // clipboard alone. + if let Some(url) = shared.iter().find_map(|s| s.url.clone()) { + ctx.copy_text(url); + } sheet.granting = None; sheet.error = None; // Recipients that went through leave the picker. The ones @@ -918,9 +921,11 @@ fn draw(ui: &mut Ui, sheet: &mut Sheet, avatars: &HashMap, label ui.add(egui::TextEdit::singleline(&mut sheet.link_key).hint_text(labels.key_hint.as_str()).password(true).desired_width(150.0)); } // A key the server insists on cannot be skipped, so the control - // stays disabled until one is typed. + // stays disabled until one is typed. It also waits, as Send does, + // while a grant is in flight: the answer to that grant is the one + // the sheet takes, and an earlier link would be dropped. let keyed = !sheet.link_key.trim().is_empty(); - let ready = keyed || !allowed.key_required; + let ready = (keyed || !allowed.key_required) && sheet.granting.is_none(); if ui.add_enabled(ready, egui::Button::new(labels.create_link.as_str())).clicked() { acts.push(Act::Grant(Grant { id: sheet.id.clone(), diff --git a/crates/cloud-ui/src/share/tests.rs b/crates/cloud-ui/src/share/tests.rs index dfdb3eb1e3..eba1a23551 100644 --- a/crates/cloud-ui/src/share/tests.rs +++ b/crates/cloud-ui/src/share/tests.rs @@ -240,6 +240,85 @@ fn a_share_reaching_four_of_five_names_the_fifth() { assert_eq!(left.chosen.first().map(|c| &c.target), Some(&ShareTarget::Email("nobody@@".into()))); } +fn copied(ctx: &Context) -> Vec { + ctx.output(|o| o.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(text) = c { Some(text.clone()) } else { None }).collect()) +} + +fn ask_for_link(dialog: &mut ShareDialog) -> u64 { + let granting = dialog.issue(Request::Grant(Grant { + id: "files/budget.xlsx".into(), + password: None, + targets: Vec::new(), + permission: Permission::View, + note: None, + notify: false, + })); + if let Some(sheet) = &mut dialog.open { + sheet.granting = Some(granting); + } + granting +} + +fn link(url: &str) -> Answer { + let mut made = share("s1", ShareTarget::Email("anyone@example.com".into())); + made.url = Some(url.into()); + Answer::Granted { shared: vec![made], failed: Vec::new() } +} + +#[test] +fn a_granted_link_goes_to_the_clipboard() { + let (ctx, mut dialog, _) = ready(); + let granting = ask_for_link(&mut dialog); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert_eq!(copied(&ctx), ["https://cloud.example/l/budget"]); +} + +#[test] +fn a_link_granted_after_the_sheet_moved_on_is_not_copied() { + let (ctx, mut dialog, _) = ready(); + let granting = ask_for_link(&mut dialog); + dialog.close(); + dialog.open("files/plan.docx", "Plan"); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert!(copied(&ctx).is_empty(), "the budget's link must not replace the clipboard while the plan is open"); + + let (ctx, mut dialog, _) = ready(); + let granting = ask_for_link(&mut dialog); + dialog.close(); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert!(copied(&ctx).is_empty(), "nor after the sheet closed"); +} + +/// Whether one frame of the sheet offers "Get a link" as a button that can +/// be pressed, read off the accessibility tree. +fn link_button_enabled(dialog: &mut ShareDialog) -> Option { + let ctx = Context::default(); + ctx.enable_accesskit(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 900.0))), ..Default::default() }; + let mut output = ctx.run_ui(raw, |ui| dialog.show_in(ui)); + output.textures_delta.clear(); + let tree = output.platform_output.accesskit_update?; + tree.nodes + .iter() + .find(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some("Get a link")) + .map(|(_, node)| !node.is_disabled()) +} + +#[test] +fn get_a_link_waits_while_a_grant_is_in_flight() { + let ctx = Context::default(); + let mut dialog = ShareDialog::new(); + dialog.connect(Silent::default()); + dialog.collect(&ctx); + dialog.receive(&ctx, 1, Ok(can(vec![Capability::Sharing, Capability::LinkShares]))); + dialog.open("files/budget.xlsx", "Budget"); + assert_eq!(link_button_enabled(&mut dialog), Some(true)); + let granting = ask_for_link(&mut dialog); + assert_eq!(link_button_enabled(&mut dialog), Some(false), "a second grant would make the first one's link be dropped"); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert_eq!(link_button_enabled(&mut dialog), Some(true)); +} + #[test] fn a_refusal_that_stopped_the_whole_call_is_not_a_failed_recipient() { let (ctx, mut dialog, _) = ready(); diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index cb2c2f3972..1705f64002 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -319,23 +319,33 @@ fn solve_cmy_by(model: &F, k: f64, limit: f64, seeds: &[[f6 const SEEDS: [[f64; 3]; 5] = [[0.3, 0.3, 0.3], [0.05, 0.05, 0.05], [0.8, 0.8, 0.8], [0.9, 0.2, 0.2], [0.2, 0.9, 0.9]]; -/// Black for a gray component `g` (the smallest of C, M, Y without black). +/// Black for a gray component `g` (the smallest of C, M, Y without black), at most the total ink +/// limit: the CMY solve gets `tac - k`, so black above `tac` would break the limit on its own. fn gcr(p: &CmykParams, g: f64) -> f64 { - let Some(first) = p.gcr_curve.first() else { + let k = match p.gcr_curve.first() { // The Photocraft profile's curve. - return if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) }; - }; - let mut k = first[1]; - for w in p.gcr_curve.windows(2) { - let ([g0, k0], [g1, k1]) = (w[0], w[1]); - if g >= g1 { - k = k1; - } else if g > g0 { - k = k0 + (k1 - k0) * (g - g0) / (g1 - g0); - break; + None => { + if g <= p.gcr_start { + 0.0 + } else { + p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) + } } - } - k.clamp(0.0, 1.0) + Some(first) => { + let mut k = first[1]; + for w in p.gcr_curve.windows(2) { + let ([g0, k0], [g1, k1]) = (w[0], w[1]); + if g >= g1 { + k = k1; + } else if g > g0 { + k = k0 + (k1 - k0) * (g - g0) / (g1 - g0); + break; + } + } + k + } + }; + k.clamp(0.0, 1.0).min(p.tac.max(0.0)) } /// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve. @@ -712,6 +722,9 @@ fn check_grids(p: &CmykParams) -> Result<(), CmsError> { if p.white_on_node && p.grid_b2a.is_multiple_of(2) { return Err(invalid_arg(format!("white on a node needs an odd BToA grid, not {}", p.grid_b2a))); } + if !(p.tac.is_finite() && p.tac >= 0.0) { + return Err(invalid_arg(format!("total ink limit {} must be finite and not negative", p.tac))); + } let valid = |v: &[f64; 2]| v.iter().all(|x| (0.0..=1.0).contains(x)); if !p.gcr_curve.iter().all(valid) || p.gcr_curve.windows(2).any(|w| w[1][0] <= w[0][0]) { return Err(invalid_arg(format!("black generation curve {:?} needs points in [0, 1] with increasing gray components", p.gcr_curve))); @@ -847,6 +860,33 @@ mod tests { } } + #[test] + fn total_ink_limit_must_be_finite_and_not_negative() { + for tac in [-0.5, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let p = CmykParams { grid_a2b: 2, grid_b2a: 2, tac, ..CmykParams::default() }; + assert!(cmyk_profile(&p).is_err(), "tac {tac}"); + } + // `separate` is public and does not validate: black is still never negative. + let p = CmykParams { tac: -0.5, gcr_curve: vec![[0.0, 0.75]], ..CmykParams::default() }; + assert_eq!(gcr(&p, 0.5), 0.0); + } + + #[test] + fn curve_black_stays_within_the_ink_limit() { + // Black from either the profile curve or the default empty-curve fallback never exceeds the ink limit. + let m = CmykModel::coated(CmykParams::default().tvi); + for gcr_curve in [vec![[0.0, 0.75]], vec![]] { + for tac in [0.5, 0.0] { + let p = CmykParams { tac, gcr_curve: gcr_curve.clone(), ..CmykParams::default() }; + assert!(gcr(&p, 1.0) <= p.tac, "tac {tac} curve {gcr_curve:?}"); + for target in [[50.0, 0.0, 0.0], [90.0, 0.0, 0.0], [30.0, 20.0, -10.0]] { + let (cmyk, _) = separate(&m, &p, target, None); + assert!(cmyk.iter().sum::() <= p.tac + 1e-6, "{target:?} -> {cmyk:?}"); + } + } + } + } + #[test] fn oklab_round_trips() { let m = CmykModel::coated(CmykParams::default().tvi); diff --git a/crates/cms/tests/fogra39.rs b/crates/cms/tests/fogra39.rs index 806bff7138..a555f34c54 100644 --- a/crates/cms/tests/fogra39.rs +++ b/crates/cms/tests/fogra39.rs @@ -430,6 +430,8 @@ fn separates_like_the_reference_application() { for (rgb, want) in REFERENCE_SEPARATIONS { for ((intent, bpc), want) in SEPARATION_INTENTS.into_iter().zip(want) { let got = separation(intent, bpc, rgb); + // `f32::max` drops a NaN, so a NaN ink would otherwise count as no difference. + assert!(got.iter().all(|v| v.is_finite()), "{rgb:?} {intent:?} bpc {bpc}: {got:?}"); let diff = (0..4).map(|i| (got[i] - want[i]).abs()).fold(0.0f32, f32::max); eprintln!("{rgb:?} {intent:?} bpc {bpc}: {got:.1?} reference {want:?} (max {diff:.1})"); worst = worst.max(diff); diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index dfbdf17872..3c8f0d18bb 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -44,13 +44,22 @@ impl Matrix { _ => None, } } + /// The ISO/IEC 23091-2 `matrix_coefficients` code to write for this matrix. + /// [`Matrix::Bt601`] writes 6 (SMPTE 170M); code 5 has the same coefficients. + pub fn to_code(self) -> u8 { + match self { + Matrix::Bt709 => 1, + Matrix::Bt601 => 6, + Matrix::Bt2020Ncl => 9, + } + } } /// 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. + /// This is not a pure-gamma BT.1886 decode; [`bt1886_eotf`] is. #[default] Bt709, Srgb, @@ -73,6 +82,17 @@ impl Transfer { _ => None, } } + /// The ISO/IEC 23091-2 `transfer_characteristics` code to write for this transfer. + /// [`Transfer::Bt709`] writes 1; codes 6, 14 and 15 also read as it. + pub fn to_code(self) -> u8 { + match self { + Transfer::Bt709 => 1, + Transfer::Linear => 8, + Transfer::Srgb => 13, + Transfer::Pq => 16, + Transfer::Hlg => 18, + } + } } /// Chromaticity primaries. @@ -86,6 +106,32 @@ pub enum Primaries { P3D65, } +impl Primaries { + /// From an ISO/IEC 23091-2 `colour_primaries` code. + pub fn from_code(c: u8) -> Option { + match c { + 1 => Some(Primaries::Bt709), + 5 => Some(Primaries::Bt601_625), + // SMPTE 240M (7) has the same primaries as SMPTE 170M (6). + 6 | 7 => Some(Primaries::Bt601_525), + 9 => Some(Primaries::Bt2020), + // H.273 table 2: code 11 is DCI-P3 with its own white point, not D65. + 12 => Some(Primaries::P3D65), + _ => None, + } + } + /// The ISO/IEC 23091-2 `colour_primaries` code to write for these primaries. + pub fn to_code(self) -> u8 { + match self { + Primaries::Bt709 => 1, + Primaries::Bt601_625 => 5, + Primaries::Bt601_525 => 6, + Primaries::Bt2020 => 9, + Primaries::P3D65 => 12, + } + } +} + /// Quantisation range of integer Y'CbCr samples. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Range { @@ -192,6 +238,144 @@ pub fn normalize_c(v: u32, bits: u32, range: Range) -> Result Result { + if !(8..=16).contains(&bits) { + return Err(InvalidBitDepth(bits)); + } + let e = if e.is_nan() { 0.0 } else { f64::from(e) }; + let scale = f64::from(1u32 << (bits - 8)); + let code = match range { + Range::Limited => (219.0 * e + 16.0) * scale, + Range::Full => f64::from((1u32 << bits) - 1) * e, + }; + Ok(clamp_code(code, bits)) +} + +/// Quantize a chroma signal in −0.5..0.5 to an integer code value: the inverse of +/// [`normalize_c`]. +/// +/// Limited range is `round((224 * E + 128) * 2^(bits - 8))`, full range is +/// `round((2^bits - 1) * E + 2^(bits - 1))` (BT.2100). Values outside the signal range are +/// clamped to the codes `0..=2^bits - 1`, and NaN is treated as 0 (no chroma). +pub fn quantize_c(e: f32, bits: u32, range: Range) -> Result { + if !(8..=16).contains(&bits) { + return Err(InvalidBitDepth(bits)); + } + let e = if e.is_nan() { 0.0 } else { f64::from(e) }; + let scale = f64::from(1u32 << (bits - 8)); + let code = match range { + Range::Limited => (224.0 * e + 128.0) * scale, + Range::Full => f64::from((1u32 << bits) - 1) * e + f64::from(1u32 << (bits - 1)), + }; + Ok(clamp_code(code, bits)) +} + +#[inline] +fn clamp_code(code: f64, bits: u32) -> u16 { + // `bits` is at most 16, so the maximum fits in u16. + code.round().clamp(0.0, f64::from((1u32 << bits) - 1)) as u16 +} + +/// Convert non-linear R'G'B' (0..1) to integer Y'CbCr code values at a bit depth and range. +pub fn rgb_to_ycbcr_codes(r: f32, g: f32, b: f32, m: Matrix, bits: u32, range: Range) -> Result<[u16; 3], InvalidBitDepth> { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + Ok([quantize_y(y, bits, range)?, quantize_c(cb, bits, range)?, quantize_c(cr, bits, range)?]) +} + +/// Convert integer Y'CbCr code values at a bit depth and range to non-linear R'G'B'. +/// +/// The result is not clamped: codes outside the nominal range (limited-range footroom and +/// headroom) give values below 0 or above 1. +pub fn ycbcr_codes_to_rgb(y: u32, cb: u32, cr: u32, m: Matrix, bits: u32, range: Range) -> Result<[f32; 3], InvalidBitDepth> { + Ok(ycbcr_to_rgb(normalize_y(y, bits, range)?, normalize_c(cb, bits, range)?, normalize_c(cr, bits, range)?, m)) +} + +/// Fixed-point conversion between 8-bit R'G'B' and 8-bit Y'CbCr for one matrix and range. +/// +/// The coefficients are computed once by [`Ycbcr8::new`]; each conversion is integer +/// multiply-adds with 16 fractional bits, for per-pixel loops over camera or encoder frames. +/// Results stay within one code of [`rgb_to_ycbcr_codes`] and [`ycbcr_codes_to_rgb`], and +/// neutral grays keep chroma at exactly 128. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Ycbcr8 { + y_offset: i32, + // R'G'B' to Y'CbCr. + y_rgb: [i32; 3], + cb_rgb: [i32; 3], + cr_rgb: [i32; 3], + // Y'CbCr to R'G'B'. + rgb_y: i32, + r_cr: i32, + g_cb: i32, + g_cr: i32, + b_cb: i32, +} + +const FIXED_ONE: f64 = 65536.0; +const FIXED_HALF: i32 = 1 << 15; + +impl Ycbcr8 { + /// Coefficients for matrix `m` and range `range`. + pub fn new(m: Matrix, range: Range) -> Ycbcr8 { + let (kr, kb) = m.kr_kb(); + let (kr, kb) = (f64::from(kr), f64::from(kb)); + let kg = 1.0 - kr - kb; + let (y_offset, y_scale, c_scale) = match range { + Range::Limited => (16, 219.0, 224.0), + Range::Full => (0, 255.0, 255.0), + }; + let fixed = |v: f64| (v * FIXED_ONE).round() as i32; + // Luma: the green weight takes the rounding remainder so 255 gray reaches the top code. + let y_total = fixed(y_scale / 255.0); + let (y_r, y_b) = (fixed(kr * y_scale / 255.0), fixed(kb * y_scale / 255.0)); + // Chroma: the green weight cancels the other two so every gray gives exactly 128. + let cb_scale = c_scale / 255.0 / (2.0 * (1.0 - kb)); + let cr_scale = c_scale / 255.0 / (2.0 * (1.0 - kr)); + let (cb_r, cb_b) = (fixed(-kr * cb_scale), fixed((1.0 - kb) * cb_scale)); + let (cr_r, cr_b) = (fixed((1.0 - kr) * cr_scale), fixed(-kb * cr_scale)); + let r_cr = 2.0 * (1.0 - kr) * 255.0 / c_scale; + let b_cb = 2.0 * (1.0 - kb) * 255.0 / c_scale; + Ycbcr8 { + y_offset, + y_rgb: [y_r, y_total - y_r - y_b, y_b], + cb_rgb: [cb_r, -cb_r - cb_b, cb_b], + cr_rgb: [cr_r, -cr_r - cr_b, cr_b], + rgb_y: fixed(255.0 / y_scale), + r_cr: fixed(r_cr), + g_cb: fixed(-kb * b_cb / kg), + g_cr: fixed(-kr * r_cr / kg), + b_cb: fixed(b_cb), + } + } + + /// 8-bit R'G'B' to 8-bit Y'CbCr code values. + #[inline] + pub fn rgb_to_ycbcr(&self, r: u8, g: u8, b: u8) -> [u8; 3] { + let rgb = [i32::from(r), i32::from(g), i32::from(b)]; + let dot = |k: &[i32; 3]| k[0] * rgb[0] + k[1] * rgb[1] + k[2] * rgb[2]; + [to_u8(dot(&self.y_rgb) + (self.y_offset << 16)), to_u8(dot(&self.cb_rgb) + (128 << 16)), to_u8(dot(&self.cr_rgb) + (128 << 16))] + } + + /// 8-bit Y'CbCr code values to 8-bit R'G'B', clamped to 0..=255. + #[inline] + pub fn ycbcr_to_rgb(&self, y: u8, cb: u8, cr: u8) -> [u8; 3] { + let y = self.rgb_y * (i32::from(y) - self.y_offset); + let (cb, cr) = (i32::from(cb) - 128, i32::from(cr) - 128); + [to_u8(y + self.r_cr * cr), to_u8(y + self.g_cb * cb + self.g_cr * cr), to_u8(y + self.b_cb * cb)] + } +} + +/// Round a 16.16 fixed-point value to the nearest integer and clamp it to a u8. +#[inline] +fn to_u8(v: i32) -> u8 { + ((v + FIXED_HALF) >> 16).clamp(0, 255) as u8 +} + /// sRGB electro-optical transfer (encoded → linear). #[inline] pub fn srgb_to_linear(v: f32) -> f32 { @@ -255,6 +439,41 @@ pub fn hlg_inverse_oetf(e: f32) -> f32 { if e <= 0.5 { e * e / 3.0 } else { (((e - c) / a).exp() + b) / 12.0 } } +/// The BT.1886 exponent. +const BT1886_GAMMA: f64 = 2.4; + +/// BT.1886 constants `a` and `b` for a display's white and black luminance, or `None` when white +/// is not measurably above black, or is NaN or infinite. A black below 0, or NaN, is taken as 0. +/// The constants are in `f64`, so a black close to white keeps the curve's endpoints. +fn bt1886_ab(white: f32, black: f32) -> Option<(f64, f64)> { + let (white, black) = (f64::from(white), f64::from(black.max(0.0))); + let (w, k) = (white.powf(1.0 / BT1886_GAMMA), black.powf(1.0 / BT1886_GAMMA)); + let d = w - k; + if d.is_finite() && d > 0.0 { Some((d.powf(BT1886_GAMMA), k / d)) } else { None } +} + +/// ITU-R BT.1886 reference display EOTF: a BT.709 signal (0..1) to screen luminance, for a +/// display with the given white and black luminance (any unit, e.g. cd/m²). With `white` 1 and +/// `black` 0 it is a pure 2.4 gamma. [`to_linear`] with [`Transfer::Bt709`] uses the sRGB curve +/// instead. A `black` below 0, or NaN, is taken as 0. When `white` is not measurably above +/// `black`, or is NaN or infinite, the result is `black`. +pub fn bt1886_eotf(v: f32, white: f32, black: f32) -> f32 { + match bt1886_ab(white, black) { + Some((a, b)) => (a * (f64::from(v) + b).max(0.0).powf(BT1886_GAMMA)) as f32, + None => black.max(0.0), + } +} + +/// Inverse of [`bt1886_eotf`]: screen luminance to a BT.709 signal. Luminance at or below +/// `black` gives 0. When `white` is not measurably above `black`, or is NaN or infinite, the +/// result is 0. +pub fn bt1886_inverse_eotf(l: f32, white: f32, black: f32) -> f32 { + match bt1886_ab(white, black) { + Some((a, b)) if l > black.max(0.0) => ((f64::from(l) / a).powf(1.0 / BT1886_GAMMA) - b).max(0.0) as f32, + _ => 0.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(); @@ -402,6 +621,108 @@ mod tests { assert_eq!(linear_to_srgb_u8(srgb_u8_to_linear_table()[128]), 128); } + /// SMPTE ST 2084 inverse EOTF in `f64`, with the constants as exact fractions from + /// Recommendation ITU-R BT.2100 Table 4. + fn st2084_inverse_eotf(y: f64) -> f64 { + let (m1, m2) = (2610.0 / 16384.0, 2523.0 / 4096.0 * 128.0); + let (c1, c2, c3) = (3424.0 / 4096.0, 2413.0 / 4096.0 * 32.0, 2392.0 / 4096.0 * 32.0); + let p = y.powf(m1); + ((c1 + c2 * p) / (1.0 + c3 * p)).powf(m2) + } + + #[test] + fn pq_matches_the_st_2084_equations() { + for nits in [0.01_f64, 0.1, 1.0, 10.0, 100.0, 203.0, 1000.0, 4000.0, 10_000.0] { + let want = st2084_inverse_eotf(nits / 10_000.0); + let got = pq_inverse_eotf((nits / 10_000.0) as f32) as f64; + assert!((got - want).abs() < 1e-5, "{nits} nits: {got} vs {want}"); + let back = pq_eotf(want as f32) as f64 * 10_000.0; + assert!((back - nits).abs() <= nits * 1e-4, "{want}: {back} vs {nits} nits"); + } + assert!((pq_inverse_eotf(1.0) - 1.0).abs() < 1e-6); + assert!((pq_eotf(1.0) - 1.0).abs() < 1e-6); + } + + /// Report ITU-R BT.2408-7 Table 1: display luminance in cd/m², then the nominal signal level in + /// whole percent for a PQ reference display and for a 1 000 cd/m² HLG display. + const BT2408_TABLE_1: [(f32, f32, f32); 4] = [(26.0, 38.0, 38.0), (162.0, 56.0, 71.0), (179.0, 57.0, 73.0), (203.0, 58.0, 75.0)]; + + #[test] + fn signal_levels_match_bt2408_table_1() { + for (nits, pq_percent, hlg_percent) in BT2408_TABLE_1 { + let pq = pq_inverse_eotf(nits / 10_000.0) * 100.0; + assert!((pq - pq_percent).abs() <= 0.5, "{nits} nits: PQ {pq}% vs {pq_percent}%"); + // The BT.2100 HLG OOTF has a system gamma of 1.2 on a 1 000 cd/m² display, so a + // neutral gray shown at `nits` comes from scene light (nits / 1000)^(1 / 1.2). + let hlg = hlg_oetf((nits / 1000.0).powf(1.0 / 1.2)) * 100.0; + assert!((hlg - hlg_percent).abs() <= 0.5, "{nits} nits: HLG {hlg}% vs {hlg_percent}%"); + } + } + + #[test] + fn hlg_matches_the_bt2100_equations() { + // Recommendation ITU-R BT.2100 Table 5: a = 0.17883277, b = 1 - 4a, c = 0.5 - a ln(4a). + let a = 0.178_832_77_f64; + let b = 1.0 - 4.0 * a; + let c = 0.5 - a * (4.0 * a).ln(); + let oetf = |e: f64| if e <= 1.0 / 12.0 { (3.0 * e).sqrt() } else { a * (12.0 * e - b).ln() + c }; + for e in [0.0_f64, 0.001, 0.01, 1.0 / 12.0, 0.1, 0.25, 0.5, 0.75, 1.0] { + let want = oetf(e); + let got = hlg_oetf(e as f32) as f64; + assert!((got - want).abs() < 1e-6, "E = {e}: {got} vs {want}"); + let back = hlg_inverse_oetf(want as f32) as f64; + assert!((back - e).abs() <= 1e-6 + e * 1e-5, "E' = {want}: {back} vs {e}"); + } + assert!((hlg_oetf(1.0 / 12.0) - 0.5).abs() < 1e-6); + assert!((hlg_oetf(1.0) - 1.0).abs() < 1e-6); + } + + /// The sRGB transfer of IEC 61966-2-1 (Amendment 1), as the ICC sRGB registry entry gives it. + #[test] + fn srgb_tables_match_the_iec_61966_2_1_equations() { + let decode = |v: f64| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; + let encode = |l: f64| if l <= 0.003_130_8 { l * 12.92 } else { 1.055 * l.powf(1.0 / 2.4) - 0.055 }; + for (i, got) in srgb_u8_to_linear_table().iter().enumerate() { + let want = decode(i as f64 / 255.0); + assert!((*got as f64 - want).abs() <= 1e-6, "code {i}: {got} vs {want}"); + } + for (i, got) in linear_to_srgb_u8_table().iter().enumerate() { + let want = (encode(i as f64 / 4095.0) * 255.0).round() as u8; + assert_eq!(*got, want, "linear {i}/4095"); + } + } + + #[test] + fn bt1886_follows_the_recommendation() { + // BT.1886 with Lw = 100 cd/m² and Lb = 0: L = 100 · V^2.4. + assert!((bt1886_eotf(0.5, 100.0, 0.0) - 100.0 * 0.5f32.powf(2.4)).abs() < 1e-3); + // A pure gamma has no linear toe, so near black it is darker than the sRGB curve. + assert!(bt1886_eotf(0.02, 1.0, 0.0) < to_linear(0.02, Transfer::Bt709) / 10.0); + // A black level lifts code 0 to the display's black and keeps code 1 at its white. + for (white, black) in [(100.0, 0.1), (300.0, 0.5), (1.0, 0.0)] { + assert!((bt1886_eotf(0.0, white, black) - black).abs() < 1e-4 * white); + assert!((bt1886_eotf(1.0, white, black) - white).abs() < 1e-4 * white); + for v in [0.0, 0.1, 0.5, 0.9, 1.0] { + let l = bt1886_eotf(v, white, black); + assert!((bt1886_inverse_eotf(l, white, black) - v).abs() < 1e-4, "{white} {black} {v}"); + } + assert_eq!(bt1886_inverse_eotf(black / 2.0, white, black), 0.0); + } + assert!(bt1886_eotf(0.5, 100.0, 0.1) > bt1886_eotf(0.5, 100.0, 0.0)); + // A black close to white keeps both endpoints of the inverse. + assert_eq!(bt1886_inverse_eotf(99.99, 100.0, 99.99), 0.0); + assert!((bt1886_inverse_eotf(100.0, 100.0, 99.99) - 1.0).abs() < 1e-3); + // A display whose white is not above its black. + assert_eq!(bt1886_eotf(0.5, 1.0, 1.0), 1.0); + assert_eq!(bt1886_inverse_eotf(0.5, 0.0, 0.0), 0.0); + assert_eq!(bt1886_inverse_eotf(0.5, f32::NAN, 0.0), 0.0); + assert_eq!(bt1886_eotf(0.5, 100.0, f32::NAN), bt1886_eotf(0.5, 100.0, 0.0)); + for (white, black) in [(1.0, 0.999_999_94), (f32::INFINITY, 0.0)] { + assert!(bt1886_eotf(0.5, white, black).is_finite()); + assert!(bt1886_inverse_eotf(0.5, white, black).is_finite()); + } + } + #[test] fn hsl_roundtrip() { let c = [0.2, 0.6, 0.9]; @@ -428,6 +749,92 @@ mod tests { assert_eq!(HdrMetadata { max_cll: Some(100.0), ..HdrMetadata::default() }.peak_nits(), Some(REFERENCE_WHITE_NITS as f32)); } + #[test] + fn code_values_match_published_levels() { + // The BT.709 and BT.2100 quantization levels: black, nominal peak and achromatic chroma. + assert_eq!(rgb_to_ycbcr_codes(0.0, 0.0, 0.0, Matrix::Bt709, 8, Range::Limited), Ok([16, 128, 128])); + assert_eq!(rgb_to_ycbcr_codes(1.0, 1.0, 1.0, Matrix::Bt709, 8, Range::Limited), Ok([235, 128, 128])); + assert_eq!(rgb_to_ycbcr_codes(1.0, 1.0, 1.0, Matrix::Bt2020Ncl, 10, Range::Limited), Ok([940, 512, 512])); + assert_eq!(rgb_to_ycbcr_codes(0.0, 0.0, 0.0, Matrix::Bt2020Ncl, 10, Range::Limited), Ok([64, 512, 512])); + assert_eq!(rgb_to_ycbcr_codes(1.0, 1.0, 1.0, Matrix::Bt2020Ncl, 12, Range::Full), Ok([4095, 2048, 2048])); + // 100% red: Y'CbCr of the BT.709 and BT.601 color bars. + assert_eq!(rgb_to_ycbcr_codes(1.0, 0.0, 0.0, Matrix::Bt709, 8, Range::Limited), Ok([63, 102, 240])); + assert_eq!(rgb_to_ycbcr_codes(1.0, 0.0, 0.0, Matrix::Bt601, 8, Range::Limited), Ok([81, 90, 240])); + // JFIF (ITU-T T.871) full-range BT.601: red is Y 76, Cb 85, Cr 255.5 clamped to 255. + assert_eq!(rgb_to_ycbcr_codes(1.0, 0.0, 0.0, Matrix::Bt601, 8, Range::Full), Ok([76, 85, 255])); + } + + #[test] + fn quantize_inverts_normalize() { + for range in [Range::Limited, Range::Full] { + for bits in [8, 10, 12, 16] { + for v in [0, 1, 16, 64, 128, 235, 240, 255] { + let v = v << (bits - 8); + assert_eq!(u32::from(quantize_y(normalize_y(v, bits, range).unwrap(), bits, range).unwrap()), v, "{range:?} {bits} y {v}"); + assert_eq!(u32::from(quantize_c(normalize_c(v, bits, range).unwrap(), bits, range).unwrap()), v, "{range:?} {bits} c {v}"); + } + let top = (1u32 << bits) - 1; + assert_eq!(u32::from(quantize_y(f32::INFINITY, bits, range).unwrap()), top); + assert_eq!(quantize_c(f32::NEG_INFINITY, bits, range), Ok(0)); + assert_eq!(quantize_c(f32::NAN, bits, range), quantize_c(0.0, bits, range)); + assert_eq!(quantize_y(f32::NAN, bits, range), quantize_y(0.0, bits, range)); + } + } + for bits in [0, 7, 17, u32::MAX] { + assert_eq!(quantize_y(0.5, bits, Range::Full), Err(InvalidBitDepth(bits))); + assert_eq!(quantize_c(0.0, bits, Range::Limited), Err(InvalidBitDepth(bits))); + assert_eq!(rgb_to_ycbcr_codes(0.5, 0.5, 0.5, Matrix::Bt709, bits, Range::Full), Err(InvalidBitDepth(bits))); + assert_eq!(ycbcr_codes_to_rgb(0, 0, 0, Matrix::Bt709, bits, Range::Full), Err(InvalidBitDepth(bits))); + } + } + + #[test] + fn ycbcr_codes_roundtrip() { + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + for range in [Range::Limited, Range::Full] { + let [y, cb, cr] = rgb_to_ycbcr_codes(0.8, 0.3, 0.1, m, 10, range).unwrap(); + let back = ycbcr_codes_to_rgb(y.into(), cb.into(), cr.into(), m, 10, range).unwrap(); + for (k, v) in [0.8, 0.3, 0.1].into_iter().enumerate() { + assert!((back[k] - v).abs() < 4e-3, "{m:?} {range:?} {back:?}"); + } + } + } + } + + #[test] + fn fixed_point_8_bit_matches_float() { + let close = |a: [u8; 3], b: [u16; 3]| a.iter().zip(b).all(|(&a, b)| (i32::from(a) - i32::from(b)).abs() <= 1); + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + for range in [Range::Limited, Range::Full] { + let conv = Ycbcr8::new(m, range); + for r in (0..=255u8).step_by(5) { + for g in (0..=255u8).step_by(5) { + for b in (0..=255u8).step_by(5) { + let float = rgb_to_ycbcr_codes(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, m, 8, range).unwrap(); + let fixed = conv.rgb_to_ycbcr(r, g, b); + assert!(close(fixed, float), "{m:?} {range:?} {r} {g} {b}: {fixed:?} vs {float:?}"); + let [y, cb, cr] = fixed; + let rgb = ycbcr_codes_to_rgb(y.into(), cb.into(), cr.into(), m, 8, range).unwrap(); + let want = rgb.map(|v| (v * 255.0).round().clamp(0.0, 255.0) as u16); + assert!(close(conv.ycbcr_to_rgb(y, cb, cr), want), "{m:?} {range:?} {fixed:?}"); + } + } + } + for v in 0..=255u8 { + let [_, cb, cr] = conv.rgb_to_ycbcr(v, v, v); + assert_eq!((cb, cr), (128, 128), "{m:?} {range:?} gray {v}"); + } + // Out-of-range codes clamp instead of wrapping. + assert_eq!(conv.ycbcr_to_rgb(255, 255, 255)[0], 255); + assert_eq!(conv.ycbcr_to_rgb(0, 0, 0)[0], 0); + } + assert_eq!(Ycbcr8::new(m, Range::Limited).rgb_to_ycbcr(255, 255, 255), [235, 128, 128]); + assert_eq!(Ycbcr8::new(m, Range::Full).rgb_to_ycbcr(255, 255, 255), [255, 128, 128]); + assert_eq!(Ycbcr8::new(m, Range::Limited).ycbcr_to_rgb(235, 128, 128), [255, 255, 255]); + assert_eq!(Ycbcr8::new(m, Range::Limited).ycbcr_to_rgb(16, 128, 128), [0, 0, 0]); + } + } + #[test] fn codes() { assert_eq!(Matrix::from_code(9), Some(Matrix::Bt2020Ncl)); @@ -437,4 +844,40 @@ mod tests { assert_eq!(Transfer::from_code(16), Some(Transfer::Pq)); assert_eq!(Transfer::from_code(99), None); } + + #[test] + fn codes_written_are_the_h273_values() { + assert_eq!([Matrix::Bt709, Matrix::Bt601, Matrix::Bt2020Ncl].map(Matrix::to_code), [1, 6, 9]); + assert_eq!([Transfer::Bt709, Transfer::Linear, Transfer::Srgb, Transfer::Pq, Transfer::Hlg].map(Transfer::to_code), [1, 8, 13, 16, 18]); + assert_eq!( + [Primaries::Bt709, Primaries::Bt601_625, Primaries::Bt601_525, Primaries::Bt2020, Primaries::P3D65].map(Primaries::to_code), + [1, 5, 6, 9, 12] + ); + } + + #[test] + fn primaries_codes() { + assert_eq!(Primaries::from_code(1), Some(Primaries::Bt709)); + assert_eq!(Primaries::from_code(5), Some(Primaries::Bt601_625)); + assert_eq!(Primaries::from_code(6), Some(Primaries::Bt601_525)); + assert_eq!(Primaries::from_code(7), Some(Primaries::Bt601_525)); + assert_eq!(Primaries::from_code(9), Some(Primaries::Bt2020)); + assert_eq!(Primaries::from_code(12), Some(Primaries::P3D65)); + for c in [0, 2, 3, 4, 8, 10, 11, 13, 22, 255] { + assert_eq!(Primaries::from_code(c), None, "{c}"); + } + } + + #[test] + fn written_codes_read_back() { + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + assert_eq!(Matrix::from_code(m.to_code()), Some(m)); + } + for t in [Transfer::Bt709, Transfer::Srgb, Transfer::Linear, Transfer::Pq, Transfer::Hlg] { + assert_eq!(Transfer::from_code(t.to_code()), Some(t)); + } + for p in [Primaries::Bt709, Primaries::Bt601_625, Primaries::Bt601_525, Primaries::Bt2020, Primaries::P3D65] { + assert_eq!(Primaries::from_code(p.to_code()), Some(p)); + } + } } diff --git a/crates/control-protocol/src/lib.rs b/crates/control-protocol/src/lib.rs index 8bdb08d660..8194dc8e96 100644 --- a/crates/control-protocol/src/lib.rs +++ b/crates/control-protocol/src/lib.rs @@ -1,7 +1,7 @@ //! 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 std::io::{BufRead, BufReader, BufWriter, Read, Write}; use subtle::ConstantTimeEq; /// Whether a session token has the control protocol's 64 hexadecimal character form. @@ -72,12 +72,14 @@ pub enum ReadFailure { Rejected(String), } -/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped). +/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped, and a `\r` +/// before it). The `\r\n` or `\n` does not count toward `max`. /// `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); + // `take` bounds the bytes buffered for one line: a peer can't make us allocate more than + // `max + 2`, the line and its `\r\n`. + let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(2); 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()), @@ -90,12 +92,11 @@ pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usiz 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. + // A complete line, or the last line without a newline, then end of stream. Ok(true) } @@ -120,18 +121,30 @@ pub fn serve_lines(read: R, mut out: W, token: &str, max_line if let Some(o) = r.as_object_mut() { o.insert("id".into(), id); } - if writeln!(out, "{r}").and_then(|()| out.flush()).is_err() { + if write_line(&mut out, &r).is_err() { return; } continue; } }, }; - let _ = writeln!(out, "{}", json!({"ok": false, "error": reject})).and_then(|()| out.flush()); + let _ = write_line(&mut out, &json!({"ok": false, "error": reject})); return; } } +/// Write `reply` and its newline to `out` through a buffer, then flush. `writeln!` with a JSON +/// value writes each string, number and separator separately, which is one system call apiece on +/// an unbuffered socket. The buffer holds at most `REPLY_BUFFER` bytes, so a large reply is not +/// copied whole before it is sent. +fn write_line(out: &mut impl Write, reply: &Value) -> std::io::Result<()> { + const REPLY_BUFFER: usize = 64 * 1024; + let mut buffered = BufWriter::with_capacity(REPLY_BUFFER, out); + serde_json::to_writer(&mut buffered, reply).map_err(std::io::Error::other)?; + buffered.write_all(b"\n")?; + buffered.flush() +} + #[cfg(test)] mod tests { use super::*; @@ -193,6 +206,36 @@ mod tests { assert_eq!(calls, 1); } #[test] + fn replies_reach_the_writer_in_few_bounded_writes() { + struct Writes(Vec>); + impl Write for Writes { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.push(buf.to_vec()); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let input = b"{\"id\":1,\"method\":\"tree\",\"token\":\"s\"}\n{\"id\":2,\"method\":\"tree\"}\n"; + let mut writes = Writes(Vec::new()); + serve_lines(&input[..], &mut writes, "s", 1024, |_, _| Some(json!({"ok": true, "result": {"names": ["a", "b", "c"], "sizes": [1, 2, 3]}}))); + assert_eq!(writes.0.len(), 2, "one write for the reply and one for the rejection"); + for line in &writes.0 { + assert_eq!(line.last(), Some(&b'\n')); + serde_json::from_slice::(line).unwrap(); + } + // A large reply goes out in a few buffer-sized writes, never as one whole copy. + let items: Vec = (0..100_000).collect(); + let mut writes = Writes(Vec::new()); + serve_lines(&b"{\"method\":\"tree\",\"token\":\"s\"}\n"[..], &mut writes, "s", 1024, |_, _| Some(json!({"ok": true, "result": items}))); + let total: usize = writes.0.iter().map(Vec::len).sum(); + assert!(writes.0.len() < items.len() / 100); + assert!(writes.0.iter().all(|w| w.len() < total)); + let reply: Value = serde_json::from_slice(&writes.0.concat()).unwrap(); + assert_eq!(reply["result"].as_array().map(Vec::len), Some(items.len())); + } + #[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}})); @@ -226,6 +269,11 @@ mod tests { 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(_)))); + // The cap counts the line without its `\r\n` or `\n`. + assert_eq!(read_bounded_line(&mut &b"abc\r\n"[..], &mut buf, 3), Ok(true)); + assert_eq!(buf, b"abc"); + assert!(matches!(read_bounded_line(&mut &b"abcd\n"[..], &mut buf, 3), Err(ReadFailure::Rejected(_)))); + assert!(matches!(read_bounded_line(&mut &b"abcd\r\n"[..], &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(); diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 3e756aff75..1464a4cece 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -24,6 +24,8 @@ serde_json = { workspace = true } [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" +# The request-line reader and the reply's result, shared with servers built on it (MIT OR Apache-2.0, ours). +craft-control-protocol = { workspace = true } # The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours). craft-ai-agents = { workspace = true, optional = true } craft-atomic = { workspace = true, optional = true } @@ -36,6 +38,10 @@ log = { workspace = true, optional = true } proptest = { workspace = true } tempfile = "3" +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +# Reserve an unused control port without opening a listener, including between assertions. +socket2 = "0.6.5" + [[test]] name = "agents" required-features = ["agents"] diff --git a/crates/control/src/client.rs b/crates/control/src/client.rs index cbad788504..346602759b 100644 --- a/crates/control/src/client.rs +++ b/crates/control/src/client.rs @@ -117,13 +117,10 @@ impl Request { } } -/// A control reply as a call's result: its `result`, or its `error`. +/// A control reply as a call's result: its `result`, or its `error` +/// ([`craft_control_protocol::reply_result`]). 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()) - } + craft_control_protocol::reply_result(v) } /// A request the app said is still running. Its reply will come on this connection, through diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs index f5af19a004..e20bada163 100644 --- a/crates/control/src/client_tests.rs +++ b/crates/control/src/client_tests.rs @@ -3,6 +3,7 @@ use super::*; use crate::ControlRequest; use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits}; +use socket2::{Domain, Socket, Type}; use std::ffi::OsString; use std::net::TcpListener; use std::path::PathBuf; @@ -78,9 +79,14 @@ 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() +/// Keep this port bound without listening, so another normal test listener cannot take it. +fn reserve_non_listening_port() -> (Socket, u16) { + let reserved = Socket::new(Domain::IPV4, Type::STREAM, Some(socket2::Protocol::TCP)).unwrap(); + let address = std::net::SocketAddr::from(([127, 0, 0, 1], 0)); + reserved.bind(&address.into()).unwrap(); + let port = reserved.local_addr().unwrap().as_socket().unwrap().port(); + assert_ne!(port, 0); + (reserved, port) } #[test] @@ -115,13 +121,22 @@ fn a_wrong_token_or_none_is_refused() { #[test] fn an_app_not_running_says_how_to_start_it() { - let port = free_port(); + let (reserved, port) = reserve_non_listening_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); + drop(reserved); +} + +#[test] +fn the_not_running_fixture_keeps_its_port_from_another_listener() { + let (reserved, port) = reserve_non_listening_port(); + let rival = TcpListener::bind(("127.0.0.1", port)); + assert!(rival.is_err(), "another listener acquired the reserved port"); + drop(reserved); } /// An app that goes away during a call is lost, not "not running"; the next call says it is not diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs index 85664a1aa9..a276060c81 100644 --- a/crates/control/src/server.rs +++ b/crates/control/src/server.rs @@ -10,6 +10,7 @@ use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; +use craft_control_protocol::ReadFailure; use serde_json::{Value, json}; use crate::Effect; @@ -215,35 +216,19 @@ pub fn new_token() -> Option { 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`. +/// One line without its newline (and a `\r` before it), or `None` at the end of the stream, read +/// with [`craft_control_protocol::read_bounded_line`]. A line of more than `max` bytes, not +/// counting its `\r\n` or `\n`, is refused with `InvalidData`, and at most `max + 2` bytes of it +/// are buffered, so a client that sends gigabytes with no newline cannot make this thread +/// allocate until the process is killed. A read that times out (the token deadline) fails with +/// `TimedOut`. 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")); - } + match craft_control_protocol::read_bounded_line(r, &mut line, max) { + Ok(true) => Ok(Some(line)), + Ok(false) => Ok(None), + Err(ReadFailure::Timeout) => Err(std::io::ErrorKind::TimedOut.into()), + Err(ReadFailure::Rejected(e)) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)), } } @@ -1335,7 +1320,73 @@ mod tests { 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}"); + assert!(e.to_string().contains(&format!("longer than {MAX_LINE} bytes")), "{e}"); + } + + /// The cap is exact: a line of `max` bytes is read, and one byte more is refused even when its + /// newline arrives in the same read as the rest of it. The `\r\n` or `\n` after the line does + /// not count toward the cap. + #[test] + fn the_cap_holds_for_a_line_read_at_once() { + for end in [&b"\n"[..], &b"\r\n"[..]] { + let mut fits = vec![b'A'; 1000]; + fits.extend_from_slice(end); + assert_eq!(read_line(&mut BufReader::new(fits.as_slice()), 1000).unwrap().unwrap().len(), 1000); + let mut over = vec![b'A'; 1001]; + over.extend_from_slice(end); + let e = read_line(&mut BufReader::new(over.as_slice()), 1000).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + } + } + + /// The cap holds when the line arrives a few bytes at a time, and at the end of the stream: + /// a `\r\n` split across two reads does not count toward it, and a last line of one byte + /// more than the cap with no newline is refused. + #[test] + fn the_cap_holds_across_reads() { + let mut fits = vec![b'A'; 1000]; + fits.extend_from_slice(b"\r\n"); + assert_eq!(read_line(&mut BufReader::with_capacity(7, fits.as_slice()), 1000).unwrap().unwrap().len(), 1000); + let last = vec![b'A'; 1001]; + let e = read_line(&mut BufReader::with_capacity(7, last.as_slice()), 1000).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + } + + /// A read interrupted by a signal is tried again instead of ending the connection, and a + /// `\r` before the newline is not part of the line. + #[test] + fn interrupted_reads_are_retried() { + struct Interrupting(Vec<&'static [u8]>); + impl std::io::Read for Interrupting { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.0.is_empty() { + return Ok(0); + } + let chunk = self.0.remove(0); + if chunk.is_empty() { + return Err(std::io::ErrorKind::Interrupted.into()); + } + buf[..chunk.len()].copy_from_slice(chunk); + Ok(chunk.len()) + } + } + let mut r = BufReader::new(Interrupting(vec![b"", b"{\"a\"", b"", b":1}\r\n"])); + assert_eq!(read_line(&mut r, MAX_LINE).unwrap().unwrap(), b"{\"a\":1}"); + assert!(read_line(&mut r, MAX_LINE).unwrap().is_none()); + } + + /// A read that times out before the token is shown fails with `TimedOut`, which closes the + /// connection without a reply. + #[test] + fn timed_out_reads_report_timed_out() { + struct Slow; + impl std::io::Read for Slow { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(std::io::ErrorKind::WouldBlock.into()) + } + } + let e = read_line(&mut BufReader::new(Slow), MAX_LINE).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::TimedOut); } /// Ordinary framing: lines split on newlines, blank lines kept, no trailing newline needed. diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index c80ef7e2da..81f53fd10e 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -229,6 +229,9 @@ craft-ppt-binary = { workspace = true, optional = true } craft-sqlite = { workspace = true, optional = true } craft-audio-dsp = { workspace = true, optional = true } craft-sbs = { workspace = true, optional = true } +craft-ease = { workspace = true, optional = true } +craft-i18n-build = { workspace = true, optional = true } +craft-pbr = { workspace = true, optional = true } [features] ui = [ @@ -350,6 +353,7 @@ audio-qoa = ["audio", "craft-audio/qoa"] audio-qoa-decode = ["audio", "craft-audio/qoa-decode"] audio-qoa-encode = ["audio", "craft-audio/qoa-encode"] audio-rayon = ["audio", "craft-audio/rayon"] +audio-s302m = ["audio", "craft-audio/s302m"] audio-sbc = ["audio", "craft-audio/sbc"] audio-serde = ["audio", "craft-audio/serde"] audio-symphonia = ["audio", "craft-audio/symphonia"] @@ -442,6 +446,9 @@ dwg = ["dep:craft-dwg"] dxf = ["dep:craft-dxf"] +ease = ["dep:craft-ease"] +ease-serde = ["ease", "craft-ease/serde"] + ecproj-format = ["dep:craft-ecproj-format"] elf = ["dep:craft-elf"] @@ -557,6 +564,8 @@ http-url = ["dep:craft-http-url"] i18n-collate = ["craft-i18n/collate"] +i18n-build = ["dep:craft-i18n-build"] + ical = ["dep:craft-ical"] idml = ["dep:craft-idml"] @@ -564,6 +573,7 @@ idml = ["dep:craft-idml"] image-codecs = ["dep:craft-image-codecs"] image-codecs-avif = ["image-codecs", "craft-image-codecs/avif"] image-codecs-avif-decode = ["image-codecs", "craft-image-codecs/avif-decode"] +image-codecs-cms = ["image-codecs", "craft-image-codecs/cms"] image-codecs-corpus = ["image-codecs", "craft-image-codecs/corpus"] image-codecs-heif = ["image-codecs", "craft-image-codecs/heif"] image-codecs-jxl = ["image-codecs", "craft-image-codecs/jxl"] @@ -627,6 +637,7 @@ mcp-server = ["dep:craft-mcp-server"] media = ["dep:craft-media"] media-avi = ["media", "craft-media/avi"] +media-bink = ["media", "craft-media/bink"] media-bitstream = ["media", "craft-media/bitstream"] media-isobmff = ["media", "craft-media/isobmff"] media-matroska = ["media", "craft-media/matroska"] @@ -666,6 +677,7 @@ odf = ["dep:craft-odf"] odf-text = ["odf", "craft-odf/text"] ods = ["dep:craft-ods"] +ods-test-support = ["ods", "craft-ods/test-support"] offcrypto = ["dep:craft-offcrypto"] @@ -680,6 +692,9 @@ pages = ["dep:craft-pages", "keymap", "text"] palette = ["dep:craft-palette"] +pbr = ["dep:craft-pbr"] +pbr-parallel = ["pbr", "craft-pbr/parallel"] + pcap = ["dep:craft-pcap"] pcraft-bundle = ["dep:craft-pcraft-bundle"] @@ -961,6 +976,8 @@ video-av1 = ["video", "craft-video/av1"] video-av1-decode = ["video", "craft-video/av1-decode"] video-av1-encode = ["video", "craft-video/av1-encode"] video-av1-large-encode = ["video", "craft-video/av1-large-encode"] +video-bink = ["video", "craft-video/bink"] +video-bink-decode = ["video", "craft-video/bink-decode"] video-dnx = ["video", "craft-video/dnx"] video-ffv1 = ["video", "craft-video/ffv1"] video-h264 = ["video", "craft-video/h264"] @@ -977,7 +994,11 @@ video-mpeg2-encode = ["video", "craft-video/mpeg2-encode"] video-mpeg4 = ["video", "craft-video/mpeg4"] video-mpeg4-encode = ["video", "craft-video/mpeg4-encode"] video-prores = ["video", "craft-video/prores"] +video-rawvideo = ["video", "craft-video/rawvideo"] video-screen-video = ["video", "craft-video/screen-video"] +video-theora = ["video", "craft-video/theora"] +video-theora-decode = ["video", "craft-video/theora-decode"] +video-theora-encode = ["video", "craft-video/theora-encode"] video-threads = ["video", "craft-video/threads"] video-vmd = ["video", "craft-video/vmd"] video-vmd-decode = ["video", "craft-video/vmd-decode"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index b465304399..8946df18b6 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -103,6 +103,8 @@ pub use craft_drawingml as drawingml; pub use craft_dwg as dwg; #[cfg(feature = "dxf")] pub use craft_dxf as dxf; +#[cfg(feature = "ease")] +pub use craft_ease as ease; #[cfg(feature = "ecproj-format")] pub use craft_ecproj_format as ecproj_format; #[cfg(feature = "elf")] @@ -181,6 +183,8 @@ pub use craft_html as html; #[cfg(feature = "http-url")] pub use craft_http_url as http_url; pub use craft_i18n as i18n; +#[cfg(feature = "i18n-build")] +pub use craft_i18n_build as i18n_build; #[cfg(feature = "ical")] pub use craft_ical as ical; #[cfg(feature = "idml")] @@ -267,6 +271,8 @@ pub use craft_ora as ora; pub use craft_pages as pages; #[cfg(feature = "palette")] pub use craft_palette as palette; +#[cfg(feature = "pbr")] +pub use craft_pbr as pbr; #[cfg(feature = "pcap")] pub use craft_pcap as pcap; #[cfg(feature = "pcraft-bundle")] diff --git a/crates/csv/README.md b/crates/csv/README.md index 7df204e104..91390ac744 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -11,7 +11,8 @@ mapping a SYLK sheet onto a document are the caller's work. | Function | What it does | |---|---| | `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 | -| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | +| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters (empty or whitespace-only quoted records are blank); when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | +| `sniff_csv_delimiter(text, quote)` | same scan as `sniff_delimiter`, but for `.csv`-named text prefers comma when comma coherently separates every sampled record with text; when no candidate coherently separates every sampled record, falls back to a coherent candidate whose header and at least one later record share a positive delimiter count with strictly more than half of the sampled records having 1 to that many delimiters (preferring comma, then tab over semicolon), or else comma if comma coherently separates the first sampled record with text | | `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 f4a82f393f..fa5aed71f3 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -4,7 +4,8 @@ //! - [`decode_text`] turns a file's bytes into a string: byte order marks, UTF-8, else //! Windows-1256 when the bytes read as Arabic and Windows-1252 otherwise. //! - [`decode_utf8`] requires valid UTF-8 and strips a leading UTF-8 byte order mark. -//! - [`sniff_delimiter`] picks comma, semicolon or tab. +//! - [`sniff_delimiter`] picks comma, semicolon or tab; [`sniff_csv_delimiter`] applies the same +//! scan while preferring comma when it coherently separates `.csv` records. //! - [`parse_records`] splits text into records of fields (RFC 4180 with the usual leniency), //! handing each record to a callback, with a cap on the fields kept per record. [`records`] //! collects them. @@ -45,14 +46,35 @@ pub use decode::{decode_text, decode_utf8}; /// with one. When one of those candidates ends the sample inside a quoted field, each of them /// counts only up to that field's opening quote. pub fn sniff_delimiter(text: &str, quote: char) -> u8 { + sniff_delimiter_inner(text, quote, false) +} + +/// Picks comma, semicolon or tab for `.csv`-named text, preferring comma when it coherently +/// separates the sampled records. +/// +/// Uses the same bounded character sample, quote-boundary coherence rules and fallback ranking +/// as [`sniff_delimiter`], with two `.csv`-specific rules: +/// - When comma has coherent quoted fields and separates every sampled record with text, comma +/// wins even if tab or semicolon also separates them. +/// - When no candidate coherently separates every sampled record with text, a coherent candidate +/// whose first record and at least one later record share the same positive delimiter count +/// (and where strictly more than half of the sampled records with text contain between one and +/// that many delimiters) is chosen — preferring comma, then the most matching records, higher +/// header count and total, then tab over semicolon. If none matches, comma still wins when it +/// has coherent quoted fields and separates the first sampled record with text. +pub fn sniff_csv_delimiter(text: &str, quote: char) -> u8 { + sniff_delimiter_inner(text, quote, true) +} + +fn sniff_delimiter_inner(text: &str, quote: char, prefer_comma: bool) -> u8 { const SAMPLE_CHARS: usize = 64 * 1024; let sample_end = text.char_indices().nth(SAMPLE_CHARS).map_or(text.len(), |(at, _)| at); let sample = &text[..sample_end]; let truncated = sample_end < text.len(); let mut scans = b"\t,;".map(|delimiter| scan_delimiter(sample, delimiter, quote)); if truncated { - if scans.iter().any(|scan| scan.coherent && scan.counts.iter().min().is_some_and(|&min| min > 0)) { - return pick_delimiter(scans); + if scans.iter().any(separates_coherently) { + return pick_delimiter(scans, prefer_comma); } // 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); @@ -93,10 +115,60 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { } } } - pick_delimiter(scans) + pick_delimiter(scans, prefer_comma) } -fn pick_delimiter(scans: [DelimiterScan; 3]) -> u8 { +fn separates_coherently(scan: &DelimiterScan) -> bool { + scan.coherent && scan.counts.iter().min().is_some_and(|&min| min > 0) +} + +/// Scores a coherent candidate whose first record and at least one later record share the same +/// positive delimiter count, and where strictly more than half of the sampled records with text +/// contain between one and that many delimiters (allowing occasional short rows). +fn header_short_row_score(scan: &DelimiterScan) -> Option<(usize, usize, usize)> { + if !scan.coherent { + return None; + } + let &header = scan.counts.first()?; + if header == 0 { + return None; + } + let exact_matches = scan.counts.iter().filter(|&&count| count == header).count(); + let in_range = scan.counts.iter().filter(|&&count| (1..=header).contains(&count)).count(); + if exact_matches < 2 || in_range * 2 <= scan.counts.len() { + return None; + } + Some((exact_matches, header, scan.counts.iter().sum())) +} + +fn pick_csv_delimiter(scans: &[DelimiterScan; 3]) -> Option { + let [tab, comma, semi] = scans; + if separates_coherently(comma) { + return Some(b','); + } + if separates_coherently(tab) || separates_coherently(semi) { + return None; + } + if header_short_row_score(comma).is_some() { + return Some(b','); + } + if let Some((delimiter, _)) = [tab, semi] + .into_iter() + .filter_map(|scan| header_short_row_score(scan).map(|score| (scan.delimiter, score))) + .reduce(|best, candidate| if candidate.1 > best.1 { candidate } else { best }) + { + return Some(delimiter); + } + if comma.coherent && comma.counts.first().is_some_and(|&first| first > 0) { + return Some(b','); + } + None +} + +fn pick_delimiter(scans: [DelimiterScan; 3], prefer_comma: bool) -> u8 { + if prefer_comma && let Some(delimiter) = pick_csv_delimiter(&scans) { + return delimiter; + } let with_text = scans.each_ref().map(|scan| (scan.delimiter, scan.counts.as_slice(), scan.coherent)); // Records of delimiters alone have no quotes, so they are coherent. let delimiters_only = @@ -205,7 +277,6 @@ fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan { 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; @@ -505,6 +576,91 @@ mod tests { assert_eq!(sniff_delimiter(&format!("{}x;y\n", ",,,\n".repeat(20_000)), '"'), b','); } + #[test] + fn delimiter_sniffing_ignores_empty_quoted_records() { + assert_eq!(sniff_delimiter("\"\"\nName\tCity\nAda\tLondon\n", '"'), b'\t'); + assert_eq!(sniff_delimiter("\"\"\nName;City\nAda;London\n", '"'), b';'); + assert_eq!(sniff_delimiter("\" \"\nName\tCity\nAda\tLondon\n", '"'), b'\t'); + // Quoted empty cells separated by a delimiter still act as delimiter-only rows. + assert_eq!(sniff_delimiter("\"\";\"\"\n\"\";\"\"\n", '"'), b';'); + // A doubled quote inside a quoted field is content, not a blank line. + assert_eq!(sniff_delimiter("\"\"\"\"\nName\tCity\nAda\tLondon\n", '"'), b','); + } + + #[test] + fn csv_delimiter_sniffing_prefers_coherent_comma_and_detects_tab_and_semicolon() { + // Coherent comma separation wins even when semicolons or tabs appear in fields. + for text in [ + "id,notes; comments\n1,a; b; c\n2,d; e; f\n", + "Ort,\"Name;Vorname\"\nBerlin,\"a;b;c\"\n", + "\"Name\",\"Last; First\"\n\"Ada\",\"Lovelace; Countess\"\n", + "Name,Note\tx\nAda,hi\tthere\n", + "\"Name\tLabel\",City\nAda,London\n", + "\"\"\nName;Team;Role,Email\nAda;Core;Eng,ada@example.com\n", + // A short comma row does not fall back to an incoherent semicolon parse. + "\"Name\",\"Note;Tag\"\nAda;Team\nGrace,Hello;2\n", + // Single-column exports with stray separators fall back to comma. + "alpha;beta\r\ngamma\r\n", + "alpha\tbeta\r\ngamma\r\n", + ] { + assert_eq!(sniff_csv_delimiter(text, '"'), b',', "{text:?}"); + } + + // Tab- and semicolon-delimited CSVs (including headers containing commas) sniff cleanly. + for (text, expected) in [ + ("Name\tPosition\tOrt\nAda\tLead\tBerlin\n", b'\t'), + ("Name;City\nAda;London\n", b';'), + ("\"Name, First\"\tOrt\nAda\tBerlin\n", b'\t'), + ("\"Name\";\"Last, First\"\n\"Ada\";\"Lovelace, Countess\"\n", b';'), + ("\"Name\"\t\"Last, First\"\n\"Ada\"\t\"Lovelace, Countess\"\n", b'\t'), + ("Last, First\tEmail\tCity\nAda Lovelace\tada@example.com\tLondon\n", b'\t'), + ("Last, First;Email;City\nAda Lovelace;ada@example.com;London\n", b';'), + ("\"\"\nName\tCity\nAda\tLondon\n", b'\t'), + ("\"\"\nName;City\nAda;London\n", b';'), + ] { + assert_eq!(sniff_csv_delimiter(text, '"'), expected, "{text:?}"); + } + + let blank_tab_rows = format!("{}a;b\nc;d\n", "\t \t\n".repeat(25)); + assert_eq!(sniff_csv_delimiter(&blank_tab_rows, '"'), b';'); + assert_eq!(sniff_csv_delimiter(&format!("{};7\n", ";\n".repeat(40_000)), '"'), b';'); + } + + #[test] + fn csv_delimiter_sniffing_handles_short_rows_conservatively() { + // Tab- and semicolon-delimited CSVs with a short row recover when the header and a later + // full row agree across a majority of sampled records. + for (text, expected) in [ + ("Name\tCity\nAda\nGrace\tParis\n", b'\t'), + ("Name;City\nAda\nGrace;Paris\n", b';'), + ("Name\tCity\tRole\nAda\nGrace\tParis\tLead\n", b'\t'), + ("Name;City;Role\nAda\nGrace;Paris;Lead\n", b';'), + ("Name\tCity\nAda\tLondon\nGrace\n", b'\t'), + ("Name;City\nAda;London\nGrace\n", b';'), + ("Last, First\tCity\nAda\nGrace\tParis\n", b'\t'), + ("Last, First;City\nAda\nGrace;Paris\n", b';'), + ("\"\"\nName\tCity\nAda\nGrace\tParis\n", b'\t'), + ("\"Name\"\t\"City;Region\"\nAda;X\nGrace\tParis;Y\n", b'\t'), + ] { + assert_eq!(sniff_csv_delimiter(text, '"'), expected, "{text:?}"); + } + + // Comma preference and conservative single-column fallbacks stay comma. + for text in [ + "Name,Note;Tag\nAda\nGrace,Hello;2\n", + "Name,Note\tTag\nAda\nGrace,Hello\t2\n", + "\"Name\",\"Note;Tag\"\nAda;Team\n", + "alpha;beta\r\ngamma\r\n", + "alpha\tbeta\r\ngamma\r\n", + "alpha;beta\r\ngamma\r\ndelta\r\n", + "Notes\r\nalpha;beta\r\ngamma;delta\r\n", + "a;b\nc\nd\ne;f\n", + "Title: a;b\nline\nx;y;z\nline\nc;d\n", + ] { + assert_eq!(sniff_csv_delimiter(text, '"'), b',', "{text:?}"); + } + } + #[test] fn parser_stops_collecting_fields_at_the_cap() { let (max, extra) = (16_384usize, 50); diff --git a/crates/develop-model/docs/xmp-interop.md b/crates/develop-model/docs/xmp-interop.md index 78cb1f467c..5fc3fbb406 100644 --- a/crates/develop-model/docs/xmp-interop.md +++ b/crates/develop-model/docs/xmp-interop.md @@ -186,7 +186,7 @@ application's renderer and is ignored: the photo keeps LightCraft's own process, | `DefringePurple/GreenAmount/HueLo/HueHi` | `optics.defringe_*` | | | `ShadowTint`, `RedHue/Saturation`, `GreenHue/Saturation`, `BlueHue/Saturation` | `calibration.shadows_tint`, `calibration.red_hue/red_sat`, … | Calibration panel, 1:1 | | `PerspectiveVertical/Horizontal/Rotate/Scale/Aspect/X/Y` | `geometry.vertical/horizontal/rotate/scale/aspect/offset_x/offset_y` | | -| `PerspectiveUpright` | `geometry.upright` | 0 off, 1 auto, 2 level, 3 vertical, 4 full, 5 guided; saved `UprightTransform_*` matrices are not imported, so photo import reports that Lightroom geometry was not preserved and the selected mode will be recalculated | +| `PerspectiveUpright` | `geometry.upright` | 0 off, 1 auto, 2 full, 3 level, 4 vertical, 5 guided; saved `UprightTransform_*` matrices are not imported, so photo import reports that Lightroom geometry was not preserved and the selected mode will be recalculated | | `HasCrop`, `CropLeft/Top/Right/Bottom`, `CropAngle` | `crop.geometry` | normalized edges → rect; angle in degrees; `HasCrop="False"` → no crop | Values pass through our control specs, so anything outside our slider ranges gets clamped. diff --git a/crates/develop-model/src/crs.rs b/crates/develop-model/src/crs.rs index 8ca35379d0..bb23e2373d 100644 --- a/crates/develop-model/src/crs.rs +++ b/crates/develop-model/src/crs.rs @@ -414,11 +414,13 @@ pub fn to_partial(props: &Props, target: Target) -> Value { n(o, "PerspectiveX", "geometry.offset_x"); n(o, "PerspectiveY", "geometry.offset_y"); if let Some(u) = num(props, "crs:PerspectiveUpright") { + // 0 Off, 1 Auto, 2 Full, 3 Level, 4 Vertical, 5 Guided: Lightroom saves one Upright matrix per + // value, and each has that mode's shape (lightcraft#205) let mode = match u as i64 { 1 => "auto", - 2 => "level", - 3 => "vertical", - 4 => "full", + 2 => "full", + 3 => "level", + 4 => "vertical", 5 => "guided", _ => "off", }; diff --git a/crates/develop-model/src/crs/tests.rs b/crates/develop-model/src/crs/tests.rs index b978c8aef2..29d4dc0009 100644 --- a/crates/develop-model/src/crs/tests.rs +++ b/crates/develop-model/src/crs/tests.rs @@ -79,7 +79,7 @@ fn assert_common_detail_fields(s: &DevelopSettings) { } fn assert_common_geometry_fields(s: &DevelopSettings) { - assert_eq!(s.geometry.upright, Upright::Level); + assert_eq!(s.geometry.upright, Upright::Full); assert_eq!(s.geometry.vertical, -10.0); assert!(s.optics.remove_ca); assert_eq!(s.treatment, crate::Treatment::Color); @@ -92,6 +92,19 @@ fn assert_common_geometry_fields(s: &DevelopSettings) { assert_eq!((c.rect.x0, c.rect.y0, c.rect.x1, c.rect.y1, c.angle), (0.05, 0.1, 0.8, 0.9, 1.5)); } +/// `crs:PerspectiveUpright` 2, 3 and 4 name Full, Level and Vertical, in that order. +#[test] +fn upright_mode_numbers_name_full_level_and_vertical() { + for (value, mode) in [(2, Upright::Full), (3, Upright::Level), (4, Upright::Vertical)] { + let xmp = format!( + r#""# + ); + let partial = to_partial(&props(&xmp), Target::Any); + let s = apply_partial(&DevelopSettings::default(), &partial, 1.0); + assert_eq!(s.geometry.upright, mode, "crs:PerspectiveUpright={value}"); + } +} + /// A sidecar curve with a `NaN` or `inf` point (Rust's `parse` reads both) is not a curve: /// it is left out, rather than stored with a point the curve editor can't place. #[test] diff --git a/crates/doc-binary/src/stsh.rs b/crates/doc-binary/src/stsh.rs index 3bd0328f32..a90fd250c1 100644 --- a/crates/doc-binary/src/stsh.rs +++ b/crates/doc-binary/src/stsh.rs @@ -32,6 +32,9 @@ pub(crate) struct StandardFonts { pub(crate) bidi: Option, } +/// `sti` of no style ([MS-DOC] `StdfBase`): read when the record is too short for one. +const STI_NIL: u16 = 0x0FFF; + /// `StshiLsd.cbLSD`: the size of a latent style's `LSD` ([MS-DOC] `StshiLsd`). const LSD_SIZE: u16 = 4; @@ -55,6 +58,287 @@ pub(crate) fn standard_fonts(table: &[u8], fc: u32, lcb: u32) -> StandardFonts { StandardFonts { ascii: at(12), east_asian: at(14), other: at(16), bidi } } +/// The names of Word's built-in styles by `sti`: the "Index within built-in styles" of the +/// reserved style names in [MS-OE376] (Part 4 §2.7.3.9, 0–266), which [MS-DOC]'s `StdfBase` says +/// `sti` is. Spelled as that table spells them. +const BUILT_IN_NAMES: [&str; 267] = [ + "Normal", + "heading 1", + "heading 2", + "heading 3", + "heading 4", + "heading 5", + "heading 6", + "heading 7", + "heading 8", + "heading 9", + "index 1", + "index 2", + "index 3", + "index 4", + "index 5", + "index 6", + "index 7", + "index 8", + "index 9", + "toc 1", + "toc 2", + "toc 3", + "toc 4", + "toc 5", + "toc 6", + "toc 7", + "toc 8", + "toc 9", + "Normal Indent", + "footnote text", + "annotation text", + "header", + "footer", + "index heading", + "caption", + "table of figures", + "envelope address", + "envelope return", + "footnote reference", + "annotation reference", + "line number", + "page number", + "endnote reference", + "endnote text", + "table of authorities", + "macro", + "toa heading", + "List", + "List Bullet", + "List Number", + "List 2", + "List 3", + "List 4", + "List 5", + "List Bullet 2", + "List Bullet 3", + "List Bullet 4", + "List Bullet 5", + "List Number 2", + "List Number 3", + "List Number 4", + "List Number 5", + "Title", + "Closing", + "Signature", + "Default Paragraph Font", + "Body Text", + "Body Text Indent", + "List Continue", + "List Continue 2", + "List Continue 3", + "List Continue 4", + "List Continue 5", + "Message Header", + "Subtitle", + "Salutation", + "Date", + "Body Text First Indent", + "Body Text First Indent 2", + "Note Heading", + "Body Text 2", + "Body Text 3", + "Body Text Indent 2", + "Body Text Indent 3", + "Block Text", + "Hyperlink", + "FollowedHyperlink", + "Strong", + "Emphasis", + "Document Map", + "Plain Text", + "E-mail Signature", + "HTML Top of Form", + "HTML Bottom of Form", + "Normal (Web)", + "HTML Acronym", + "HTML Address", + "HTML Cite", + "HTML Code", + "HTML Definition", + "HTML Keyboard", + "HTML Preformatted", + "HTML Sample", + "HTML Typewriter", + "HTML Variable", + "Normal Table", + "annotation subject", + "No List", + "Outline List 1", + "Outline List 2", + "Outline List 3", + "Table Simple 1", + "Table Simple 2", + "Table Simple 3", + "Table Classic 1", + "Table Classic 2", + "Table Classic 3", + "Table Classic 4", + "Table Colorful 1", + "Table Colorful 2", + "Table Colorful 3", + "Table Columns 1", + "Table Columns 2", + "Table Columns 3", + "Table Columns 4", + "Table Columns 5", + "Table Grid 1", + "Table Grid 2", + "Table Grid 3", + "Table Grid 4", + "Table Grid 5", + "Table Grid 6", + "Table Grid 7", + "Table Grid 8", + "Table List 1", + "Table List 2", + "Table List 3", + "Table List 4", + "Table List 5", + "Table List 6", + "Table List 7", + "Table List 8", + "Table 3D effects 1", + "Table 3D effects 2", + "Table 3D effects 3", + "Table Contemporary", + "Table Elegant", + "Table Professional", + "Table Subtle 1", + "Table Subtle 2", + "Table Web 1", + "Table Web 2", + "Table Web 3", + "Balloon Text", + "Table Grid", + "Table Theme", + "Placeholder Text", + "No Spacing", + "Light Shading", + "Light List", + "Light Grid", + "Medium Shading 1", + "Medium Shading 2", + "Medium List 1", + "Medium List 2", + "Medium Grid 1", + "Medium Grid 2", + "Medium Grid 3", + "Dark List", + "Colorful Shading", + "Colorful List", + "Colorful Grid", + "Light Shading Accent 1", + "Light List Accent 1", + "Light Grid Accent 1", + "Medium Shading 1 Accent 1", + "Medium Shading 2 Accent 1", + "Medium List 1 Accent 1", + "Revision", + "List Paragraph", + "Quote", + "Intense Quote", + "Medium List 2 Accent 1", + "Medium Grid 1 Accent 1", + "Medium Grid 2 Accent 1", + "Medium Grid 3 Accent 1", + "Dark List Accent 1", + "Colorful Shading Accent 1", + "Colorful List Accent 1", + "Colorful Grid Accent 1", + "Light Shading Accent 2", + "Light List Accent 2", + "Light Grid Accent 2", + "Medium Shading 1 Accent 2", + "Medium Shading 2 Accent 2", + "Medium List 1 Accent 2", + "Medium List 2 Accent 2", + "Medium Grid 1 Accent 2", + "Medium Grid 2 Accent 2", + "Medium Grid 3 Accent 2", + "Dark List Accent 2", + "Colorful Shading Accent 2", + "Colorful List Accent 2", + "Colorful Grid Accent 2", + "Light Shading Accent 3", + "Light List Accent 3", + "Light Grid Accent 3", + "Medium Shading 1 Accent 3", + "Medium Shading 2 Accent 3", + "Medium List 1 Accent 3", + "Medium List 2 Accent 3", + "Medium Grid 1 Accent 3", + "Medium Grid 2 Accent 3", + "Medium Grid 3 Accent 3", + "Dark List Accent 3", + "Colorful Shading Accent 3", + "Colorful List Accent 3", + "Colorful Grid Accent 3", + "Light Shading Accent 4", + "Light List Accent 4", + "Light Grid Accent 4", + "Medium Shading 1 Accent 4", + "Medium Shading 2 Accent 4", + "Medium List 1 Accent 4", + "Medium List 2 Accent 4", + "Medium Grid 1 Accent 4", + "Medium Grid 2 Accent 4", + "Medium Grid 3 Accent 4", + "Dark List Accent 4", + "Colorful Shading Accent 4", + "Colorful List Accent 4", + "Colorful Grid Accent 4", + "Light Shading Accent 5", + "Light List Accent 5", + "Light Grid Accent 5", + "Medium Shading 1 Accent 5", + "Medium Shading 2 Accent 5", + "Medium List 1 Accent 5", + "Medium List 2 Accent 5", + "Medium Grid 1 Accent 5", + "Medium Grid 2 Accent 5", + "Medium Grid 3 Accent 5", + "Dark List Accent 5", + "Colorful Shading Accent 5", + "Colorful List Accent 5", + "Colorful Grid Accent 5", + "Light Shading Accent 6", + "Light List Accent 6", + "Light Grid Accent 6", + "Medium Shading 1 Accent 6", + "Medium Shading 2 Accent 6", + "Medium List 1 Accent 6", + "Medium List 2 Accent 6", + "Medium Grid 1 Accent 6", + "Medium Grid 2 Accent 6", + "Medium Grid 3 Accent 6", + "Dark List Accent 6", + "Colorful Shading Accent 6", + "Colorful List Accent 6", + "Colorful Grid Accent 6", + "Subtle Emphasis", + "Intense Emphasis", + "Subtle Reference", + "Intense Reference", + "Book Title", + "Bibliography", + "TOC Heading", +]; + +/// The built-in name of a style whose `sti` is `sti`. Word names a built-in style by its `sti`, +/// whatever name the file stores (a non-English Word stores "Обычный" or "Kop 1"): `None` for a +/// user-defined style (0x0FFE), the null 0x0FFF, and anything else past the table, which keep the +/// stored name. +pub(crate) fn built_in_name(sti: u16) -> Option<&'static str> { + BUILT_IN_NAMES.get(usize::from(sti)).copied() +} + /// Parse the `STSH` at `table[fc..fc+lcb]`. pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result, DocbinError> { let fc = fc as usize; @@ -95,6 +379,7 @@ pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result, Do // StdfBase ([MS-DOC] §2.9.260, 10 bytes): sti(12)+flags(4); stk(4)+istdBase(12); // cupx(4)+istdNext(12); bchUpe(16) (= cbStd); grfstd(16). istdBase is a zero-based // index into the stylesheet, 0x0FFF meaning "no parent". + let sti = stdf.get(0..2).map_or(STI_NIL, |b| u16::from_le_bytes([b[0], b[1]]) & 0x0FFF); let stk = (stdf.get(2).copied().unwrap_or(1) & 0x0F).max(1); let w1 = stdf.get(2..4).map(|b| u16::from_le_bytes([b[0], b[1]])).unwrap_or(0xFFF1); let istd_base = w1 >> 4; @@ -135,6 +420,8 @@ pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result, Do { chpx = u.clone(); } + // A built-in style goes by its built-in name ("Normal", "heading 1"), as in Word. + let name = built_in_name(sti).map_or(name, str::to_owned); out.push(RawStyle { stk, istd_base, name, papx, chpx }); } Ok(out) @@ -192,3 +479,84 @@ pub(crate) fn fonts(table: &[u8], fc: u32, lcb: u32) -> Vec { /// Bytes of an FFN before its primary name ([MS-DOC] §2.9.82). const FFN_HEADER: usize = 39; + +#[cfg(test)] +mod tests { + use super::*; + + /// One Word 97 STD ([MS-DOC] §2.9.260, `cbSTDBaseInFile` 10) with this `sti`, `stk` and + /// stored name, and empty UPXs. + fn std_record(sti: u16, stk: u16, name: &str) -> Vec { + let cupx: u16 = if stk == 1 { 2 } else { 1 }; + let mut v = Vec::new(); + v.extend_from_slice(&sti.to_le_bytes()); + v.extend_from_slice(&(stk | 0x0FFF << 4).to_le_bytes()); // stk, istdBase none + v.extend_from_slice(&(cupx | 0x0FFF << 4).to_le_bytes()); // cupx, istdNext none + v.extend_from_slice(&[0; 4]); // bchUpe, grfstd + let units: Vec = name.encode_utf16().collect(); + v.extend_from_slice(&(units.len() as u16).to_le_bytes()); + v.extend(units.iter().flat_map(|u| u.to_le_bytes())); + v.extend_from_slice(&[0, 0]); + if stk == 1 { + v.extend_from_slice(&[2, 0, 0, 0]); // UpxPapx: istd 0, no sprms + } + v.extend_from_slice(&[0, 0]); // UpxChpx: no sprms + [(v.len() as u16).to_le_bytes().to_vec(), v].concat() + } + + /// An STSH holding these STDs. + fn stsh(stds: &[Vec]) -> Vec { + let mut v = vec![4, 0]; + v.extend_from_slice(&(stds.len() as u16).to_le_bytes()); + v.extend_from_slice(&10u16.to_le_bytes()); + v.extend(stds.iter().flatten()); + v + } + + fn names(stds: &[Vec]) -> Vec { + let t = stsh(stds); + parse(&t, 0, t.len() as u32).expect("STSH").into_iter().map(|s| s.name).collect() + } + + /// #1805: a non-English Word stores its built-in styles under its own names; Word reads them + /// by `sti`, under the built-in names. + #[test] + fn built_in_styles_take_their_built_in_names() { + let read = names(&[ + std_record(0, 1, "Обычный"), + std_record(1, 1, "Kop 1"), + std_record(65, 2, "Fuente de párrafo predeter."), + std_record(153, 1, "Sprechblasentext"), + std_record(154, 3, "表 (格子)"), + std_record(266, 1, "Inhaltsverzeichnisüberschrift"), + ]); + assert_eq!(read, ["Normal", "heading 1", "Default Paragraph Font", "Balloon Text", "Table Grid", "TOC Heading"]); + } + + /// #1805: a user-defined style (0x0FFE), and an `sti` past the table, keep the stored name. + #[test] + fn other_styles_keep_their_stored_names() { + assert_eq!( + names(&[std_record(0x0FFE, 1, "Mijn stijl"), std_record(267, 2, "Later"), std_record(0x0FFF, 1, "Nil")]), + ["Mijn stijl", "Later", "Nil"] + ); + } + + /// #1805: the document's own Normal is the model's `Normal`, and a heading is a heading. + #[test] + fn a_localized_normal_is_the_models_normal() { + let t = stsh(&[std_record(0, 1, "Standaard"), std_record(1, 1, "Kop 1")]); + let sheet = crate::fmt::stylesheet(&parse(&t, 0, t.len() as u32).expect("STSH"), &[], StandardFonts::default()); + assert!(sheet.get("Normal").is_some()); + let h = sheet.styles.iter().find(|s| s.name == "Heading 1").expect("Heading 1"); + assert_eq!(h.para.outline_level, Some(0)); + } + + #[test] + fn the_table_has_every_sti_of_ms_oe376() { + assert_eq!(BUILT_IN_NAMES.len(), 267); + assert_eq!(built_in_name(106), Some("annotation subject")); + assert_eq!(built_in_name(107), Some("No List")); + assert_eq!(built_in_name(0x0FFE), None); + } +} diff --git a/crates/doc-binary/src/word6.rs b/crates/doc-binary/src/word6.rs index e9fab2d740..f293fd4fbf 100644 --- a/crates/doc-binary/src/word6.rs +++ b/crates/doc-binary/src/word6.rs @@ -389,119 +389,6 @@ fn stylesheet(word: &[u8], fc: u32, lcb: u32) -> (Vec, Vec (styles, facts) } -/// The names of the built-in styles by sti: the "Index within built-in styles" of the reserved -/// style names in [MS-OE376] (Part 4 §2.7.3.9), which [MS-DOC]'s StdfBase says sti is. 0x0FFE -/// (user-defined) and anything past the table keep the name stored in the file. -const BUILT_IN_NAMES: [&str; 107] = [ - "Normal", - "heading 1", - "heading 2", - "heading 3", - "heading 4", - "heading 5", - "heading 6", - "heading 7", - "heading 8", - "heading 9", - "index 1", - "index 2", - "index 3", - "index 4", - "index 5", - "index 6", - "index 7", - "index 8", - "index 9", - "toc 1", - "toc 2", - "toc 3", - "toc 4", - "toc 5", - "toc 6", - "toc 7", - "toc 8", - "toc 9", - "Normal Indent", - "footnote text", - "annotation text", - "header", - "footer", - "index heading", - "caption", - "table of figures", - "envelope address", - "envelope return", - "footnote reference", - "annotation reference", - "line number", - "page number", - "endnote reference", - "endnote text", - "table of authorities", - "macro", - "toa heading", - "List", - "List Bullet", - "List Number", - "List 2", - "List 3", - "List 4", - "List 5", - "List Bullet 2", - "List Bullet 3", - "List Bullet 4", - "List Bullet 5", - "List Number 2", - "List Number 3", - "List Number 4", - "List Number 5", - "Title", - "Closing", - "Signature", - "Default Paragraph Font", - "Body Text", - "Body Text Indent", - "List Continue", - "List Continue 2", - "List Continue 3", - "List Continue 4", - "List Continue 5", - "Message Header", - "Subtitle", - "Salutation", - "Date", - "Body Text First Indent", - "Body Text First Indent 2", - "Note Heading", - "Body Text 2", - "Body Text 3", - "Body Text Indent 2", - "Body Text Indent 3", - "Block Text", - "Hyperlink", - "FollowedHyperlink", - "Strong", - "Emphasis", - "Document Map", - "Plain Text", - "E-mail Signature", - "HTML Top of Form", - "HTML Bottom of Form", - "Normal (Web)", - "HTML Acronym", - "HTML Address", - "HTML Cite", - "HTML Code", - "HTML Definition", - "HTML Keyboard", - "HTML Preformatted", - "HTML Sample", - "HTML Typewriter", - "HTML Variable", - "Normal Table", - "annotation subject", -]; - /// One style entry (`None` for an empty slot or one too short for its fixed part and name). fn style(std: &[u8], cb_base: usize) -> Option<(RawStyle, StyleFacts)> { let u16_at = |at: usize| std.get(at..at + 2).map(|x| u16::from_le_bytes([x[0], x[1]])); @@ -515,8 +402,8 @@ fn style(std: &[u8], cb_base: usize) -> Option<(RawStyle, StyleFacts)> { // ("Default" or "Обычный" for Normal). Other names are 8-bit, as Word shows them // (Windows-1252: names it couldn't store read back with '?'). let stored = std.get(cb_base + 1..cb_base + 1 + len)?; - let name: String = match BUILT_IN_NAMES.get(usize::from(sti)) { - Some(built_in) => (*built_in).to_owned(), + let name: String = match crate::stsh::built_in_name(sti) { + Some(built_in) => built_in.to_owned(), None => stored.iter().map(|&b| craft_codepage::cp1252(b)).collect(), }; let mut upxs: Vec<&[u8]> = Vec::new(); diff --git a/crates/doc-binary/src/write/styles.rs b/crates/doc-binary/src/write/styles.rs index d1d6a6649a..6286d5ade0 100644 --- a/crates/doc-binary/src/write/styles.rs +++ b/crates/doc-binary/src/write/styles.rs @@ -72,7 +72,7 @@ const BUILTIN: &[(&str, u16)] = &[ ("FollowedHyperlink", 86), ("Strong", 87), ("Emphasis", 88), - ("Plain Text", 91), + ("Plain Text", 90), ("Normal (Web)", 94), ("Normal Table", 105), ("No List", 107), @@ -397,4 +397,30 @@ mod tests { let t = font_table(&names); assert_eq!(crate::stsh::fonts(&t, 0, t.len() as u32), names); } + + /// #1805: the reader names a built-in style by its `sti`, so each one the writer gives must be + /// the one [MS-OE376] lists for the name it writes (Plain Text is 90; 91 is E-mail Signature). + #[test] + fn every_built_in_sti_names_the_style_written() { + for &(name, sti) in BUILTIN { + assert_eq!(crate::stsh::built_in_name(sti), Some(name), "sti {sti}"); + } + } + + /// #1805: a built-in style the writer gives an `sti` reads back under its own name. + #[test] + fn a_plain_text_style_reads_back_as_plain_text() { + let mut d = craft_wordmodel::Document::new(); + std::sync::Arc::make_mut(&mut d.styles).styles.push(Style { + id: "PlainText".into(), + name: "Plain Text".into(), + kind: StyleKind::Paragraph, + based_on: Some("Normal".into()), + ..Default::default() + }); + d.body = vec![craft_wordmodel::para_block(craft_wordmodel::para::Paragraph::with_text("x", CharProps::default()).styled("PlainText"))]; + let r = crate::read(&crate::write(&d).expect("write")).expect("read back"); + let style = r.body[0].as_para().and_then(|p| p.props.style.clone()).and_then(|id| r.styles.get(&id).map(|s| s.name.clone())); + assert_eq!(style.as_deref(), Some("Plain Text")); + } } diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 18c9ea47a0..518f3e6b47 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -73,7 +73,7 @@ pub(crate) struct Reader<'p> { file_orders: craft_wordmodel::para::FileOrders, pub doc: Document, pub pc: PropCtx, - revs: HashMap<(u8, String, String, Option), u32>, + revs: HashMap<(u8, String, String, Option, Option), u32>, /// Move ranges (`w:moveFromRangeStart` …) seen so far. pub moves: MoveCtx, media_by_path: HashMap, diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index 9cc23be27c..851ecae67f 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -34,6 +34,8 @@ impl Reader<'_> { "w:linkStyles" => s.link_styles = on_off(k), "w:removePersonalInformation" => s.remove_personal_info = on_off(k), "w:removeDateAndTime" => s.remove_date_time = on_off(k), + "w:hideSpellingErrors" => s.hide_spelling_errors = on_off(k), + "w:hideGrammaticalErrors" => s.hide_grammar_errors = on_off(k), "w:compat" => { s.allow_space_of_same_style_in_table = k.child("w:allowSpaceOfSameStyleInTable").is_some_and(on_off); // Only Word's own setting: another `w:uri` names a different application's. diff --git a/crates/docx/src/read/parts.rs b/crates/docx/src/read/parts.rs index 79bdacb890..5c0d8ed9bc 100644 --- a/crates/docx/src/read/parts.rs +++ b/crates/docx/src/read/parts.rs @@ -74,17 +74,22 @@ impl Reader<'_> { pub(super) fn revision_named(&mut self, kind: RevisionKind, e: &El, move_name: Option) -> u32 { let author = e.attr("w:author").unwrap_or("").chars().take(256).collect::(); let date = e.attr("w:date").unwrap_or("").chars().take(64).collect::(); + // Only the Word namespace's `dateUtc`: a bare one would be saved under that namespace + // without having come from it. + let date_utc = e.attr_exact("w16du:dateUtc").filter(|d| !d.is_empty()).map(|d| d.chars().take(64).collect::()); let k = match kind { RevisionKind::Insert => 0, RevisionKind::Delete => 1, RevisionKind::Format => 2, }; - let key = (k, author.clone(), date.clone(), move_name.clone()); + // Two changes with one local `w:date` (the hour the clocks go back over) are told apart + // by their UTC time. + let key = (k, author.clone(), date.clone(), move_name.clone(), date_utc.clone()); if let Some(i) = self.revs.get(&key) { return *i; } let i = self.doc.revisions.len() as u32; - self.doc.revisions.push(Revision { kind, author, date, move_name }); + self.doc.revisions.push(Revision { kind, author, date, move_name, date_utc }); self.revs.insert(key, i); i } diff --git a/crates/docx/src/read/story/vml.rs b/crates/docx/src/read/story/vml.rs index 2460be72b2..4fd74b2c92 100644 --- a/crates/docx/src/read/story/vml.rs +++ b/crates/docx/src/read/story/vml.rs @@ -144,7 +144,9 @@ impl Reader<'_> { // Brightness and contrast (Word's picture watermark "Washout" sets them, #1711). let frac = |k: &str| img.attr(k).and_then(crate::units::vml_number); let fx = craft_wordmodel::picfx::PicFx::from_vml(frac("gain").unwrap_or(1.0), frac("blacklevel").unwrap_or(0.0)); - return Some(InlineObject::Image { media, w, h, alt, float, crop: [0.0; 4], fx, ole: None }); + let crop = + ["cropleft", "croptop", "cropright", "cropbottom"].map(|key| img.attr(key).and_then(vml_fraction).unwrap_or(0.0).clamp(0.0, 1.0)); + return Some(InlineObject::Image { media, w, h, alt, float, crop, fx, ole: None }); } // The shapetype the shape is drawn from (its `type`, ECMA-376 Part 4 VML), when written in // the same picture: what the shape leaves out, it takes from there. diff --git a/crates/docx/src/write/props.rs b/crates/docx/src/write/props.rs index 497ffc412e..086d0cad5a 100644 --- a/crates/docx/src/write/props.rs +++ b/crates/docx/src/write/props.rs @@ -225,6 +225,12 @@ pub fn open_change(w: &mut W, tag: &str, a: &ChangeAttrs) { w.open(tag, &refs); } +/// [`open_change`] for an empty element. +pub fn empty_change(w: &mut W, tag: &str, a: &ChangeAttrs) { + let refs: Vec<(&str, &str)> = a.iter().map(|(k, v)| (*k, v.as_str())).collect(); + w.empty(tag, &refs); +} + /// A tracked change element holding the properties before the change: `…`. fn change_el(w: &mut W, tag: &str, inner: &str, a: &ChangeAttrs, body: impl FnOnce(&mut W)) { open_change(w, tag, a); diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index 2d97e4a01c..a76ded663a 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -54,6 +54,13 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp 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", &[]); + } + if s.hide_grammar_errors { + w.empty("w:hideGrammaticalErrors", &[]); + } if let Some(id) = template_rel { w.empty("w:attachedTemplate", &[("r:id", id)]); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 6add6f0ebb..ac673c63ad 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -20,6 +20,8 @@ const OWNED: &[&str] = &[ "w:displayBackgroundShape", "w:mirrorMargins", "w:gutterAtTop", + "w:hideSpellingErrors", + "w:hideGrammaticalErrors", "w:attachedTemplate", "w:linkStyles", "w:mailMerge", diff --git a/crates/docx/src/write/story.rs b/crates/docx/src/write/story.rs index 26f1f2a449..377abc75c4 100644 --- a/crates/docx/src/write/story.rs +++ b/crates/docx/src/write/story.rs @@ -8,7 +8,7 @@ use craft_wordmodel::section::{LineNumberRestart, NoteProps, SectionProps, Secti use craft_wordmodel::table::Table; use craft_wordmodel::{Block, Blocks, InlineObject, Paragraph, RevisionKind}; -use super::props::{ChangeAttrs, borders, open_change, ppr_inner, rpr, rpr_inner, tblpr, tcpr, trpr}; +use super::props::{ChangeAttrs, borders, empty_change, open_change, ppr_inner, rpr, rpr_inner, tblpr, tcpr, trpr}; use super::{PartRels, Writer}; use crate::package::rt; use crate::units::{emu, n, twips}; diff --git a/crates/docx/src/write/story/blocks.rs b/crates/docx/src/write/story/blocks.rs index bdb2fb5427..c65fc734fc 100644 --- a/crates/docx/src/write/story/blocks.rs +++ b/crates/docx/src/write/story/blocks.rs @@ -1,5 +1,5 @@ use super::toc::written_toc_span; -use super::{Block, Blocks, CharProps, MAX_DEPTH, PartRels, Table, W, Writer, tblpr, tcpr, trpr, twips}; +use super::{Block, Blocks, CharProps, MAX_DEPTH, PartRels, Table, W, Writer, empty_change, tblpr, tcpr, trpr, twips}; impl Writer<'_> { fn write_trailing_para(&mut self, w: &mut W, depth: usize) { @@ -77,13 +77,11 @@ impl Writer<'_> { continue; } let name = self.doc.move_name(Some(rev)).unwrap_or("").to_string(); - let (id, author, date) = self.rev_attrs(rev); + let mut a = self.change_attrs(rev); + let id = a.first().map(|(_, id)| id.clone()).unwrap_or_default(); + a.insert(1, ("w:name", name)); let tag = if to { "w:moveToRangeStart" } else { "w:moveFromRangeStart" }; - if date.is_empty() { - w.empty(tag, &[("w:id", &id), ("w:name", &name), ("w:author", &author)]); - } else { - w.empty(tag, &[("w:id", &id), ("w:name", &name), ("w:author", &author), ("w:date", &date)]); - } + empty_change(w, tag, &a); self.open_moves.push((rev, id, to)); } } diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index babed9de51..624ce32381 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -1,5 +1,6 @@ use super::{ - ChangeAttrs, CharProps, InlineObject, Paragraph, PartRels, Piece, PropChange, RevisionKind, W, Writer, open_change, ppr_inner, rpr, rpr_inner, rt, + ChangeAttrs, CharProps, InlineObject, Paragraph, PartRels, Piece, PropChange, RevisionKind, W, Writer, empty_change, open_change, ppr_inner, rpr, + rpr_inner, rt, }; impl Writer<'_> { @@ -37,12 +38,8 @@ impl Writer<'_> { fn write_mark_rpr(&mut self, w: &mut W, mark: &CharProps, mark_revs: &[(u32, &str)]) { w.open("w:rPr", &[]); for (idx, tag) in mark_revs { - let (id, author, date) = self.rev_attrs(*idx); - if date.is_empty() { - w.empty(tag, &[("w:id", &id), ("w:author", &author)]); - } else { - w.empty(tag, &[("w:id", &id), ("w:author", &author), ("w:date", &date)]); - } + let a = self.change_attrs(*idx); + empty_change(w, tag, &a); } rpr_inner(w, mark); if let Some(ch) = mark.fmt_change.as_deref() { @@ -300,21 +297,20 @@ impl Writer<'_> { } } - pub(super) fn rev_attrs(&mut self, idx: u32) -> (String, String, String) { + /// `w:id`, `w:author`, `w:date` and `w16du:dateUtc` of a tracked change by revision `idx`. + pub(crate) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs { self.next_rev_id += 1; let r = self.doc.revisions.get(idx as usize); let author = crate::write::annotation_author(self.doc, r.map_or("", |r| r.author.as_str())).to_string(); - // Remove date and time (§17.15.1.69): tracked changes are saved without `w:date`. - let date = if self.doc.settings.remove_date_time { String::new() } else { r.map(|r| r.date.clone()).unwrap_or_default() }; - (self.next_rev_id.to_string(), author, date) - } - - /// `w:id`, `w:author` and `w:date` of a tracked change by revision `idx`. - pub(crate) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs { - let (id, author, date) = self.rev_attrs(idx); - let mut a = vec![("w:id", id), ("w:author", author)]; - if !date.is_empty() { - a.push(("w:date", date)); + let mut a = vec![("w:id", self.next_rev_id.to_string()), ("w:author", author)]; + // Remove date and time (§17.15.1.69): tracked changes are saved without their dates. + if let Some(r) = r.filter(|_| !self.doc.settings.remove_date_time) { + if !r.date.is_empty() { + a.push(("w:date", r.date.clone())); + } + if let Some(utc) = r.date_utc.as_ref().filter(|d| !d.is_empty()) { + a.push(("w16du:dateUtc", utc.clone())); + } } a } @@ -344,12 +340,8 @@ impl Writer<'_> { continue; } let tag = self.rev_tag(idx, tag); - let (id, author, date) = self.rev_attrs(idx); - if date.is_empty() { - w.open(tag, &[("w:id", &id), ("w:author", &author)]); - } else { - w.open(tag, &[("w:id", &id), ("w:author", &author), ("w:date", &date)]); - } + let a = self.change_attrs(idx); + open_change(w, tag, &a); } } diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index 46da6911d4..a6d8794fb6 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -49,6 +49,8 @@ pub const NAMESPACES: &[(&str, &str)] = &[ ("cx6", "http://schemas.microsoft.com/office/drawing/2016/5/12/chartex"), ("cx7", "http://schemas.microsoft.com/office/drawing/2016/5/13/chartex"), ("cx8", "http://schemas.microsoft.com/office/drawing/2016/5/14/chartex"), + // A tracked change's UTC time (`w16du:dateUtc`). + ("w16du", "http://schemas.microsoft.com/office/word/2023/wordml/word16du"), ]; /// The `a:ext` URI under which a drawing is marked decorative ([MS-ODRAWXML]), and the @@ -201,15 +203,20 @@ impl El { /// Attribute by canonical name (`w:val`); falls back to an unqualified attribute with the /// same local name (some producers omit the prefix). pub fn attr(&self, name: &str) -> Option<&str> { - if let Some((_, v)) = self.attrs.iter().find(|(k, _)| k == name) { + if let Some(v) = self.attr_exact(name) { return Some(v); } let local = name.rsplit(':').next().unwrap_or(name); if local != name { - return self.attrs.iter().find(|(k, _)| k == local).map(|(_, v)| v.as_str()); + return self.attr_exact(local); } None } + /// Attribute by canonical name only, for one whose namespace carries meaning an unqualified + /// attribute can't claim. + pub fn attr_exact(&self, name: &str) -> Option<&str> { + self.attrs.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str()) + } /// Child elements. pub fn els(&self) -> impl Iterator { self.kids.iter().filter_map(|n| match n { @@ -531,7 +538,7 @@ impl W { /// `xmlns:` declarations for the body-part namespaces, plus `mc:Ignorable`. pub fn body_ns() -> Vec<(String, String)> { let mut v: Vec<(String, String)> = NAMESPACES.iter().map(|(p, u)| (format!("xmlns:{p}"), (*u).to_string())).collect(); - v.push(("mc:Ignorable".into(), "w14 w15 wp14".into())); + v.push(("mc:Ignorable".into(), "w14 w15 wp14 w16du".into())); v } diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 4f2b9de277..e58fb3e0a7 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -2706,6 +2706,42 @@ fn move_revisions_round_trip() { check(&craft_docx::read(&out).unwrap()); } +/// Two insertions by one author with one local `w:date`, told apart (or not) by `dateUtc`. +fn two_insertions_at_one_local_time(utc: [&str; 2]) -> String { + let ins = |id: u32, utc: &str, text: &str| { + format!(r#"{text}"#) + }; + format!("{}{}", ins(1, utc[0], " One"), ins(2, utc[1], " Two")) +} + +/// Issue #3206: a tracked change's `dateUtc` is read under any prefix bound to Word's namespace +/// for it, and saved under that namespace. +#[test] +fn a_tracked_change_utc_time_is_read_under_any_prefix_for_its_namespace() { + let du = r#"xmlns:du="http://schemas.microsoft.com/office/word/2023/wordml/word16du""#; + let body = two_insertions_at_one_local_time([ + &format!(r#"{du} du:dateUtc="2026-11-01T05:30:00Z""#), + &format!(r#"{du} du:dateUtc="2026-11-01T06:30:00Z""#), + ]); + let d = read_body(&body); + let utc: Vec<_> = d.revisions.iter().map(|r| r.date_utc.as_deref()).collect(); + assert_eq!(utc, [Some("2026-11-01T05:30:00Z"), Some("2026-11-01T06:30:00Z")]); + let xml = text(&unzip(&craft_docx::write(&d).unwrap()), "word/document.xml"); + assert_eq!(attr_values(&xml, "w:ins", "w16du:dateUtc"), ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"]); +} + +/// Issue #3206: an unqualified `dateUtc` doesn't say it's Word's UTC time, so it neither tells +/// changes apart nor is saved under Word's namespace. +#[test] +fn an_unqualified_date_utc_is_not_a_tracked_change_utc_time() { + let body = two_insertions_at_one_local_time([r#"dateUtc="2026-11-01T05:30:00Z""#, r#"dateUtc="2026-11-01T06:30:00Z""#]); + let d = read_body(&body); + assert_eq!(d.revisions.len(), 1, "one author, kind and local date is one change"); + assert_eq!(d.revisions[0].date_utc, None); + let xml = text(&unzip(&craft_docx::write(&d).unwrap()), "word/document.xml"); + assert!(!xml.contains("dateUtc="), "{xml}"); +} + /// A document's own footnote separators and continuation notice are kept (ECMA-376 §17.11), and /// written back as Word numbers them: -1, 0 and 1, the notes after them. #[test] diff --git a/crates/docx/tests/it/picture_links.rs b/crates/docx/tests/it/picture_links.rs index dc5f53e19c..34cf625e1b 100644 --- a/crates/docx/tests/it/picture_links.rs +++ b/crates/docx/tests/it/picture_links.rs @@ -125,3 +125,91 @@ fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() { let edited = out.finish().unwrap().into_inner(); assert_eq!(picture_links(&craft_docx::read(&edited).unwrap())[0], Some("https://example.com/saved".to_string())); } + +// Original synthetic VML package for #2912, reported by denstu473; no reference-app asset. +#[test] +fn a_vml_picture_keeps_its_crop_when_saved() { + fn image_crop(doc: &Document, original_png: &[u8]) -> [f32; 4] { + let paragraph = doc.body[0].as_para().expect("the synthetic picture's paragraph"); + assert_eq!(paragraph.objects.len(), 1, "the VML picture must be decoded before testing crop"); + let InlineObject::Image { media, w, h, alt, crop, fx, .. } = ¶graph.objects[0] else { + panic!("the synthetic object must be an image"); + }; + assert!((*w - 24.0).abs() < 0.001 && (*h - 12.0).abs() < 0.001, "picture size changed: {w} x {h}"); + assert_eq!(alt, "cropped square"); + assert_eq!(doc.media.get(media).expect("the picture's embedded media").as_slice(), original_png); + assert_eq!(*fx, craft_wordmodel::picfx::PicFx::new(40_000, 0, 0)); + *crop + } + fn crops_near(actual: [f32; 4], expected: [f32; 4], tolerance: f32) -> bool { + actual.into_iter().zip(expected).all(|(a, b)| (a - b).abs() <= tolerance) + } + + let original_png = png(); + let mut lost = Vec::new(); + // Crop slots are left, top, right, bottom. These distinct fractions are exactly binary. + let positive = [0.125, 0.0625, 0.25, 0.5]; + for (label, attributes, expected, saved_rect) in [ + ("default", "", [0.0; 4], None), + ( + "report fixed fractions", + r#"cropleft="8192f" croptop="3277f" cropright="16384f" cropbottom="6554f""#, + [8192.0f32 / 65_536.0, 3277.0 / 65_536.0, 16384.0 / 65_536.0, 6554.0 / 65_536.0], + Some(r#""#), + ), + ( + "fixed fractions", + r#"cropleft="8192f" croptop="4096f" cropright="16384f" cropbottom="32768f""#, + positive, + Some(r#""#), + ), + ( + "decimal fractions", + r#"cropleft="0.125" croptop="0.0625" cropright="0.25" cropbottom="0.5""#, + positive, + Some(r#""#), + ), + ( + "percentage fractions", + r#"cropleft="12.5%" croptop="6.25%" cropright="25%" cropbottom="50%""#, + positive, + Some(r#""#), + ), + ( + "bounded fractions", + r#"cropleft="-25%" croptop="125%" cropright="not-a-fraction" cropbottom="NaN""#, + [0.0, 1.0, 0.0, 0.0], + Some(r#""#), + ), + ] { + // The local namespace keeps the existing package helper and every old fixture intact. + let body = format!( + r#""# + ); + let doc = craft_docx::read(&package(&body)).unwrap(); + let read_crop = image_crop(&doc, &original_png); + let saved = craft_docx::write(&doc).unwrap(); + let xml = part(&saved, "word/document.xml"); + let reopened = craft_docx::read(&saved).unwrap(); + let reopened_crop = image_crop(&reopened, &original_png); + + if let Some(saved_rect) = saved_rect { + if !crops_near(read_crop, expected, 0.000_001) { + lost.push(format!("{label}: read crop {read_crop:?}")); + } + if !xml.contains(saved_rect) { + lost.push(format!("{label}: saved srcRect")); + } + // DrawingML uses 100000 units per fraction; allow its rounding on a real re-read. + if !crops_near(reopened_crop, expected, 0.000_01) { + lost.push(format!("{label}: reopened crop {reopened_crop:?}")); + } + } else { + // The zero/default control must work before any positive-crop regression is reported. + assert_eq!(read_crop, [0.0; 4]); + assert!(!xml.contains(" Vec { @@ -29,11 +30,11 @@ fn unzip(bytes: &[u8]) -> BTreeMap { parts } -/// A package with two named commenters, a tracked insertion and deletion, the document -/// properties' creator and last-modified-by, and `settings` inside `w:settings`. +/// A package with two named commenters, a tracked insertion (with its UTC time) and deletion, the +/// document properties' creator and last-modified-by, and `settings` inside `w:settings`. fn fixture(settings: &str) -> Vec { let body = r#"Clause one. -AddedRemoved"#; +AddedRemoved"#; let comments = format!( r#"Check this.Agreed."# ); @@ -46,7 +47,7 @@ fn fixture(settings: &str) -> Vec { ); zip(&[ ("_rels/.rels", root_rels), - ("word/document.xml", format!(r#"{body}"#)), + ("word/document.xml", format!(r#"{body}"#)), ("word/_rels/document.xml.rels", doc_rels), ("word/comments.xml", comments), ("word/settings.xml", format!(r#"{settings}"#)), @@ -77,7 +78,7 @@ fn remove_personal_information_and_dates_on_save() { for name in NAMES { assert!(!all.contains(name), "{name} saved"); } - assert!(!all.contains("w:date="), "annotation date saved"); + assert!(!all.contains("w:date=") && !all.contains("dateUtc="), "annotation date saved"); assert!(!all.contains("2026-03-0"), "annotation date saved"); let comments = &parts["word/comments.xml"]; assert_eq!(comments.matches(r#"w:author="Author""#).count(), 2, "{comments}"); @@ -103,7 +104,7 @@ fn each_privacy_setting_works_alone() { // Dates only: names stay. let doc = craft_docx::read(&fixture("")).unwrap(); let (parts, all) = saved(&doc); - assert!(!all.contains("w:date=")); + assert!(!all.contains("w:date=") && !all.contains("dateUtc=")); assert!(all.contains("Quill Ramsey") && all.contains("Ona Vettel")); assert!(parts["docProps/core.xml"].contains("Quill Ramsey")); assert!(!parts["word/settings.xml"].contains("removePersonalInformation")); @@ -121,6 +122,7 @@ fn each_privacy_setting_works_alone() { let (parts, all) = saved(&doc); assert!(all.contains("Quill Ramsey") && all.contains(r#"w:initials="OV""#)); assert_eq!(all.matches("w:date=").count(), 4); + assert!(all.contains(r#"w16du:dateUtc="2026-03-04T13:06:07Z""#), "the insertion keeps its UTC time"); assert!(parts["docProps/core.xml"].contains("Ona Vettel")); assert!(!parts["word/settings.xml"].contains("removeDateAndTime")); } diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 4927cd09c8..f826bdf57e 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -229,6 +229,8 @@ fn every_para_prop_round_trips() { fmt_change: None, snap_to_grid: Some(false), text_alignment: Some(TextAlignment::Top), + // A list item's further paragraph: WordprocessingML has no such paragraph. + list_item: None, }; let variants = [ ParaProps { line_spacing: Some(LineSpacing::AtLeast(14.0)), indent_first: Some(24.0), align: Some(Align::Center), ..Default::default() }, @@ -976,8 +978,20 @@ fn toc_field_skips_nested_stories() { #[test] fn tracked_changes_round_trip() { let mut d = Document::new(); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None }); - d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None }); + d.revisions.push(Revision { + kind: RevisionKind::Insert, + author: "Alice".into(), + date: "2026-05-01T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); + d.revisions.push(Revision { + kind: RevisionKind::Delete, + author: "Bob".into(), + date: "2026-05-02T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); d.settings.track_changes = true; let ins = CharProps { ins: Some(0), ..Default::default() }; let del = CharProps { del: Some(1), bold: Some(true), ..Default::default() }; @@ -1001,12 +1015,51 @@ fn tracked_changes_round_trip() { assert!(r.settings.track_changes); } +/// Two changes by one author with one local `w:date` (the hour the clocks go back over) stay two +/// changes across a save, told apart by their UTC time (`w16du:dateUtc`). +#[test] +fn tracked_changes_with_one_local_date_stay_apart_by_their_utc_time() { + let mut d = Document::new(); + for utc in ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"] { + let mut r = Revision::new(RevisionKind::Insert, "Ada", "2026-11-01T01:30:00Z"); + r.date_utc = Some(utc.into()); + d.revisions.push(r); + } + d.settings.track_changes = true; + let p = para_runs(&[ + ("Draft.", CharProps::default()), + (" One", CharProps { ins: Some(0), ..Default::default() }), + (" Two", CharProps { ins: Some(1), ..Default::default() }), + ]); + d.body = vec![para_block(p.clone())]; + let r = rt(&d); + assert_eq!(r.revisions, d.revisions); + assert_eq!(paras(&r)[0].runs, p.runs); + // Without their UTC times, the file can't tell them apart. + for r in &mut d.revisions { + r.date_utc = None; + } + assert_eq!(rt(&d).revisions.len(), 1, "one author, kind and date is one change"); +} + #[test] fn tracked_equations_round_trip() { // Issue #6011: equations saved with tracked revision marks (w:ins / w:del) around math. let mut d = Document::new(); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None }); - d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None }); + d.revisions.push(Revision { + kind: RevisionKind::Insert, + author: "Alice".into(), + date: "2026-05-01T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); + d.revisions.push(Revision { + kind: RevisionKind::Delete, + author: "Bob".into(), + date: "2026-05-02T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); d.settings.track_changes = true; let ins = CharProps { ins: Some(0), ..Default::default() }; let del = CharProps { del: Some(1), ..Default::default() }; @@ -1061,8 +1114,20 @@ fn tracked_equations_round_trip() { fn nested_omath_para_revisions_read() { // Defensive reader check: w:ins and w:del nested inside m:oMathPara. let mut d = Document::new(); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None }); - d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Charles".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None }); + d.revisions.push(Revision { + kind: RevisionKind::Insert, + author: "Ada".into(), + date: "2026-05-01T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); + d.revisions.push(Revision { + kind: RevisionKind::Delete, + author: "Charles".into(), + date: "2026-05-02T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); let doc_xml = r#"x+1y-1"#; let base = craft_docx::write(&d).unwrap(); let bytes = replace_part(&base, "word/document.xml", doc_xml.as_bytes()); @@ -1080,8 +1145,20 @@ fn tracked_paragraph_marks_round_trip() { // Issue #229: an inserted / deleted paragraph mark is `w:ins` / `w:del` in the mark's // `w:rPr` (ECMA-376 §17.13.5.16, §17.13.5.15), alone or with mark formatting. let mut d = Document::new(); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None }); - d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None }); + d.revisions.push(Revision { + kind: RevisionKind::Insert, + author: "Alice".into(), + date: "2026-05-01T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); + d.revisions.push(Revision { + kind: RevisionKind::Delete, + author: "Bob".into(), + date: "2026-05-02T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); let mut split = Paragraph::with_text("Owned ALPHA ", CharProps::default()); split.mark.ins = Some(0); let mut joined = Paragraph::with_text("Owned BETA", CharProps::default()); @@ -1821,7 +1898,7 @@ fn kitchen_sink() -> Document { let f = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Note", CharProps::default()))]); let c = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment", CharProps::default()))]); d.comments.insert(3, Comment { author: "X".into(), part: c, ..Default::default() }); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None }); + d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None, date_utc: None }); d.last_section.headers.default = Some(h); let mut blocks: Blocks = Vec::new(); let mut p = para_runs(&[ diff --git a/crates/docx/tests/it/section_metadata_preservation.rs b/crates/docx/tests/it/section_metadata_preservation.rs index 7e83d46877..67cce5a338 100644 --- a/crates/docx/tests/it/section_metadata_preservation.rs +++ b/crates/docx/tests/it/section_metadata_preservation.rs @@ -41,7 +41,7 @@ fn section_metadata_survives_native_json_and_two_docx_save_reopen_cycles() { assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); assert!(xml.contains(r#"w:chapStyle="1" w:chapSep="hyphen""#), "cycle {cycle}: {xml}"); assert!(xml.contains(r#"w:chapStyle="10" w:chapSep="colon""#), "cycle {cycle}: {xml}"); - assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14\""), "cycle {cycle}: {xml}"); + assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14 w16du\""), "cycle {cycle}: {xml}"); document = craft_docx::read(&bytes).unwrap(); let json = serde_json::to_vec(&document).unwrap(); document = serde_json::from_slice(&json).unwrap(); diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index 556203f0c7..554d53b16a 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -204,3 +204,50 @@ fn do_not_track_moves_round_trips() { assert!(s.contains(""), "{s}"); assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves); } + +/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`, +/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged +/// part), written in a generated part, and left out when they are turned off. +#[test] +fn hidden_proofing_errors_round_trip() { + let original = SETTINGS.replace("") < pos(&s, "")); + assert!(pos(&s, "") < pos(&s, ""), "{s}"); + assert!(pos(&s, "") < pos(&s, "") && !s.contains("hideSpellingErrors"), "{s}"); + let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors); +} diff --git a/crates/docx/tests/it/wordml2003_write.rs b/crates/docx/tests/it/wordml2003_write.rs index 6256c6b91a..f68662b3d1 100644 --- a/crates/docx/tests/it/wordml2003_write.rs +++ b/crates/docx/tests/it/wordml2003_write.rs @@ -37,7 +37,7 @@ fn sample() -> Document { let foot = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Sown in May.", CharProps::default()))]); let com = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Too short?", CharProps::default()))]); d.comments.insert(3, Comment { author: "Bo".into(), part: com, ..Default::default() }); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None }); + d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None }); d.last_section.headers.default = Some(head); let mut p = Paragraph::new(); diff --git a/crates/dwg/README.md b/crates/dwg/README.md index 80088a89e6..495db1ff71 100644 --- a/crates/dwg/README.md +++ b/crates/dwg/README.md @@ -13,7 +13,7 @@ startup and call `serve_if_asked()` before normal argument handling. Subsequent is contained to that child. The worker has no operating-system memory limit yet. Without a configured worker, conversions are refused rather than run in the current process: call `allow_in_process()` only for input that is known to be trusted (tests, or bytes this process -produced itself). Coordinates, once a worker is configured but cannot start, also fail closed. +produced itself). Conversions, once a worker is configured but cannot start, also fail closed. The bridge is not built for `wasm32` or FreeBSD/aarch64. Those targets retain the public API and return a clear unsupported-build error. The `acadrust` 0.6.6 dependency is used unmodified under diff --git a/crates/dwg/src/worker.rs b/crates/dwg/src/worker.rs index 1d16f5701b..bb73f1b348 100644 --- a/crates/dwg/src/worker.rs +++ b/crates/dwg/src/worker.rs @@ -6,8 +6,9 @@ //! that reads one request from standard input and writes one reply to standard output. A file that //! kills the worker then costs that one open or save, and every other open drawing stays safe. //! -//! Without a worker [`decode`] and [`encode_as`] refuse rather than run the conversion in the -//! calling process, because the third-party code is the part that can end a process. +//! Without a worker [`decode`], [`encode_as`], [`encode_noted`] and [`encode_kept_noted`] refuse +//! rather than run the conversion in the calling process, because the third-party code is the part +//! that can end a process. //! [`allow_in_process`] is the explicit exception, for input the caller knows is trusted (tests, or //! bytes this process produced itself). There's no memory limit on the worker yet: that takes //! per-platform system calls, which `unsafe_code = "forbid"` keeps out of this crate. @@ -62,7 +63,9 @@ pub fn use_worker(program: PathBuf, args: Vec) { } /// Use a copy of this program as the worker, started with [`WORKER_ARG`]. If its path can't be -/// found, the reader and writer stay in this process. +/// found, the worker setting does not change. When no worker was set before, [`decode`], +/// [`encode_as`], [`encode_noted`] and [`encode_kept_noted`] then refuse unless +/// [`allow_in_process`] was called. pub fn use_own_worker() { match std::env::current_exe() { Ok(program) => use_worker(program, vec![WORKER_ARG.into()]), @@ -70,7 +73,8 @@ pub fn use_own_worker() { } } -/// Let [`decode`] and [`encode_as`] run the conversion in this process when no worker is set. +/// Let [`decode`], [`encode_as`], [`encode_noted`] and [`encode_kept_noted`] run the conversion in +/// this process when no worker is set. /// /// This opts out of the isolation the crate exists for: the third-party code allocates from sizes /// a hostile file declares, and a failed allocation ends the process. Call it for input the caller diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 5dd52af53d..b4035fdc30 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -35,6 +35,10 @@ pub enum DxfError { /// The memory for `tags` group codes couldn't be had: an error, not the process ending. #[error("not enough memory to read this drawing's {tags} DXF group codes")] OutOfMemory { tags: usize }, + /// An invalid integer value ([`Value::Invalid`]) cannot be encoded in binary DXF + /// because binary integer fields have no non-finite sentinel. + #[error("cannot encode invalid integer tag (group {code}) as binary DXF: `{text}`")] + InvalidInteger { code: i32, text: String }, } pub type Result = std::result::Result; @@ -48,12 +52,21 @@ pub enum Value { Bool(bool), /// Binary chunk (310–319, 1004) as hex text. Hex(String), + /// Non-finite or malformed numeric group value preserved as raw text. + Invalid(String), +} + +const I64_MIN_F64: f64 = -9_223_372_036_854_775_808.0; +const I64_MAX_EXCLUSIVE_F64: f64 = 9_223_372_036_854_775_808.0; + +fn f64_to_i64_checked(r: f64) -> Option { + if r.is_finite() && (I64_MIN_F64..I64_MAX_EXCLUSIVE_F64).contains(&r) { Some(r as i64) } else { None } } impl Value { pub fn as_str(&self) -> String { match self { - Value::Str(s) | Value::Hex(s) => s.clone(), + Value::Str(s) | Value::Hex(s) | Value::Invalid(s) => s.clone(), Value::Real(r) => format_real(*r), Value::Int(i) => i.to_string(), Value::Bool(b) => i64::from(*b).to_string(), @@ -84,6 +97,41 @@ impl Value { _ => 0, } } + /// Return the finite float value, or `None` if this value is non-finite or represents an invalid numeric group. + pub fn checked_f64(&self) -> Option { + match self { + Value::Real(r) if r.is_finite() => Some(*r), + Value::Int(i) => Some(*i as f64), + Value::Str(s) => s.trim().parse::().ok().filter(|v| v.is_finite()), + Value::Bool(b) => Some(f64::from(u8::from(*b))), + _ => None, + } + } + /// Return the integer value, or `None` if this value represents an invalid numeric group or cannot be converted to `i64`. + pub fn checked_i64(&self) -> Option { + match self { + Value::Int(i) => Some(*i), + Value::Real(r) => f64_to_i64_checked(*r), + Value::Str(s) => match s.trim().parse::() { + Ok(i) => Some(i), + Err(err) if matches!(err.kind(), std::num::IntErrorKind::PosOverflow | std::num::IntErrorKind::NegOverflow) => None, + Err(_) => s.trim().parse::().ok().and_then(f64_to_i64_checked), + }, + Value::Bool(b) => Some(i64::from(*b)), + _ => None, + } + } + /// Whether this value represents a malformed or non-finite numeric group. + pub fn is_invalid(&self) -> bool { + matches!(self, Value::Invalid(_)) + } + /// The raw text of the invalid value, if this is [`Value::Invalid`]. + pub fn invalid_str(&self) -> Option<&str> { + match self { + Value::Invalid(s) => Some(s), + _ => None, + } + } } #[derive(Clone, Debug, PartialEq)] @@ -100,11 +148,14 @@ impl Tag { Tag { code, value: Value::Str(v.into()) } } pub fn f(code: i32, v: f64) -> Self { - Tag { code, value: Value::Real(if v.is_finite() { v } else { 0.0 }) } + Tag { code, value: if v.is_finite() { Value::Real(v) } else { Value::Invalid(v.to_string()) } } } pub fn i(code: i32, v: i64) -> Self { Tag { code, value: Value::Int(v) } } + pub fn invalid(code: i32, v: impl Into) -> Self { + Tag { code, value: Value::Invalid(v.into()) } + } pub fn str(&self) -> String { self.value.as_str() } @@ -121,6 +172,20 @@ impl Tag { pub fn i64(&self) -> i64 { self.value.as_i64() } + /// Return the finite float value, or `None` if this tag's value is non-finite or invalid. + pub fn checked_f64(&self) -> Option { + self.value.checked_f64() + } + /// Return the integer value, or `None` if this tag's value is invalid or cannot be converted to `i64`. + pub fn checked_i64(&self) -> Option { + self.value.checked_i64() + } + pub fn is_invalid(&self) -> bool { + self.value.is_invalid() + } + pub fn invalid_str(&self) -> Option<&str> { + self.value.invalid_str() + } } /// The value type for a group code (DXF Reference, "Group Code Value Types"). @@ -151,18 +216,26 @@ pub fn kind_of(code: i32) -> Kind { fn typed(code: i32, text: &str) -> Value { let t = text.trim(); match kind_of(code) { - Kind::Real => t.parse::().ok().filter(|v| v.is_finite()).map_or(Value::Real(0.0), Value::Real), + Kind::Real => match t.parse::() { + Ok(v) if v.is_finite() => Value::Real(v), + _ => Value::Invalid(t.to_string()), + }, Kind::Int16 | Kind::Int32 | Kind::Int64 => { // A float spelling ("1e3", "12.0") is accepted when finite, clamped to what the // group's width holds, signed or unsigned (files write 16-bit flags up to 65535, as - // the integer spelling reads them); NaN, inf and text become 0. + // the integer spelling reads them); NaN, inf and non-numeric text become Value::Invalid. let (lo, hi) = match kind_of(code) { Kind::Int16 => (i64::from(i16::MIN), i64::from(u16::MAX)), Kind::Int32 => (i64::from(i32::MIN), i64::from(u32::MAX)), _ => (i64::MIN, i64::MAX), }; - t.parse::() - .map_or_else(|_| Value::Int(t.parse::().ok().filter(|f| f.is_finite()).map_or(0, |f| (f as i64).clamp(lo, hi))), Value::Int) + match t.parse::() { + Ok(i) => Value::Int(i), + Err(_) => match t.parse::() { + Ok(f) if f.is_finite() => Value::Int((f as i64).clamp(lo, hi)), + _ => Value::Invalid(t.to_string()), + }, + } } Kind::Bool => Value::Bool(t.parse::().unwrap_or(0) != 0), Kind::Hex => Value::Hex(normalize_hex(t)), @@ -201,8 +274,9 @@ pub use codepage::decode_code_page; /// /// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair, /// 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. +/// [`MAX_TAGS`] by default. For ASCII input, invalid numeric text is preserved as [`Value::Invalid`], +/// and an EOF tag is not required. Numeric accessors ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or +/// `0` for backward compatibility. pub fn parse(bytes: &[u8]) -> Result> { parse_with_limit(bytes, max_tags()) } @@ -255,7 +329,8 @@ fn count_ascii_pairs(bytes: &[u8]) -> usize { /// /// 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. +/// text is preserved as [`Value::Invalid`], and an EOF tag is not required. Numeric accessors +/// ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or `0` for backward compatibility. pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result> { if let Some(body) = bytes.strip_prefix(BINARY_SENTINEL) { return parse_binary_with_limit(body, max_tags); @@ -404,7 +479,8 @@ fn byte_lines(mut rest: &[u8]) -> impl Iterator { /// # Errors /// /// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair, -/// or too many tags. Invalid numeric text becomes `0.0` for real values or `0` for integer values. +/// or too many tags. Invalid numeric text is preserved as [`Value::Invalid`]. Numeric accessors +/// ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or `0` for backward compatibility. /// A complete tag stream does not require an EOF tag. pub fn parse_ascii(text: &str) -> Result> { parse_ascii_counted(text, max_tags(), 0) @@ -418,6 +494,21 @@ fn parse_ascii_counted(text: &str, max_tags: usize, expected: usize) -> Result String { + let unescaped = unescape_owned(s.clone()); + if unescaped == s { + return s; + } + let becomes_valid_numeric = match kind_of(code) { + Kind::Real => unescaped.trim().parse::().ok().filter(|v| v.is_finite()).is_some(), + Kind::Int16 | Kind::Int32 | Kind::Int64 => { + unescaped.trim().parse::().is_ok() || unescaped.trim().parse::().ok().filter(|f| f.is_finite()).is_some() + } + _ => false, + }; + if becomes_valid_numeric { s } else { unescaped } +} + /// The tags of ASCII DXF text. With `recover`, a line that is no group code, or a group code /// with no value after it, ends the reading instead of failing it: the tags before it are /// returned with the 1-based number of that line. @@ -450,6 +541,7 @@ fn ascii_tags(text: &str, max_tags: usize, expected: usize, recover: bool) -> Re let v = match typed(code, val) { // Only text with a backslash can hold an escape; the rest moves in as it is. Value::Str(s) => Value::Str(unescape_owned(s)), + Value::Invalid(s) => Value::Invalid(unescape_invalid(code, s)), o => o, }; let eof = code == 0 && matches!(&v, Value::Str(s) if s.trim_end() == "EOF"); @@ -570,7 +662,10 @@ fn parse_binary_pass(b: &[u8], max_tags: usize, text: &mut codepage::BinaryText) }; let v = match kind_of(code) { Kind::Str => Value::Str(unescape_unicode(&text.string(code, c.cstr()?))), - Kind::Real => Value::Real(Some(c.f64()?).filter(|v| v.is_finite()).unwrap_or(0.0)), + Kind::Real => { + let r = c.f64()?; + if r.is_finite() { Value::Real(r) } else { Value::Invalid(r.to_string()) } + } Kind::Int16 => Value::Int(i64::from(c.i16()?)), Kind::Int32 => Value::Int(i64::from(c.i32()?)), Kind::Int64 => Value::Int(c.i64()?), @@ -766,6 +861,7 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec { out.extend_from_slice(chunk.as_bytes()); } } + Value::Invalid(s) => push_string(s, strings, &mut out), } out.extend_from_slice(b"\r\n"); } @@ -779,17 +875,36 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec { /// several groups of the same code). Strings are UTF-8 when `utf8` (R2007+), otherwise escaped as /// in [`write_ascii`]. A tag's value is converted to its code's kind, so a number written as text /// is stored as a number; a code outside the 16-bit range is skipped. -pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec { - binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }) +/// +/// Invalid real values ([`Value::Invalid`]) are preserved across binary serialization using +/// `f64::NAN`. +/// +/// # Errors +/// +/// Returns [`DxfError::InvalidInteger`] if any integer tag holds an invalid value ([`Value::Invalid`]), +/// because binary DXF integer representations have no IEEE-754 non-finite sentinel. Callers who +/// want invalid integers normalized to `0` can use [`write_binary_lossy`]. +pub fn write_binary(tags: &[Tag], utf8: bool) -> Result> { + binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }, false) } /// Write tags as pre-R2007 binary DXF with text in the code page `code_page` names, as /// [`write_ascii_in`] does. -pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Vec { - binary(tags, Strings::Escaped(codepage::encoder(code_page))) +/// +/// # Errors +/// +/// Returns [`DxfError::InvalidInteger`] if any integer tag holds an invalid value ([`Value::Invalid`]). +pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Result> { + binary(tags, Strings::Escaped(codepage::encoder(code_page)), false) } -fn binary(tags: &[Tag], strings: Strings) -> Vec { +/// Write tags as binary DXF, normalizing invalid integer tags ([`Value::Invalid`]) to `0` +/// instead of returning an error. +pub fn write_binary_lossy(tags: &[Tag], utf8: bool) -> Vec { + binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }, true).unwrap_or_default() +} + +fn binary(tags: &[Tag], strings: Strings, normalize_invalid_integers: bool) -> Result> { let mut out = Vec::with_capacity(BINARY_SENTINEL.len() + tags.len() * 12); out.extend_from_slice(BINARY_SENTINEL); for t in tags { @@ -809,19 +924,44 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { } Kind::Real => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&t.value.as_f64().to_le_bytes()); + let r = match &t.value { + Value::Invalid(s) => s.parse::().unwrap_or(f64::NAN), + _ => t.value.checked_f64().unwrap_or(0.0), + }; + out.extend_from_slice(&r.to_le_bytes()); } Kind::Int16 => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&wrap_i16(t.value.as_i64())); + let i = match t.value.checked_i64() { + Some(i) => i, + None if normalize_invalid_integers => 0, + None => { + return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() }); + } + }; + out.extend_from_slice(&wrap_i16(i)); } Kind::Int32 => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&wrap_i32(t.value.as_i64())); + let i = match t.value.checked_i64() { + Some(i) => i, + None if normalize_invalid_integers => 0, + None => { + return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() }); + } + }; + out.extend_from_slice(&wrap_i32(i)); } Kind::Int64 => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&t.value.as_i64().to_le_bytes()); + let i = match t.value.checked_i64() { + Some(i) => i, + None if normalize_invalid_integers => 0, + None => { + return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() }); + } + }; + out.extend_from_slice(&i.to_le_bytes()); } Kind::Bool => { out.extend_from_slice(&code_bytes); @@ -842,7 +982,7 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { } } } - out + Ok(out) } /// Hex text cleaned up: only the hex digits are kept, and an odd trailing digit is padded with @@ -1219,6 +1359,137 @@ mod tests { assert_eq!(t[0].str(), expect, "{s:?}"); } } + + #[test] + fn invalid_numeric_values_produce_value_invalid_and_preserve_compatibility() { + let val = Value::Invalid("not_a_number".into()); + assert!(val.is_invalid()); + assert_eq!(val.invalid_str(), Some("not_a_number")); + assert_eq!(val.as_str(), "not_a_number"); + assert_eq!(val.as_f64(), 0.0); + assert_eq!(val.as_i64(), 0); + + let tag = Tag::invalid(10, "NaN"); + assert!(tag.is_invalid()); + assert_eq!(tag.invalid_str(), Some("NaN")); + assert_eq!(tag.str(), "NaN"); + assert_eq!(tag.str_ref(), None); + assert_eq!(tag.f64(), 0.0); + assert_eq!(tag.i64(), 0); + } + + #[test] + fn parse_ascii_invalid_and_non_finite_reals() { + let text = "10\nNaN\n20\ninf\n30\n-inf\n40\ngarbage\n50\n 12.34.56 \n0\nEOF\n"; + let tags = parse(text.as_bytes()).unwrap(); + assert_eq!(tags.len(), 6); + + assert_eq!(tags[0], Tag::invalid(10, "NaN")); + assert!(tags[0].is_invalid()); + assert_eq!(tags[0].f64(), 0.0); + + assert_eq!(tags[1], Tag::invalid(20, "inf")); + assert!(tags[1].is_invalid()); + assert_eq!(tags[1].f64(), 0.0); + + assert_eq!(tags[2], Tag::invalid(30, "-inf")); + assert!(tags[2].is_invalid()); + assert_eq!(tags[2].f64(), 0.0); + + assert_eq!(tags[3], Tag::invalid(40, "garbage")); + assert!(tags[3].is_invalid()); + assert_eq!(tags[3].f64(), 0.0); + + assert_eq!(tags[4], Tag::invalid(50, "12.34.56")); + assert!(tags[4].is_invalid()); + assert_eq!(tags[4].f64(), 0.0); + } + + #[test] + fn invalid_reals_roundtrip_in_ascii_and_binary() { + let tags = vec![Tag::invalid(10, "NaN"), Tag::invalid(20, "inf"), Tag::invalid(30, "malformed"), Tag::s(0, "EOF")]; + let ascii_out = write_ascii(&tags); + let back_ascii = parse(ascii_out.as_bytes()).unwrap(); + assert_eq!(back_ascii[0], Tag::invalid(10, "NaN")); + assert_eq!(back_ascii[1], Tag::invalid(20, "inf")); + assert_eq!(back_ascii[2], Tag::invalid(30, "malformed")); + + let bin_out = write_binary(&tags, true).unwrap(); + let back_bin = parse(&bin_out).unwrap(); + assert_eq!(back_bin[0], Tag::invalid(10, "NaN")); + assert_eq!(back_bin[1], Tag::invalid(20, "inf")); + // Invalid text that cannot be parsed as a float is preserved in binary DXF as NaN, + // so it remains invalid rather than silently converting to genuine zero. + assert_eq!(back_bin[2], Tag::invalid(30, "NaN")); + assert_eq!(back_bin[2].f64(), 0.0); + assert!(back_bin[2].is_invalid()); + } + + #[test] + fn checked_i64_bounds_enforced_including_exclusive_upper_bound() { + // Inclusive lower bound: -2^63 fits + assert_eq!(Value::Real(-9_223_372_036_854_775_808.0).checked_i64(), Some(i64::MIN)); + assert_eq!(Value::Str("-9223372036854775808".into()).checked_i64(), Some(i64::MIN)); + + // Adjacent decimal below lower bound: must not round to i64::MIN via float fallback + assert_eq!(Value::Str("-9223372036854775809".into()).checked_i64(), None); + + // Far below lower bound: does not fit + assert_eq!(Value::Real(-1e30).checked_i64(), None); + assert_eq!(Value::Str("-1e30".into()).checked_i64(), None); + + // Inclusive upper bound: 2^63 - 1 fits + assert_eq!(Value::Str("9223372036854775807".into()).checked_i64(), Some(i64::MAX)); + + // Exclusive upper bound / adjacent decimal above upper bound: does not fit + assert_eq!(Value::Real(9_223_372_036_854_775_808.0).checked_i64(), None); + assert_eq!(Value::Str("9223372036854775808".into()).checked_i64(), None); + + // Just below exclusive upper bound: 2^63 - 2048 (largest representable f64 < 2^63) + assert_eq!(Value::Real(9_223_372_036_854_774_784.0).checked_i64(), Some(9_223_372_036_854_774_784)); + + // Float syntax fallback still converts finite real strings within integer range + assert_eq!(Value::Str("12.0".into()).checked_i64(), Some(12)); + assert_eq!(Value::Str("-12.0".into()).checked_i64(), Some(-12)); + assert_eq!(Value::Str("1e3".into()).checked_i64(), Some(1000)); + + // Normal values + assert_eq!(Value::Real(42.0).checked_i64(), Some(42)); + assert_eq!(Value::Int(42).checked_i64(), Some(42)); + assert_eq!(Value::Invalid("foo".into()).checked_i64(), None); + } + + #[test] + fn invalid_numeric_escape_does_not_decode_into_valid_numeric_spelling() { + let text = "10\n\\U+0030\n0\nEOF\n"; + let tags = parse(text.as_bytes()).unwrap(); + assert_eq!(tags[0], Tag::invalid(10, "\\U+0030")); + assert!(tags[0].is_invalid()); + + // Roundtrip in ASCII preserves raw invalid escape and signal + let ascii_out = write_ascii(&tags); + let back_ascii = parse(ascii_out.as_bytes()).unwrap(); + assert_eq!(back_ascii[0], Tag::invalid(10, "\\U+0030")); + assert!(back_ascii[0].is_invalid()); + + // Roundtrip in binary preserves invalid signal via NaN sentinel + let bin_out = write_binary(&tags, true).unwrap(); + let back_bin = parse(&bin_out).unwrap(); + assert_eq!(back_bin[0], Tag::invalid(10, "NaN")); + assert!(back_bin[0].is_invalid()); + } + + #[test] + fn binary_integer_writer_reports_error_unless_lossy_normalized() { + let tags = vec![Tag::invalid(70, "corrupted"), Tag::s(0, "EOF")]; + // Checked write_binary returns error for invalid integer tag + assert!(matches!(write_binary(&tags, true), Err(DxfError::InvalidInteger { code: 70, .. }))); + + // Explicit write_binary_lossy normalizes invalid integer to 0 + let lossy_bin = write_binary_lossy(&tags, true); + let back = parse(&lossy_bin).unwrap(); + assert_eq!(back[0], Tag::i(70, 0)); + } } #[cfg(test)] diff --git a/crates/dxf/tests/it/audit_followups.rs b/crates/dxf/tests/it/audit_followups.rs index de61bf175a..bd82631019 100644 --- a/crates/dxf/tests/it/audit_followups.rs +++ b/crates/dxf/tests/it/audit_followups.rs @@ -9,7 +9,7 @@ fn group_code_255_is_an_ordinary_code_in_binary_dxf() { // Code 255 used to be read as an R12 escape (`FF 00 `), so a file with that code could // not be read back. let tags = vec![Tag::s(255, "x"), Tag::s(0, "EOF")]; - let back = parse(&write_binary(&tags, true)).unwrap(); + let back = parse(&write_binary(&tags, true).unwrap()).unwrap(); assert_eq!(back.len(), 2); assert_eq!((back[0].code, back[0].str()), (255, "x".to_string())); } @@ -117,7 +117,7 @@ fn escapes_next_to_other_text_and_backslashes() { assert_eq!(parse(&file).unwrap()[0].str(), "éA\\ ü"); // And the writer keeps the literal text literal. let tags = [Tag::s(1, "é\\U+0041\\ ü"), Tag::s(0, "EOF")]; - assert_eq!(parse(&write_binary(&tags, true)).unwrap()[0].str(), "é\\U+0041\\ ü"); + assert_eq!(parse(&write_binary(&tags, true).unwrap()).unwrap()[0].str(), "é\\U+0041\\ ü"); } #[test] diff --git a/crates/dxf/tests/it/binary_write.rs b/crates/dxf/tests/it/binary_write.rs index 6c56c3a336..ab70341d39 100644 --- a/crates/dxf/tests/it/binary_write.rs +++ b/crates/dxf/tests/it/binary_write.rs @@ -27,7 +27,7 @@ fn binary_converts_values_to_their_codes_kind() { // A number held as text at a numeric code, an out-of-range 16-bit value, a long chunk. let long = "AB".repeat(300); let tags = vec![Tag::s(70, "12"), Tag::i(62, 1 << 20), Tag::new(310, Value::Hex(long)), Tag::s(0, "EOF")]; - let back = parse(&write_binary(&tags, true)).unwrap(); + let back = parse(&write_binary(&tags, true).unwrap()).unwrap(); assert_eq!(back[0], Tag::i(70, 12)); assert_eq!(back[1], Tag::i(62, i64::from(i16::MAX))); let sizes: Vec = back.iter().filter(|t| t.code == 310).map(|t| t.str().len()).collect(); @@ -36,7 +36,7 @@ fn binary_converts_values_to_their_codes_kind() { #[test] fn hostile_binary_input_never_panics() { - let good = write_binary(&sample(), true); + let good = write_binary(&sample(), true).unwrap(); // Every truncation, and every single-byte corruption of the body. for n in 0..good.len() { let _ = parse(good.get(..n).unwrap()); diff --git a/crates/dxf/tests/it/code_page_write.rs b/crates/dxf/tests/it/code_page_write.rs index 02e8a75d2b..35ce1ed457 100644 --- a/crates/dxf/tests/it/code_page_write.rs +++ b/crates/dxf/tests/it/code_page_write.rs @@ -43,7 +43,7 @@ fn text_is_written_in_the_code_page() { ]; for (cp, text, raw) in cases { let tags = file(cp, text); - for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] { assert!(contains(&bytes, raw), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); } @@ -60,7 +60,7 @@ fn unknown_ascii_and_utf8_code_pages_are_pure_ascii() { assert!(bytes.is_ascii(), "{cp}"); assert_eq!(bytes, write_ascii(&tags).into_bytes(), "{cp}"); assert!(contains(&bytes, b"A\\U+00E7\\U+00E3o fim"), "{cp}"); - assert!(write_binary_in(&tags, cp).iter().all(u8::is_ascii), "{cp} binary"); + assert!(write_binary_in(&tags, cp).unwrap().iter().all(u8::is_ascii), "{cp} binary"); } } @@ -74,7 +74,7 @@ fn code_page_bytes_that_are_valid_utf8_are_escaped_in_ascii() { assert!(ascii.is_ascii(), "{:?}", String::from_utf8_lossy(&ascii)); assert!(contains(&ascii, b"\\U+0421\\U+0406")); assert_eq!(parse(&ascii).unwrap()[10].str(), "СІ"); - let binary = write_binary_in(&tags, "ANSI_1251"); + let binary = write_binary_in(&tags, "ANSI_1251").unwrap(); assert!(contains(&binary, b"\xD1\xB2")); assert_eq!(parse(&binary).unwrap()[10].str(), "СІ"); // Bytes that are not valid UTF-8 stay as they are. @@ -111,7 +111,7 @@ fn literal_escapes_survive_code_page_text() { [("ANSI_1252", "Ação \\U+00E9 \\M+183A4F"), ("ANSI_1251", "Слой \\U+0041"), ("ANSI_1251", "СІ \\U+0041"), ("ANSI_932", "表 \\M+1")] { let tags = file(cp, text); - for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] { assert!(contains(&bytes, b"\\U+005C"), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); } @@ -132,7 +132,7 @@ fn a_trail_byte_backslash_never_starts_an_escape() { ]; for (cp, text, written, never) in cases { let tags = file(cp, text); - for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] { assert!(contains(&bytes, written), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); assert!(!contains(&bytes, never), "{cp} {what}: a trail byte starts an escape"); assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); diff --git a/crates/dxf/tests/it/conformance.rs b/crates/dxf/tests/it/conformance.rs index 2c09e28e81..8112a30758 100644 --- a/crates/dxf/tests/it/conformance.rs +++ b/crates/dxf/tests/it/conformance.rs @@ -42,7 +42,7 @@ fn writes_independently_specified_ascii_and_binary_bytes() { for utf8 in [false, true] { let tags = std::slice::from_ref(&tag); assert_eq!(write_ascii_as(tags, utf8).as_bytes(), ascii, "ASCII code {}", tag.code); - assert_eq!(write_binary(tags, utf8), [SENTINEL, binary].concat(), "binary code {}", tag.code); + assert_eq!(write_binary(tags, utf8).unwrap(), [SENTINEL, binary].concat(), "binary code {}", tag.code); } } } @@ -66,7 +66,7 @@ fn integer_code_ranges_have_independent_binary_widths() { let expected = [SENTINEL, &code_bytes, &value_bytes[..width]].concat(); let tags = [Tag::i(code, value)]; for utf8 in [false, true] { - assert_eq!(write_binary(&tags, utf8), expected, "code={code} value={value} utf8={utf8}"); + assert_eq!(write_binary(&tags, utf8).unwrap(), expected, "code={code} value={value} utf8={utf8}"); } assert_eq!(parse(&expected).unwrap(), tags, "code={code} value={value}"); } @@ -83,7 +83,7 @@ fn text_encoding_has_independent_wire_expectations() { let ascii = [b" 1\r\n".as_slice(), text, b"\r\n"].concat(); let binary = [SENTINEL, b"\x01\0", text, b"\0"].concat(); assert_eq!(write_ascii_as(&tags, unicode).as_bytes(), ascii, "utf8={unicode}"); - assert_eq!(write_binary(&tags, unicode), binary, "utf8={unicode}"); + assert_eq!(write_binary(&tags, unicode).unwrap(), binary, "utf8={unicode}"); assert_eq!(parse(&ascii).unwrap(), tags); assert_eq!(parse(&binary).unwrap(), tags); } diff --git a/crates/dxf/tests/it/hardening.rs b/crates/dxf/tests/it/hardening.rs index 4d013f1f4f..c35067540a 100644 --- a/crates/dxf/tests/it/hardening.rs +++ b/crates/dxf/tests/it/hardening.rs @@ -13,17 +13,36 @@ fn bin_with(f: impl FnOnce(&mut Vec)) -> Vec { } #[test] -fn binary_reals_that_are_not_finite_become_zero() { +fn binary_reals_that_are_not_finite_become_invalid() { for bits in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { let b = bin_with(|b| { b.extend_from_slice(&10i16.to_le_bytes()); b.extend_from_slice(&bits.to_le_bytes()); }); let tags = parse(&b).unwrap(); - assert_eq!(tags[0], Tag::f(10, 0.0), "{bits}"); + assert_eq!(tags[0], Tag::invalid(10, bits.to_string()), "{bits}"); + assert_eq!(tags[0].f64(), 0.0, "backward compatibility for f64: {bits}"); + assert_eq!(tags[0].i64(), 0, "backward compatibility for i64: {bits}"); + assert!(tags[0].is_invalid()); } } +#[test] +fn malformed_path_coordinates_are_invalid_and_do_not_silently_snap_to_origin() { + // Malformed line entity coordinates (groups 10, 20, 11, 21) + let dxf = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n10\n100.0\n20\nNaN\n11\ncorrupted\n21\n200.0\n0\nENDSEC\n0\nEOF\n"; + let tags = parse(dxf).unwrap(); + let y0 = tags.iter().find(|t| t.code == 20).unwrap(); + let x1 = tags.iter().find(|t| t.code == 11).unwrap(); + assert_eq!(y0.value, Value::Invalid("NaN".into())); + assert_eq!(x1.value, Value::Invalid("corrupted".into())); + assert!(y0.is_invalid()); + assert!(x1.is_invalid()); + // Legacy callers still get 0.0 + assert_eq!(y0.f64(), 0.0); + assert_eq!(x1.f64(), 0.0); +} + #[test] fn ascii_accepts_bom_and_cr_only_line_ends() { let want = vec![Tag::s(0, "SECTION"), Tag::s(2, "ENTITIES"), Tag::s(0, "ENDSEC"), Tag::s(0, "EOF")]; @@ -107,19 +126,68 @@ fn trailing_spaces_keep_sections_and_eof() { #[test] fn integer_groups_reject_non_finite_and_clamp() { let t = parse(b"70\ninf\n70\nNaN\n70\n1e30\n70\n-1e30\n90\n1e30\n160\n1e30\n160\n-inf\n62\n12.0\n0\nEOF\n").unwrap(); - assert_eq!(t[0], Tag::i(70, 0)); - assert_eq!(t[1], Tag::i(70, 0)); + assert_eq!(t[0], Tag::invalid(70, "inf")); + assert_eq!(t[0].i64(), 0); + assert_eq!(t[1], Tag::invalid(70, "NaN")); + assert_eq!(t[1].i64(), 0); // Clamped to what the group's width holds, unsigned values included (the binary writer // keeps up to 65535 and 4294967295 as their bit patterns). assert_eq!(t[2], Tag::i(70, i64::from(u16::MAX))); assert_eq!(t[3], Tag::i(70, i64::from(i16::MIN))); assert_eq!(t[4], Tag::i(90, i64::from(u32::MAX))); assert_eq!(t[5], Tag::i(160, i64::MAX)); - assert_eq!(t[6], Tag::i(160, 0)); + assert_eq!(t[6], Tag::invalid(160, "-inf")); + assert_eq!(t[6].i64(), 0); assert_eq!(t[7], Tag::i(62, 12)); assert_eq!(Value::Str("inf".into()).as_i64(), 0); } +#[test] +fn tag_f_non_finite_creates_invalid() { + let nan_tag = Tag::f(10, f64::NAN); + assert!(nan_tag.is_invalid()); + assert_eq!(nan_tag.f64(), 0.0); + assert_eq!(nan_tag.checked_f64(), None); + assert_eq!(nan_tag.checked_i64(), None); + assert_eq!(nan_tag.invalid_str(), Some("NaN")); + + let inf_tag = Tag::f(20, f64::INFINITY); + assert!(inf_tag.is_invalid()); + assert_eq!(inf_tag.f64(), 0.0); + assert_eq!(inf_tag.checked_f64(), None); + assert_eq!(inf_tag.checked_i64(), None); + assert_eq!(inf_tag.invalid_str(), Some("inf")); +} + +#[test] +fn invalid_numbers_with_dxf_escapes_roundtrip_through_ascii_write_and_parse() { + let tags = + vec![Tag::invalid(10, "12.34\\U+0020xyz"), Tag::invalid(20, "bad\\U+005Cpath"), Tag::invalid(70, "corrupted\\U+0041"), Tag::s(0, "EOF")]; + let ascii_out = write_ascii(&tags); + let back = parse(ascii_out.as_bytes()).unwrap(); + assert_eq!(back[0], Tag::invalid(10, "12.34\\U+0020xyz")); + assert_eq!(back[1], Tag::invalid(20, "bad\\U+005Cpath")); + assert_eq!(back[2], Tag::invalid(70, "corrupted\\U+0041")); +} + +#[test] +fn binary_integer_writer_reports_error_unless_lossy_normalized() { + let invalid_int_tag = Tag::invalid(70, "corrupted"); + assert!(invalid_int_tag.is_invalid()); + assert_eq!(invalid_int_tag.checked_i64(), None); + assert_eq!(invalid_int_tag.i64(), 0); + + // Binary DXF integer groups have no NaN marker, so write_binary reports conversion error + let res = write_binary(&[invalid_int_tag.clone(), Tag::s(0, "EOF")], true); + assert!(matches!(res, Err(craft_dxf::DxfError::InvalidInteger { code: 70, .. }))); + + // Explicit write_binary_lossy normalizes invalid integer to 0 + let lossy_bin = craft_dxf::write_binary_lossy(&[invalid_int_tag, Tag::s(0, "EOF")], true); + let back = parse(&lossy_bin).unwrap(); + assert_eq!(back[0], Tag::i(70, 0)); + assert_eq!(back[0].checked_i64(), Some(0)); +} + /// An unsigned value spelled as a float reads as the same spelled as an integer (#1026 review): /// `65535.0` is 65535 like `65535`, not 32767. #[test] @@ -139,7 +207,7 @@ fn hex_groups_pad_odd_digits_and_drop_junk() { assert_eq!(t[2].value, Value::Hex(String::new())); assert_eq!(t[3].value, Value::Hex("0aF0".into())); // The binary writer agrees with the reader: the odd digit is padded, nothing shifts. - let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true)).unwrap(); + let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true).unwrap()).unwrap(); assert_eq!(back[0].value, Value::Hex("ABC0".into())); } @@ -171,7 +239,7 @@ fn binary_sixteen_and_thirty_two_bit_values_wrap_in_range_and_clamp_outside() { Tag::i(90, -(1 << 40)), Tag::s(0, "EOF"), ]; - let back = parse(&write_binary(&tags, true)).unwrap(); + let back = parse(&write_binary(&tags, true).unwrap()).unwrap(); assert_eq!(back[0], Tag::i(70, -1)); assert_eq!(back[1], Tag::i(70, 40000 - 65536)); assert_eq!(back[2], Tag::i(70, i64::from(i16::MAX))); diff --git a/crates/dxf/tests/it/hex_chunks.rs b/crates/dxf/tests/it/hex_chunks.rs index 80e9e91933..e9f34fa0c4 100644 --- a/crates/dxf/tests/it/hex_chunks.rs +++ b/crates/dxf/tests/it/hex_chunks.rs @@ -52,7 +52,7 @@ fn check_ascii(code: i32, bytes: &[u8], utf8: bool) { } fn check_binary(code: i32, bytes: &[u8], utf8: bool) { - let wire = write_binary(&input(code, bytes), utf8); + let wire = write_binary(&input(code, bytes), utf8).unwrap(); let mut chunks = wire.strip_prefix(SENTINEL).unwrap().strip_suffix(FOLLOWING_BINARY).unwrap(); assert!(!chunks.is_empty(), "an empty payload must still have a tag"); let context = format!("binary code={code} bytes={} utf8={utf8}", bytes.len()); diff --git a/crates/dxf/tests/it/recovering.rs b/crates/dxf/tests/it/recovering.rs index 1dffd87f39..8df6a5231e 100644 --- a/crates/dxf/tests/it/recovering.rs +++ b/crates/dxf/tests/it/recovering.rs @@ -10,7 +10,7 @@ fn an_intact_file_reads_as_parse_reads_it() { assert_eq!(damaged, None); assert_eq!(tags, parse(WHOLE.as_bytes()).expect("reads")); // Binary files are read as before. - let binary = write_binary(&tags, true); + let binary = write_binary(&tags, true).unwrap(); assert_eq!(parse_recovering(&binary).expect("reads"), (tags, None)); } diff --git a/crates/dxf/tests/it/roundtrip.rs b/crates/dxf/tests/it/roundtrip.rs index d4b5883c00..2dc48bf274 100644 --- a/crates/dxf/tests/it/roundtrip.rs +++ b/crates/dxf/tests/it/roundtrip.rs @@ -23,7 +23,8 @@ fn check(case: &str, body: &[Tag]) { let mut current = original.clone(); for pass in 1..=2 { let context = format!("{case} · {version} · binary={binary} · pass={pass}"); - let bytes = if binary { write_binary(¤t, version.utf8()) } else { write_ascii_as(¤t, version.utf8()).into_bytes() }; + let bytes = + if binary { write_binary(¤t, version.utf8()).unwrap() } else { write_ascii_as(¤t, version.utf8()).into_bytes() }; assert_eq!(is_binary(&bytes), binary, "{context}"); let back = parse(&bytes).unwrap_or_else(|e| panic!("{context}: {e}")); assert_eq!(back.len(), original.len(), "{context}: tag count"); diff --git a/crates/ease/Cargo.toml b/crates/ease/Cargo.toml new file mode 100644 index 0000000000..c14b54f0d2 --- /dev/null +++ b/crates/ease/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "craft-ease" +description = "Easing curves, keyed tracks, motion paths and springs for animation: named eases, cubic Bezier and speed/influence eases, editable custom curves, sampled tables, hold keys, constant-speed Bezier paths and an O(1) damped spring" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = ["serde"] +# Reading and writing eases (spring eases included) and tracks with serde. +serde = ["dep:serde"] + +[dependencies] +serde = { workspace = true, features = ["rc"], optional = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/ease/README.md b/crates/ease/README.md new file mode 100644 index 0000000000..fc5612f6cc --- /dev/null +++ b/crates/ease/README.md @@ -0,0 +1,102 @@ +# craft-ease + +Easing curves, keyed tracks, constant-speed motion paths and damped springs for animation in the +Craft apps. The crate depends only on the standard library, with `serde` as an optional feature +(on by default). It builds for `wasm32-unknown-unknown`. + +Its parts come from AniCraft and EffectCraft: + +- `Easing`, `CustomEase`, `SampledEase` and the curve editing came from AniCraft's `anicraft-doc` + (`crates/doc/src/easing.rs`). They now use `f64` and the crate's own `Vec2`, the Back and + Elastic In Out curves follow the published equations, and `Hold` and `Spring` are new + variants. +- Speed and influence eases, hold keys and the constant-speed motion paths came from + EffectCraft's `effectcraft-keyframe` (`crates/keyframe/src/lib.rs`). `Track` takes any + `Animatable` value instead of the app's value type, and `MotionPath` continues in a straight + line past either end. +- `Spring` replaces AniCraft's stepped spring (`crates/doc/src/spring.rs`) with the exact + solution of the damped spring equation, so a step costs O(1) and any step length is stable. + +Licensed under MIT OR Apache-2.0. + +## Contents + +- `Easing` maps linear progress `t` in `0..=1` to eased progress. The variants are no ease + (`Linear`), `Hold`, the Classic slider (−100 to +100), nine named families (Quad, Cubic, Quart, + Quint, Sine, Back, Circ, Bounce, Elastic) each In, Out and In Out, `CubicBezier` as the CSS + Easing Functions specification defines `cubic-bezier()`, an editable `CustomEase`, a + `SampledEase` table and a physical `SpringEase`. `Easing::apply(t)` returns exactly 0 for + `t <= 0` and NaN, and exactly 1 for `t >= 1`. It does not allocate. +- `Easing::from_temporal` builds the cubic Bezier for a segment from the speed and influence of + its two sides (`TemporalEase`), as keyframe velocity dialogs give them. `Easing::temporal` + reads them back. +- `Track` holds keys of any `Animatable` value (`f32`, `f64`, `Vec2`, `[f32; N]`, + `[f64; N]`), each with the ease to the next key. `Track::sample` is a binary search and does + not allocate. +- `MotionPath` is a chain of cubic Bezier segments with an arc-length table per segment, built + once. `point_at` and `point_at_length` move at constant speed along it and continue in a + straight line past either end. `MotionPath::through` sets the handles of a smooth path through + a list of anchors. +- `Spring` and `SpringState` move a value toward a target. `SpringState::step` applies the exact + solution of the damped spring equation over the step, so a step costs O(1), any step length is + stable, and many short steps give the same value as one long one. + +## Checked and lenient constructors + +Every type has a checked constructor that returns `EaseError` for a value that is not finite or +is out of range: `Easing::cubic_bezier`, `Easing::from_temporal`, `Easing::spring`, +`CustomEase::try_new`, `SampledEase::try_new`, `Track::from_keys`, `MotionPath::new`, +`Spring::new` and `Spring::from_physical`. `CustomEase::new` and `SampledEase::new` repair what +they are given instead, and files are read through the same repairs. Reading a track refuses a +file with more than `MAX_TRACK_KEYS` keys while it reads. + +## Limits + +| Constant | Value | +| --- | --- | +| `MAX_EASE_Y` | 10 (eased values stay within ±10) | +| `MAX_EASE_POINTS` | 64 points in a custom ease | +| `MAX_EASE_SAMPLES` | 1,025 samples in a sampled ease | +| `MAX_TRACK_KEYS` | 100,000 keys in a track | +| `MAX_PATH_SEGMENTS` | 10,000 segments in a motion path | +| `MAX_SPRING_HZ` | 10,000 swings a second | +| `MAX_DAMPING_RATIO` | 1,000,000 | +| `MIN_INFLUENCE` | 0.001 | + +## Sources + +- The named families are the easing equations published by Robert Penner. Back In Out and + Elastic In Out use the published In Out equations, which scale Back's overshoot by 1.525 and + give Elastic a longer period. +- `CubicBezier` follows the CSS Easing Functions Level 1 specification. + +## Details + +- Values are `f64` throughout. +- The `serde` feature reads and writes `Easing` (spring eases included) and `Track`. + `MotionPath`, `Spring` and `SpringState` are not serialized. +- Serialized eases keep their form: presets are strings such as `"QuadIn"`, and `Classic`, + `CubicBezier`, `Custom` and `Sampled` are one-key objects. `Hold` and `Spring` are the last + variants. A track is read from its fields by name or in order. +- `Easing::apply` returns exactly 0 and 1 at the ends for every variant, and `+∞` gives 1. +- `CubicBezier` keeps y1 and y2 within ±10 when it is evaluated. Its solver inverts the curve + with both handles at full reach in closed form, and otherwise stops within 1e-12 of the span + in at most 64 steps. +- A sampled ease's name drops control characters, bidirectional overrides and invisible format + characters such as zero-width spaces. A sampled ease with no name left is named "Sampled ease". + Reading a file keeps the first 65,536 entries of a custom ease's points or a sampled ease's + values and skips the rest. +- Without the `serde` feature the crate has no dependencies, and its tests that read and write + files are left out. +- `Track` takes `Easing::Hold` for held keys and treats −0 and +0 as one time. It samples keys + at opposite ends of the `f64` range without overflow, and returns `EaseError::Overflow` when + an overshooting ease carries a value past what its type holds. +- Speed and influence become a `CubicBezier` (`Easing::from_temporal`), with the influence + allowed from 0.001 to 1 on each side, including a sum above 1. +- Motion paths are measured by Gauss-Legendre quadrature per table cell with Newton refinement. + `MotionPath::through` sets each handle to a sixth of the line between the anchor's neighbors. + A segment whose handles lie on its chord is treated as a straight line. +- `Spring::from_physical(mass, stiffness, damping)` takes a mass, a stiffness and a damping + coefficient. A spring ease that is still moving after 10 seconds has the distance it is still + off taken out evenly over the ease, so it reaches 1 without a jump. Any other spring ease is + within about 0.1 % of 1 just before it reaches 1. diff --git a/crates/ease/src/custom.rs b/crates/ease/src/custom.rs new file mode 100644 index 0000000000..af4e4cd57d --- /dev/null +++ b/crates/ease/src/custom.rs @@ -0,0 +1,450 @@ +//! [`CustomEase`]: an editable curve of several Bezier segments from (0, 0) to (1, 1). + +use crate::{EaseError, Vec2, bez, solve_monotonic}; + +/// Most points (anchors) a custom ease keeps; longer curves are thinned evenly. +pub const MAX_EASE_POINTS: usize = 64; +/// Values a custom ease (and its handles) may reach: overshoot well past 0..1, never unbounded. +pub const MAX_EASE_Y: f64 = 10.0; +/// Most points read from a file or a caller before thinning (bounds the sort). +const MAX_EASE_INPUT: usize = 65_536; + +/// A point of a custom ease: where it is (x = time, y = progress), its handles as offsets from +/// it (in toward the previous point, out toward the next), and whether it is smooth (handles in +/// line, moved together) or a corner. In files the in handle is `"in"`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct EasePoint { + pub at: Vec2, + #[cfg_attr(feature = "serde", serde(rename = "in", default))] + pub h_in: Vec2, + #[cfg_attr(feature = "serde", serde(default))] + pub out: Vec2, + #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))] + pub smooth: bool, +} + +#[cfg(feature = "serde")] +fn is_false(b: &bool) -> bool { + !*b +} + +/// Which handle of a point. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Handle { + In, + Out, +} + +/// A custom ease: Bezier segments through its points, from (0, 0) to (1, 1). +/// +/// Always valid, however it was made: 2 to [`MAX_EASE_POINTS`] finite points sorted by x, the +/// ends fixed at (0, 0) and (1, 1), every handle reaching toward its neighbor in x and every +/// segment's x running forwards (so time never runs backwards), and every value within +/// ±[`MAX_EASE_Y`]. A handle whose x lies between its point and that neighbor always keeps x +/// running forwards; a handle may reach past the neighbor (as a piece of a split segment can) +/// only while its segment's x still runs forwards. Reading a file repairs a curve the way +/// [`CustomEase::new`] does. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(from = "CustomEaseFile"))] +pub struct CustomEase { + points: Vec, +} + +#[cfg(feature = "serde")] +#[derive(serde::Deserialize)] +struct CustomEaseFile { + #[serde(default, deserialize_with = "read_points")] + points: Vec, +} + +/// The first [`MAX_EASE_INPUT`] points of a file's list, the way [`CustomEase::new`] keeps them. +#[cfg(feature = "serde")] +fn read_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + crate::read_first(d, MAX_EASE_INPUT) +} + +#[cfg(feature = "serde")] +impl From for CustomEase { + fn from(f: CustomEaseFile) -> CustomEase { + CustomEase::new(f.points) + } +} + +impl Default for CustomEase { + fn default() -> CustomEase { + CustomEase::linear() + } +} + +impl CustomEase { + /// The straight line, its handles a third of the way along. + pub fn linear() -> CustomEase { + CustomEase::linear_points() + } + + /// One segment with handles `(x1, y1)` and `(x2, y2)` in the unit box (x is clamped to + /// `0..=1`). + pub fn from_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> CustomEase { + let (x1, x2) = (x1.clamp(0.0, 1.0), x2.clamp(0.0, 1.0)); + CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(x1, y1), smooth: false }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(x2 - 1.0, y2 - 1.0), out: Vec2::ZERO, smooth: false }, + ]) + } + + /// The curve of absolute points `[p0, c1, c2, p1, c3, c4, p2, …]` (3n + 1 of them): `None` + /// when the count is wrong. + pub fn from_flat(pts: &[Vec2]) -> Option { + if pts.len() < 4 || pts.len() % 3 != 1 || pts.len() > MAX_EASE_INPUT { + return None; + } + let mut out: Vec = Vec::with_capacity(pts.len() / 3 + 1); + for (i, at) in pts.iter().enumerate().step_by(3) { + let h_in = if i == 0 { Vec2::ZERO } else { pts.get(i - 1).map_or(Vec2::ZERO, |c| *c - *at) }; + let h_out = pts.get(i + 1).map_or(Vec2::ZERO, |c| *c - *at); + // Handles in line (opposite ways) make a smooth point, as an editor would draw it. + let smooth = h_in.length() > 1e-6 && h_out.length() > 1e-6 && (h_in.normalized().dot(h_out.normalized()) + 1.0).abs() < 1e-3; + out.push(EasePoint { at: *at, h_in, out: h_out, smooth }); + } + Some(CustomEase::new(out)) + } + + /// A curve from points a caller supplies, checked: an error for a point or handle that is + /// not finite, fewer than 2 points or more than [`MAX_EASE_POINTS`]. The points are then + /// sorted, the ends pinned and the handles brought within reach as [`CustomEase::new`] does. + pub fn try_new(pts: Vec) -> Result { + if pts.iter().any(|p| !(p.at.is_finite() && p.h_in.is_finite() && p.out.is_finite())) { + return Err(EaseError::NotFinite("ease point")); + } + if pts.len() < 2 { + return Err(EaseError::TooFew { what: "a custom ease", need: 2 }); + } + if pts.len() > MAX_EASE_POINTS { + return Err(EaseError::Full(MAX_EASE_POINTS)); + } + Ok(CustomEase::new(pts)) + } + + /// A valid curve from any points, as a file holds them (see the type's docs): non-finite + /// points are dropped and non-finite handles zeroed, the rest sorted by x, a curve longer + /// than [`MAX_EASE_POINTS`] thinned evenly, the ends pinned and every handle brought within + /// reach. Fewer than two points make the straight line. + pub fn new(mut pts: Vec) -> CustomEase { + pts.truncate(MAX_EASE_INPUT); + pts.retain(|p| p.at.is_finite()); + for p in pts.iter_mut() { + p.at = Vec2::new(p.at.x.clamp(0.0, 1.0), p.at.y.clamp(-MAX_EASE_Y, MAX_EASE_Y)); + if !p.h_in.is_finite() { + p.h_in = Vec2::ZERO; + } + if !p.out.is_finite() { + p.out = Vec2::ZERO; + } + } + pts.sort_by(|a, b| a.at.x.total_cmp(&b.at.x)); + if pts.len() > MAX_EASE_POINTS { + let n = pts.len(); + let keep: Vec = (0..MAX_EASE_POINTS).map(|k| k * (n - 1) / (MAX_EASE_POINTS - 1)).collect(); + pts = keep.into_iter().filter_map(|i| pts.get(i).copied()).collect(); + } + if pts.len() < 2 { + return CustomEase::linear_points(); + } + if let Some(p) = pts.first_mut() { + p.at = Vec2::ZERO; + } + if let Some(p) = pts.last_mut() { + p.at = Vec2::new(1.0, 1.0); + } + let mut c = CustomEase { points: pts }; + // A point marked smooth whose handles are not in line is a corner: it loses the mark + // before the handles are brought within reach, so they are clipped as a corner's, and + // again if bringing them within reach put them out of line. + c.clear_broken_smooth(); + c.clamp_handles(); + c.clear_broken_smooth(); + c + } + + /// Clears the smooth mark of every end and of every point whose handles are not in line. + fn clear_broken_smooth(&mut self) { + let n = self.points.len(); + for (i, p) in self.points.iter_mut().enumerate() { + if p.smooth && (i == 0 || i + 1 == n || !handles_in_line(p.h_in, p.out)) { + p.smooth = false; + } + } + } + + /// [`CustomEase::linear`] built directly (so [`CustomEase::new`] does not recurse). + fn linear_points() -> CustomEase { + let third = 1.0 / 3.0; + CustomEase { + points: vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(third, third), smooth: false }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-third, -third), out: Vec2::ZERO, smooth: false }, + ], + } + } + + /// Brings every handle within reach (see the type's docs): each handle toward its neighbor + /// in x and within ±[`MAX_EASE_Y`], then, in a segment whose x would run backwards, each + /// handle that reaches past the neighbor back to it. A smooth point's handles are shortened + /// along their own line, so they stay in line; a corner's are clipped. + fn clamp_handles(&mut self) { + let n = self.points.len(); + for (i, p) in self.points.iter_mut().enumerate() { + let (lo, hi) = (-MAX_EASE_Y - p.at.y, MAX_EASE_Y - p.at.y); + p.h_in = if i == 0 { Vec2::ZERO } else { fit_y(Vec2::new(p.h_in.x.min(0.0), p.h_in.y), lo, hi, p.smooth) }; + p.out = if i + 1 == n { Vec2::ZERO } else { fit_y(Vec2::new(p.out.x.max(0.0), p.out.y), lo, hi, p.smooth) }; + } + for i in 1..n { + let (Some(a), Some(b)) = (self.points.get(i - 1).copied(), self.points.get(i).copied()) else { continue }; + let span = b.at.x - a.at.x; + if runs_forwards(span, a.out.x, -b.h_in.x) { + continue; + } + if let Some(p) = self.points.get_mut(i - 1) { + p.out = fit_x(p.out, span, p.smooth); + } + if let Some(p) = self.points.get_mut(i) { + p.h_in = fit_x(p.h_in, span, p.smooth); + } + } + } + + pub fn points(&self) -> &[EasePoint] { + &self.points + } + + /// The control points of segment `i` (from point `i` to point `i + 1`), absolute; x runs + /// forwards along it (see the type's docs). + pub fn segment(&self, i: usize) -> Option<[Vec2; 4]> { + let (a, b) = (self.points.get(i)?, self.points.get(i.checked_add(1)?)?); + Some([a.at, a.at + a.out, b.at + b.h_in, b.at]) + } + + /// The segment that time `t` falls in. + fn segment_at(&self, t: f64) -> usize { + self.points.partition_point(|p| p.at.x <= t).saturating_sub(1).min(self.points.len().saturating_sub(2)) + } + + /// The eased value at time `t` (0 at the start, 1 at the end, anything between, overshoot + /// included). `t` outside `0..=1` is clamped, and NaN reads as 0. + pub fn apply(&self, t: f64) -> f64 { + if t.is_nan() || t <= 0.0 { + return 0.0; + } + if t >= 1.0 { + return 1.0; + } + let Some([p0, p1, p2, p3]) = self.segment(self.segment_at(t)) else { return t }; + if p3.x <= p0.x { + return p3.y; + } + let s = solve_monotonic(t, [p0.x, p1.x, p2.x, p3.x]); + bez(s, [p0.y, p1.y, p2.y, p3.y]) + } + + /// Adds a point on the curve at time `t`, leaving its shape as it was (the segment is split + /// in two): the new curve and the point's index. `None` at the ends, on an existing point, + /// where the split cannot be placed at `t` (on a curve so flat there that its time cannot be + /// solved closely enough), or when the curve is full. + pub fn insert_at(&self, t: f64) -> Option<(CustomEase, usize)> { + if !(t > 0.0 && t < 1.0) || self.points.len() >= MAX_EASE_POINTS || self.points.iter().any(|p| p.at.x == t) { + return None; + } + let i = self.segment_at(t); + let [p0, p1, p2, p3] = self.segment(i)?; + let s = solve_monotonic(t, [p0.x, p1.x, p2.x, p3.x]); + // de Casteljau at s. + let (a, b, c) = (p0.lerp(p1, s), p1.lerp(p2, s), p2.lerp(p3, s)); + let (d, e) = (a.lerp(b, s), b.lerp(c, s)); + let m = d.lerp(e, s); + // Refused when the split cannot be placed at `t`: it lands on an anchor, or farther from + // `t` than a millionth of the way to the nearer anchor. + if !(m.x > p0.x && m.x < p3.x && (m.x - t).abs() <= 1e-6 * (t - p0.x).min(p3.x - t)) { + return None; + } + let mut pts = self.points.clone(); + if let Some(q) = pts.get_mut(i) { + q.out = a - p0; + } + if let Some(q) = pts.get_mut(i + 1) { + q.h_in = c - p3; + } + pts.insert(i + 1, EasePoint { at: m, h_in: d - m, out: e - m, smooth: true }); + Some((CustomEase::new(pts), i + 1)) + } + + /// Moves point `i` (not an end) to `to`, its handles with it; its x stays between its + /// neighbors' so time keeps running forwards. `None` for an end, a missing point or a + /// non-finite `to`. + pub fn move_point(&self, i: usize, to: Vec2) -> Option { + if i == 0 || i >= self.points.len().saturating_sub(1) || !to.is_finite() { + return None; + } + let (lo, hi) = (self.points.get(i - 1)?.at.x, self.points.get(i + 1)?.at.x); + let mut c = self.clone(); + let p = c.points.get_mut(i)?; + p.at = Vec2::new(to.x.clamp(lo, hi), to.y.clamp(-MAX_EASE_Y, MAX_EASE_Y)); + c.clamp_handles(); + Some(c) + } + + /// Moves handle `which` of point `i` to `to` (absolute); a smooth point's other handle turns + /// to stay in line, keeping its length. `None` for a handle the point does not have (the + /// first point's in, the last's out) or a non-finite `to`. + pub fn move_handle(&self, i: usize, which: Handle, to: Vec2) -> Option { + let n = self.points.len(); + if !to.is_finite() || i >= n || (which == Handle::In && i == 0) || (which == Handle::Out && i + 1 == n) { + return None; + } + let mut c = self.clone(); + let p = c.points.get_mut(i)?; + let off = to - p.at; + match which { + Handle::In => p.h_in = off, + Handle::Out => p.out = off, + } + c.clamp_handles(); + if i > 0 && i + 1 < n { + let (prev, next) = (c.points.get(i - 1)?.at.x, c.points.get(i + 1)?.at.x); + if let Some(p) = c.points.get_mut(i).filter(|p| p.smooth) { + let at = p.at; + let (moved, other, x_reach) = match which { + Handle::In => (p.h_in, &mut p.out, next - at.x), + Handle::Out => (p.out, &mut p.h_in, prev - at.x), + }; + let dir = -moved.normalized(); + if dir != Vec2::ZERO { + // Shortened to stay within reach along `dir`, so the clamp below does not + // turn it out of line. + // A handle with no length is given one, so the point stays smooth. + let mut len = other.length(); + if len <= 0.0 { + len = 1e-3; + } + if dir.x != 0.0 { + len = len.min((x_reach / dir.x).max(0.0)); + } + if dir.y != 0.0 { + let y_reach = if dir.y > 0.0 { MAX_EASE_Y - at.y } else { -MAX_EASE_Y - at.y }; + len = len.min((y_reach / dir.y).max(0.0)); + } + *other = dir * len; + } + } + } + c.clamp_handles(); + Some(c) + } + + /// Removes point `i` (not an end). `None` for an end or a missing point. + pub fn remove(&self, i: usize) -> Option { + if i == 0 || i >= self.points.len().saturating_sub(1) { + return None; + } + let mut pts = self.points.clone(); + pts.remove(i); + Some(CustomEase::new(pts)) + } + + /// Makes point `i` smooth (its handles in line with its neighbors' chord, a third of the way + /// to each) or a corner (its handles on the point, so the curve turns sharply there). + pub fn set_smooth(&self, i: usize, smooth: bool) -> Option { + let n = self.points.len(); + let prev = if i == 0 { None } else { self.points.get(i - 1).map(|p| p.at) }; + let next = i.checked_add(1).and_then(|j| self.points.get(j)).map(|p| p.at); + let mut c = self.clone(); + let p = c.points.get_mut(i)?; + p.smooth = smooth && i > 0 && i + 1 < n; + if smooth { + let (a, b) = (prev.unwrap_or(p.at), next.unwrap_or(p.at)); + let chord = b - a; + let dir = if chord.x > 1e-6 { chord * (1.0 / chord.x) } else { Vec2::new(1.0, 0.0) }; + if prev.is_some() { + p.h_in = -dir * ((p.at.x - a.x) / 3.0); + } + if next.is_some() { + p.out = dir * ((b.x - p.at.x) / 3.0); + } + } else { + p.h_in = Vec2::ZERO; + p.out = Vec2::ZERO; + } + c.clamp_handles(); + Some(c) + } + + /// The flat list of absolute points `[p0, c1, c2, p1, …]` (see [`CustomEase::from_flat`]). + pub fn to_flat(&self) -> Vec { + let mut out = Vec::with_capacity(self.points.len() * 3); + for (i, p) in self.points.iter().enumerate() { + if i > 0 { + out.push(p.at + p.h_in); + } + out.push(p.at); + if i + 1 < self.points.len() { + out.push(p.at + p.out); + } + } + out + } +} + +/// Whether a segment `span` wide in x whose out handle reaches `a` forwards and whose in handle +/// reaches `c` backwards (both at least 0) runs forwards in x. Its x′ is the quadratic with +/// Bernstein coefficients `a`, `span − a − c` and `c`, which is never negative when the middle +/// one is at least −√(ac); that always holds while neither handle reaches past the other end, +/// and never holds when one reaches past 4/3 of the span. The test is made on reaches divided by +/// the span, so squaring them does not underflow on a very narrow segment. +fn runs_forwards(span: f64, a: f64, c: f64) -> bool { + if a <= span && c <= span { + return true; + } + if a > 2.0 * span || c > 2.0 * span { + return false; + } + // Here span > 0: a handle reaches past it, and no more than twice it. + let (a, c) = (a / span, c / span); + let b = 1.0 - a - c; + b >= 0.0 || b * b <= a * c * (1.0 + 1e-12) +} + +/// Whether handles `a` and `b` point opposite ways along one line (as a smooth point's do), or +/// one of them has no length. +fn handles_in_line(a: Vec2, b: Vec2) -> bool { + a.length() <= 1e-9 || b.length() <= 1e-9 || (a.normalized().dot(b.normalized()) + 1.0).abs() < 1e-3 +} + +/// Handle `h` (an offset) with its y within `lo..=hi`: a smooth point's shortened along its line, +/// a corner's clipped. +fn fit_y(h: Vec2, lo: f64, hi: f64, smooth: bool) -> Vec2 { + let k = if h.y > hi { + hi / h.y + } else if h.y < lo { + lo / h.y + } else { + return h; + }; + if smooth { Vec2::new(h.x * k, (h.y * k).clamp(lo, hi)) } else { Vec2::new(h.x, h.y.clamp(lo, hi)) } +} + +/// Handle `h` (an offset) reaching at most `span` in x: a smooth point's shortened along its line, +/// a corner's clipped. +fn fit_x(h: Vec2, span: f64, smooth: bool) -> Vec2 { + let reach = h.x.abs(); + if reach <= span { + return h; + } + let span = span.max(0.0); + if smooth { + let k = span / reach; + Vec2::new((h.x * k).clamp(-span, span), h.y * k) + } else { + Vec2::new(span.copysign(h.x), h.y) + } +} diff --git a/crates/ease/src/easing.rs b/crates/ease/src/easing.rs new file mode 100644 index 0000000000..807fcd4590 --- /dev/null +++ b/crates/ease/src/easing.rs @@ -0,0 +1,655 @@ +//! [`Easing`]: maps linear progress to eased progress. + +use std::sync::Arc; + +use crate::custom::{CustomEase, EasePoint, MAX_EASE_Y}; +use crate::sampled::SampledEase; +use crate::spring::Spring; +use crate::{EaseError, Vec2, bez, finite, solve_monotonic, within}; + +/// The Back family's overshoot (about 10 %). +const BACK: f64 = 1.701_58; +/// Back In Out's overshoot, as the published equation scales it. +const BACK_IN_OUT: f64 = BACK * 1.525; +/// The smallest influence a [`TemporalEase`] may have. +pub const MIN_INFLUENCE: f64 = 0.001; + +/// The families of named eases. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum EaseFamily { + Quad, + Cubic, + Quart, + Quint, + Sine, + Back, + Circ, + Bounce, + Elastic, +} + +impl EaseFamily { + pub const ALL: [EaseFamily; 9] = [ + EaseFamily::Quad, + EaseFamily::Cubic, + EaseFamily::Quart, + EaseFamily::Quint, + EaseFamily::Sine, + EaseFamily::Back, + EaseFamily::Circ, + EaseFamily::Bounce, + EaseFamily::Elastic, + ]; + + /// The family's English name. + pub fn label(self) -> &'static str { + match self { + EaseFamily::Quad => "Quad", + EaseFamily::Cubic => "Cubic", + EaseFamily::Quart => "Quart", + EaseFamily::Quint => "Quint", + EaseFamily::Sine => "Sine", + EaseFamily::Back => "Back", + EaseFamily::Circ => "Circ", + EaseFamily::Bounce => "Bounce", + EaseFamily::Elastic => "Elastic", + } + } + + /// The ease in, `In(t)`. With `in_out` set, the curve whose halves make In Out: the + /// published In Out equations scale Back's overshoot by 1.525 and give Elastic a longer + /// period (4.5 instead of 3 per unit) and its own phase; the other families use `In(t)`. + fn ease_in(self, t: f64, in_out: bool) -> f64 { + use std::f64::consts::PI; + match self { + EaseFamily::Quad => t * t, + EaseFamily::Cubic => t * t * t, + EaseFamily::Quart => t * t * t * t, + EaseFamily::Quint => t * t * t * t * t, + EaseFamily::Sine => 1.0 - (t * PI * 0.5).cos(), + EaseFamily::Back => { + let c = if in_out { BACK_IN_OUT } else { BACK }; + (c + 1.0) * t * t * t - c * t * t + } + EaseFamily::Circ => 1.0 - (1.0 - t * t).max(0.0).sqrt(), + EaseFamily::Bounce => 1.0 - bounce_out(1.0 - t), + EaseFamily::Elastic => { + if t <= 0.0 { + 0.0 + } else if t >= 1.0 { + 1.0 + } else if in_out { + -(2f64.powf(10.0 * t - 10.0)) * ((10.0 * t - 11.125) * (2.0 * PI / 4.5)).sin() + } else { + -(2f64.powf(10.0 * t - 10.0)) * ((10.0 * t - 10.75) * (2.0 * PI / 3.0)).sin() + } + } + } + } + + /// Where the ease in changes formula (other than 0 and 1): Bounce is four parabolas. + fn breaks_in(self) -> &'static [f64] { + match self { + // 1 − the Out breakpoints (1/2.75, 2/2.75, 2.5/2.75), in order. + EaseFamily::Bounce => &[0.25 / 2.75, 0.75 / 2.75, 1.75 / 2.75], + _ => &[], + } + } + + /// Bezier segments per ease in that draw it to within a hair (see [`Easing::to_custom`]); + /// cubic polynomials (Quad, Cubic, Back) and the parabolas of Bounce are exact with one. + fn pieces_in(self) -> usize { + match self { + EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce | EaseFamily::Circ => 1, + EaseFamily::Quart | EaseFamily::Quint | EaseFamily::Sine => 4, + EaseFamily::Elastic => 24, + } + } +} + +fn bounce_out(t: f64) -> f64 { + const N: f64 = 7.5625; + const D: f64 = 2.75; + if t < 1.0 / D { + N * t * t + } else if t < 2.0 / D { + let u = t - 1.5 / D; + N * u * u + 0.75 + } else if t < 2.5 / D { + let u = t - 2.25 / D; + N * u * u + 0.9375 + } else { + let u = t - 2.625 / D; + N * u * u + 0.984_375 + } +} + +/// Which way a named ease eases. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum EaseDir { + In, + Out, + InOut, +} + +impl EaseDir { + pub const ALL: [EaseDir; 3] = [EaseDir::In, EaseDir::Out, EaseDir::InOut]; + + pub fn label(self) -> &'static str { + match self { + EaseDir::In => "In", + EaseDir::Out => "Out", + EaseDir::InOut => "In Out", + } + } +} + +/// One side of a segment's ease as a keyframe velocity dialog gives it: `speed` normalized +/// (speed × segment duration ÷ value change, so 1 is the straight line's speed) and +/// `influence` the fraction of the segment its handle reaches. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct TemporalEase { + pub speed: f64, + pub influence: f64, +} + +impl TemporalEase { + /// A side that leaves at rest with a third of the segment's influence. + pub const EASY: TemporalEase = TemporalEase { speed: 0.0, influence: 1.0 / 3.0 }; + /// A linear side next to an eased one: the segment's average speed with a sixth of its + /// influence. + pub const LINEAR: TemporalEase = TemporalEase { speed: 1.0, influence: 1.0 / 6.0 }; +} + +/// A damped spring as an ease: a mass on a spring with damping, released from 0 toward 1 and +/// played over the time it takes to stay within 0.1 % of 1 (at most 10 seconds of its motion). +/// Values outside the ranges [`Spring::from_physical`] accepts are brought into them when the +/// ease is evaluated. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct SpringEase { + pub mass: f64, + pub stiffness: f64, + pub damping: f64, +} + +impl SpringEase { + /// A gentle spring with a small overshoot (mass 1, stiffness 100, damping 15). + pub const GENTLE: SpringEase = SpringEase { mass: 1.0, stiffness: 100.0, damping: 15.0 }; + + fn apply(self, t: f64) -> f64 { + Spring::physical_lenient(self.mass, self.stiffness, self.damping).ease(t) + } +} + +/// Maps linear progress `t ∈ [0, 1]` to eased progress. +/// +/// The unit variants are the named presets; their names are the file format and the names +/// commands use. [`Easing::apply`] returns exactly 0 for `t <= 0` (and for NaN) and exactly 1 +/// for `t >= 1`, whatever the variant holds. +#[derive(Clone, Debug, Default, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Easing { + #[default] + Linear, + QuadIn, + QuadOut, + QuadInOut, + CubicIn, + CubicOut, + CubicInOut, + /// The traditional single-slider ease: −100 (ease in) … 0 (linear) … +100 (ease out). + Classic(f64), + /// A cubic Bezier through (0, 0), (x1, y1), (x2, y2), (1, 1), as the CSS Easing Functions + /// specification defines `cubic-bezier()`. Evaluation keeps x1 and x2 within `0..=1` and + /// y1 and y2 within ±[`MAX_EASE_Y`]. + CubicBezier(f64, f64, f64, f64), + QuartIn, + QuartOut, + QuartInOut, + QuintIn, + QuintOut, + QuintInOut, + SineIn, + SineOut, + SineInOut, + BackIn, + BackOut, + BackInOut, + CircIn, + CircOut, + CircInOut, + BounceIn, + BounceOut, + BounceInOut, + ElasticIn, + ElasticOut, + ElasticInOut, + /// A curve of several Bezier segments, shared when copied. + Custom(Arc), + /// A table of values, read between samples by straight lines. + Sampled(Arc), + /// A damped spring. + Spring(SpringEase), + /// Stays at the start until the end, then jumps: 0 for `t < 1`. + Hold, +} + +impl Easing { + pub const LINEAR_LABEL: &'static str = "Linear"; + /// The `smooth` alias's curve. + pub const SMOOTH: Easing = Easing::CubicBezier(0.25, 0.1, 0.25, 1.0); + + /// A cubic Bezier ease, checked: every value finite, `x1` and `x2` within `0..=1` (so time + /// runs forwards), `y1` and `y2` within ±[`MAX_EASE_Y`]. + pub fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> Result { + within(x1, 0.0, 1.0, "x1")?; + within(x2, 0.0, 1.0, "x2")?; + within(y1, -MAX_EASE_Y, MAX_EASE_Y, "y1")?; + within(y2, -MAX_EASE_Y, MAX_EASE_Y, "y2")?; + Ok(Easing::CubicBezier(x1, y1, x2, y2)) + } + + /// The ease of a segment from its two sides: `out` leaving the first key, `into` arriving at + /// the second. Each influence must be within [`MIN_INFLUENCE`] to 1 and each speed finite. + /// The result is the cubic Bezier with handles `(i0, s0 × i0)` and `(1 − i1, 1 − s1 × i1)`. + pub fn from_temporal(out: TemporalEase, into: TemporalEase) -> Result { + finite(out.speed, "out speed")?; + finite(into.speed, "in speed")?; + let i0 = within(out.influence, MIN_INFLUENCE, 1.0, "out influence")?; + let i1 = within(into.influence, MIN_INFLUENCE, 1.0, "in influence")?; + let (y1, y2) = (out.speed * i0, 1.0 - into.speed * i1); + if !(y1.abs() <= MAX_EASE_Y && y2.abs() <= MAX_EASE_Y) { + return Err(EaseError::OutOfRange { what: "speed × influence", min: -MAX_EASE_Y, max: MAX_EASE_Y }); + } + Ok(Easing::CubicBezier(i0, y1, 1.0 - i1, y2)) + } + + /// The two sides of an ease that one cubic Bezier draws (see [`Easing::from_temporal`] and + /// [`Easing::as_bezier`]). A handle with no reach has speed 0. `None` when a handle's reach + /// is so short that its speed is too large to represent. + pub fn temporal(&self) -> Option<(TemporalEase, TemporalEase)> { + let (x1, y1, x2, y2) = self.as_bezier()?; + let (i0, i1) = (x1.clamp(0.0, 1.0), (1.0 - x2).clamp(0.0, 1.0)); + let s0 = if i0 > 0.0 { y1 / i0 } else { 0.0 }; + let s1 = if i1 > 0.0 { (1.0 - y2) / i1 } else { 0.0 }; + if !(s0.is_finite() && s1.is_finite()) { + return None; + } + Some((TemporalEase { speed: s0, influence: i0 }, TemporalEase { speed: s1, influence: i1 })) + } + + /// A spring ease, checked as [`Spring::from_physical`] checks its values. + pub fn spring(mass: f64, stiffness: f64, damping: f64) -> Result { + Spring::from_physical(mass, stiffness, damping)?; + Ok(Easing::Spring(SpringEase { mass, stiffness, damping })) + } + + /// The named ease of `family` easing `dir`. + pub fn preset(family: EaseFamily, dir: EaseDir) -> Easing { + use EaseDir::*; + use EaseFamily::*; + match (family, dir) { + (Quad, In) => Easing::QuadIn, + (Quad, Out) => Easing::QuadOut, + (Quad, InOut) => Easing::QuadInOut, + (Cubic, In) => Easing::CubicIn, + (Cubic, Out) => Easing::CubicOut, + (Cubic, InOut) => Easing::CubicInOut, + (Quart, In) => Easing::QuartIn, + (Quart, Out) => Easing::QuartOut, + (Quart, InOut) => Easing::QuartInOut, + (Quint, In) => Easing::QuintIn, + (Quint, Out) => Easing::QuintOut, + (Quint, InOut) => Easing::QuintInOut, + (Sine, In) => Easing::SineIn, + (Sine, Out) => Easing::SineOut, + (Sine, InOut) => Easing::SineInOut, + (Back, In) => Easing::BackIn, + (Back, Out) => Easing::BackOut, + (Back, InOut) => Easing::BackInOut, + (Circ, In) => Easing::CircIn, + (Circ, Out) => Easing::CircOut, + (Circ, InOut) => Easing::CircInOut, + (Bounce, In) => Easing::BounceIn, + (Bounce, Out) => Easing::BounceOut, + (Bounce, InOut) => Easing::BounceInOut, + (Elastic, In) => Easing::ElasticIn, + (Elastic, Out) => Easing::ElasticOut, + (Elastic, InOut) => Easing::ElasticInOut, + } + } + + /// The family and direction of a named ease. + pub fn family(&self) -> Option<(EaseFamily, EaseDir)> { + use EaseDir::*; + use EaseFamily::*; + Some(match self { + Easing::QuadIn => (Quad, In), + Easing::QuadOut => (Quad, Out), + Easing::QuadInOut => (Quad, InOut), + Easing::CubicIn => (Cubic, In), + Easing::CubicOut => (Cubic, Out), + Easing::CubicInOut => (Cubic, InOut), + Easing::QuartIn => (Quart, In), + Easing::QuartOut => (Quart, Out), + Easing::QuartInOut => (Quart, InOut), + Easing::QuintIn => (Quint, In), + Easing::QuintOut => (Quint, Out), + Easing::QuintInOut => (Quint, InOut), + Easing::SineIn => (Sine, In), + Easing::SineOut => (Sine, Out), + Easing::SineInOut => (Sine, InOut), + Easing::BackIn => (Back, In), + Easing::BackOut => (Back, Out), + Easing::BackInOut => (Back, InOut), + Easing::CircIn => (Circ, In), + Easing::CircOut => (Circ, Out), + Easing::CircInOut => (Circ, InOut), + Easing::BounceIn => (Bounce, In), + Easing::BounceOut => (Bounce, Out), + Easing::BounceInOut => (Bounce, InOut), + Easing::ElasticIn => (Elastic, In), + Easing::ElasticOut => (Elastic, Out), + Easing::ElasticInOut => (Elastic, InOut), + Easing::Linear + | Easing::Classic(_) + | Easing::CubicBezier(..) + | Easing::Custom(_) + | Easing::Sampled(_) + | Easing::Spring(_) + | Easing::Hold => return None, + }) + } + + /// Every named preset: no ease, then each family In, Out, In Out. + pub fn named() -> impl Iterator { + std::iter::once(Easing::Linear).chain(EaseFamily::ALL.into_iter().flat_map(|f| EaseDir::ALL.into_iter().map(move |d| Easing::preset(f, d)))) + } + + /// The preset's name in commands and files (`"QuadIn"`, `"ElasticInOut"`, `"Hold"`), `None` + /// for eases with values. + pub fn name(&self) -> Option { + match self { + Easing::Linear => Some("Linear".into()), + Easing::Hold => Some("Hold".into()), + _ => self.family().map(|(f, d)| format!("{}{}", f.label(), d.label().replace(' ', ""))), + } + } + + /// The preset named `name`, ignoring case, spaces, `-` and `_` (`"back in out"`), with the + /// aliases `none`, `easein`, `easeout`, `easeinout` and `smooth`. + pub fn from_name(name: &str) -> Option { + // No preset or alias is longer than this, so a longer name is unknown and is not copied + // past it. + const LONGEST: usize = 12; + let key: String = name.chars().filter(|c| !matches!(c, '-' | '_' | ' ')).flat_map(char::to_lowercase).take(LONGEST + 1).collect(); + if key.chars().count() > LONGEST { + return None; + } + match key.as_str() { + "none" | "noease" => return Some(Easing::Linear), + "hold" => return Some(Easing::Hold), + "easein" => return Some(Easing::QuadIn), + "easeout" => return Some(Easing::QuadOut), + "easeinout" => return Some(Easing::QuadInOut), + "smooth" => return Some(Easing::SMOOTH), + _ => {} + } + Easing::named().find(|e| e.name().is_some_and(|n| n.to_lowercase() == key)) + } + + /// An English label for menus and reports. + pub fn label(&self) -> String { + match self { + Easing::Linear => Easing::LINEAR_LABEL.to_string(), + Easing::Hold => "Hold".to_string(), + Easing::Classic(s) => format!("Classic {s:+.0}"), + Easing::CubicBezier(..) if *self == Easing::SMOOTH => "Smooth (bezier)".to_string(), + Easing::CubicBezier(a, b, c, d) => format!("Bezier({a:.2}, {b:.2}, {c:.2}, {d:.2})"), + Easing::Custom(_) => "Custom".to_string(), + Easing::Sampled(s) => s.name().to_string(), + Easing::Spring(s) => format!("Spring {:.0}, {:.0}, {:.0}", s.mass, s.stiffness, s.damping), + other => other.family().map_or_else(|| "Custom".to_string(), |(f, d)| format!("{} {}", f.label(), d.label())), + } + } + + /// The single cubic Bezier `(x1, y1, x2, y2)` that draws this ease: exact for linear, the + /// Classic slider, the Quad, Cubic and Back eases in and out, and a custom ease of one + /// segment; the Quad and Cubic in-outs get their usual one-curve approximations. `None` for + /// eases one curve cannot draw (Bounce, Elastic, the other families, hold, springs, sampled + /// tables, custom eases of several segments, and a custom ease of one segment whose handle + /// reaches past the unit box in x). + pub fn as_bezier(&self) -> Option<(f64, f64, f64, f64)> { + const THIRD: f64 = 1.0 / 3.0; + Some(match self { + Easing::Linear => (THIRD, THIRD, 2.0 * THIRD, 2.0 * THIRD), + // t², t³ and (c+1)t³ − ct² and their mirrors, with x(s) = s. + Easing::QuadIn => (THIRD, 0.0, 2.0 * THIRD, THIRD), + Easing::QuadOut => (THIRD, 2.0 * THIRD, 2.0 * THIRD, 1.0), + Easing::CubicIn => (THIRD, 0.0, 2.0 * THIRD, 0.0), + Easing::CubicOut => (THIRD, 1.0, 2.0 * THIRD, 1.0), + Easing::BackIn => (THIRD, 0.0, 2.0 * THIRD, -BACK * THIRD), + Easing::BackOut => (THIRD, 1.0 + BACK * THIRD, 2.0 * THIRD, 1.0), + Easing::QuadInOut => (0.45, 0.0, 0.55, 1.0), + Easing::CubicInOut => (0.65, 0.0, 0.35, 1.0), + Easing::Classic(strength) => { + // The quadratic 2(1 − t)t·c + t², raised to a cubic. + let c = 0.5 + 0.5 * classic_strength(*strength); + (THIRD, 2.0 * c * THIRD, 2.0 * THIRD, (2.0 * c + 1.0) * THIRD) + } + Easing::CubicBezier(a, b, c, d) => bezier_handles(*a, *b, *c, *d), + Easing::Custom(c) => match c.points() { + [a, b] if a.out.x <= 1.0 && b.h_in.x >= -1.0 => (a.out.x, a.out.y, b.at.x + b.h_in.x, b.at.y + b.h_in.y), + _ => return None, + }, + _ => return None, + }) + } + + /// Eased progress at `t`: exactly 0 for `t <= 0` or NaN, exactly 1 for `t >= 1`. + pub fn apply(&self, t: f64) -> f64 { + if t.is_nan() || t <= 0.0 { + return 0.0; + } + if t >= 1.0 { + return 1.0; + } + let v = match self { + Easing::Linear => t, + Easing::Hold => 0.0, + Easing::Classic(strength) => { + // Quadratic Bezier with the middle control point moved by `strength`. + let c = 0.5 + 0.5 * classic_strength(*strength); + 2.0 * (1.0 - t) * t * c + t * t + } + Easing::CubicBezier(x1, y1, x2, y2) => { + let (x1, y1, x2, y2) = bezier_handles(*x1, *y1, *x2, *y2); + bez(solve_monotonic(t, [0.0, x1, x2, 1.0]), [0.0, y1, y2, 1.0]) + } + Easing::Custom(c) => c.apply(t), + Easing::Sampled(s) => s.apply(t), + Easing::Spring(s) => s.apply(t), + named => match named.family() { + Some((f, d)) => eval_named(f, d, t), + None => t, + }, + }; + if v.is_finite() { v } else { t } + } + + /// This ease as a custom curve for a graph editor: exact for linear, Classic, a Bezier, + /// the Quad, Cubic, Back and Bounce families and custom eases; Circ is two circular arcs, + /// and Quart, Quint, Sine and Elastic are fitted by matching values and slopes at a few + /// points (all within 0.5 % of the range everywhere). A sampled ease or a spring becomes the + /// straight segments through [`crate::POLYLINE_POINTS`] of its values, and a hold a corner + /// at the end. + pub fn to_custom(&self) -> CustomEase { + match self { + Easing::Custom(c) => (**c).clone(), + Easing::Sampled(s) => s.to_polyline(), + Easing::Spring(_) => { + let n = crate::MAX_EASE_SAMPLES; + let values = (0..n).map(|i| self.apply(i as f64 / (n - 1) as f64)).collect(); + SampledEase::new("Spring", "", "", values).to_polyline() + } + Easing::Hold => { + // Flat at 0 across the segment, then straight up to 1 at the end. + let third = 1.0 / 3.0; + CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(third, 0.0), smooth: false }, + EasePoint { at: Vec2::new(1.0, 0.0), h_in: Vec2::new(-third, 0.0), out: Vec2::ZERO, smooth: false }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false }, + ]) + } + Easing::Linear => CustomEase::linear(), + Easing::Classic(_) | Easing::CubicBezier(..) => { + let Some((x1, y1, x2, y2)) = self.as_bezier() else { return CustomEase::linear() }; + CustomEase::from_bezier(x1, y1, x2, y2) + } + named => match named.family() { + Some((f, d)) => fit_named(f, d), + None => CustomEase::linear(), + }, + } + } + + /// The custom curve, when this is one. + pub fn custom(&self) -> Option<&CustomEase> { + match self { + Easing::Custom(c) => Some(c), + _ => None, + } + } + + /// The sampled curve, when this is one. + pub fn sampled(&self) -> Option<&SampledEase> { + match self { + Easing::Sampled(s) => Some(s), + _ => None, + } + } +} + +/// A cubic Bezier's handles as evaluation uses them: x within `0..=1`, y within ±[`MAX_EASE_Y`], +/// and the straight line for a handle that is not finite. +fn bezier_handles(x1: f64, y1: f64, x2: f64, y2: f64) -> (f64, f64, f64, f64) { + if ![x1, y1, x2, y2].iter().all(|v| v.is_finite()) { + return (1.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0); + } + (x1.clamp(0.0, 1.0), y1.clamp(-MAX_EASE_Y, MAX_EASE_Y), x2.clamp(0.0, 1.0), y2.clamp(-MAX_EASE_Y, MAX_EASE_Y)) +} + +fn classic_strength(s: f64) -> f64 { + if s.is_finite() { s.clamp(-100.0, 100.0) / 100.0 } else { 0.0 } +} + +fn eval_named(f: EaseFamily, d: EaseDir, t: f64) -> f64 { + match d { + EaseDir::In => f.ease_in(t, false), + EaseDir::Out => 1.0 - f.ease_in(1.0 - t, false), + EaseDir::InOut => { + if t < 0.5 { + 0.5 * f.ease_in(2.0 * t, true) + } else { + 1.0 - 0.5 * f.ease_in(2.0 - 2.0 * t, true) + } + } + } +} + +/// The slope of `y` at `x`, from inside `[lo, hi]`: one-sided, a step in from `x` (so a value +/// pinned at an end, as Elastic's are, does not count), exact for parabolas but for that step. +fn slope(y: &dyn Fn(f64) -> f64, x: f64, lo: f64, hi: f64) -> f64 { + const H: f64 = 1e-6; + let s = if x + 3.0 * H <= hi { + let d = (-3.0 * y(x + H) + 4.0 * y(x + 2.0 * H) - y(x + 3.0 * H)) / (2.0 * H); + let d2 = (y(x + H) - 2.0 * y(x + 2.0 * H) + y(x + 3.0 * H)) / (H * H); + d - d2 * H + } else if x - 3.0 * H >= lo { + let d = (3.0 * y(x - H) - 4.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (2.0 * H); + let d2 = (y(x - H) - 2.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (H * H); + d + d2 * H + } else { + 0.0 + }; + if s.is_finite() { s } else { 0.0 } +} + +/// The ease in of `f` (its In Out form with `in_out`) as Bezier points: Hermite segments (value +/// and slope matched at each end, so exact for cubic polynomials and for each parabola of +/// Bounce), except Circ, whose quarter circle is two 45° arcs (within 4·10⁻⁶ of the circle). +fn fit_in(f: EaseFamily, in_out: bool) -> Vec { + let pt = |x: f64, y: f64, i: (f64, f64), o: (f64, f64)| EasePoint { + at: Vec2::new(x, y), + h_in: Vec2::new(i.0, i.1), + out: Vec2::new(o.0, o.1), + smooth: false, + }; + if f == EaseFamily::Circ { + // The circle about (0, 1) from (0, 0) to (1, 1); each arc's handles are k = 4/3·tan(φ/4) + // long along the tangents. + let k = 4.0 / 3.0 * (std::f64::consts::PI / 16.0).tan(); + let c = std::f64::consts::FRAC_1_SQRT_2; + return vec![pt(0.0, 0.0, (0.0, 0.0), (k, 0.0)), pt(c, 1.0 - c, (-k * c, -k * c), (k * c, k * c)), pt(1.0, 1.0, (0.0, -k), (0.0, 0.0))]; + } + let y = move |t: f64| f.ease_in(t, in_out); + let mut xs: Vec = Vec::new(); + let pieces = f.pieces_in(); + let bounds: Vec = std::iter::once(0.0).chain(f.breaks_in().iter().copied()).chain(std::iter::once(1.0)).collect(); + for w in bounds.windows(2) { + if let [a, c] = w { + xs.extend((0..pieces).map(|k| a + (c - a) * k as f64 / pieces as f64)); + } + } + xs.push(1.0); + let mut pts: Vec = xs.iter().map(|&x| pt(x, y(x), (0.0, 0.0), (0.0, 0.0))).collect(); + for i in 0..xs.len().saturating_sub(1) { + let (Some(&a), Some(&b)) = (xs.get(i), xs.get(i + 1)) else { continue }; + let h = (b - a) / 3.0; + let (sa, sb) = (slope(&y, a, a, b), slope(&y, b, a, b)); + if let Some(p) = pts.get_mut(i) { + p.out = Vec2::new(h, sa * h); + } + if let Some(p) = pts.get_mut(i + 1) { + p.h_in = Vec2::new(-h, -sb * h); + } + } + pts +} + +/// The curve turned half a turn about (½, ½): an ease in becomes the ease out. +fn mirrored(pts: &[EasePoint]) -> Vec { + pts.iter().rev().map(|p| EasePoint { at: Vec2::new(1.0 - p.at.x, 1.0 - p.at.y), h_in: -p.out, out: -p.h_in, smooth: p.smooth }).collect() +} + +fn scaled(pts: &[EasePoint], by: f64, from: Vec2) -> Vec { + pts.iter().map(|p| EasePoint { at: from + p.at * by, h_in: p.h_in * by, out: p.out * by, smooth: p.smooth }).collect() +} + +/// A named ease as a custom curve (see [`Easing::to_custom`]). +fn fit_named(f: EaseFamily, d: EaseDir) -> CustomEase { + let mut pts = match d { + EaseDir::In => fit_in(f, false), + EaseDir::Out => mirrored(&fit_in(f, false)), + EaseDir::InOut => { + let half = fit_in(f, true); + let mut a = scaled(&half, 0.5, Vec2::ZERO); + let b = scaled(&mirrored(&half), 0.5, Vec2::new(0.5, 0.5)); + // The two halves meet at (½, ½): one point, the first half's in, the second's out. + if let (Some(last), Some(first)) = (a.last_mut(), b.first()) { + last.out = first.out; + } + a.extend(b.into_iter().skip(1)); + a + } + }; + // Points where the slope carries on are smooth (Bounce's floor hits are corners). + let n = pts.len(); + for (i, p) in pts.iter_mut().enumerate() { + p.smooth = + i > 0 && i + 1 < n && p.h_in.length() > 1e-9 && p.out.length() > 1e-9 && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-3; + } + CustomEase::new(pts) +} diff --git a/crates/ease/src/lib.rs b/crates/ease/src/lib.rs new file mode 100644 index 0000000000..b63fb31e13 --- /dev/null +++ b/crates/ease/src/lib.rs @@ -0,0 +1,228 @@ +//! Easing curves, keyed tracks, motion paths and springs. +//! +//! * [`Easing`] maps linear progress `t` in `0..=1` to eased progress: no ease, hold, the +//! Classic slider, nine named families (Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce, +//! Elastic), each In, Out and In Out, one cubic Bezier (also built from speed and influence, +//! [`TemporalEase`]), an editable multi-segment [`CustomEase`], a [`SampledEase`] table and a +//! [`SpringEase`]. [`Easing::apply`] is a pure function that does not allocate, and it returns +//! exactly 0 at the start and exactly 1 at the end. +//! * [`Track`] holds keys of any [`Animatable`] value (`f32`, `f64`, [`Vec2`], `[f32; N]`, +//! `[f64; N]`) at times in seconds, each easing into the next. Sampling is a binary search and +//! does not allocate for these value types; for another [`Animatable`] type it allocates +//! whatever that type's `Clone` and `Animatable` implementations allocate. +//! * [`MotionPath`] is a chain of cubic Bezier segments with arc-length tables built once, for +//! constant-speed motion along a curve. +//! * [`Spring`] and [`SpringState`] move a value toward a target as a damped spring. Each step +//! uses the exact solution of the spring equation, so a step costs the same at any frame rate +//! and length. +//! +//! The named families are the classic public easing equations published by Robert Penner. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod custom; +mod easing; +mod path; +mod sampled; +mod spring; +mod track; +mod vec2; + +pub use custom::{CustomEase, EasePoint, Handle, MAX_EASE_POINTS, MAX_EASE_Y}; +pub use easing::{EaseDir, EaseFamily, Easing, MIN_INFLUENCE, SpringEase, TemporalEase}; +pub use path::{MAX_PATH_SEGMENTS, MotionPath}; +pub use sampled::{MAX_EASE_SAMPLES, POLYLINE_POINTS, SampledEase}; +pub use spring::{MAX_DAMPING_RATIO, MAX_SPRING_HZ, Spring, SpringState}; +pub use track::{Animatable, Key, MAX_TRACK_KEYS, Track}; +pub use vec2::Vec2; + +/// Why a value was refused. +#[derive(Clone, Debug, PartialEq)] +pub enum EaseError { + /// The named input is NaN or infinite. + NotFinite(&'static str), + /// The named input is outside the range it must lie in. + OutOfRange { what: &'static str, min: f64, max: f64 }, + /// A track or path holds as many entries as it may. + Full(usize), + /// A path or curve needs more points than it was given. + TooFew { what: &'static str, need: usize }, + /// The track has no keys. + Empty, + /// Two keys are at this time. + SameTime(f64), + /// The result is too large to represent. + Overflow, +} + +impl std::fmt::Display for EaseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + EaseError::NotFinite(what) => write!(f, "{what} is not a finite number"), + EaseError::OutOfRange { what, min, max } => write!(f, "{what} must be between {min} and {max}"), + EaseError::Full(n) => write!(f, "at most {n} entries are allowed"), + EaseError::TooFew { what, need } => write!(f, "{what} needs at least {need} points"), + EaseError::Empty => write!(f, "the track has no keys"), + EaseError::SameTime(t) => write!(f, "two keys are at {t} s"), + EaseError::Overflow => write!(f, "the result is too large"), + } + } +} + +impl std::error::Error for EaseError {} + +/// `v` itself when it is finite. +pub(crate) fn finite(v: f64, what: &'static str) -> Result { + if v.is_finite() { Ok(v) } else { Err(EaseError::NotFinite(what)) } +} + +/// `v` itself when it is finite and within `min..=max`. +pub(crate) fn within(v: f64, min: f64, max: f64, what: &'static str) -> Result { + let v = finite(v, what)?; + if (min..=max).contains(&v) { Ok(v) } else { Err(EaseError::OutOfRange { what, min, max }) } +} + +/// The value `t` of the way from `a` to `b`. When a step on the way is too large to represent +/// (`a` and `b` near opposite ends of the `f64` range, or an overshooting `t`), it is worked +/// out at half scale, so only a result too large to represent is infinite. `t` of exactly 0 or +/// 1 returns `a` or `b` itself. +pub(crate) fn lerp(a: f64, b: f64, t: f64) -> f64 { + if t == 0.0 { + return a; + } + if t == 1.0 { + return b; + } + let r = a + (b - a) * t; + if r.is_finite() { r } else { 2.0 * (0.5 * a + (0.5 * b - 0.5 * a) * t) } +} + +/// Reads a list, keeping its first `max` entries and skipping the rest without storing them. +#[cfg(feature = "serde")] +pub(crate) fn read_first<'de, D, T>(d: D, max: usize) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: serde::Deserialize<'de>, +{ + use serde::de::{IgnoredAny, SeqAccess, Visitor}; + struct V(usize, std::marker::PhantomData); + impl<'de, T: serde::Deserialize<'de>> Visitor<'de> for V { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "a list") + } + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(self.0).min(1024)); + while out.len() < self.0 { + match seq.next_element()? { + Some(v) => out.push(v), + None => return Ok(out), + } + } + while seq.next_element::()?.is_some() {} + Ok(out) + } + } + d.deserialize_seq(V(max, std::marker::PhantomData)) +} + +/// Reads a string and keeps only what `clean` makes of it, so a long string in a file is never +/// copied whole into the value. +/// +/// This bounds the memory the value keeps. A format that has to decode escapes may still build +/// the whole string in a temporary buffer first; that buffer is no larger than the input, so the +/// caller bounds it by limiting the size of the file it reads. +#[cfg(feature = "serde")] +pub(crate) fn read_cleaned<'de, D: serde::Deserializer<'de>>(d: D, clean: fn(&str) -> String) -> Result { + struct V(fn(&str) -> String); + impl serde::de::Visitor<'_> for V { + type Value = String; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "a string") + } + fn visit_str(self, s: &str) -> Result { + Ok((self.0)(s)) + } + } + d.deserialize_str(V(clean)) +} + +/// Cubic Bezier in one dimension. +pub(crate) fn bez(t: f64, p: [f64; 4]) -> f64 { + let mt = 1.0 - t; + mt * mt * mt * p[0] + 3.0 * mt * mt * t * p[1] + 3.0 * mt * t * t * p[2] + t * t * t * p[3] +} + +/// The derivative of [`bez`]. +pub(crate) fn dbez(t: f64, p: [f64; 4]) -> f64 { + let mt = 1.0 - t; + 3.0 * mt * mt * (p[1] - p[0]) + 6.0 * mt * t * (p[2] - p[1]) + 3.0 * t * t * (p[3] - p[2]) +} + +/// Most steps [`solve_monotonic`] takes. +pub(crate) const SOLVE_STEPS: u32 = 64; +/// How close [`solve_monotonic`] brings `bez(s)` to `x`, relative to the curve's span. +pub(crate) const SOLVE_TOLERANCE: f64 = 1e-12; + +/// The parameter where the Bezier `p` (non-decreasing, as it is when its inner points lie +/// between its ends) reaches `x`: Newton steps kept inside a shrinking bracket, halving when a step leaves it, to +/// within [`SOLVE_TOLERANCE`] of the span in at most [`SOLVE_STEPS`] steps. The curve is solved +/// shifted to start at 0 and scaled to a span of 1, so a narrow segment far from 0 is solved as +/// precisely as a wide one. The curve with both handles at full reach (`p1 = p3`, `p2 = p0`), +/// whose slope is zero halfway, is inverted in closed form. +pub(crate) fn solve_monotonic(x: f64, p: [f64; 4]) -> f64 { + solve_counted(x, p).0 +} + +/// [`solve_monotonic`] and the number of steps it took. +pub(crate) fn solve_counted(x: f64, p: [f64; 4]) -> (f64, u32) { + let span = p[3] - p[0]; + if span.is_nan() || span <= 0.0 { + return (0.5, 0); + } + if x <= p[0] { + return (0.0, 0); + } + if x >= p[3] { + return (1.0, 0); + } + let u = (x - p[0]) / span; + if p[1] == p[3] && p[2] == p[0] { + // x(s) = 0.5 + 4 (s − 0.5)³ on the unit span. + return ((0.5 + ((u - 0.5) * 0.25).cbrt()).clamp(0.0, 1.0), 0); + } + let q = [0.0, (p[1] - p[0]) / span, (p[2] - p[0]) / span, 1.0]; + let (mut lo, mut hi) = (0.0f64, 1.0f64); + let mut s = u.clamp(0.0, 1.0); + for step in 1..=SOLVE_STEPS { + let err = bez(s, q) - u; + if err.abs() <= SOLVE_TOLERANCE { + return (s, step); + } + if err < 0.0 { + lo = s; + } else { + hi = s; + } + let d = dbez(s, q); + let next = if d.abs() > 1e-300 { s - err / d } else { f64::NAN }; + s = if next > lo && next < hi { next } else { 0.5 * (lo + hi) }; + } + (s, SOLVE_STEPS) +} + +#[cfg(test)] +#[path = "tests/easing_tests.rs"] +mod easing_tests; + +#[cfg(test)] +#[path = "tests/track_tests.rs"] +mod track_tests; + +#[cfg(test)] +#[path = "tests/path_tests.rs"] +mod path_tests; + +#[cfg(test)] +#[path = "tests/spring_tests.rs"] +mod spring_tests; diff --git a/crates/ease/src/path.rs b/crates/ease/src/path.rs new file mode 100644 index 0000000000..fc6a065511 --- /dev/null +++ b/crates/ease/src/path.rs @@ -0,0 +1,355 @@ +//! [`MotionPath`]: constant-speed motion along a chain of cubic Bezier segments. + +use crate::{EaseError, Vec2, bez, dbez}; + +/// Most segments one path holds. +pub const MAX_PATH_SEGMENTS: usize = 10_000; +/// Cells in each segment's arc-length table. +const ARC_N: usize = 32; +/// Most steps `Segment::param_at` takes; halving a table cell this often reaches the smallest +/// step an `f64` parameter can take. +const PARAM_STEPS: u32 = 64; + +/// 5-point Gauss-Legendre nodes and weights on −1..1. +const GAUSS: [(f64, f64); 5] = [ + (0.0, 0.568_888_888_888_888_9), + (-0.538_469_310_105_683_1, 0.478_628_670_499_366_5), + (0.538_469_310_105_683_1, 0.478_628_670_499_366_5), + (-0.906_179_845_938_664, 0.236_926_885_056_189_1), + (0.906_179_845_938_664, 0.236_926_885_056_189_1), +]; + +#[derive(Clone, Debug, PartialEq)] +struct Segment { + p: [Vec2; 4], + /// Arc length from the segment's start at `u = i / ARC_N`. + table: [f64; ARC_N + 1], + /// Both handles on the chord: the segment is the straight line between its ends. + straight: bool, + /// The parameters inside `0..1` where the x or y derivative is zero, in order, with the + /// unused entries set to 1. Arc lengths are integrated in pieces split there, since the + /// speed has a kink where the curve stops and turns back. + stops: [f64; 4], + /// Arc length from the path's start to this segment's start. + start: f64, +} + +impl Segment { + fn new(p: [Vec2; 4], start: f64) -> Segment { + let straight = on_chord(p[0], p[1], p[3]) && on_chord(p[0], p[2], p[3]); + let stops = stationary(&p); + let mut table = [0.0; ARC_N + 1]; + if straight { + let len = p[0].distance(p[3]); + for (i, v) in table.iter_mut().enumerate() { + *v = len * (i as f64 / ARC_N as f64); + } + } else { + let mut acc = 0.0; + for i in 1..=ARC_N { + acc += arc(&p, &stops, (i - 1) as f64 / ARC_N as f64, i as f64 / ARC_N as f64); + if let Some(v) = table.get_mut(i) { + *v = acc; + } + } + } + Segment { p, table, straight, stops, start } + } + + fn length(&self) -> f64 { + self.table[ARC_N] + } + + fn point(&self, u: f64) -> Vec2 { + let p = &self.p; + Vec2::new(bez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), bez(u, [p[0].y, p[1].y, p[2].y, p[3].y])) + } + + /// The parameter at arc length `s` from the segment's start (`0..=length`): the table + /// cell's straight-line guess refined with Newton steps on the true arc length, kept inside + /// a shrinking bracket and halving it when a step would leave it (where the curve stands + /// still, for one), until the arc length is within 1e-12 of the segment's length of `s`, in + /// at most [`PARAM_STEPS`] steps. + fn param_at(&self, s: f64) -> f64 { + let len = self.length(); + if len <= 0.0 { + return 0.0; + } + let s = s.clamp(0.0, len); + if self.straight { + return s / len; + } + let i = self.table.partition_point(|&v| v < s).clamp(1, ARC_N); + let (Some(&a), Some(&b)) = (self.table.get(i - 1), self.table.get(i)) else { return s / len }; + let (u0, u1) = ((i - 1) as f64 / ARC_N as f64, i as f64 / ARC_N as f64); + let mut u = u0 + if b > a { (s - a) / (b - a) } else { 0.0 } * (u1 - u0); + let (mut lo, mut hi) = (u0, u1); + for _ in 0..PARAM_STEPS { + let e = a + arc(&self.p, &self.stops, u0, u) - s; + if e.abs() <= 1e-12 * len { + break; + } + if e < 0.0 { + lo = u; + } else { + hi = u; + } + let d = speed(&self.p, u); + let next = if d > 0.0 { u - e / d } else { f64::NAN }; + u = if next > lo && next < hi { next } else { 0.5 * (lo + hi) }; + } + u + } + + /// The direction of travel at `u`, or the chord's where the curve's derivative vanishes. + fn direction(&self, u: f64) -> Vec2 { + let p = &self.p; + let d = Vec2::new(dbez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), dbez(u, [p[0].y, p[1].y, p[2].y, p[3].y])).normalized(); + if d != Vec2::ZERO { + return d; + } + // At an end whose handle sits on it, the curve leaves toward the next control point. + let toward = if u < 0.5 { + [p[1], p[2], p[3]].into_iter().find(|q| *q != p[0]).map(|q| q - p[0]) + } else { + [p[2], p[1], p[0]].into_iter().find(|q| *q != p[3]).map(|q| p[3] - q) + }; + toward.unwrap_or(Vec2::ZERO).normalized() + } +} + +/// |dB/du|. +fn speed(p: &[Vec2; 4], u: f64) -> f64 { + Vec2::new(dbez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), dbez(u, [p[0].y, p[1].y, p[2].y, p[3].y])).length() +} + +/// Arc length between parameters `a` and `b` (Gauss-Legendre; exact enough on one table cell), +/// in pieces split at the parameters `stops` that lie between them. +fn arc(p: &[Vec2; 4], stops: &[f64; 4], a: f64, b: f64) -> f64 { + let mut from = a; + let mut total = 0.0; + for &r in stops.iter().filter(|&&r| r > a && r < b) { + total += gauss(p, from, r); + from = r; + } + total + gauss(p, from, b) +} + +/// [`arc`] over one piece. Each term is scaled by the interval before they are added, so a +/// length near the largest `f64` does not overflow on the way. +fn gauss(p: &[Vec2; 4], a: f64, b: f64) -> f64 { + let (m, h) = ((a + b) * 0.5, (b - a) * 0.5); + GAUSS.iter().map(|(x, w)| w * h * speed(p, m + h * x)).sum::() +} + +/// The parameters inside `0..1` where the x or y derivative of the segment `p` is zero, sorted +/// and padded with 1 (see `Segment::stops`). +fn stationary(p: &[Vec2; 4]) -> [f64; 4] { + let mut out = [1.0; 4]; + let mut n = 0; + for k in [[p[0].x, p[1].x, p[2].x, p[3].x], [p[0].y, p[1].y, p[2].y, p[3].y]] { + for r in quadratic_roots(k[1] - k[0], k[2] - k[1], k[3] - k[2]) { + if let Some(slot) = out.get_mut(n) { + *slot = r; + n += 1; + } + } + } + out.sort_by(f64::total_cmp); + out +} + +/// The roots inside `0..1` of the quadratic with Bernstein coefficients `k0`, `k1` and `k2` +/// (a cubic's derivative, up to a factor of 3). The coefficients are scaled to the largest +/// first, so coordinates near the ends of the `f64` range do not overflow when squared. +fn quadratic_roots(k0: f64, k1: f64, k2: f64) -> impl Iterator { + let m = k0.abs().max(k1.abs()).max(k2.abs()); + let (k0, k1, k2) = if m.is_finite() && m > 0.0 { (k0 / m, k1 / m, k2 / m) } else { (0.0, 0.0, 0.0) }; + // a u² + b u + c in powers of u. + let (a, b, c) = (k0 - 2.0 * k1 + k2, 2.0 * (k1 - k0), k0); + let roots = if a.abs() < 1e-12 { + [if b != 0.0 { -c / b } else { f64::NAN }, f64::NAN] + } else { + let disc = b * b - 4.0 * a * c; + if disc < 0.0 { + [f64::NAN, f64::NAN] + } else { + // The root of larger size first, then the other from their product, without + // cancellation. + let q = -0.5 * (b + disc.sqrt().copysign(b)); + [q / a, if q != 0.0 { c / q } else { f64::NAN }] + } + }; + roots.into_iter().filter(|r| *r > 0.0 && *r < 1.0) +} + +/// Whether control point `c` lies on the segment `a`–`b` (within rounding). +fn on_chord(a: Vec2, c: Vec2, b: Vec2) -> bool { + let (mut d, mut v) = (b - a, c - a); + // Scaled to the largest component first, so squaring coordinates near 1e154 and above does + // not overflow and make a curve look straight. + let scale = d.x.abs().max(d.y.abs()).max(v.x.abs()).max(v.y.abs()); + if scale.is_finite() && scale > 0.0 { + (d, v) = (Vec2::new(d.x / scale, d.y / scale), Vec2::new(v.x / scale, v.y / scale)); + } + let dd = d.dot(d); + if dd <= 0.0 { + // A segment of zero length is straight when its handles sit on its point. + return v == Vec2::ZERO; + } + let t = v.dot(d) / dd; + let off = v - d * t; + (0.0..=1.0).contains(&t) && off.dot(off) <= dd * 1e-28 +} + +/// A path of cubic Bezier segments with an arc-length table per segment, built once, so a point +/// at a distance along it costs a binary search and a few curve evaluations and does not +/// allocate. +/// +/// A distance before the start or past the end continues in a straight line along the path's +/// direction there, so an ease that overshoots carries the motion past the end the same way on +/// curved and straight paths. +#[derive(Clone, Debug, PartialEq)] +pub struct MotionPath { + segments: Vec, + length: f64, + /// The first and last segments that have length (the first and last when none has), so the + /// ends' directions skip anchors repeated at an end. + ends: (usize, usize), +} + +impl MotionPath { + /// A path from the absolute points `[p0, c1, c2, p1, c3, c4, p2, …]` (3n + 1 of them, n from + /// 1 to [`MAX_PATH_SEGMENTS`]). An error for a wrong count, a point that is not finite, or + /// a path too long to measure. + pub fn new(points: &[Vec2]) -> Result { + if points.len() < 4 { + return Err(EaseError::TooFew { what: "a motion path", need: 4 }); + } + if points.len() % 3 != 1 { + return Err(EaseError::OutOfRange { what: "the point count (3n + 1)", min: 4.0, max: (3 * MAX_PATH_SEGMENTS + 1) as f64 }); + } + if points.len() > 3 * MAX_PATH_SEGMENTS + 1 { + return Err(EaseError::Full(MAX_PATH_SEGMENTS)); + } + if points.iter().any(|p| !p.is_finite()) { + return Err(EaseError::NotFinite("path point")); + } + let mut segments = Vec::with_capacity(points.len() / 3); + let mut start = 0.0; + for w in points.windows(4).step_by(3) { + let [a, b, c, d] = w else { continue }; + let s = Segment::new([*a, *b, *c, *d], start); + start += s.length(); + segments.push(s); + } + if !start.is_finite() { + return Err(EaseError::Overflow); + } + let first = segments.iter().position(|g| g.length() > 0.0).unwrap_or(0); + let last = segments.iter().rposition(|g| g.length() > 0.0).unwrap_or(segments.len().saturating_sub(1)); + Ok(MotionPath { segments, length: start, ends: (first, last) }) + } + + /// A smooth path through `anchors` (at least 2), its handles set automatically: each inner + /// anchor's handles point along the line from the anchor before it to the anchor after it, + /// a sixth of that line long, and an end anchor's handle points a sixth of the way toward + /// its neighbor. A side that faces an anchor at the same place has no handle, so two equal + /// anchors make a segment of zero length. + pub fn through(anchors: &[Vec2]) -> Result { + if anchors.len() < 2 { + return Err(EaseError::TooFew { what: "a motion path", need: 2 }); + } + if anchors.len() > MAX_PATH_SEGMENTS + 1 { + return Err(EaseError::Full(MAX_PATH_SEGMENTS)); + } + if anchors.iter().any(|p| !p.is_finite()) { + return Err(EaseError::NotFinite("path point")); + } + let n = anchors.len(); + let at = |i: usize| anchors.get(i).copied().unwrap_or(Vec2::ZERO); + let handles = |i: usize| -> (Vec2, Vec2) { + let (a, p, c) = (at(i.saturating_sub(1)), at(i), at((i + 1).min(n - 1))); + let out = (c - a) * (1.0 / 6.0); + let h_in = if i > 0 && a == p { Vec2::ZERO } else { -out }; + let h_out = if i + 1 < n && c == p { Vec2::ZERO } else { out }; + (h_in, h_out) + }; + let mut points = Vec::with_capacity(3 * n - 2); + for i in 0..n { + let (h_in, h_out) = handles(i); + if i > 0 { + points.push(at(i) + h_in); + } + points.push(at(i)); + if i + 1 < n { + points.push(at(i) + h_out); + } + } + MotionPath::new(&points) + } + + /// The path's length. + pub fn length(&self) -> f64 { + self.length + } + + /// How many segments the path has. + pub fn segments(&self) -> usize { + self.segments.len() + } + + /// The segment holding distance `s` (clamped to the path) and the distance into it. + fn locate(&self, s: f64) -> Option<(&Segment, f64)> { + let i = self.segments.partition_point(|g| g.start <= s).saturating_sub(1); + let g = self.segments.get(i)?; + Some((g, s - g.start)) + } + + /// The segments at the ends (see the `ends` field). + fn ends(&self) -> Option<(&Segment, &Segment)> { + Some((self.segments.get(self.ends.0)?, self.segments.get(self.ends.1)?)) + } + + /// The point `s` along the path. Before the start and past the end it continues along the + /// path's direction there; NaN and −∞ give the start, and +∞ the end. + pub fn point_at_length(&self, s: f64) -> Vec2 { + let Some((first, last)) = self.ends() else { return Vec2::ZERO }; + if s.is_nan() || s <= 0.0 { + let s = if s.is_finite() { s } else { 0.0 }; + return first.p[0] + first.direction(0.0) * s; + } + if s >= self.length { + let past = if s.is_finite() { s - self.length } else { 0.0 }; + return last.p[3] + last.direction(1.0) * past; + } + match self.locate(s) { + Some((g, into)) if g.straight => { + let len = g.length(); + if len > 0.0 { g.p[0].lerp(g.p[3], into / len) } else { g.p[0] } + } + Some((g, into)) => g.point(g.param_at(into)), + None => first.p[0], + } + } + + /// The point `progress` of the way along the path (0 the start, 1 the end). + pub fn point_at(&self, progress: f64) -> Vec2 { + self.point_at_length(progress * self.length) + } + + /// The unit direction of travel `s` along the path (zero for a path of zero length). + pub fn direction_at_length(&self, s: f64) -> Vec2 { + let Some((first, last)) = self.ends() else { return Vec2::ZERO }; + if s.is_nan() || s <= 0.0 { + return first.direction(0.0); + } + if s >= self.length { + return last.direction(1.0); + } + match self.locate(s) { + Some((g, into)) => g.direction(g.param_at(into)), + None => Vec2::ZERO, + } + } +} diff --git a/crates/ease/src/sampled.rs b/crates/ease/src/sampled.rs new file mode 100644 index 0000000000..314613166f --- /dev/null +++ b/crates/ease/src/sampled.rs @@ -0,0 +1,203 @@ +//! [`SampledEase`]: an ease kept as a table of values. + +use crate::Vec2; +use crate::custom::{CustomEase, EasePoint, MAX_EASE_Y}; + +/// Most samples a sampled ease keeps (longer tables are thinned evenly). +pub const MAX_EASE_SAMPLES: usize = 1025; +/// Points of the custom curve a sampled ease becomes when edited (of [`crate::MAX_EASE_POINTS`]). +pub const POLYLINE_POINTS: usize = 48; +/// Longest source or ease id a sampled ease keeps. +const MAX_EASE_ID: usize = 64; +/// Longest name a sampled ease keeps. +const MAX_EASE_NAME: usize = 64; + +/// An ease as a table: `values[i]` is the eased progress at `t = i / (n - 1)`, read between +/// samples by linear interpolation, so evaluation is a constant-time function of `t`. It keeps +/// a name and where it came from (a source id, such as a plug-in's, and the ease's id there). +/// +/// Always valid, however it was made: 2 to [`MAX_EASE_SAMPLES`] finite values within +/// ±[`MAX_EASE_Y`], starting at exactly 0 and ending at exactly 1. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(from = "SampledEaseFile"))] +pub struct SampledEase { + name: String, + plugin: String, + ease: String, + values: Vec, +} + +#[cfg(feature = "serde")] +#[derive(serde::Deserialize)] +struct SampledEaseFile { + #[serde(default, deserialize_with = "read_name")] + name: String, + #[serde(default, deserialize_with = "read_id")] + plugin: String, + #[serde(default, deserialize_with = "read_id")] + ease: String, + #[serde(default, deserialize_with = "read_values")] + values: Vec, +} + +/// Most values read from a file's list; the rest are skipped. +#[cfg(feature = "serde")] +const MAX_SAMPLE_INPUT: usize = 65_536; + +#[cfg(feature = "serde")] +fn read_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + crate::read_cleaned(d, |s| ease_name(s).unwrap_or_default()) +} + +#[cfg(feature = "serde")] +fn read_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + crate::read_cleaned(d, ease_id) +} + +#[cfg(feature = "serde")] +fn read_values<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + crate::read_first(d, MAX_SAMPLE_INPUT) +} + +#[cfg(feature = "serde")] +impl From for SampledEase { + fn from(f: SampledEaseFile) -> SampledEase { + SampledEase::new(&f.name, &f.plugin, &f.ease, f.values) + } +} + +/// An id as a sampled ease keeps it: `[A-Za-z0-9._-]`, at most [`MAX_EASE_ID`] characters. +fn ease_id(s: &str) -> String { + s.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')).take(MAX_EASE_ID).collect() +} + +/// A name as kept: control characters, bidirectional overrides and invisible format characters +/// (zero-width spaces and joiners, word joiners, the byte-order mark, soft hyphens) removed, +/// trimmed, at most [`MAX_EASE_NAME`] characters; `None` when nothing is left. +fn ease_name(name: &str) -> Option { + let n: String = name + .chars() + .filter(|c| { + !c.is_control() + && !matches!( + c, + '\u{ad}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}' + ) + }) + .skip_while(|c| c.is_whitespace()) + .take(MAX_EASE_NAME) + .collect(); + let n = n.trim().to_string(); + (!n.is_empty()).then_some(n) +} + +/// The index of the `k`th of [`MAX_EASE_SAMPLES`] samples spread evenly over `n` values, +/// computed in 128 bits so a long table cannot overflow a 32-bit `usize`. +pub(crate) fn thinned(k: usize, n: usize) -> usize { + let i = (k as u128) * (n.saturating_sub(1) as u128) / ((MAX_EASE_SAMPLES - 1) as u128); + usize::try_from(i).unwrap_or(usize::MAX) +} + +impl SampledEase { + /// A valid table from any values (see the type's docs): a longer table is thinned evenly, a + /// value that is not finite becomes the straight line's, values are clamped, the ends pinned; + /// fewer than two values make the straight line. + pub fn new(name: &str, plugin: &str, ease: &str, mut values: Vec) -> SampledEase { + if values.len() > MAX_EASE_SAMPLES { + let n = values.len(); + values = (0..MAX_EASE_SAMPLES).filter_map(|k| values.get(thinned(k, n)).copied()).collect(); + } + if values.len() < 2 { + values = vec![0.0, 1.0]; + } + let last = (values.len() - 1) as f64; + for (i, v) in values.iter_mut().enumerate() { + *v = if v.is_finite() { v.clamp(-MAX_EASE_Y, MAX_EASE_Y) } else { i as f64 / last }; + } + if let Some(v) = values.first_mut() { + *v = 0.0; + } + if let Some(v) = values.last_mut() { + *v = 1.0; + } + SampledEase { name: ease_name(name).unwrap_or_else(|| "Sampled ease".to_string()), plugin: ease_id(plugin), ease: ease_id(ease), values } + } + + /// The name an ease menu shows. + pub fn name(&self) -> &str { + &self.name + } + /// The id of the source it came from. + pub fn plugin(&self) -> &str { + &self.plugin + } + /// Its id within that source. + pub fn ease(&self) -> &str { + &self.ease + } + pub fn values(&self) -> &[f64] { + &self.values + } + + /// A table a caller supplies, checked: an error for a value that is not finite or outside + /// ±[`MAX_EASE_Y`], fewer than 2 values or more than [`MAX_EASE_SAMPLES`]. The ends are then + /// pinned to 0 and 1 as [`SampledEase::new`] does. + pub fn try_new(name: &str, plugin: &str, ease: &str, values: Vec) -> Result { + for v in &values { + crate::within(*v, -MAX_EASE_Y, MAX_EASE_Y, "sample")?; + } + if values.len() < 2 { + return Err(crate::EaseError::TooFew { what: "a sampled ease", need: 2 }); + } + if values.len() > MAX_EASE_SAMPLES { + return Err(crate::EaseError::Full(MAX_EASE_SAMPLES)); + } + Ok(SampledEase::new(name, plugin, ease, values)) + } + + /// The eased value at time `t`, between the two nearest samples. `t` outside `0..=1` is + /// clamped, and NaN reads as 0. + pub fn apply(&self, t: f64) -> f64 { + let t = if t.is_finite() { + t.clamp(0.0, 1.0) + } else if t > 0.0 { + 1.0 + } else { + 0.0 + }; + let last = self.values.len().saturating_sub(1); + if last == 0 { + return t; + } + let x = t * last as f64; + let i = (x.floor() as usize).min(last - 1); + let f = x - i as f64; + let (a, b) = (self.values.get(i).copied().unwrap_or(0.0), self.values.get(i + 1).copied().unwrap_or(1.0)); + a + (b - a) * f + } + + /// The custom curve of straight segments through [`POLYLINE_POINTS`] of its samples, for a + /// graph editor: editing a sampled ease makes it a custom ease drawn like it, with room left + /// to add points. + pub fn to_polyline(&self) -> CustomEase { + let n = self.values.len(); + let m = POLYLINE_POINTS.min(n).max(2); + let at: Vec = (0..m) + .map(|k| { + let i = k * (n - 1) / (m - 1); + Vec2::new(i as f64 / (n - 1).max(1) as f64, self.values.get(i).copied().unwrap_or(0.0)) + }) + .collect(); + let pts = at + .iter() + .enumerate() + .map(|(k, p)| { + let prev = if k == 0 { *p } else { at.get(k - 1).copied().unwrap_or(*p) }; + let next = at.get(k + 1).copied().unwrap_or(*p); + EasePoint { at: *p, h_in: (prev - *p) * (1.0 / 3.0), out: (next - *p) * (1.0 / 3.0), smooth: false } + }) + .collect(); + CustomEase::new(pts) + } +} diff --git a/crates/ease/src/spring.rs b/crates/ease/src/spring.rs new file mode 100644 index 0000000000..f50dedec43 --- /dev/null +++ b/crates/ease/src/spring.rs @@ -0,0 +1,247 @@ +//! Damped springs: [`Spring`] and [`SpringState`]. +//! +//! A spring pulls a value `x` toward a target with +//! +//! ```text +//! x'' = −ω² (x − target) − 2ζω x' +//! ``` +//! +//! where `ω` is the natural angular frequency and `ζ` the damping ratio (below 1 the value +//! overshoots and swings back, at 1 it arrives as fast as it can without overshooting, above 1 +//! it creeps in). [`SpringState::step`] moves the value by the exact solution of that equation +//! over the step, so a step costs O(1), any step length is stable, and many short steps give the +//! same value as one long one. + +use crate::{EaseError, within}; + +/// Highest natural frequency a spring may have, in swings per second. +pub const MAX_SPRING_HZ: f64 = 10_000.0; +/// Highest damping ratio a spring may have. +pub const MAX_DAMPING_RATIO: f64 = 1e6; +/// The ranges [`Spring::from_physical`] accepts: mass, stiffness and damping coefficient. +const MASS: (f64, f64) = (0.01, 1e4); +const STIFFNESS: (f64, f64) = (0.01, 1e6); +const DAMPING: (f64, f64) = (0.0, 1e6); +/// Longest motion a spring ease plays, in seconds of the spring's own time. +const MAX_SETTLE: f64 = 10.0; + +/// A damped spring's constants. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Spring { + omega: f64, + zeta: f64, +} + +impl Spring { + /// A spring that would swing `frequency` times a second without damping, with damping ratio + /// `damping`. `frequency` must be above 0 and at most [`MAX_SPRING_HZ`], `damping` within 0 + /// to [`MAX_DAMPING_RATIO`]. + pub fn new(frequency: f64, damping: f64) -> Result { + let f = within(frequency, 0.0, MAX_SPRING_HZ, "frequency")?; + if f <= 0.0 { + return Err(EaseError::OutOfRange { what: "frequency", min: f64::MIN_POSITIVE, max: MAX_SPRING_HZ }); + } + let z = within(damping, 0.0, MAX_DAMPING_RATIO, "damping")?; + Ok(Spring::raw(f, z)) + } + + /// A spring from two `0..=1` controls: `strength` sets the frequency from 0.5 to 10 swings a + /// second, evenly spread in pitch, and `damping` the ratio (0 swings on, 2/3 is critical, + /// 1 gives [`MAX_DAMPING_RATIO`]). + pub fn from_controls(strength: f64, damping: f64) -> Result { + let s = within(strength, 0.0, 1.0, "strength")?; + let d = within(damping, 0.0, 1.0, "damping")?; + let zeta = if d >= 1.0 { MAX_DAMPING_RATIO } else { (0.5 * d / (1.0 - d)).min(MAX_DAMPING_RATIO) }; + Ok(Spring::raw(0.5 * 20f64.powf(s), zeta)) + } + + /// A mass on a spring with damping: `mass` within 0.01 to 10,000, `stiffness` within 0.01 + /// to 1,000,000 and the damping coefficient `damping` within 0 to 1,000,000. An error when + /// the three give a damping ratio above [`MAX_DAMPING_RATIO`]. + pub fn from_physical(mass: f64, stiffness: f64, damping: f64) -> Result { + let m = within(mass, MASS.0, MASS.1, "mass")?; + let k = within(stiffness, STIFFNESS.0, STIFFNESS.1, "stiffness")?; + let c = within(damping, DAMPING.0, DAMPING.1, "damping")?; + if c / (2.0 * (k * m).sqrt()) > MAX_DAMPING_RATIO { + return Err(EaseError::OutOfRange { what: "damping ratio", min: 0.0, max: MAX_DAMPING_RATIO }); + } + Ok(Spring::physical(m, k, c)) + } + + /// [`Spring::from_physical`] with each value brought into its range (a value that is not + /// finite takes the default: mass 1, stiffness 100, damping 15). + pub(crate) fn physical_lenient(mass: f64, stiffness: f64, damping: f64) -> Spring { + let ok = |v: f64, (lo, hi): (f64, f64), d: f64| if v.is_finite() { v.clamp(lo, hi) } else { d }; + Spring::physical(ok(mass, MASS, 1.0), ok(stiffness, STIFFNESS, 100.0), ok(damping, DAMPING, 15.0)) + } + + fn physical(m: f64, k: f64, c: f64) -> Spring { + Spring { omega: (k / m).sqrt(), zeta: (c / (2.0 * (k * m).sqrt())).min(MAX_DAMPING_RATIO) } + } + + /// A spring from values already in range. + pub(crate) fn raw(frequency: f64, damping: f64) -> Spring { + Spring { omega: std::f64::consts::TAU * frequency, zeta: damping } + } + + /// Seconds until a spring released from rest stays within about 0.1 % of its target, at + /// least 0.05 and at most 10. + pub fn settle_time(&self) -> f64 { + let (w, z) = (self.omega, self.zeta); + // The slowest mode's decay rate; e^−6.9 is 0.1 %, and a critically or over-damped + // spring's larger lead factor needs about 9.2. Released from rest, an under-damped + // spring's offset stays within e^−ζωt · min(1/√(1 − ζ²), 1 + ζωt), so its lead factor + // grows by ln(1/√(1 − ζ²)) up to the critical spring's 9.2. + let (rate, k) = if z < 1.0 { (z * w, (6.9 - 0.5 * (1.0 - z * z).ln()).min(9.2)) } else { (w / (z + (z * z - 1.0).sqrt()), 9.2) }; + let settle = if rate > 1e-6 { (k / rate).clamp(0.05, MAX_SETTLE) } else { MAX_SETTLE }; + if settle.is_finite() { settle } else { MAX_SETTLE } + } + + /// The spring as an ease: released from rest at 0 toward 1, `t` of the way through its + /// [`Spring::settle_time`]. Exactly 0 at `t <= 0` and exactly 1 at `t >= 1`. A spring with + /// so little damping that it is still moving after 10 seconds has the distance it is still + /// off at that point taken out evenly over the ease, so it reaches 1 without a jump. + pub fn ease(&self, t: f64) -> f64 { + if t.is_nan() || t <= 0.0 { + return 0.0; + } + if t >= 1.0 { + return 1.0; + } + let settle = self.settle_time(); + let mut x = 1.0 + self.response(-1.0, 0.0, t * settle).0; + if settle >= MAX_SETTLE { + x -= t * self.response(-1.0, 0.0, settle).0; + } + if x.is_finite() { x } else { 1.0 } + } + + /// The natural angular frequency `ω`, in radians a second. + pub fn omega(&self) -> f64 { + self.omega + } + + /// The damping ratio `ζ`. + pub fn damping(&self) -> f64 { + self.zeta + } + + /// Offset and velocity `(y, v)` after `t` seconds, from offset `y0` (value minus target) and + /// velocity `v0`: the exact solution of the spring equation. + pub(crate) fn response(&self, y0: f64, v0: f64, t: f64) -> (f64, f64) { + let (w, z) = (self.omega, self.zeta); + if t <= 0.0 { + return (y0, v0); + } + // Past this much decay e^(−decay) is below the smallest f64: the spring has settled. + const SETTLED: f64 = 800.0; + // Damping ratios near 1 use the under- and over-damped solutions below, which stay + // precise there, so every ratio is solved as given; only exactly 1 is critical. + if z == 1.0 { + if w * t > SETTLED { + return (0.0, 0.0); + } + let b = v0 + w * y0; + let e = (-w * t).exp(); + // The velocity is e^−ωt (v0 − ω b t), written so v0 is not recovered by subtracting + // the rounded position terms. + return (e * (y0 + b * t), e * (v0 - w * (b * t))); + } + if z < 1.0 { + if z * w * t > SETTLED { + return (0.0, 0.0); + } + // 1 − ζ² as (1 − ζ)(1 + ζ), precise for ζ near 1. + let wd = w * ((1.0 - z) * (1.0 + z)).sqrt(); + let q = v0 + z * w * y0; + let e = (-z * w * t).exp(); + // A step so long that the phase overflows (a spring with little or no damping) is + // reduced by whole periods first. + let reduced = !(wd * t).is_finite(); + let phase = if reduced { wd * (t % (std::f64::consts::TAU / wd)) } else { wd * t }; + let (s, c) = phase.sin_cos(); + // sin(phase) / ωd is at most t, so it stays finite for a spring of any low frequency, + // where q / ωd alone would overflow. A small unreduced phase uses t · sin(phase) / phase + // from its series, which is t when ωd or the phase rounds to 0. + let sw = if !reduced && phase < 1e-4 { + let p2 = phase * phase; + t * (1.0 - p2 / 6.0 * (1.0 - p2 / 20.0)) + } else { + s / wd + }; + return (e * (y0 * c + q * sw), e * (v0 * c - (y0 * wd * s + z * w * q * sw))); + } + // ζ² − 1 as (ζ − 1)(ζ + 1), precise for ζ near 1. + let root = ((z - 1.0) * (z + 1.0)).sqrt(); + // r1 = −ω(ζ − √(ζ² − 1)), written without the cancellation for large ζ. + let (r1, r2) = (-w / (z + root), -w * (z + root)); + if -r1 * t > SETTLED { + return (0.0, 0.0); + } + // Written with the divided difference q = (e1 − e2) / (r1 − r2) rather than the two modes' + // coefficients, which overflow (in opposite signs) when r1 − r2 is tiny. + let (e1, e2) = ((r1 * t).exp(), (r2 * t).exp()); + let x = (r1 - r2) * t; + let q = if x <= 1.0 { + // e2 · t · (e^x − 1) / x, with its series where x is too small for expm1's quotient. + let g = if x < 1e-5 { 1.0 + x * (0.5 + x / 6.0) } else { x.exp_m1() / x }; + e2 * t * g + } else { + (e1 - e2) / (r1 - r2) + }; + (y0 * (e1 - r1 * q) + v0 * q, v0 * (e2 + r1 * q) - y0 * (w * w) * q) + } +} + +/// A value moved by a spring: where it is and how fast it moves. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct SpringState { + pub value: f64, + pub velocity: f64, +} + +impl SpringState { + /// A value at rest at `value`. + pub fn at(value: f64) -> SpringState { + SpringState { value, velocity: 0.0 } + } + + /// Moves the value `dt` seconds toward `target` (which holds still over the step) and + /// returns the new value. An error, with the state unchanged, for a `target` or `dt` that is + /// not finite, a negative `dt`, or a result too large to represent. A state whose value or + /// velocity is not finite is refused with [`EaseError::Overflow`] at every step length, and + /// stays as it is. + pub fn step(&mut self, spring: &Spring, target: f64, dt: f64) -> Result { + let target = crate::finite(target, "target")?; + let dt = within(dt, 0.0, f64::MAX, "step")?; + if !(self.value.is_finite() && self.velocity.is_finite()) { + return Err(EaseError::Overflow); + } + if dt == 0.0 { + return Ok(self.value); + } + let (y, v) = spring.response(self.value - target, self.velocity, dt); + let (mut value, mut v) = (target + y, v); + if !(value.is_finite() && v.is_finite()) { + // The motion is linear in the offset and velocity, so they are moved again scaled by + // a power of two to at most 2, for a value and target near opposite ends of the f64 + // range whose step overflowed on the way. + let (hy, hv) = (0.5 * self.value - 0.5 * target, 0.5 * self.velocity); + let m = hy.abs().max(hv.abs()); + let scale = if m > 0.0 && m.is_finite() { 2f64.powi((m.log2().ceil() as i32).min(1023)) } else { 1.0 }; + let (y, w) = spring.response(hy / scale, hv / scale, dt); + (value, v) = (2.0 * (0.5 * target + y * scale), 2.0 * (w * scale)); + } + if !(value.is_finite() && v.is_finite()) { + return Err(EaseError::Overflow); + } + *self = SpringState { value, velocity: v }; + Ok(value) + } + + /// Whether the value is within `tolerance` of `target` and moves slower than `tolerance` + /// a second. + pub fn settled(&self, target: f64, tolerance: f64) -> bool { + (self.value - target).abs() <= tolerance && self.velocity.abs() <= tolerance + } +} diff --git a/crates/ease/src/tests/easing_tests.rs b/crates/ease/src/tests/easing_tests.rs new file mode 100644 index 0000000000..96a21a004a --- /dev/null +++ b/crates/ease/src/tests/easing_tests.rs @@ -0,0 +1,1014 @@ +use crate::*; +use std::sync::Arc; + +fn all() -> Vec { + let mut v: Vec = Easing::named().collect(); + v.extend([Easing::Classic(-60.0), Easing::Classic(100.0), Easing::CubicBezier(0.25, 0.1, 0.25, 1.0), Easing::Custom(Arc::new(wave()))]); + v +} + +/// Every ease kind, values included. +fn every_kind() -> Vec { + let mut v = all(); + v.extend([Easing::Hold, Easing::Spring(SpringEase::GENTLE), Easing::Sampled(Arc::new(steps()))]); + v +} + +/// Three segments that overshoot both ways. +fn wave() -> CustomEase { + CustomEase::from_flat( + &[(0.0, 0.0), (0.1, 0.6), (0.2, 1.3), (0.3, 1.3), (0.4, 1.3), (0.5, -0.2), (0.6, 0.4), (0.7, 1.0), (0.9, 1.0), (1.0, 1.0)] + .map(|(x, y)| Vec2::new(x, y)), + ) + .unwrap() +} + +#[test] +fn a_narrow_custom_segment_is_evaluated_not_skipped() { + let d = 1e-10; + let e = CustomEase::from_flat( + &[ + (0.0, 0.0), + (0.1, 0.0), + (0.4, 0.0), + (0.5, 0.0), + (0.5 + d / 3.0, 1.0 / 3.0), + (0.5 + 2.0 * d / 3.0, 2.0 / 3.0), + (0.5 + d, 1.0), + (0.6, 1.0), + (0.9, 1.0), + (1.0, 1.0), + ] + .map(|(x, y)| Vec2::new(x, y)), + ) + .unwrap(); + let mid = e.apply(0.5 + d / 2.0); + assert!((mid - 0.5).abs() < 0.05, "{mid}"); +} + +/// Four steps, as a stepped ease samples them. +fn steps() -> SampledEase { + SampledEase::new("Stepped 4", "org.example.stepped-ease", "steps4", (0..257).map(|i| ((i as f64 / 256.0) * 4.0).floor() / 4.0).collect()) +} + +#[test] +fn endpoints_are_exact() { + for e in every_kind() { + assert_eq!(e.apply(0.0), 0.0, "{e:?}"); + assert_eq!(e.apply(1.0), 1.0, "{e:?}"); + assert_eq!(e.apply(-0.0), 0.0, "{e:?}"); + assert_eq!(e.apply(-5.0), 0.0, "{e:?}"); + assert_eq!(e.apply(5.0), 1.0, "{e:?}"); + assert_eq!(e.apply(f64::NEG_INFINITY), 0.0, "{e:?}"); + assert_eq!(e.apply(f64::INFINITY), 1.0, "{e:?}"); + assert_eq!(e.apply(f64::NAN), 0.0, "{e:?}"); + } +} + +#[test] +fn presets_at_known_times() { + use std::f64::consts::{FRAC_1_SQRT_2, PI}; + let cases: [(Easing, f64, f64); 22] = [ + (Easing::Linear, 0.3, 0.3), + (Easing::QuadIn, 0.5, 0.25), + (Easing::QuadOut, 0.5, 0.75), + (Easing::QuadInOut, 0.25, 0.125), + (Easing::CubicIn, 0.5, 0.125), + (Easing::CubicOut, 0.5, 0.875), + (Easing::QuartIn, 0.5, 0.0625), + (Easing::QuartInOut, 0.75, 0.96875), + (Easing::QuintIn, 0.5, 0.03125), + (Easing::QuintOut, 0.5, 0.96875), + (Easing::SineIn, 0.5, 1.0 - FRAC_1_SQRT_2), + (Easing::SineOut, 1.0 / 3.0, 0.5), + (Easing::SineInOut, 0.25, 0.5 * (1.0 - FRAC_1_SQRT_2)), + // (c + 1)/8 − c/4 with c = 1.70158: dips below zero first. + (Easing::BackIn, 0.5, -0.087_697_5), + (Easing::BackOut, 0.5, 1.087_697_5), + (Easing::CircIn, 0.6, 0.2), + (Easing::CircOut, 0.5, 0.866_025_403_784_438_6), + (Easing::BounceOut, 0.5, 0.765_625), + (Easing::BounceIn, 0.5, 0.234_375), + (Easing::BounceOut, 1.0 / 2.75, 1.0), + // −2⁻⁵ · sin(−5.75 · 2π/3) = −1/64; Out is its mirror. + (Easing::ElasticIn, 0.5, -0.015_625), + (Easing::ElasticOut, 0.5, 1.015_625), + ]; + for (e, t, want) in cases { + assert!((e.apply(t) - want).abs() < 1e-9, "{e:?} at {t}: {} vs {want}", e.apply(t)); + } + assert!((Easing::Classic(-100.0).apply(0.5) - 0.25).abs() < 1e-12); + assert!((Easing::Classic(100.0).apply(0.5) - 0.75).abs() < 1e-12); + assert!((Easing::SineIn.apply(1.0 / 3.0) - (1.0 - (PI / 6.0).cos())).abs() < 1e-12); +} + +/// Back and Elastic In Out follow the published In Out equations, which are not In's halves. +#[test] +fn back_and_elastic_in_out_follow_the_published_equations() { + for (e, t, want) in [ + (Easing::BackInOut, 0.25, -0.099_68), + (Easing::BackInOut, 0.75, 1.099_68), + (Easing::ElasticInOut, 0.25, 0.011_97), + (Easing::ElasticInOut, 0.4, -0.117_46), + (Easing::ElasticInOut, 0.75, 0.988_03), + ] { + assert!((e.apply(t) - want).abs() < 5e-6, "{e:?} at {t}: {}", e.apply(t)); + } + // Back In Out: ((2t)²((c+1)2t − c))/2 with c = 1.70158 × 1.525. + let c = 1.701_58 * 1.525; + for k in 1..20 { + let t = k as f64 / 40.0; + let want = (2.0 * t).powi(2) * ((c + 1.0) * 2.0 * t - c) / 2.0; + assert!((Easing::BackInOut.apply(t) - want).abs() < 1e-12, "{t}"); + } +} + +#[test] +fn out_mirrors_in_and_in_out_is_symmetric() { + for f in EaseFamily::ALL { + let (i, o, io) = (Easing::preset(f, EaseDir::In), Easing::preset(f, EaseDir::Out), Easing::preset(f, EaseDir::InOut)); + for k in 0..=40 { + let t = k as f64 / 40.0; + assert!((o.apply(t) - (1.0 - i.apply(1.0 - t))).abs() < 1e-12, "{f:?} at {t}"); + assert!((io.apply(t) + io.apply(1.0 - t) - 1.0).abs() < 1e-12, "{f:?} at {t}"); + // In Out is In's halves for every family but Back and Elastic. + if !matches!(f, EaseFamily::Back | EaseFamily::Elastic) { + assert!((io.apply(t * 0.5) - 0.5 * i.apply(t)).abs() < 1e-12, "{f:?} at {t}"); + } + } + assert_eq!(Easing::preset(f, EaseDir::In).family(), Some((f, EaseDir::In))); + } +} + +#[test] +fn monotonic_families_never_turn_back_and_the_others_overshoot() { + for e in all() { + let overshoots = matches!(e.family(), Some((EaseFamily::Back | EaseFamily::Elastic, _))) || e.custom().is_some(); + // Bounce turns back (off the floor) without leaving 0..1. + let turns = overshoots || matches!(e.family(), Some((EaseFamily::Bounce, _))); + let (mut lo, mut hi, mut prev, mut turned) = (0.0f64, 1.0f64, -1e-6f64, false); + for i in 0..=400 { + let v = e.apply(i as f64 / 400.0); + turned |= v < prev - 1e-4; + prev = v; + lo = lo.min(v); + hi = hi.max(v); + } + assert_eq!(turned, turns, "{e:?}"); + assert_eq!(lo < -1e-3 || hi > 1.0 + 1e-3, overshoots, "{e:?}: {lo}..{hi}"); + } +} + +/// The eases meant to be monotonic never step backwards on a fine grid, not even by rounding. +#[test] +fn monotonic_eases_are_non_decreasing_everywhere() { + let mut eases: Vec = [EaseFamily::Quad, EaseFamily::Cubic, EaseFamily::Quart, EaseFamily::Quint, EaseFamily::Sine, EaseFamily::Circ] + .into_iter() + .flat_map(|f| EaseDir::ALL.map(|d| Easing::preset(f, d))) + .collect(); + eases.extend([ + Easing::Linear, + Easing::Hold, + Easing::Classic(-100.0), + Easing::Classic(37.0), + Easing::Classic(100.0), + Easing::SMOOTH, + Easing::CubicBezier(1.0, 0.0, 0.0, 1.0), + Easing::CubicBezier(0.0, 1.0, 1.0, 0.0), + Easing::CubicBezier(0.9, 0.0, 0.1, 1.0), + ]); + eases.push(Easing::from_temporal(TemporalEase::EASY, TemporalEase::EASY).unwrap()); + eases.push(Easing::from_temporal(TemporalEase { speed: 0.0, influence: 1.0 }, TemporalEase { speed: 0.0, influence: 1.0 }).unwrap()); + eases.push(Easing::Spring(SpringEase { mass: 1.0, stiffness: 100.0, damping: 40.0 })); + for e in eases { + let mut prev = 0.0; + for i in 0..=20_000 { + let v = e.apply(i as f64 / 20_000.0); + assert!(v >= prev, "{e:?} steps back at {i}: {prev} → {v}"); + assert!((0.0..=1.0).contains(&v), "{e:?} leaves 0..1 at {i}: {v}"); + prev = v; + } + } +} + +#[test] +fn hostile_input_is_clamped() { + assert_eq!(Easing::Linear.apply(f64::NAN), 0.0); + assert_eq!(Easing::QuadIn.apply(5.0), 1.0); + assert_eq!(Easing::ElasticOut.apply(f64::INFINITY), 1.0); + assert!(Easing::CubicBezier(f64::NAN, 0.0, 1.0, 1.0).apply(0.5).is_finite()); + assert!(Easing::Classic(f64::INFINITY).apply(0.5).is_finite()); + assert!(Easing::Custom(Arc::new(wave())).apply(f64::NAN).is_finite()); + assert!(Easing::Spring(SpringEase { mass: f64::NAN, stiffness: -1.0, damping: f64::INFINITY }).apply(0.5).is_finite()); + // Huge handles are kept within ±MAX_EASE_Y when evaluated. + let wild = Easing::CubicBezier(0.5, 1e300, 0.5, -1e300); + for k in 0..=100 { + let v = wild.apply(k as f64 / 100.0); + assert!(v.abs() <= MAX_EASE_Y, "{k}: {v}"); + } + // Times next to the ends, and subnormal ones. + for e in all() { + for t in [f64::MIN_POSITIVE, 5e-324, 1e-300, 1.0 - f64::EPSILON / 2.0, 1.0 - 1e-16] { + assert!(e.apply(t).is_finite(), "{e:?} at {t}"); + } + } +} + +#[test] +fn checked_constructors_refuse_bad_values() { + assert!(Easing::cubic_bezier(0.2, 0.0, 0.8, 1.0).is_ok()); + assert_eq!(Easing::cubic_bezier(f64::NAN, 0.0, 0.8, 1.0), Err(EaseError::NotFinite("x1"))); + assert!(matches!(Easing::cubic_bezier(1.2, 0.0, 0.8, 1.0), Err(EaseError::OutOfRange { what: "x1", .. }))); + assert!(matches!(Easing::cubic_bezier(0.2, 0.0, -0.1, 1.0), Err(EaseError::OutOfRange { what: "x2", .. }))); + assert!(matches!(Easing::cubic_bezier(0.2, 11.0, 0.8, 1.0), Err(EaseError::OutOfRange { what: "y1", .. }))); + assert_eq!(Easing::cubic_bezier(0.2, 0.0, 0.8, f64::INFINITY), Err(EaseError::NotFinite("y2"))); + let ok = TemporalEase { speed: 0.0, influence: 0.5 }; + assert!(matches!( + Easing::from_temporal(TemporalEase { speed: 0.0, influence: 0.0 }, ok), + Err(EaseError::OutOfRange { what: "out influence", .. }) + )); + assert!(matches!( + Easing::from_temporal(ok, TemporalEase { speed: 0.0, influence: 1.5 }), + Err(EaseError::OutOfRange { what: "in influence", .. }) + )); + assert_eq!(Easing::from_temporal(TemporalEase { speed: f64::NAN, influence: 0.5 }, ok), Err(EaseError::NotFinite("out speed"))); + assert!(matches!(Easing::from_temporal(TemporalEase { speed: 1e6, influence: 0.5 }, ok), Err(EaseError::OutOfRange { .. }))); + assert!(Easing::spring(1.0, 100.0, 15.0).is_ok()); + assert!(matches!(Easing::spring(0.0, 100.0, 15.0), Err(EaseError::OutOfRange { what: "mass", .. }))); + assert_eq!(Easing::spring(1.0, f64::NAN, 15.0), Err(EaseError::NotFinite("stiffness"))); +} + +/// Sample values from a keyframe velocity dialog: two keys a second apart, both sides eased +/// with speed (units a second) and influence. The values are the ease's progress there. +#[test] +fn speed_and_influence_give_the_dialog_curves() { + for (out, into, samples) in [ + ( + TemporalEase { speed: 0.0, influence: 0.8 }, + TemporalEase { speed: 0.0, influence: 0.8 }, + [(0.1, 0.005_924_393_903_632_7), (0.25, 0.047_643_803_060_876_4), (0.4, 0.184_284_394_271_562), (0.75, 0.952_356_196_939_123)], + ), + ( + TemporalEase { speed: 0.2, influence: 0.8 }, + TemporalEase { speed: 0.8, influence: 0.6 }, + [(0.1, 0.022_575_494_262_157_7), (0.25, 0.069_984_188_941_293_1), (0.4, 0.149_334_636_959_052), (0.75, 0.738_196_785_378_389)], + ), + ( + TemporalEase { speed: 0.2, influence: 0.6 }, + TemporalEase { speed: 0.8, influence: 0.8 }, + [(0.1, 0.023_604_533_665_406), (0.25, 0.084_029_514_287_08), (0.4, 0.254_632_042_525_662), (0.75, 0.776_210_872_246_874)], + ), + ] { + let e = Easing::from_temporal(out, into).unwrap(); + for (t, want) in samples { + assert!((e.apply(t) - want).abs() < 1e-9, "{out:?} {into:?} at {t}: {} vs {want}", e.apply(t)); + } + let (o, i) = e.temporal().unwrap(); + assert!((o.speed - out.speed).abs() < 1e-12 && (o.influence - out.influence).abs() < 1e-12); + assert!((i.speed - into.speed).abs() < 1e-12 && (i.influence - into.influence).abs() < 1e-12); + } + // The straight line's speed with a third of influence on both sides is no ease. + let line = Easing::from_temporal(TemporalEase { speed: 1.0, influence: 1.0 / 3.0 }, TemporalEase { speed: 1.0, influence: 1.0 / 3.0 }).unwrap(); + for k in 0..=20 { + let t = k as f64 / 20.0; + assert!((line.apply(t) - t).abs() < 1e-12, "{t}"); + } + // Easy ease is symmetric and slow at its ends. + let easy = Easing::from_temporal(TemporalEase::EASY, TemporalEase::EASY).unwrap(); + assert!((easy.apply(0.5) - 0.5).abs() < 1e-12); + assert!(easy.apply(0.1) > 0.0 && easy.apply(0.1) < 0.1); +} + +/// Both handles at full influence leave the time curve flat halfway; the closed-form inverse +/// keeps that point exact. +#[test] +fn full_influence_is_solved_exactly_at_the_flat_midpoint() { + let e = Easing::from_temporal(TemporalEase { speed: 0.0, influence: 1.0 }, TemporalEase { speed: 0.0, influence: 1.0 }).unwrap(); + for t in [0.5 - 1e-9, 0.5 - 1e-12, 0.5, 0.5 + 1e-12, 0.5 + 1e-9, 0.1, 0.9] { + // x = 0.5 + 4 (u − 0.5)³ exactly, and y = bez(u, [0, 0, 1, 1]). + let u = 0.5 + ((t - 0.5) / 4.0f64).cbrt(); + let want = 3.0 * (1.0 - u) * u * u + u * u * u; + assert!((e.apply(t) - want).abs() < 1e-12, "{t}: {} vs {want}", e.apply(t)); + } +} + +/// The Bezier solver converges inside its step limit for any monotonic curve, to its tolerance. +#[test] +fn the_bezier_solver_converges_within_its_bound() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1_000_001) as f64 / 1_000_000.0 + }; + let mut worst = 0; + for _ in 0..20_000 { + let (x1, x2, t) = (rnd(), rnd(), rnd()); + let p = [0.0, x1, x2, 1.0]; + let (s, steps) = crate::solve_counted(t, p); + worst = worst.max(steps); + assert!(steps < crate::SOLVE_STEPS, "{p:?} at {t}"); + assert!((crate::bez(s, p) - t).abs() <= crate::SOLVE_TOLERANCE, "{p:?} at {t}: {}", crate::bez(s, p)); + } + // Near-flat curves, where Newton steps fail and halving takes over. + for (x1, x2) in [(1.0, 0.0), (0.999_999, 0.0), (1.0, 1e-9), (0.0, 1.0), (0.0, 0.0), (1.0, 1.0)] { + for k in 0..=1000 { + let t = k as f64 / 1000.0; + let p = [0.0, x1, x2, 1.0]; + let (s, steps) = crate::solve_counted(t, p); + assert!(steps < crate::SOLVE_STEPS && (crate::bez(s, p) - t).abs() <= crate::SOLVE_TOLERANCE, "{p:?} at {t}: {steps} steps"); + } + } + assert!(worst <= 20, "{worst} steps"); + // A narrow segment far from 0, where the curve's x values differ only in their last bits: + // x(s) = a + span s³, so the query halfway across the span is at s = 0.5^(1/3). + let (a, span) = (0.5, 2f64.powi(-52)); + let p = [a, a, a, a + span]; + let s = crate::solve_monotonic(a + span / 2.0, p); + assert!((s - 0.5f64.cbrt()).abs() < 1e-9, "{s}"); +} + +/// A handle so short that its speed overflows has no speed and influence form. +#[test] +fn a_handle_too_short_for_a_finite_speed_has_no_temporal_form() { + assert_eq!(Easing::CubicBezier(f64::from_bits(1), 1.0, 0.5, 0.5).temporal(), None); + assert!(Easing::CubicBezier(0.0, 0.0, 1.0, 1.0).temporal().is_some()); +} + +/// A Bezier with a handle past ±MAX_EASE_Y plays the same curve the graph editor shows for it. +#[test] +fn a_bezier_plays_the_curve_its_custom_form_draws() { + for e in [Easing::CubicBezier(0.3, 20.0, 0.6, 1.0), Easing::CubicBezier(0.3, -1e30, 0.6, 1e30)] { + let c = e.to_custom(); + for k in 0..=40 { + let t = k as f64 * 0.025; + assert!((e.apply(t) - c.apply(t)).abs() < 1e-5, "{e:?} at {t}: {} vs {}", e.apply(t), c.apply(t)); + } + } +} + +/// Any speed and influence a caller can supply either is refused or plays a finite curve. +#[test] +fn speed_and_influence_over_their_whole_range_play_finite_curves() { + let mut seed = 0x51_7cc1_b727_220au64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1_000_001) as f64 / 1_000_000.0 + }; + let mut accepted = 0; + for _ in 0..20_000 { + // Speeds from 1e-4 to 1e4 either way, spread evenly in magnitude. + let side = |r: f64, i: f64| TemporalEase { + speed: (r - 0.5).signum() * 10f64.powf((r - 0.5).abs() * 16.0 - 4.0), + influence: MIN_INFLUENCE + i * (1.0 - MIN_INFLUENCE), + }; + let (out, into) = (side(rnd(), rnd()), side(rnd(), rnd())); + let Ok(e) = Easing::from_temporal(out, into) else { continue }; + accepted += 1; + for k in 0..=20 { + let v = e.apply(k as f64 / 20.0); + assert!(v.is_finite() && v.abs() <= MAX_EASE_Y, "{out:?} {into:?}: {v}"); + } + } + assert!(accepted > 5_000, "{accepted}"); +} + +/// Eases, tracks and paths can be shared between render and export threads. +#[test] +fn the_types_are_send_and_sync() { + fn check() {} + check::(); + check::>(); + check::>(); + check::(); + check::(); + check::(); +} + +#[test] +fn bezier_forms_draw_the_same_curves() { + // Exact for these. + for e in [ + Easing::Linear, + Easing::QuadIn, + Easing::QuadOut, + Easing::CubicIn, + Easing::CubicOut, + Easing::BackIn, + Easing::BackOut, + Easing::Classic(-60.0), + Easing::Classic(100.0), + Easing::CubicBezier(0.2, 1.4, 0.6, -0.3), + ] { + let (a, b, c, d) = e.as_bezier().unwrap(); + let bez = Easing::CubicBezier(a, b, c, d); + for i in 0..=20 { + let t = i as f64 / 20.0; + assert!((e.apply(t) - bez.apply(t)).abs() < 1e-9, "{e:?} at {t}"); + } + } + for e in [Easing::QuadInOut, Easing::CubicInOut] { + let (a, b, c, d) = e.as_bezier().unwrap(); + let bez = Easing::CubicBezier(a, b, c, d); + assert!((0..=20).all(|i| (e.apply(i as f64 / 20.0) - bez.apply(i as f64 / 20.0)).abs() < 0.08), "{e:?}"); + } + // One curve can't draw a bounce, a hold or a multi-segment ease. + assert_eq!(Easing::BounceOut.as_bezier(), None); + assert_eq!(Easing::Hold.as_bezier(), None); + assert_eq!(Easing::Custom(Arc::new(wave())).as_bezier(), None); + let one = Easing::Custom(Arc::new(CustomEase::from_bezier(0.1, 0.9, 0.3, 1.2))); + let (a, b, c, d) = one.as_bezier().unwrap(); + assert!((a - 0.1).abs() < 1e-15 && (b - 0.9).abs() < 1e-15 && (c - 0.3).abs() < 1e-15 && (d - 1.2).abs() < 1e-15); +} + +#[test] +fn every_preset_becomes_a_custom_curve_for_the_graph() { + for e in all() { + let c = e.to_custom(); + assert!(c.points().len() <= MAX_EASE_POINTS, "{e:?}"); + let exact = + matches!(e.family(), Some((EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce, _))) || e.family().is_none(); + let tol = if exact { 2e-4 } else { 5e-3 }; + let mut worst = 0.0f64; + for i in 0..=500 { + let t = i as f64 / 500.0; + worst = worst.max((c.apply(t) - e.apply(t)).abs()); + } + assert!(worst < tol, "{e:?}: off by {worst} with {} points", c.points().len()); + } + // A hold stays flat until a jump at the end; a spring is its polyline. + let h = Easing::Hold.to_custom(); + for t in [1e-9, 0.25, 0.5, 0.9, 0.999_999] { + assert_eq!(h.apply(t), Easing::Hold.apply(t), "{t}"); + } + assert_eq!(h.apply(1.0), 1.0); + let s = Easing::Spring(SpringEase::GENTLE); + let sc = s.to_custom(); + assert_eq!(sc.points().len(), POLYLINE_POINTS); + assert!((0..=100).all(|i| (sc.apply(i as f64 / 100.0) - s.apply(i as f64 / 100.0)).abs() < 0.02)); +} + +#[test] +fn ease_in_is_slow_at_start() { + assert!(Easing::QuadIn.apply(0.25) < 0.25); + assert!(Easing::QuadOut.apply(0.25) > 0.25); + assert!(Easing::Classic(-100.0).apply(0.25) < 0.25); + assert!(Easing::Classic(100.0).apply(0.25) > 0.25); +} + +#[test] +fn hold_stays_at_the_start_until_the_end() { + for t in [1e-300, 0.25, 0.5, 0.999_999_999] { + assert_eq!(Easing::Hold.apply(t), 0.0); + } + assert_eq!(Easing::Hold.apply(1.0), 1.0); + assert_eq!(Easing::from_name("hold"), Some(Easing::Hold)); +} + +#[test] +fn names_round_trip_and_older_aliases_still_read() { + for e in Easing::named().chain([Easing::Hold]) { + let n = e.name().unwrap(); + assert_eq!(Easing::from_name(&n), Some(e.clone()), "{n}"); + // The file form is the same name. + #[cfg(feature = "serde")] + assert_eq!(serde_json::to_string(&e).unwrap(), format!("\"{n}\"")); + } + assert_eq!(Easing::from_name("back in-out"), Some(Easing::BackInOut)); + assert_eq!(Easing::from_name("ease_in"), Some(Easing::QuadIn)); + assert_eq!(Easing::from_name("Smooth"), Some(Easing::CubicBezier(0.25, 0.1, 0.25, 1.0))); + assert_eq!(Easing::from_name("wobble"), None); + // Separators do not count toward the longest name; a name longer than any preset is unknown. + assert_eq!(Easing::from_name(&format!("{}elastic in out{}", " ".repeat(10_000), "-".repeat(10_000))), Some(Easing::ElasticInOut)); + assert_eq!(Easing::from_name(&"x".repeat(100_000)), None); + assert_eq!(Easing::from_name("ElasticInOutX"), None); + assert_eq!(Easing::named().count(), 28); + assert_eq!(Easing::BounceInOut.label(), "Bounce In Out"); + // Files written with the variant names read back. + #[cfg(feature = "serde")] + { + let old: Vec = serde_json::from_str(r#"["QuadIn", {"Classic": 30.0}, {"CubicBezier": [0.1, 0.2, 0.3, 0.4]}, "Linear"]"#).unwrap(); + assert_eq!(old, [Easing::QuadIn, Easing::Classic(30.0), Easing::CubicBezier(0.1, 0.2, 0.3, 0.4), Easing::Linear]); + let spring: Easing = serde_json::from_str(r#"{"Spring": {"mass": 1.0, "stiffness": 600.0, "damping": 15.0}}"#).unwrap(); + assert_eq!(spring, Easing::Spring(SpringEase { mass: 1.0, stiffness: 600.0, damping: 15.0 })); + assert_eq!( + serde_json::to_string(&Easing::Spring(SpringEase::GENTLE)).unwrap(), + r#"{"Spring":{"mass":1.0,"stiffness":100.0,"damping":15.0}}"# + ); + } +} + +#[test] +fn a_multi_segment_curve_evaluates_continuously_through_its_points() { + let c = wave(); + assert_eq!(c.points().len(), 4); + for p in c.points() { + assert!((c.apply(p.at.x) - p.at.y).abs() < 1e-9 || p.at.x == 0.0, "{p:?}"); + } + let mut prev = c.apply(0.0); + for i in 1..=10_000 { + let v = c.apply(i as f64 / 10_000.0); + assert!((v - prev).abs() < 2e-3, "a jump at {i}: {prev} → {v}"); + prev = v; + } + // Rises past the end value, then falls back below where it was, as drawn. + assert!(c.apply(0.3) > 1.2 && c.apply(0.55) < 0.4); +} + +#[test] +fn adding_a_point_keeps_the_shape() { + let c = wave(); + let (d, i) = c.insert_at(0.42).unwrap(); + assert_eq!((d.points().len(), i), (5, 2)); + assert!(d.points()[2].smooth); + for k in 0..=200 { + let t = k as f64 / 200.0; + assert!((c.apply(t) - d.apply(t)).abs() < 1e-4, "at {t}"); + } + // Not at an end or on a point. + assert!(c.insert_at(0.0).is_none() && c.insert_at(1.0).is_none() && c.insert_at(0.3).is_none() && c.insert_at(f64::NAN).is_none()); +} + +/// Splitting a steep curve can put a piece's handle past that piece's other end in x; the piece +/// still runs forwards, so the handle is kept and the curve keeps its shape. +#[test] +fn adding_a_point_keeps_the_shape_where_the_pieces_handles_cross() { + let c = CustomEase::from_bezier(1.0, 0.0, 0.0, 1.0); + for t in [7.0 / 16.0, 0.2, 0.49, 0.51, 0.8] { + let (d, i) = c.insert_at(t).unwrap(); + assert_eq!(i, 1); + assert_forwards(&d); + // x is flat at 0.5, so a solve within 1e-12 in x is within about 1e-4 in y there. + assert!((d.apply(0.5) - 0.5).abs() < 2e-4, "{t}: {}", d.apply(0.5)); + for k in 0..=400 { + let u = k as f64 / 400.0; + let tol = if (u - 0.5).abs() > 0.05 { 1e-9 } else { 2e-4 }; + assert!((c.apply(u) - d.apply(u)).abs() < tol, "{t} at {u}: {} vs {}", c.apply(u), d.apply(u)); + } + // Removing the point again leaves a valid curve of one segment. + assert_forwards(&d.remove(1).unwrap()); + } + // A handle past the far end is kept only while x still runs forwards. + let one = |out_x: f64| { + CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, out: Vec2::new(out_x, 0.0), ..Default::default() }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-0.4, 0.0), ..Default::default() }, + ]) + }; + let (kept, cut) = (one(1.2), one(2.5)); + assert_eq!((kept.points()[0].out.x, cut.points()[0].out.x), (1.2, 1.0)); + assert_forwards(&kept); + assert_forwards(&cut); + // Such a curve is not a cubic-bezier() one, and from_bezier keeps x in the unit box. + assert_eq!(Easing::Custom(Arc::new(kept)).as_bezier(), None); + assert_eq!(Easing::Custom(Arc::new(cut)).as_bezier(), Some((1.0, 0.0, 0.6, 1.0))); + assert_eq!(CustomEase::from_bezier(1.2, 0.0, -0.1, 1.0).points()[0].out.x, 1.0); + assert_eq!(CustomEase::from_bezier(1.2, 0.0, -0.1, 1.0).points()[1].h_in.x, -1.0); +} + +/// A smooth point near the value limit has its handles shortened along their line, so they stay +/// in line. +#[test] +fn a_smooth_point_near_the_value_limit_keeps_its_handles_in_line() { + let c = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, ..Default::default() }, + EasePoint { at: Vec2::new(0.1, 9.9), ..Default::default() }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let s = c.set_smooth(1, true).unwrap(); + let p = s.points()[1]; + assert!(p.smooth && p.out.length() > 0.05 && p.h_in.length() > 0.01 && in_line(&p), "{p:?}"); + assert!(p.at.y + p.out.y <= MAX_EASE_Y && p.at.y + p.h_in.y >= -MAX_EASE_Y, "{p:?}"); + assert_forwards(&s); + // Moving the smooth point up to the limit, or next to a neighbor, keeps them in line too. + for to in [Vec2::new(0.5, 9.99), Vec2::new(0.999, 5.0), Vec2::new(0.001, -9.99)] { + let m = s.move_point(1, to).unwrap(); + let q = m.points()[1]; + assert!(q.smooth && in_line(&q), "{to:?}: {q:?}"); + assert_forwards(&m); + } +} + +#[test] +fn point_edits_keep_time_running_forwards() { + let c = wave(); + // Dragging a point past its neighbor stops at the neighbor. + let d = c.move_point(1, Vec2::new(0.95, 2.0)).unwrap(); + assert_eq!(d.points()[1].at, Vec2::new(0.6, 2.0)); + // The ends don't move. + assert!(c.move_point(0, Vec2::new(0.5, 0.5)).is_none() && c.move_point(3, Vec2::new(0.5, 0.5)).is_none()); + // A handle dragged backwards in time stops at its point. + let h = c.move_handle(1, Handle::Out, Vec2::new(0.0, 5.0)).unwrap(); + assert_eq!(h.points()[1].out.x, 0.0); + // A smooth point's other handle turns with it. + let s = c.set_smooth(1, true).unwrap(); + let t = s.move_handle(1, Handle::Out, Vec2::new(0.45, 1.5)).unwrap(); + let p = t.points()[1]; + assert!(p.smooth && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-4, "{p:?}"); + // A corner has its handles on the point. + let k = s.set_smooth(1, false).unwrap(); + assert_eq!((k.points()[1].h_in, k.points()[1].out), (Vec2::ZERO, Vec2::ZERO)); + // Removing. + assert_eq!(c.remove(2).unwrap().points().len(), 3); + assert!(c.remove(0).is_none() && c.remove(3).is_none()); +} + +/// Whether a smooth inner point's handles are in line (or one of them has no length). +fn in_line(p: &EasePoint) -> bool { + let (a, b) = (p.h_in, p.out); + a.length() < 1e-9 || b.length() < 1e-9 || (a.normalized().dot(b.normalized()) + 1.0).abs() < 1e-9 +} + +/// Turning a smooth point's other handle keeps it in line even where it has less room on its +/// side than its length: it is shortened along the line instead of clamped out of it. +#[test] +fn a_smooth_point_keeps_its_handles_in_line_near_a_neighbor() { + let c = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(0.3, 0.0), smooth: false }, + EasePoint { at: Vec2::new(0.9, 0.5), h_in: Vec2::new(-0.1, -0.3), out: Vec2::new(0.1, 0.3), smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-0.05, 0.0), out: Vec2::ZERO, smooth: false }, + ]); + let d = c.move_handle(1, Handle::In, Vec2::new(0.5, 0.1)).unwrap(); + let p = d.points()[1]; + assert!(p.smooth && p.out.length() > 0.05 && in_line(&p), "{p:?}"); + assert!(p.out.x <= 0.1 + 1e-12, "{p:?}"); + assert_forwards(&d); + // The same near the y limit. + let e = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false }, + EasePoint { at: Vec2::new(0.5, 9.9), h_in: Vec2::new(-0.2, 0.0), out: Vec2::new(0.2, 0.0), smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false }, + ]); + let f = e.move_handle(1, Handle::Out, Vec2::new(0.6, 9.0)).unwrap(); + let q = f.points()[1]; + assert!(q.h_in.length() > 0.05 && in_line(&q) && q.at.y + q.h_in.y <= MAX_EASE_Y + 1e-12, "{q:?}"); +} + +/// Turning a smooth point's other handle keeps that handle's length when it fits, however short. +#[test] +fn turning_a_smooth_point_keeps_a_short_other_handle_short() { + let c = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, ..Default::default() }, + EasePoint { at: Vec2::new(0.5, 0.5), h_in: Vec2::new(-0.0005, 0.0), out: Vec2::new(0.2, 0.0), smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let d = c.move_handle(1, Handle::Out, Vec2::new(0.7, 0.6)).unwrap(); + let p = d.points()[1]; + assert!(p.smooth && in_line(&p) && (p.h_in.length() - 0.0005).abs() < 1e-15, "{p:?}"); + // A handle with no length is given one. + let z = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, ..Default::default() }, + EasePoint { at: Vec2::new(0.5, 0.5), out: Vec2::new(0.2, 0.0), smooth: true, ..Default::default() }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let q = z.move_handle(1, Handle::Out, Vec2::new(0.7, 0.6)).unwrap().points()[1]; + assert!(q.smooth && in_line(&q) && (q.h_in.length() - 1e-3).abs() < 1e-15, "{q:?}"); +} + +/// A point marked smooth whose handles are not in line is read as a corner, its handles kept. +#[test] +fn a_smooth_mark_on_a_corner_is_cleared() { + let pts = |out: Vec2| { + vec![ + EasePoint { at: Vec2::ZERO, out: Vec2::new(0.1, 0.0), smooth: true, ..Default::default() }, + EasePoint { at: Vec2::new(0.5, 0.5), h_in: Vec2::new(-0.1, 0.0), out, smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-0.1, 0.0), smooth: true, ..Default::default() }, + ] + }; + let corner = CustomEase::new(pts(Vec2::new(0.1, 0.1))); + let p = corner.points()[1]; + assert!(!p.smooth && p.h_in == Vec2::new(-0.1, 0.0) && p.out == Vec2::new(0.1, 0.1), "{p:?}"); + let smooth = CustomEase::new(pts(Vec2::new(0.2, 0.0))); + assert!(smooth.points()[1].smooth); + // The ends have one handle each and are never smooth. + assert!(!smooth.points()[0].smooth && !smooth.points()[2].smooth); + // Past the value limit, such a point's handle is clipped as a corner's: its x is kept. + let high = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, ..Default::default() }, + EasePoint { at: Vec2::new(0.5, 9.5), h_in: Vec2::new(-0.2, 2.0), out: Vec2::new(0.1, 0.0), smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let q = high.points()[1]; + assert!(!q.smooth && q.h_in == Vec2::new(-0.2, 0.5), "{q:?}"); + #[cfg(feature = "serde")] + { + let f: CustomEase = serde_json::from_str( + r#"{"points": [ + {"at": {"x": 0.0, "y": 0.0}, "out": {"x": 0.1, "y": 0.0}, "smooth": true}, + {"at": {"x": 0.5, "y": 0.5}, "in": {"x": -0.1, "y": 0.0}, "out": {"x": 0.1, "y": 0.1}, "smooth": true}, + {"at": {"x": 1.0, "y": 1.0}, "in": {"x": -0.1, "y": 0.0}, "smooth": true} + ]}"#, + ) + .unwrap(); + assert_eq!(f, corner); + } +} + +/// A point can be added at any time strictly inside the curve that is not already a point's. +#[test] +fn a_point_can_be_added_close_to_an_end_or_a_point() { + let line = CustomEase::linear(); + let (d, i) = line.insert_at(0.00005).unwrap(); + assert_eq!((d.points().len(), i), (3, 1)); + assert!((d.points()[1].at.x - 0.00005).abs() < 1e-15, "{:?}", d.points()[1]); + assert_forwards(&d); + let (e, _) = d.insert_at(0.00006).unwrap(); + assert_eq!(e.points().len(), 4); + assert_forwards(&e); + for k in 0..=200 { + let t = k as f64 / 200.0; + assert!((e.apply(t) - t).abs() < 1e-9, "at {t}"); + } + assert!(d.insert_at(d.points()[1].at.x).is_none()); + // Where the curve is too flat in x to solve for the time, no point is added rather than one + // at another time. + let flat = CustomEase::from_bezier(0.0, 0.0, 0.0, 0.0); + assert!(flat.insert_at(1e-13).is_none()); + let (g, _) = flat.insert_at(0.3).unwrap(); + assert!((g.points()[1].at.x - 0.3).abs() < 1e-9, "{:?}", g.points()[1]); +} + +/// On a segment far narrower than its handle's reach can underflow when squared, a handle that +/// would make x run backwards is still brought back. +#[test] +fn a_very_narrow_segment_does_not_run_backwards() { + let c = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, out: Vec2::new(1.5e-180, 0.0), ..Default::default() }, + EasePoint { at: Vec2::new(1e-180, 0.5), ..Default::default() }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let [a, b, cc, d] = c.segment(0).unwrap(); + // x on the span 0..1, sampled: it never decreases. + let span = d.x - a.x; + let xs = [0.0, (b.x - a.x) / span, (cc.x - a.x) / span, 1.0]; + let mut prev = 0.0; + for k in 0..=1000 { + let x = crate::bez(k as f64 / 1000.0, xs); + assert!(x >= prev - 1e-15, "{xs:?} at {k}: {x} after {prev}"); + prev = x; + } + assert_forwards(&c); +} + +/// Every segment's x never decreases: its handles reach toward their neighbors, and x′ (a +/// quadratic with Bernstein coefficients b − a, cc − b and d − cc) is never negative. +fn assert_forwards(c: &CustomEase) { + let pts = c.points(); + assert!(pts.len() >= 2 && pts.len() <= MAX_EASE_POINTS); + assert_eq!((pts[0].at, pts[pts.len() - 1].at), (Vec2::ZERO, Vec2::new(1.0, 1.0))); + for i in 0..pts.len() - 1 { + let [a, b, cc, d] = c.segment(i).unwrap(); + // Divided by the span, so squaring does not underflow on a narrow segment. + let unit = if d.x > a.x { d.x - a.x } else { 1.0 }; + let (k0, k1, k2) = ((b.x - a.x) / unit, (cc.x - b.x) / unit, (d.x - cc.x) / unit); + let forwards = a.x <= d.x && k0 >= 0.0 && k2 >= 0.0 && (k1 >= 0.0 || k1 * k1 <= k0 * k2 * (1.0 + 1e-9)); + assert!(forwards, "segment {i}: {a:?} {b:?} {cc:?} {d:?}"); + for v in [a, b, cc, d] { + assert!(v.is_finite() && v.y.abs() <= MAX_EASE_Y + 1e-9); + } + } + for k in 0..=100 { + assert!(c.apply(k as f64 / 100.0).is_finite()); + } +} + +#[test] +fn x_stays_monotonic_after_any_edit() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 10_000) as f64 / 10_000.0 + }; + let mut c = wave(); + for _ in 0..3000 { + let n = c.points().len(); + let i = (rnd() * n as f64) as usize % n; + let to = Vec2::new(rnd() * 1.6 - 0.3, rnd() * 30.0 - 15.0); + let op = (rnd() * 6.0) as u32; + let next = match op { + 0 => c.insert_at(rnd()).map(|r| r.0), + 1 => c.move_point(i, to), + 2 => c.move_handle(i, Handle::In, to), + 3 => c.move_handle(i, Handle::Out, to), + 4 => c.set_smooth(i, rnd() > 0.5), + _ => { + if n > 6 { + c.remove(i) + } else { + None + } + } + }; + if let Some(d) = next { + assert_forwards(&d); + if matches!(op, 2 | 3) + && let Some(p) = d.points().get(i).filter(|p| p.smooth) + { + assert!(in_line(p), "{p:?}"); + } + c = d; + } + } +} + +#[test] +fn the_largest_index_is_a_missing_point() { + let w = wave(); + assert!(w.segment(usize::MAX).is_none()); + assert!(w.move_point(usize::MAX, Vec2::new(0.5, 0.5)).is_none()); + assert!(w.move_handle(usize::MAX, Handle::Out, Vec2::new(0.1, 0.1)).is_none()); + assert!(w.remove(usize::MAX).is_none()); + assert!(w.set_smooth(usize::MAX, true).is_none()); +} + +#[test] +fn hostile_curves_are_repaired() { + // NaN, reversed x, out-of-range values and handles reaching backwards. + let nan = EasePoint { at: Vec2::new(f64::NAN, 0.5), ..Default::default() }; + let pts = vec![ + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-5.0, f64::INFINITY), ..Default::default() }, + EasePoint { at: Vec2::new(0.6, 400.0), h_in: Vec2::new(3.0, 0.0), out: Vec2::new(-2.0, 0.0), smooth: true }, + nan, + EasePoint { at: Vec2::new(0.2, -1.0), ..Default::default() }, + EasePoint { at: Vec2::new(-3.0, 0.0), out: Vec2::new(f64::NAN, 1.0), ..Default::default() }, + ]; + assert_eq!(CustomEase::try_new(pts.clone()), Err(EaseError::NotFinite("ease point"))); + let c = CustomEase::new(pts); + assert_eq!(c.points().len(), 4); + assert_forwards(&c); + assert_eq!(c.points()[2].at, Vec2::new(0.6, MAX_EASE_Y)); + // Thousands of points are thinned to the cap, and stay a valid curve. + let many: Vec = (0..20_000) + .map(|i| EasePoint { + at: Vec2::new(((i * 7919) % 20_000) as f64 / 20_000.0, (i as f64 * 0.37).sin()), + out: Vec2::new(0.5, 0.0), + h_in: Vec2::new(-0.5, 0.0), + smooth: false, + }) + .collect(); + assert_eq!(CustomEase::try_new(many.clone()), Err(EaseError::Full(MAX_EASE_POINTS))); + let c = CustomEase::new(many); + assert_eq!(c.points().len(), MAX_EASE_POINTS); + assert_forwards(&c); + // Too few points: the line. + assert_eq!(CustomEase::new(vec![nan]), CustomEase::linear()); + assert_eq!(CustomEase::try_new(vec![EasePoint::default()]), Err(EaseError::TooFew { what: "a custom ease", need: 2 })); + // From a file, the same repairs. + #[cfg(feature = "serde")] + { + let f: CustomEase = serde_json::from_str( + r#"{"points": [{"at": {"x": 0.9, "y": 3.0}}, {"at": {"x": 0.1, "y": 0.0}, "out": {"x": -1.0, "y": 0.0}}, {"at": {"x": 0.5, "y": 0.5}}]}"#, + ) + .unwrap(); + assert_forwards(&f); + let e: Easing = serde_json::from_str(r#"{"Custom": {"points": []}}"#).unwrap(); + assert_eq!(e, Easing::Custom(Arc::new(CustomEase::linear()))); + } +} + +#[test] +fn custom_eases_round_trip_through_files_and_flat_lists() { + #[cfg(feature = "serde")] + { + let e = Easing::Custom(Arc::new(wave())); + let back: Easing = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); + assert_eq!(back, e); + } + let flat = wave().to_flat(); + assert_eq!(flat.len(), 10); + assert_eq!(CustomEase::from_flat(&flat), Some(wave())); + assert!(CustomEase::from_flat(&flat[..9]).is_none()); +} + +#[test] +fn a_sampled_ease_reads_its_table_between_samples() { + let s = steps(); + let e = Easing::Sampled(Arc::new(s.clone())); + assert_eq!((e.apply(0.0), e.apply(0.1), e.apply(0.25), e.apply(0.6), e.apply(0.9), e.apply(1.0)), (0.0, 0.0, 0.25, 0.5, 0.75, 1.0)); + // Between two samples, the straight line between them. + let lin = SampledEase::new("Line", "p", "l", vec![0.0, 0.5, 1.0]); + assert!((lin.apply(0.25) - 0.25).abs() < 1e-12 && (lin.apply(0.75) - 0.75).abs() < 1e-12); + // Time outside 0..1, or not a number, is clamped. + assert_eq!((e.apply(-3.0), e.apply(7.0), e.apply(f64::NAN)), (0.0, 1.0, 0.0)); + assert_eq!(e.label(), "Stepped 4"); + assert!(e.family().is_none() && e.as_bezier().is_none()); + assert_eq!(e.sampled().map(|s| (s.plugin(), s.ease())), Some(("org.example.stepped-ease", "steps4"))); +} + +#[test] +fn a_sampled_ease_is_always_valid() { + let s = SampledEase::new(" ", "bad id!/..", "x\u{202e}y", vec![0.3, f64::NAN, 99.0, -f64::INFINITY, 0.2]); + assert_eq!(s.values(), &[0.0, 0.25, MAX_EASE_Y, 0.75, 1.0]); + assert_eq!((s.name(), s.plugin(), s.ease()), ("Sampled ease", "badid..", "xy")); + assert_eq!(SampledEase::new("x", "p", "e", vec![]).values(), &[0.0, 1.0]); + assert_eq!(SampledEase::new("x", "p", "e", vec![0.5]).values(), &[0.0, 1.0]); + let long = SampledEase::new("x", "p", "e", (0..100_000).map(|i| i as f64 / 99_999.0).collect()); + assert_eq!(long.values().len(), MAX_EASE_SAMPLES); + assert!((long.apply(0.5) - 0.5).abs() < 1e-3); + // The checked form refuses instead. + assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.0, f64::NAN, 1.0]), Err(EaseError::NotFinite("sample"))); + assert!(matches!(SampledEase::try_new("x", "p", "e", vec![0.0, 99.0, 1.0]), Err(EaseError::OutOfRange { .. }))); + assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.0]), Err(EaseError::TooFew { what: "a sampled ease", need: 2 })); + assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.5; MAX_EASE_SAMPLES + 1]), Err(EaseError::Full(MAX_EASE_SAMPLES))); + assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.2, 0.5, 0.9]).unwrap().values(), &[0.0, 0.5, 1.0]); +} + +/// Thinning a table picks evenly spread samples, first and last included, for any length a +/// `usize` can hold (a 32-bit target overflows `k · (n − 1)` from about 4.2 million values). +#[test] +fn thinning_a_huge_table_does_not_overflow() { + use crate::sampled::thinned; + let last = MAX_EASE_SAMPLES - 1; + for n in [MAX_EASE_SAMPLES + 1, 5_000_000, usize::MAX / 3, usize::MAX] { + assert_eq!(thinned(0, n), 0); + assert_eq!(thinned(last, n), n - 1, "{n}"); + assert!(thinned(last / 2, n) >= (n - 1) / 2 - 1 && thinned(last / 2, n) <= (n - 1) / 2, "{n}"); + assert!((1..=last).all(|k| thinned(k, n) > thinned(k - 1, n)), "{n}"); + } +} + +/// Invisible format characters do not count as a name, so a name of only those shows as +/// "Sampled ease"; they are taken out of a visible name too. +#[test] +fn a_sampled_ease_name_of_invisible_characters_is_no_name() { + let blank: String = "\u{200b}\u{200d}\u{feff}\u{2060}\u{ad}".repeat(13); + assert_eq!(SampledEase::new(&blank, "p", "e", vec![0.0, 1.0]).name(), "Sampled ease"); + assert_eq!(SampledEase::new(" \u{200b} Bounce\u{200d}y \u{feff}", "p", "e", vec![0.0, 1.0]).name(), "Bouncey"); + // A visible name longer than the limit keeps its first 64 characters, after leading padding. + let padded = format!("{}{}", " \u{200b}".repeat(100), "a".repeat(80)); + assert_eq!(SampledEase::new(&padded, "p", "e", vec![0.0, 1.0]).name(), "a".repeat(64)); +} + +#[cfg(feature = "serde")] +#[test] +fn a_sampled_ease_round_trips_through_the_file_format_and_survives_bad_files() { + let e = Easing::Sampled(Arc::new(steps())); + let text = serde_json::to_string(&e).unwrap(); + assert!( + text.starts_with("{\"Sampled\":{\"name\":\"Stepped 4\",\"plugin\":\"org.example.stepped-ease\",\"ease\":\"steps4\",\"values\":[0.0,"), + "{text}" + ); + assert_eq!(serde_json::from_str::(&text).unwrap(), e); + // A hand-edited table is made valid on load; a value that is not a number is a broken file. + assert!(serde_json::from_str::(r#"{"Sampled":{"values":[5,0.5,"x"]}}"#).is_err()); + let odd: Easing = serde_json::from_str(r#"{"Sampled":{"name":"Odd","values":[5,0.5,-20]}}"#).unwrap(); + assert_eq!(odd.sampled().unwrap().values(), &[0.0, 0.5, 1.0]); +} + +/// A file with a huge list loads from its first 65,536 entries; the rest are skipped unread, +/// so they are never stored (here they would not even parse as entries). +#[cfg(feature = "serde")] +#[test] +fn huge_lists_in_files_are_read_only_up_to_a_limit() { + let mut values = String::from(r#"{"Sampled":{"values":["#); + for i in 0..70_000 { + values.push_str(if i < 65_536 { "0.5," } else { r#"{"not":"a value"},"# }); + } + values.push_str("1]}}"); + let e: Easing = serde_json::from_str(&values).unwrap(); + assert_eq!(e.sampled().unwrap().values().len(), MAX_EASE_SAMPLES); + let mut points = String::from(r#"{"Custom":{"points":["#); + for i in 0..70_000 { + points.push_str(if i < 65_536 { r#"{"at":{"x":0.5,"y":0.5}},"# } else { r#""not a point","# }); + } + points.push_str(r#"{"at":{"x":1,"y":1}}]}}"#); + let c: Easing = serde_json::from_str(&points).unwrap(); + assert!(matches!(&c, Easing::Custom(f) if f.points().len() <= MAX_EASE_POINTS), "{c:?}"); + // A long name keeps only its first characters. + let long = format!(r#"{{"Sampled":{{"name":"{}","plugin":"p","ease":"e","values":[0,1]}}}}"#, "é".repeat(100_000)); + let s: Easing = serde_json::from_str(&long).unwrap(); + assert_eq!(s.sampled().unwrap().name(), "é".repeat(64)); + // Characters the cleanup removes do not push the kept text out of reach. + let padded = format!(r#"{{"Sampled":{{"name":"{}Curve","plugin":"{}p1","ease":"e","values":[0,1]}}}}"#, " ".repeat(10_000), "!".repeat(10_000)); + let s: Easing = serde_json::from_str(&padded).unwrap(); + assert_eq!((s.sampled().unwrap().name(), s.sampled().unwrap().plugin()), ("Curve", "p1")); +} + +#[test] +fn a_sampled_ease_becomes_a_custom_curve_through_its_samples() { + let wave = SampledEase::new( + "Wave", + "p", + "w", + (0..257) + .map(|i| { + let t = i as f64 / 256.0; + t + 0.2 * (t * std::f64::consts::TAU).sin() + }) + .collect(), + ); + let c = wave.to_polyline(); + assert_eq!(c.points().len(), POLYLINE_POINTS); + for i in 0..=100 { + let t = i as f64 / 100.0; + assert!((c.apply(t) - wave.apply(t)).abs() < 0.01, "t = {t}: {} vs {}", c.apply(t), wave.apply(t)); + } + let short = SampledEase::new("Short", "p", "s", vec![0.0, 0.8, 1.0]).to_polyline(); + assert_eq!(short.points().len(), 3); + assert!((short.apply(0.5) - 0.8).abs() < 1e-3); +} diff --git a/crates/ease/src/tests/path_tests.rs b/crates/ease/src/tests/path_tests.rs new file mode 100644 index 0000000000..5d7891140d --- /dev/null +++ b/crates/ease/src/tests/path_tests.rs @@ -0,0 +1,227 @@ +use crate::*; + +/// A quarter circle of radius 100 about the origin, from (100, 0) to (0, 100). +fn quarter() -> MotionPath { + let k = 4.0 / 3.0 * (std::f64::consts::PI / 8.0).tan() * 100.0; + MotionPath::new(&[Vec2::new(100.0, 0.0), Vec2::new(100.0, k), Vec2::new(k, 100.0), Vec2::new(0.0, 100.0)]).unwrap() +} + +/// The length of the curve through `n` evenly spaced points along it. +fn polyline_length(p: &MotionPath, n: usize) -> f64 { + (1..=n).map(|i| p.point_at_length(p.length() * i as f64 / n as f64).distance(p.point_at_length(p.length() * (i - 1) as f64 / n as f64))).sum() +} + +/// A tiny curve is walked at constant speed like the same curve at full size. +#[test] +fn a_tiny_curve_is_walked_at_constant_speed() { + let r = 1e-15; + let k = 4.0 / 3.0 * (std::f64::consts::PI / 8.0).tan() * r; + let tiny = MotionPath::new(&[Vec2::new(r, 0.0), Vec2::new(r, k), Vec2::new(k, r), Vec2::new(0.0, r)]).unwrap(); + let big = quarter(); + for i in 1..20 { + let t = i as f64 / 20.0; + let (a, b) = (tiny.point_at(t), big.point_at(t)); + assert!((a.x / r - b.x / 100.0).abs() < 1e-9 && (a.y / r - b.y / 100.0).abs() < 1e-9, "{t}: {a:?} vs {b:?}"); + } +} + +#[test] +fn a_curve_is_measured_and_walked_at_constant_speed() { + let p = quarter(); + // The Bezier quarter circle is within 0.03 % of the circle's length. + assert!((p.length() - 50.0 * std::f64::consts::PI).abs() < 0.05, "{}", p.length()); + assert!((polyline_length(&p, 20_000) - p.length()).abs() < 1e-6, "{} vs {}", polyline_length(&p, 20_000), p.length()); + // Equal steps of distance are equal chords. + let n = 200; + let steps: Vec = (1..=n).map(|i| p.point_at(i as f64 / n as f64).distance(p.point_at((i - 1) as f64 / n as f64))).collect(); + let (lo, hi) = steps.iter().fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(*s), hi.max(*s))); + assert!(hi - lo < 1e-6, "{lo}..{hi}"); + assert_eq!(p.point_at(0.0), Vec2::new(100.0, 0.0)); + let end = p.point_at(1.0); + assert!(end.distance(Vec2::new(0.0, 100.0)) < 1e-9, "{end:?}"); + // Each point is on the curve: about 100 from the center. + for i in 0..=50 { + let r = p.point_at(i as f64 / 50.0).length(); + assert!((r - 100.0).abs() < 0.03, "{r}"); + } +} + +#[test] +fn a_straight_segment_with_uneven_handles_still_moves_evenly() { + // Handles on the chord but bunched near the start: the curve's own parameter speeds up. + let p = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap(); + assert_eq!(p.length(), 100.0); + for i in 0..=10 { + assert_eq!(p.point_at(i as f64 / 10.0), Vec2::new(i as f64 * 10.0, 0.0)); + } +} + +#[test] +fn past_the_ends_the_motion_continues_along_the_path() { + let p = quarter(); + // At the end the circle heads in −x; past it the point keeps going that way. + let past = p.point_at_length(p.length() + 10.0); + assert!(past.distance(Vec2::new(-10.0, 100.0)) < 1e-6, "{past:?}"); + let before = p.point_at_length(-5.0); + assert!(before.distance(Vec2::new(100.0, -5.0)) < 1e-6, "{before:?}"); + // A track's overshooting ease drives the same distance through point_at. + let over = Easing::BackOut; + let peak = (1..100).map(|i| over.apply(i as f64 / 100.0)).fold(f64::MIN, f64::max); + let beyond = p.point_at(peak); + assert!(beyond.x < 0.0 && (beyond.y - 100.0).abs() < 1e-6, "{beyond:?}"); + let d = p.direction_at_length(p.length() * 2.0); + assert!(d.distance(Vec2::new(-1.0, 0.0)) < 1e-9, "{d:?}"); + assert_eq!(p.point_at_length(f64::INFINITY), p.point_at(1.0)); + assert_eq!(p.point_at_length(f64::NAN), Vec2::new(100.0, 0.0)); + assert_eq!(p.point_at_length(f64::NEG_INFINITY), Vec2::new(100.0, 0.0)); + let flat = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(3.0, 0.0)]).unwrap(); + assert_eq!(flat.point_at_length(f64::NEG_INFINITY), Vec2::ZERO); +} + +/// Moving a handle off the chord by a rounding error does not change where an overshoot goes. +#[test] +fn an_overshoot_goes_the_same_way_on_a_straight_and_an_almost_straight_path() { + let straight = MotionPath::new(&[Vec2::ZERO, Vec2::new(30.0, 0.0), Vec2::new(70.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap(); + let bent = MotionPath::new(&[Vec2::ZERO, Vec2::new(30.0, 1e-6), Vec2::new(70.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap(); + for progress in [-0.2, 1.1, 1.25] { + let (a, b) = (straight.point_at(progress), bent.point_at(progress)); + assert!(a.distance(b) < 0.01, "{progress}: {a:?} vs {b:?}"); + } + assert!(straight.point_at(1.25).distance(Vec2::new(125.0, 0.0)) < 1e-9); +} + +#[test] +fn a_path_through_anchors_passes_through_each_one() { + let anchors = [Vec2::new(0.0, 0.0), Vec2::new(100.0, 50.0), Vec2::new(200.0, 0.0), Vec2::new(300.0, 80.0)]; + let p = MotionPath::through(&anchors).unwrap(); + assert_eq!(p.segments(), 3); + // Each anchor is reached at some distance along it. + for a in anchors { + let nearest = (0..=4000).map(|i| p.point_at(i as f64 / 4000.0).distance(a)).fold(f64::MAX, f64::min); + assert!(nearest < 0.1, "{a:?}: {nearest}"); + } + // Smooth through the inner anchors: no turn in direction across them. + let mut prev = p.direction_at_length(0.0); + for i in 1..=2000 { + let d = p.direction_at_length(p.length() * i as f64 / 2000.0); + assert!(d.dot(prev) > 0.99, "a corner at {i}"); + prev = d; + } + // Two anchors at one place make a segment of zero length, which is skipped over. + let q = MotionPath::through(&[Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(20.0, 0.0)]).unwrap(); + assert!((q.length() - 20.0).abs() < 1e-9, "{}", q.length()); + assert!(q.point_at(0.75).distance(Vec2::new(15.0, 0.0)) < 1e-6); + // Anchors repeated at either end still let the motion continue past it. + let r = MotionPath::through(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 0.0)]).unwrap(); + assert!(r.point_at(1.2).distance(Vec2::new(12.0, 0.0)) < 1e-6, "{:?}", r.point_at(1.2)); + assert!(r.point_at(-0.1).distance(Vec2::new(-1.0, 0.0)) < 1e-6, "{:?}", r.point_at(-0.1)); + assert!(r.direction_at_length(20.0).distance(Vec2::new(1.0, 0.0)) < 1e-9); + assert!(r.direction_at_length(-1.0).distance(Vec2::new(1.0, 0.0)) < 1e-9); +} + +#[test] +fn bad_paths_are_refused() { + assert_eq!(MotionPath::new(&[Vec2::ZERO; 3]), Err(EaseError::TooFew { what: "a motion path", need: 4 })); + assert!(matches!(MotionPath::new(&[Vec2::ZERO; 5]), Err(EaseError::OutOfRange { .. }))); + assert_eq!(MotionPath::new(&[Vec2::ZERO, Vec2::new(f64::NAN, 0.0), Vec2::ZERO, Vec2::ZERO]), Err(EaseError::NotFinite("path point"))); + assert_eq!(MotionPath::new(&vec![Vec2::ZERO; 3 * MAX_PATH_SEGMENTS + 4]), Err(EaseError::Full(MAX_PATH_SEGMENTS))); + assert_eq!(MotionPath::through(&[Vec2::ZERO]), Err(EaseError::TooFew { what: "a motion path", need: 2 })); + assert_eq!(MotionPath::through(&[Vec2::ZERO, Vec2::new(0.0, f64::INFINITY)]), Err(EaseError::NotFinite("path point"))); + // A path too long to measure. + assert_eq!( + MotionPath::new(&[Vec2::new(-f64::MAX, 0.0), Vec2::new(-f64::MAX, 0.0), Vec2::new(f64::MAX, 0.0), Vec2::new(f64::MAX, 0.0)]), + Err(EaseError::Overflow) + ); + // A path of one point stands still. + let still = MotionPath::new(&[Vec2::new(3.0, 4.0); 4]).unwrap(); + assert_eq!((still.length(), still.point_at(0.5), still.direction_at_length(1.0)), (0.0, Vec2::new(3.0, 4.0), Vec2::ZERO)); +} + +/// A curve with huge coordinates (whose squares overflow) is walked as the same curve scaled, +/// not taken for a straight line. +#[test] +fn a_huge_curve_is_not_taken_for_a_straight_line() { + let shape = |k: f64| MotionPath::new(&[Vec2::ZERO, Vec2::new(0.0, k), Vec2::new(0.0, k), Vec2::new(2.0 * k, 0.0)]).unwrap(); + let (small, huge) = (shape(1.0), shape(1e154)); + for i in 0..=10 { + let t = i as f64 / 10.0; + let (a, b) = (small.point_at(t), huge.point_at(t)); + assert!((b.x / 1e154 - a.x).abs() < 1e-9 && (b.y / 1e154 - a.y).abs() < 1e-9, "{t}: {a:?} vs {b:?}"); + } + assert!(huge.point_at(0.5).y > 5e153, "{:?}", huge.point_at(0.5)); + // A long chord with handles a small distance off it still bends. + let long = MotionPath::new(&[Vec2::ZERO, Vec2::new(1e12 / 3.0, 1000.0), Vec2::new(2e12 / 3.0, 1000.0), Vec2::new(1e12, 0.0)]).unwrap(); + let mid = long.point_at_length(long.length() / 2.0); + assert!((mid.y - 750.0).abs() < 1.0, "{mid:?}"); +} + +/// Paths whose length is representable are measured even when their scale is near the f64 limit. +#[test] +fn a_path_near_the_largest_length_is_measured() { + let straight = MotionPath::new(&[Vec2::ZERO, Vec2::new(1e307 / 3.0, 0.0), Vec2::new(2e307 / 3.0, 0.0), Vec2::new(1e307, 0.0)]).unwrap(); + assert_eq!(straight.length(), 1e307); + assert!((straight.point_at(0.5).x / 5e306 - 1.0).abs() < 1e-12, "{:?}", straight.point_at(0.5)); + let curved = MotionPath::new(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(0.0, 1e306), Vec2::new(5e307, 0.0)]).unwrap(); + assert!(curved.length() > 5e307 && curved.length() < 5.2e307, "{}", curved.length()); + assert!(curved.point_at(1.0).distance(Vec2::new(5e307, 0.0)) < 1e295); +} + +/// A distance close to a start where the curve stands still is found on the curve, not where a +/// few Newton steps from the table's guess happen to stop. +#[test] +fn a_short_distance_from_a_still_start_is_found() { + let p = MotionPath::new(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)]).unwrap(); + for s in [1e-10, 1e-8, 1e-6] { + let q = p.point_at_length(s); + // The curve leaves the start straight up, so the point is `s` above it. + assert!((q.y - s).abs() < 1e-11 && q.x.abs() < 1e-9, "{s}: {q:?}"); + } +} + +#[test] +fn a_vector_of_any_finite_size_has_a_unit_direction() { + let h = std::f64::consts::FRAC_1_SQRT_2; + let big = Vec2::new(f64::MAX, f64::MAX).normalized(); + assert!((big.x - h).abs() < 1e-15 && (big.y - h).abs() < 1e-15, "{big:?}"); + assert_eq!(Vec2::new(-f64::MAX, 0.0).normalized(), Vec2::new(-1.0, 0.0)); + let tiny = Vec2::new(f64::from_bits(1), f64::from_bits(1)).normalized(); + assert!((tiny.x - h).abs() < 1e-15 && (tiny.y - h).abs() < 1e-15, "{tiny:?}"); + let odd = Vec2::new(3.0 * f64::from_bits(1), -4.0 * f64::from_bits(1)).normalized(); + assert!((odd.x - 0.6).abs() < 1e-15 && (odd.y + 0.8).abs() < 1e-15, "{odd:?}"); + assert_eq!(Vec2::ZERO.normalized(), Vec2::ZERO); + assert_eq!(Vec2::new(f64::INFINITY, 1.0).normalized(), Vec2::ZERO); + assert_eq!(Vec2::new(1.0, f64::NAN).normalized(), Vec2::ZERO); +} + +/// The ends of an interpolation are the end values themselves, even where the difference +/// between them rounds. +#[test] +fn interpolating_returns_the_exact_ends() { + let (a, b) = (Vec2::new(1e20, -3.0), Vec2::new(1.0, 1e-30)); + assert_eq!(a.lerp(b, 0.0), a); + assert_eq!(a.lerp(b, 1.0), b); + assert_eq!(Vec2::new(-f64::MAX, 0.0).lerp(Vec2::new(f64::MAX, 0.0), 1.0), Vec2::new(f64::MAX, 0.0)); +} + +/// A curve that stops and turns back inside one table cell is measured to its true length: x +/// runs out to 4/9 at u = 1/3 and back to 0, so the length is 8/9. +#[test] +fn a_curve_that_turns_back_is_measured_exactly() { + let p = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::ZERO, Vec2::ZERO]).unwrap(); + assert!((p.length() - 8.0 / 9.0).abs() < 1e-12, "{}", p.length()); + let turn = p.point_at_length(4.0 / 9.0); + assert!((turn.x - 4.0 / 9.0).abs() < 1e-9 && turn.y == 0.0, "{turn:?}"); + for (s, x) in [(0.2, 0.2), (0.6, 4.0 / 9.0 - (0.6 - 4.0 / 9.0)), (0.8, 4.0 / 9.0 - (0.8 - 4.0 / 9.0))] { + let q = p.point_at_length(s); + assert!((q.x - x).abs() < 1e-9, "{s}: {q:?} vs {x}"); + } +} + +#[test] +fn a_long_path_finds_its_segment_by_binary_search() { + let anchors: Vec = (0..=MAX_PATH_SEGMENTS).map(|i| Vec2::new(i as f64, ((i as f64) * 0.1).sin())).collect(); + let p = MotionPath::through(&anchors).unwrap(); + assert_eq!(p.segments(), MAX_PATH_SEGMENTS); + let mid = p.point_at(0.5); + assert!(mid.x > 4000.0 && mid.x < 6000.0, "{mid:?}"); +} diff --git a/crates/ease/src/tests/spring_tests.rs b/crates/ease/src/tests/spring_tests.rs new file mode 100644 index 0000000000..bbc7cb0d82 --- /dev/null +++ b/crates/ease/src/tests/spring_tests.rs @@ -0,0 +1,347 @@ +use crate::*; + +/// A spring released from 0 toward 1, `t` seconds in, from the closed forms written out +/// separately: under-damped, critically damped and over-damped. +fn released(w: f64, z: f64, t: f64) -> f64 { + if z < 1.0 { + let wd = w * (1.0 - z * z).sqrt(); + 1.0 - (-z * w * t).exp() * ((wd * t).cos() + z * w / wd * (wd * t).sin()) + } else if (z - 1.0).abs() < 1e-9 { + 1.0 - (-w * t).exp() * (1.0 + w * t) + } else { + let s = (z * z - 1.0).sqrt(); + let (r1, r2) = (-w / (z + s), -w * (z + s)); + 1.0 - (r2 * (r1 * t).exp() - r1 * (r2 * t).exp()) / (r2 - r1) + } +} + +const PRESETS: [(f64, f64, f64); 5] = [(1.0, 100.0, 15.0), (1.0, 300.0, 20.0), (1.0, 600.0, 15.0), (1.0, 80.0, 20.0), (2.5, 40.0, 2.0)]; + +#[test] +fn a_physical_spring_ease_matches_the_closed_form() { + for (m, k, c) in PRESETS { + let spring = Spring::from_physical(m, k, c).unwrap(); + let (w, z) = ((k / m).sqrt(), c / (2.0 * (k * m).sqrt())); + assert!((spring.omega() - w).abs() < 1e-12 && (spring.damping() - z).abs() < 1e-12); + let rate = if z < 1.0 { z * w } else { w / (z + (z * z - 1.0).sqrt()) }; + let lead = if z < 1.0 { (6.9 - 0.5 * (1.0 - z * z).ln()).min(9.2) } else { 9.2 }; + let settle = (lead / rate).clamp(0.05, 10.0); + assert!((spring.settle_time() - settle).abs() < 1e-12); + let ease = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c }); + // A spring cut short at 10 seconds has what it is still off taken out evenly. + let rest = if settle < 10.0 { 0.0 } else { 1.0 - released(w, z, settle) }; + for i in 1..1000 { + let t = i as f64 / 1000.0; + let want = released(w, z, t * settle) + t * rest; + assert!((ease.apply(t) - want).abs() < 1e-12, "{m} {k} {c} at {t}: {} vs {want}", ease.apply(t)); + } + // It ends within 0.1 % (0.2 % for the slower lead factor) of 1 before the jump to 1. + assert!((ease.apply(0.999_999) - 1.0).abs() < 2e-3, "{m} {k} {c}"); + } +} + +/// A step of no time returns the value unchanged, even when its distance to the target is too +/// large to represent. +#[test] +fn a_zero_length_step_keeps_a_far_value() { + let spring = Spring::new(1.0, 0.5).unwrap(); + let mut s = SpringState::at(1e308); + assert_eq!(s.step(&spring, -1e308, 0.0), Ok(1e308)); + assert_eq!(s, SpringState::at(1e308)); + // A state that is not finite is still refused. + let mut bad = SpringState::at(f64::NAN); + assert_eq!(bad.step(&spring, 0.0, 0.0), Err(EaseError::Overflow)); +} + +/// A value and target at opposite ends of the f64 range move like any others. +#[test] +fn a_step_across_the_whole_range_does_not_overflow() { + let spring = Spring::new(1.0, 1.0).unwrap(); + let mut s = SpringState::at(f64::MAX); + let v = s.step(&spring, -f64::MAX, 10.0).unwrap(); + assert!(v.is_finite() && v < 0.0 && s.velocity.is_finite(), "{s:?}"); +} + +/// The smallest positive target is reached. +#[test] +fn a_spring_reaches_a_subnormal_target() { + let spring = Spring::new(1.0, 1.0).unwrap(); + let mut s = SpringState::at(0.0); + assert_eq!(s.step(&spring, f64::from_bits(1), 1000.0), Ok(f64::from_bits(1))); +} + +/// A spring of the lowest frequency still moves at its velocity over a step. +#[test] +fn a_very_slow_spring_steps_without_overflow() { + let spring = Spring::new(1e-320, 0.0).unwrap(); + let mut s = SpringState { value: 0.0, velocity: 1.0 }; + let v = s.step(&spring, 0.0, 1.0).unwrap(); + assert!((v - 1.0).abs() < 1e-12 && (s.velocity - 1.0).abs() < 1e-12, "{s:?}"); + // The same over-damped. + let spring = Spring::new(1e-320, 2.0).unwrap(); + let mut s = SpringState { value: 0.0, velocity: 1.0 }; + let v = s.step(&spring, 0.0, 1.0).unwrap(); + assert!((v - 1.0).abs() < 1e-12 && (s.velocity - 1.0).abs() < 1e-12, "{s:?}"); +} + +/// Physical values whose damping ratio is above the limit are refused, not changed. +#[test] +fn physical_values_past_the_damping_ratio_limit_are_refused() { + assert_eq!( + Spring::from_physical(0.01, 0.01, 1_000_000.0), + Err(EaseError::OutOfRange { what: "damping ratio", min: 0.0, max: MAX_DAMPING_RATIO }) + ); + assert!(Spring::from_physical(0.01, 0.01, 19.0).is_ok()); +} + +/// A spring just under critical damping is within about 0.1 % of 1 just before the end, so the +/// ease does not jump when it reaches 1. +#[test] +fn a_nearly_critical_spring_ease_ends_without_a_jump() { + for z in [0.5, 0.9, 0.99, 0.999, 0.9999, 1.0 - 2e-4] { + let s = Spring::new(1.0, z).unwrap(); + let end = s.ease(1.0 - 1e-9); + assert!((end - 1.0).abs() < 1.1e-3, "ζ {z}: {end}"); + // The bound holds after the settle time too, not only at it. + let late = 1.0 + s.response(-1.0, 0.0, 1.5 * s.settle_time()).0; + assert!((late - 1.0).abs() < 1.1e-3, "ζ {z} later: {late}"); + } +} + +/// An undamped or barely damped spring ease still arrives at 1 without a jump. +#[test] +fn a_spring_that_never_settles_still_ends_at_one() { + for (m, k, c) in [(1.0, 100.0, 0.0), (1.0, 100.0, 0.01), (10.0, 0.5, 0.0)] { + let e = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c }); + assert!((e.apply(1.0 - 1e-9) - 1.0).abs() < 1e-6, "{m} {k} {c}: {}", e.apply(1.0 - 1e-9)); + assert!((1..1000).all(|i| e.apply(i as f64 / 1000.0).is_finite())); + } +} + +/// Stepping a spring from rest toward 1 frame by frame traces its ease. +#[test] +fn stepping_from_rest_traces_the_spring_ease() { + // Springs that settle within 10 seconds (the others have their ease adjusted to end at 1). + for (m, k, c) in PRESETS.into_iter().filter(|&(m, k, c)| Spring::from_physical(m, k, c).unwrap().settle_time() < 10.0) { + let s = Spring::from_physical(m, k, c).unwrap(); + let ease = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c }); + let (settle, frames) = (s.settle_time(), 600); + let mut st = SpringState::at(0.0); + for f in 1..frames { + let v = st.step(&s, 1.0, settle / frames as f64).unwrap(); + let want = ease.apply(f as f64 / frames as f64); + assert!((v - want).abs() < 1e-9, "{m} {k} {c} frame {f}: {v} vs {want}"); + } + } +} + +/// The spring equation integrated with small fourth-order Runge-Kutta steps, from 0 at rest +/// toward 1: value and velocity after `t` seconds. +fn integrated(w: f64, z: f64, t: f64) -> (f64, f64) { + let n = 100_000; + let h = t / n as f64; + let f = |x: f64, v: f64| (v, -w * w * (x - 1.0) - 2.0 * z * w * v); + let (mut x, mut v) = (0.0, 0.0); + for _ in 0..n { + let (a1, b1) = f(x, v); + let (a2, b2) = f(x + 0.5 * h * a1, v + 0.5 * h * b1); + let (a3, b3) = f(x + 0.5 * h * a2, v + 0.5 * h * b2); + let (a4, b4) = f(x + h * a3, v + h * b3); + x += h / 6.0 * (a1 + 2.0 * a2 + 2.0 * a3 + a4); + v += h / 6.0 * (b1 + 2.0 * b2 + 2.0 * b3 + b4); + } + (x, v) +} + +/// Damping ratios just off 1 are solved with the ratio given, not the critical one. +#[test] +fn a_nearly_critical_spring_steps_with_its_own_damping_ratio() { + let w = 10.0; + for t in [0.1, 0.3, 1.0] { + let crit = released(w, 1.0, t); + for z in [1.0 - 5e-5, 1.0 + 5e-5, 1.0 - 1e-9, 1.0 + 1e-9] { + let s = Spring::new(w / std::f64::consts::TAU, z).unwrap(); + let mut st = SpringState::at(0.0); + st.step(&s, 1.0, t).unwrap(); + let (x, v) = integrated(w, z, t); + assert!((st.value - x).abs() < 1e-10 && (st.velocity - v).abs() < 1e-9, "ζ {z} at {t}: {st:?} vs {x}, {v}"); + if (z - 1.0).abs() > 1e-6 { + // The two differ by far more than the tolerance above. + assert!((x - crit).abs() > 1e-7, "ζ {z} at {t}: {x} vs {crit}"); + } + } + } +} + +/// A critically damped step keeps the velocity a tiny step leaves, beside a huge offset. +#[test] +fn a_critical_step_keeps_its_velocity_beside_a_huge_offset() { + let s = Spring::from_physical(1.0, 1.0, 2.0).unwrap(); + assert_eq!(s.damping(), 1.0); + let mut st = SpringState { value: 1e20, velocity: 1.0 }; + st.step(&s, 0.0, 1e-22).unwrap(); + assert!((st.velocity - 0.99).abs() < 1e-12, "{st:?}"); +} + +/// A spring whose damped frequency rounds to 0 moves at its velocity over a step. +#[test] +fn a_spring_whose_damped_frequency_rounds_to_zero_still_steps() { + let s = Spring::new(f64::from_bits(1), 0.9998).unwrap(); + let mut st = SpringState { value: 0.0, velocity: 1.0 }; + let v = st.step(&s, 0.0, 1.0).unwrap(); + assert!((v - 1.0).abs() < 1e-12 && (st.velocity - 1.0).abs() < 1e-12, "{st:?}"); +} + +/// A spring whose damped frequency is above 0 but whose phase over a short step rounds to 0 +/// still moves at its velocity over the step. +#[test] +fn a_step_whose_phase_rounds_to_zero_still_moves() { + let s = Spring::new(1e-320, 0.99995).unwrap(); + let mut st = SpringState { value: 0.0, velocity: 1.0 }; + let v = st.step(&s, 0.0, 0.001).unwrap(); + assert!((v - 0.001).abs() < 1e-15 && (st.velocity - 1.0).abs() < 1e-12, "{st:?}"); +} + +/// A state that is not finite is refused at every step length and in every damping regime, +/// and stays as it is. +#[test] +fn a_state_that_is_not_finite_is_refused_at_any_step_length() { + for z in [0.5, 1.0, 2.0] { + let s = Spring::new(1.0, z).unwrap(); + for start in [SpringState::at(f64::NAN), SpringState { value: 0.0, velocity: f64::INFINITY }] { + for dt in [0.0, 0.1, 200.0, 1e300] { + let mut st = start; + assert_eq!(st.step(&s, 1.0, dt), Err(EaseError::Overflow), "ζ {z}, {dt}"); + assert_eq!((st.value.to_bits(), st.velocity.to_bits()), (start.value.to_bits(), start.velocity.to_bits())); + } + } + } +} + +#[test] +fn the_three_damping_regimes_agree_near_critical_damping() { + // Either side of critical damping, the solutions meet the critically damped one. + let w = 10.0; + for t in [0.01, 0.1, 0.3, 1.0] { + let crit = released(w, 1.0, t); + for z in [1.0 - 2e-4, 1.0 - 5e-5, 1.0, 1.0 + 5e-5, 1.0 + 2e-4] { + let s = Spring::new(w / std::f64::consts::TAU, z).unwrap(); + let mut st = SpringState::at(0.0); + let v = st.step(&s, 1.0, t).unwrap(); + assert!((v - crit).abs() < 1e-3, "ζ {z} at {t}: {v} vs {crit}"); + } + } +} + +#[test] +fn a_spring_settles_on_its_target() { + for (f, z) in [(2.0, 0.2), (1.0, 1.0), (0.5, 3.0), (8.0, 0.05)] { + let s = Spring::new(f, z).unwrap(); + let mut st = SpringState::at(0.0); + for _ in 0..60 * 120 { + st.step(&s, 10.0, 1.0 / 60.0).unwrap(); + } + assert!(st.settled(10.0, 1e-6), "{f} Hz ζ {z}: {st:?}"); + } + // An undamped spring keeps swinging, its energy kept. + let s = Spring::new(1.0, 0.0).unwrap(); + let mut st = SpringState::at(0.0); + for _ in 0..60 * 100 { + st.step(&s, 1.0, 1.0 / 60.0).unwrap(); + } + let w = s.omega(); + let energy = (st.value - 1.0).powi(2) + (st.velocity / w).powi(2); + assert!((energy - 1.0).abs() < 1e-9, "{energy}"); +} + +/// Many short steps land where one long step does: the step is exact, not an integrator. +#[test] +fn many_small_steps_equal_one_long_step() { + for (f, z) in [(3.0, 0.3), (1.0, 1.0), (1.0, 4.0), (0.7, 0.0)] { + let s = Spring::new(f, z).unwrap(); + let mut one = SpringState { value: -2.0, velocity: 5.0 }; + let mut many = one; + one.step(&s, 1.0, 2.0).unwrap(); + for _ in 0..240 { + many.step(&s, 1.0, 2.0 / 240.0).unwrap(); + } + assert!((one.value - many.value).abs() < 1e-9 && (one.velocity - many.velocity).abs() < 1e-8, "{f} {z}: {one:?} {many:?}"); + } + // Variable frame lengths too. + let s = Spring::new(2.0, 0.4).unwrap(); + let (mut a, mut b) = (SpringState::at(0.0), SpringState::at(0.0)); + a.step(&s, 1.0, 0.5).unwrap(); + for dt in [0.1, 0.016, 0.05, 0.034, 0.2, 0.1] { + b.step(&s, 1.0, dt).unwrap(); + } + assert!((a.value - b.value).abs() < 1e-9); +} + +#[test] +fn huge_steps_land_on_the_target() { + for (f, z) in [(MAX_SPRING_HZ, 0.0001), (1e-6, 0.5), (1.0, MAX_DAMPING_RATIO), (5.0, 1.0)] { + let s = Spring::new(f, z).unwrap(); + for dt in [1e6, 1e300, f64::MAX] { + let mut st = SpringState { value: 5.0, velocity: -3.0 }; + let v = st.step(&s, 2.0, dt).unwrap(); + assert!(v.is_finite() && st.velocity.is_finite(), "{f} {z} {dt}"); + } + } + let s = Spring::new(4.0, 0.5).unwrap(); + let mut st = SpringState { value: 5.0, velocity: -3.0 }; + assert_eq!(st.step(&s, 2.0, 1e300).unwrap(), 2.0); + assert_eq!(st.velocity, 0.0); + // An undamped spring keeps its energy over any finite step, the longest included. + let s = Spring::new(MAX_SPRING_HZ, 0.0).unwrap(); + let w = s.omega(); + for dt in [1e300, f64::MAX] { + let mut st = SpringState { value: 5.0, velocity: -3.0 }; + st.step(&s, 2.0, dt).unwrap(); + let energy = (st.value - 2.0).powi(2) + (st.velocity / w).powi(2); + assert!((energy - (9.0 + (3.0 / w).powi(2))).abs() < 1e-9, "{dt}: {st:?}"); + } + let s = Spring::new(4.0, 0.5).unwrap(); + // A zero step changes nothing. + let mut st = SpringState { value: 5.0, velocity: -3.0 }; + assert_eq!(st.step(&s, 2.0, 0.0).unwrap(), 5.0); + assert_eq!(st.velocity, -3.0); +} + +#[test] +fn bad_inputs_are_refused_and_leave_the_state_alone() { + assert_eq!(Spring::new(f64::NAN, 0.5), Err(EaseError::NotFinite("frequency"))); + assert!(matches!(Spring::new(0.0, 0.5), Err(EaseError::OutOfRange { what: "frequency", .. }))); + assert!(matches!(Spring::new(MAX_SPRING_HZ * 2.0, 0.5), Err(EaseError::OutOfRange { what: "frequency", .. }))); + assert!(matches!(Spring::new(1.0, -0.1), Err(EaseError::OutOfRange { what: "damping", .. }))); + assert_eq!(Spring::new(1.0, f64::INFINITY), Err(EaseError::NotFinite("damping"))); + assert!(matches!(Spring::from_controls(1.5, 0.5), Err(EaseError::OutOfRange { what: "strength", .. }))); + assert!(matches!(Spring::from_physical(1.0, 0.0, 1.0), Err(EaseError::OutOfRange { what: "stiffness", .. }))); + let s = Spring::new(1.0, 0.5).unwrap(); + let start = SpringState { value: 1.0, velocity: 2.0 }; + for (target, dt, err) in [ + (f64::NAN, 0.1, EaseError::NotFinite("target")), + (f64::INFINITY, 0.1, EaseError::NotFinite("target")), + (0.0, f64::NAN, EaseError::NotFinite("step")), + (0.0, f64::INFINITY, EaseError::NotFinite("step")), + ] { + let mut st = start; + assert_eq!(st.step(&s, target, dt), Err(err)); + assert_eq!(st, start); + } + let mut st = start; + assert!(matches!(st.step(&s, 0.0, -0.1), Err(EaseError::OutOfRange { what: "step", .. }))); + assert_eq!(st, start); + // A value too far from the target to measure is refused, not turned into NaN. + let mut far = SpringState { value: f64::MAX, velocity: 0.0 }; + assert_eq!(far.step(&s, -f64::MAX, 0.1), Err(EaseError::Overflow)); + assert_eq!(far, SpringState { value: f64::MAX, velocity: 0.0 }); +} + +#[test] +fn the_controls_map_onto_frequency_and_damping() { + let s = Spring::from_controls(0.0, 0.0).unwrap(); + assert!((s.omega() - std::f64::consts::TAU * 0.5).abs() < 1e-12 && s.damping() == 0.0); + let s = Spring::from_controls(1.0, 2.0 / 3.0).unwrap(); + assert!((s.omega() - std::f64::consts::TAU * 10.0).abs() < 1e-9 && (s.damping() - 1.0).abs() < 1e-12); + assert_eq!(Spring::from_controls(0.5, 1.0).unwrap().damping(), MAX_DAMPING_RATIO); +} diff --git a/crates/ease/src/tests/track_tests.rs b/crates/ease/src/tests/track_tests.rs new file mode 100644 index 0000000000..d39ae5a830 --- /dev/null +++ b/crates/ease/src/tests/track_tests.rs @@ -0,0 +1,162 @@ +use crate::*; + +fn key(time: f64, value: T, ease: Easing) -> Key { + Key { time, value, ease } +} + +#[test] +fn a_track_eases_between_its_keys_and_holds_outside_them() { + let t = Track::from_keys(vec![ + key(2.0, 10.0f64, Easing::QuadIn), + key(0.0, 0.0, Easing::Linear), + key(4.0, 0.0, Easing::Hold), + key(6.0, 50.0, Easing::Linear), + ]) + .unwrap(); + assert_eq!(t.keys().iter().map(|k| k.time).collect::>(), [0.0, 2.0, 4.0, 6.0]); + assert_eq!(t.sample(-1.0), Ok(0.0)); + assert_eq!(t.sample(1.0), Ok(5.0)); + assert_eq!(t.sample(2.0), Ok(10.0)); + // Quad in: a quarter of the way at half time. + assert_eq!(t.sample(3.0), Ok(7.5)); + // Hold keeps the value until the next key. + assert_eq!(t.sample(4.0), Ok(0.0)); + assert_eq!(t.sample(5.999), Ok(0.0)); + assert_eq!(t.sample(6.0), Ok(50.0)); + assert_eq!(t.sample(1e300), Ok(50.0)); +} + +#[test] +fn an_overshooting_ease_carries_the_value_past_its_keys() { + let t = Track::from_keys(vec![key(0.0, 0.0f64, Easing::BackOut), key(1.0, 100.0, Easing::Linear)]).unwrap(); + let peak = (1..100).map(|i| t.sample(i as f64 / 100.0).unwrap()).fold(f64::MIN, f64::max); + assert!(peak > 105.0 && peak < 115.0, "{peak}"); +} + +#[test] +fn tracks_hold_any_animatable_value() { + let p = Track::from_keys(vec![key(0.0, Vec2::new(0.0, 0.0), Easing::Linear), key(1.0, Vec2::new(10.0, -20.0), Easing::Linear)]).unwrap(); + assert_eq!(p.sample(0.5), Ok(Vec2::new(5.0, -10.0))); + let c = Track::from_keys(vec![key(0.0, [0.0f32, 1.0, 0.5, 1.0], Easing::Linear), key(2.0, [1.0, 0.0, 0.5, 0.0], Easing::Linear)]).unwrap(); + assert_eq!(c.sample(1.0), Ok([0.5, 0.5, 0.5, 0.5])); + let s = Track::from_keys(vec![key(0.0, 1.0f32, Easing::Linear), key(1.0, 3.0, Easing::Linear)]).unwrap(); + assert_eq!(s.sample(0.25), Ok(1.5)); + let d = Track::from_keys(vec![key(0.0, [0.0f64; 3], Easing::Linear), key(1.0, [3.0, 6.0, 9.0], Easing::Linear)]).unwrap(); + assert_eq!(d.sample(1.0 / 3.0).map(|v| v.map(|x| (x * 1e9).round() / 1e9)), Ok([1.0, 2.0, 3.0])); +} + +#[test] +fn bad_keys_and_times_are_refused() { + assert_eq!(Track::::new().sample(0.0), Err(EaseError::Empty)); + let t = Track::from_keys(vec![key(0.0, 1.0f64, Easing::Linear)]).unwrap(); + assert_eq!(t.sample(f64::NAN), Err(EaseError::NotFinite("time"))); + assert_eq!(t.sample(f64::INFINITY), Err(EaseError::NotFinite("time"))); + assert_eq!(t.sample(5.0), Ok(1.0)); + assert_eq!(Track::from_keys(vec![key(f64::NAN, 1.0f64, Easing::Linear)]), Err(EaseError::NotFinite("time"))); + assert_eq!(Track::from_keys(vec![key(0.0, f64::NAN, Easing::Linear)]), Err(EaseError::NotFinite("value"))); + assert_eq!(Track::from_keys(vec![key(0.0, Vec2::new(0.0, f64::INFINITY), Easing::Linear)]), Err(EaseError::NotFinite("value"))); + assert_eq!(Track::from_keys(vec![key(1.0, 1.0f64, Easing::Linear), key(1.0, 2.0, Easing::Linear)]), Err(EaseError::SameTime(1.0))); + // −0 and +0 are one time. + assert_eq!(Track::from_keys(vec![key(-0.0, 1.0f64, Easing::Linear), key(0.0, 2.0, Easing::Linear)]), Err(EaseError::SameTime(0.0))); + let mut z = Track::from_keys(vec![key(-0.0, 1.0f64, Easing::Linear), key(1.0, 2.0, Easing::Linear)]).unwrap(); + assert_eq!(z.key_at(0.0), Some(0)); + assert_eq!(z.key_at(-0.0), Some(0)); + assert_eq!(z.insert(0.0, 5.0), Ok(0)); + assert_eq!(z.len(), 2); + let too_many: Vec> = (0..=MAX_TRACK_KEYS).map(|i| key(i as f64, 0.0, Easing::Linear)).collect(); + assert_eq!(Track::from_keys(too_many), Err(EaseError::Full(MAX_TRACK_KEYS))); +} + +#[test] +fn inserting_splits_a_segment_with_its_ease() { + let mut t = Track::from_keys(vec![key(0.0, 0.0f64, Easing::CubicIn), key(2.0, 8.0, Easing::Linear)]).unwrap(); + assert_eq!(t.insert(1.0, 1.0), Ok(1)); + assert_eq!(t.keys()[1].ease, Easing::CubicIn); + // Setting an existing key keeps its ease. + t.set_ease(1, Easing::Hold).unwrap(); + assert_eq!(t.insert(1.0, 3.0), Ok(1)); + assert_eq!((t.keys()[1].value, &t.keys()[1].ease), (3.0, &Easing::Hold)); + assert_eq!(t.insert(-0.0, 7.0), Ok(0)); + assert_eq!(t.len(), 3); + assert_eq!(t.key_at(0.0), Some(0)); + assert_eq!(t.insert(5.0, f64::NAN), Err(EaseError::NotFinite("value"))); + assert_eq!(t.insert(f64::NEG_INFINITY, 1.0), Err(EaseError::NotFinite("time"))); + assert_eq!(t.remove(1).map(|k| k.value), Some(3.0)); + assert!(t.remove(9).is_none() && t.set_ease(9, Easing::Linear).is_none()); + // Before the first key, a new key eases linearly. + assert_eq!(t.insert(-1.0, 0.0), Ok(0)); + assert_eq!(t.keys()[0].ease, Easing::Linear); +} + +#[test] +fn keys_at_the_ends_of_the_number_range_sample_without_overflow() { + let t = Track::from_keys(vec![key(-f64::MAX, -1.0f64, Easing::Linear), key(f64::MAX, 1.0, Easing::Linear)]).unwrap(); + assert_eq!(t.sample(0.0), Ok(0.0)); + let v = t.sample(f64::MAX / 2.0).unwrap(); + assert!((v - 0.5).abs() < 1e-12, "{v}"); + // Keys a hair apart. + let near = Track::from_keys(vec![key(1.0, 0.0f64, Easing::Linear), key(1.0 + f64::EPSILON, 1.0, Easing::Linear)]).unwrap(); + assert!(near.sample(1.0 + f64::EPSILON / 2.0).unwrap().is_finite()); + // Values at opposite ends of the range interpolate without overflowing their difference. + let wide = Track::from_keys(vec![key(0.0, f64::MAX, Easing::Linear), key(1.0, -f64::MAX, Easing::Linear)]).unwrap(); + assert_eq!(wide.sample(0.5), Ok(0.0)); + let v = + Track::from_keys(vec![key(0.0, Vec2::new(-f64::MAX, 1e308), Easing::Linear), key(1.0, Vec2::new(f64::MAX, -1e308), Easing::Linear)]).unwrap(); + assert_eq!(v.sample(0.5), Ok(Vec2::ZERO)); + let a = Track::from_keys(vec![key(0.0, [f64::MAX; 2], Easing::Linear), key(1.0, [-f64::MAX; 2], Easing::Linear)]).unwrap(); + assert!(a.sample(0.25).unwrap().iter().all(|x| x.is_finite())); + // Keys a subnormal step either side of 0 still interpolate between them. + let tiny = Track::from_keys(vec![key(-f64::from_bits(1), 0.0f64, Easing::Linear), key(f64::from_bits(1), 1.0, Easing::Linear)]).unwrap(); + assert_eq!(tiny.sample(0.0), Ok(0.5)); + // An overshoot past the largest f32 is refused, not returned as infinity. + let over = Track::from_keys(vec![key(0.0, -f32::MAX, Easing::BackOut), key(1.0, f32::MAX, Easing::Linear)]).unwrap(); + assert_eq!(over.sample(0.6), Err(EaseError::Overflow)); + // An overshoot whose step past the far key is too large to represent, with a result that + // is not. + let r = crate::lerp(-1e308, 5e307, 1.25); + assert!((r / 8.75e307 - 1.0).abs() < 1e-12, "{r}"); + let back = Track::from_keys(vec![key(0.0, -f64::MAX, Easing::BackOut), key(1.0, -1e300, Easing::Linear)]).unwrap(); + assert!(back.sample(0.6).unwrap() > 0.0); +} + +#[cfg(feature = "serde")] +#[test] +fn tracks_round_trip_through_files_and_bad_files_are_refused() { + let t = Track::from_keys(vec![key(0.0, 1.0f64, Easing::Linear), key(1.5, 2.0, Easing::Hold), key(3.0, 0.5, Easing::QuadOut)]).unwrap(); + let text = serde_json::to_string(&t).unwrap(); + assert_eq!( + text, + r#"{"keys":[{"time":0.0,"value":1.0,"ease":"Linear"},{"time":1.5,"value":2.0,"ease":"Hold"},{"time":3.0,"value":0.5,"ease":"QuadOut"}]}"# + ); + assert_eq!(serde_json::from_str::>(&text).unwrap(), t); + // Keys out of order are sorted; a missing ease is linear. + let r: Track = serde_json::from_str(r#"{"keys":[{"time":2,"value":1},{"time":1,"value":0}]}"#).unwrap(); + assert_eq!((r.keys()[0].time, &r.keys()[1].ease), (1.0, &Easing::Linear)); + // Two keys at one time, or a time that is not a number, are a broken file. + assert!(serde_json::from_str::>(r#"{"keys":[{"time":1,"value":1},{"time":1,"value":0}]}"#).is_err()); + assert!(serde_json::from_str::>(r#"{"keys":[{"time":"x","value":1}]}"#).is_err()); + // More keys than a track holds are refused while reading, before the rest are read. + let mut big = String::from(r#"{"keys":["#); + for i in 0..=MAX_TRACK_KEYS { + if i > 0 { + big.push(','); + } + big.push_str(&format!(r#"{{"time":{i},"value":0}}"#)); + } + big.push_str("]}"); + let err = serde_json::from_str::>(&big).unwrap_err().to_string(); + assert!(err.contains("more than 100000 keys"), "{err}"); +} + +/// Formats that write a struct as its fields in order (rather than by name) read a track too, +/// through the same checks. +#[cfg(feature = "serde")] +#[test] +fn tracks_read_from_formats_that_write_fields_in_order() { + let t: Track = serde_json::from_str(r#"[[{"time":2,"value":1},{"time":1,"value":0,"ease":"QuadIn"}]]"#).unwrap(); + assert_eq!(t.keys().iter().map(|k| (k.time, k.value)).collect::>(), [(1.0, 0.0), (2.0, 1.0)]); + assert_eq!(t.keys()[0].ease, Easing::QuadIn); + assert!(serde_json::from_str::>(r#"[[{"time":1,"value":1},{"time":1,"value":0}]]"#).is_err()); + assert!(serde_json::from_str::>("[]").is_err()); + assert!(serde_json::from_str::>("[[], 1]").is_err()); +} diff --git a/crates/ease/src/track.rs b/crates/ease/src/track.rs new file mode 100644 index 0000000000..c2c139ddc2 --- /dev/null +++ b/crates/ease/src/track.rs @@ -0,0 +1,269 @@ +//! [`Track`]: keyed values with an ease between each key and the next. + +use crate::{EaseError, Easing, Vec2, finite}; + +/// Most keys one track holds. +pub const MAX_TRACK_KEYS: usize = 100_000; + +/// A value a track can animate: interpolated in a straight line between keys, the ease giving +/// how far along. Eases that overshoot pass `t` outside `0..=1`, which extrapolates. +pub trait Animatable: Clone { + /// The value `t` of the way from `self` to `to`. + fn lerp(&self, to: &Self, t: f64) -> Self; + /// Whether every component is finite. + fn is_finite(&self) -> bool; +} + +impl Animatable for f32 { + fn lerp(&self, to: &f32, t: f64) -> f32 { + crate::lerp(f64::from(*self), f64::from(*to), t) as f32 + } + fn is_finite(&self) -> bool { + f32::is_finite(*self) + } +} + +impl Animatable for f64 { + fn lerp(&self, to: &f64, t: f64) -> f64 { + crate::lerp(*self, *to, t) + } + fn is_finite(&self) -> bool { + f64::is_finite(*self) + } +} + +impl Animatable for Vec2 { + fn lerp(&self, to: &Vec2, t: f64) -> Vec2 { + Vec2::lerp(*self, *to, t) + } + fn is_finite(&self) -> bool { + Vec2::is_finite(*self) + } +} + +impl Animatable for [f32; N] { + fn lerp(&self, to: &[f32; N], t: f64) -> [f32; N] { + let mut out = *self; + for (o, b) in out.iter_mut().zip(to) { + *o = Animatable::lerp(&*o, b, t); + } + out + } + fn is_finite(&self) -> bool { + self.iter().all(|v| v.is_finite()) + } +} + +impl Animatable for [f64; N] { + fn lerp(&self, to: &[f64; N], t: f64) -> [f64; N] { + let mut out = *self; + for (o, b) in out.iter_mut().zip(to) { + *o = crate::lerp(*o, *b, t); + } + out + } + fn is_finite(&self) -> bool { + self.iter().all(|v| v.is_finite()) + } +} + +/// A key: a value at a time (seconds), and the ease to the next key ([`Easing::Hold`] keeps the +/// value until the next key). +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Key { + pub time: f64, + pub value: T, + #[cfg_attr(feature = "serde", serde(default))] + pub ease: Easing, +} + +/// Keys sorted by time, one per time, at most [`MAX_TRACK_KEYS`], every time and value finite. +/// +/// Before the first key a track gives the first key's value, after the last key the last's. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct Track { + keys: Vec>, +} + +impl Default for Track { + fn default() -> Self { + Track { keys: Vec::new() } + } +} + +impl Track { + pub fn new() -> Self { + Track::default() + } + + /// A track from keys a caller or a file supplies: an error for a time or value that is not + /// finite, two keys at one time, or more than [`MAX_TRACK_KEYS`]. The keys may come in any + /// order. + pub fn from_keys(mut keys: Vec>) -> Result { + if keys.len() > MAX_TRACK_KEYS { + return Err(EaseError::Full(MAX_TRACK_KEYS)); + } + for k in &mut keys { + check(k.time, &k.value)?; + // -0.0 and 0.0 are one time. + if k.time == 0.0 { + k.time = 0.0; + } + } + keys.sort_by(|a, b| a.time.total_cmp(&b.time)); + if let Some(w) = keys.windows(2).find(|w| matches!(w, [a, b] if a.time == b.time)) { + return Err(EaseError::SameTime(w.first().map_or(0.0, |k| k.time))); + } + Ok(Track { keys }) + } + + pub fn keys(&self) -> &[Key] { + &self.keys + } + + pub fn is_empty(&self) -> bool { + self.keys.is_empty() + } + + pub fn len(&self) -> usize { + self.keys.len() + } + + /// Sets the value at `time`, keeping that key's ease, or adds a key there that eases like + /// the segment it splits. Returns the key's index. An error for a time or value that is not + /// finite, or a full track. + pub fn insert(&mut self, time: f64, value: T) -> Result { + check(time, &value)?; + // -0.0 and 0.0 are one time. + let time = if time == 0.0 { 0.0 } else { time }; + match self.keys.binary_search_by(|k| k.time.total_cmp(&time)) { + Ok(i) => { + if let Some(k) = self.keys.get_mut(i) { + k.value = value; + } + Ok(i) + } + Err(i) => { + if self.keys.len() >= MAX_TRACK_KEYS { + return Err(EaseError::Full(MAX_TRACK_KEYS)); + } + let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or_else(Easing::default, |k| k.ease.clone()); + self.keys.insert(i, Key { time, value, ease }); + Ok(i) + } + } + } + + /// Sets the ease from key `i` to the next one. `None` for a missing key. + pub fn set_ease(&mut self, i: usize, ease: Easing) -> Option<()> { + self.keys.get_mut(i)?.ease = ease; + Some(()) + } + + /// Removes key `i`, returning it. + pub fn remove(&mut self, i: usize) -> Option> { + (i < self.keys.len()).then(|| self.keys.remove(i)) + } + + /// The index of the key at exactly `time` (−0 and +0 are one time). + pub fn key_at(&self, time: f64) -> Option { + let time = if time == 0.0 { 0.0 } else { time }; + self.keys.binary_search_by(|k| k.time.total_cmp(&time)).ok() + } + + /// The value at `time`. An error for an empty track, a `time` that is not finite, or an + /// overshooting ease that carries the value past what the type can hold. + pub fn sample(&self, time: f64) -> Result { + let time = finite(time, "time")?; + let (Some(first), Some(last)) = (self.keys.first(), self.keys.last()) else { return Err(EaseError::Empty) }; + if time <= first.time { + return Ok(first.value.clone()); + } + if time >= last.time { + return Ok(last.value.clone()); + } + let i = self.keys.partition_point(|k| k.time <= time); + let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| self.keys.get(j)), self.keys.get(i)) else { return Ok(last.value.clone()) }; + if a.ease == Easing::Hold { + return Ok(a.value.clone()); + } + // Keys at opposite ends of the f64 range overflow the span; halving both sides keeps it. + let span = b.time - a.time; + let t = if span.is_finite() { (time - a.time) / span } else { (time * 0.5 - a.time * 0.5) / (b.time * 0.5 - a.time * 0.5) }; + let v = a.value.lerp(&b.value, a.ease.apply(t.clamp(0.0, 1.0))); + if v.is_finite() { Ok(v) } else { Err(EaseError::Overflow) } + } +} + +fn check(time: f64, value: &T) -> Result<(), EaseError> { + finite(time, "time")?; + if value.is_finite() { Ok(()) } else { Err(EaseError::NotFinite("value")) } +} + +#[cfg(feature = "serde")] +mod serde_impl { + use super::{Animatable, Key, MAX_TRACK_KEYS, Track}; + use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + use std::marker::PhantomData; + + /// The key list, read one key at a time and refused once it passes [`MAX_TRACK_KEYS`], so a + /// hostile file cannot make it allocate more. + struct Keys(Vec>); + + impl<'de, T: Deserialize<'de>> Deserialize<'de> for Keys { + fn deserialize>(d: D) -> Result { + struct V(PhantomData); + impl<'de, T: Deserialize<'de>> Visitor<'de> for V { + type Value = Keys; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "a list of at most {MAX_TRACK_KEYS} keys") + } + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let mut keys = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(1024)); + while let Some(k) = seq.next_element()? { + if keys.len() >= MAX_TRACK_KEYS { + return Err(A::Error::custom(format!("more than {MAX_TRACK_KEYS} keys"))); + } + keys.push(k); + } + Ok(Keys(keys)) + } + } + d.deserialize_seq(V(PhantomData)) + } + } + + impl<'de, T: Animatable + Deserialize<'de>> Deserialize<'de> for Track { + fn deserialize>(d: D) -> Result { + struct V(PhantomData); + impl<'de, T: Animatable + Deserialize<'de>> Visitor<'de> for V { + type Value = Track; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "a track") + } + fn visit_map>(self, mut map: A) -> Result, A::Error> { + let mut keys: Option>> = None; + while let Some(name) = map.next_key::()? { + if name == "keys" { + keys = Some(map.next_value::>()?.0); + } else { + map.next_value::()?; + } + } + Track::from_keys(keys.unwrap_or_default()).map_err(A::Error::custom) + } + /// Formats that write a struct as its fields in order. + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let keys = seq.next_element::>()?.ok_or_else(|| A::Error::invalid_length(0, &self))?.0; + if seq.next_element::()?.is_some() { + return Err(A::Error::invalid_length(2, &self)); + } + Track::from_keys(keys).map_err(A::Error::custom) + } + } + d.deserialize_struct("Track", &["keys"], V(PhantomData)) + } + } +} diff --git a/crates/ease/src/vec2.rs b/crates/ease/src/vec2.rs new file mode 100644 index 0000000000..60a1b6896a --- /dev/null +++ b/crates/ease/src/vec2.rs @@ -0,0 +1,83 @@ +//! A 2D point or vector, for ease curve points and motion paths. + +use std::ops::{Add, Mul, Neg, Sub}; + +/// A 2D point or vector. In files it is `{"x": …, "y": …}`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Vec2 { + pub x: f64, + pub y: f64, +} + +impl Vec2 { + pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 }; + + pub const fn new(x: f64, y: f64) -> Self { + Vec2 { x, y } + } + + pub fn dot(self, o: Vec2) -> f64 { + self.x * o.x + self.y * o.y + } + + /// The length. Large components do not overflow on the way, so the length is finite whenever + /// it is at most `f64::MAX`; a longer vector, such as `(f64::MAX, f64::MAX)`, has an infinite + /// length. [`Vec2::normalized`] still gives such a vector's direction. + pub fn length(self) -> f64 { + self.x.hypot(self.y) + } + + /// The vector scaled to length 1, or zero for a zero (or non-finite) vector. The components + /// are divided by the larger one first, so a vector near the largest or smallest `f64` still + /// gives a unit vector. + pub fn normalized(self) -> Vec2 { + let m = self.x.abs().max(self.y.abs()); + if !(self.is_finite() && m > 0.0) { + return Vec2::ZERO; + } + let (x, y) = (self.x / m, self.y / m); + let l = x.hypot(y); + Vec2::new(x / l, y / l) + } + + pub fn lerp(self, o: Vec2, t: f64) -> Vec2 { + Vec2::new(crate::lerp(self.x, o.x, t), crate::lerp(self.y, o.y, t)) + } + + pub fn distance(self, o: Vec2) -> f64 { + (o - self).length() + } + + pub fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() + } +} + +impl Add for Vec2 { + type Output = Vec2; + fn add(self, o: Vec2) -> Vec2 { + Vec2::new(self.x + o.x, self.y + o.y) + } +} + +impl Sub for Vec2 { + type Output = Vec2; + fn sub(self, o: Vec2) -> Vec2 { + Vec2::new(self.x - o.x, self.y - o.y) + } +} + +impl Mul for Vec2 { + type Output = Vec2; + fn mul(self, s: f64) -> Vec2 { + Vec2::new(self.x * s, self.y * s) + } +} + +impl Neg for Vec2 { + type Output = Vec2; + fn neg(self) -> Vec2 { + Vec2::new(-self.x, -self.y) + } +} diff --git a/crates/exr/Cargo.toml b/crates/exr/Cargo.toml index 28a1649b8b..f5b5ee93e0 100644 --- a/crates/exr/Cargo.toml +++ b/crates/exr/Cargo.toml @@ -18,6 +18,7 @@ decode = ["dep:exr", "dep:half", "dep:thiserror", "zlib-inflate"] zlib-inflate = ["dep:flate2"] [dependencies] +serde = { workspace = true } serde_json = { workspace = true } exr = { version = "1.73", default-features = false, optional = true } half = { version = "2", optional = true } diff --git a/crates/exr/src/decode.rs b/crates/exr/src/decode.rs index 1ec050565f..94efc864de 100644 --- a/crates/exr/src/decode.rs +++ b/crates/exr/src/decode.rs @@ -8,12 +8,14 @@ //! 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. Other parts may be deep. -//! - [`fn@write`] writes one scan-line part. +//! - [`fn@write`] writes one scan-line part. [`crate::write`] accepts rows incrementally for one +//! or more parts. //! //! The `exr` crate sizes buffers from headers before it reads pixels, so everything that reaches //! it is checked first: preview attributes against their own size, each part's samples against -//! [`Limits`], all parts together against the budget, and the samples against what a file of -//! this size can decompress to. +//! [`Limits`], all parts together against the budget, the samples against what a file of this +//! size can decompress to, and the packed length of each chunk of the part being read against the +//! rest of the file and the budget. use std::io::Cursor; @@ -64,6 +66,10 @@ fn map_exr(e: exr::error::Error) -> Error { } } +/// The most attributes one header may hold, standard ones included. The readers refuse a header +/// above it and the writer refuses to produce one. +pub(crate) const MAX_HEADER_ATTRIBUTES: usize = 4096; + /// Caps on what a file may ask the reader to allocate. `#[non_exhaustive]`: start from /// [`Limits::default`] and set the fields you change. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -456,7 +462,11 @@ pub fn decode_display_part( if pixels > limits.max_pixels { return Err(Error::LimitExceeded(format!("display window of {pixels} pixels exceeds {}", limits.max_pixels))); } - let kept = info.channels.iter().filter(|channel| keep(&part_channel_name(info.name.as_deref(), &channel.name))).count(); + let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?; + let prefix = header.own_attributes.layer_name.as_ref().map(|name| name.to_string()).filter(|name| !name.is_empty()); + let kept_names = kept_channel_names(header, prefix.as_deref(), keep); + let kept = + header.channels.list.iter().filter(|channel| kept_names.contains(&part_channel_name(prefix.as_deref(), &channel.name.to_string()))).count(); let bytes_needed = pixels .checked_mul(4) .and_then(|bytes_per_channel| bytes_per_channel.checked_mul(kept as u64)) @@ -464,16 +474,18 @@ pub fn decode_display_part( if bytes_needed > limits.max_bytes || usize::try_from(bytes_needed).is_err() { return Err(Error::LimitExceeded(format!("{bytes_needed} display-window bytes exceed {}", limits.max_bytes))); } + let recorded = |name: &str| kept_names.contains(name); + let keep: &dyn Fn(&str) -> bool = &recorded; 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 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 { + check_flat_packed_lengths(bytes, &meta, index, kept > 0, limits)?; ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}) .from_buffered(Cursor::new(bytes)) .map_err(exr_error)? @@ -822,6 +834,104 @@ pub(super) fn flat_block_ordinal(header: &Header, tile: TileCoordinates) -> Resu Err(malformed("flat tile names a missing level")) } +/// Part `index`'s offset table (one `u64` per chunk) and where the last offset table ends. The +/// tables follow the headers, one per part in header order, and must all lie inside the file. +fn part_offset_table<'a>(bytes: &'a [u8], meta: &MetaData, index: usize) -> Result<(&'a [u8], u64)> { + let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?; + 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)?; + Ok((offsets, tables_end)) +} + +/// The bytes from `offset` to the end of the file, and the packed length the flat chunk there +/// declares. The chunk must start past the last offset table and inside the file, carry part +/// number `index` in a multipart file, and declare no more bytes than the file has left after its +/// length field. +fn flat_chunk_at<'a>(bytes: &'a [u8], header: &Header, multipart: bool, index: usize, offset: u64, tables_end: u64) -> Result<(&'a [u8], usize)> { + 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"))?; + Ok((chunk, size)) +} + +/// The names of `header`'s channels that `keep` accepts, named as the channel readers name them +/// (behind `prefix`, the part's name, when there is one). `keep` is asked once per channel, and +/// the readers and the packed-length check use this one answer. +fn kept_channel_names(header: &Header, prefix: Option<&str>, keep: &dyn Fn(&str) -> bool) -> std::collections::HashSet { + let names = header.channels.list.iter().map(|channel| part_channel_name(prefix, &channel.name.to_string())); + names.filter(|name| keep(name)).collect() +} + +/// Checks every chunk of flat part `index` before the `exr` crate's image reader reads the part. +/// That reader reserves a chunk's declared packed length, up to the part's nominal block size, +/// before it reads the payload, so each chunk is checked as [`flat_chunk_at`] describes. The +/// reader picks the chunks it reads by their place in the offset table, which follows the +/// part's blocks in increasing y order, and reads only the blocks of the largest resolution +/// level, and none when the decode keeps no channel (`reads_any` false). The packed length of +/// each chunk the reader reads must also fit in [`Limits::max_bytes`]. +/// +/// The table has one entry per block (`header.chunk_count`). Every block of a scan-line part is +/// at the largest level. In a tiled part the largest level's tiles come first, so an entry is at +/// that level when its place is below that level's tile count. The check works from these counts +/// and does not list the blocks, so its memory does not grow with the size of the offset table. +fn check_flat_packed_lengths(bytes: &[u8], meta: &MetaData, index: usize, reads_any: bool, limits: &Limits) -> Result<()> { + let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?; + let multipart = meta.requirements.is_multilayer(); + let (offsets, tables_end) = part_offset_table(bytes, meta, index)?; + let largest_level_blocks = match &header.blocks { + exr::meta::BlockDescription::Tiles(tiles) => { + let (tile_w, tile_h) = (tiles.tile_size.width(), tiles.tile_size.height()); + if tile_w == 0 || tile_h == 0 { + return Err(malformed("flat block has a zero dimension")); + } + header.layer_size.width().div_ceil(tile_w).saturating_mul(header.layer_size.height().div_ceil(tile_h)) + } + exr::meta::BlockDescription::ScanLines => header.chunk_count, + }; + let read_count = if reads_any { largest_level_blocks } else { 0 }; + for (place, &entry) in offsets.as_chunks::<8>().0.iter().enumerate() { + let (_, size) = flat_chunk_at(bytes, header, multipart, index, u64::from_le_bytes(entry), tables_end)?; + let read = place < read_count; + if read && size as u64 > limits.max_bytes { + return Err(Error::LimitExceeded("packed flat block exceeds the byte budget".into())); + } + } + Ok(()) +} + /// 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 @@ -839,19 +949,7 @@ fn read_flat_part_chunks(bytes: &[u8], meta: &MetaData, index: usize, reader: &m 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)?; + let (offsets, tables_end) = part_offset_table(bytes, meta, index)?; // 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); @@ -863,31 +961,7 @@ fn read_flat_part_chunks(bytes: &[u8], meta: &MetaData, index: usize, reader: &m 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"))?; + let (chunk, size) = flat_chunk_at(bytes, header, multipart, index, offset, tables_end)?; // 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 }; @@ -959,6 +1033,10 @@ pub fn decode_part(bytes: &[u8], index: usize, keep: &dyn Fn(&str) -> bool, limi return Err(Error::Unsupported("HTJ2K compression".into())); } let info = part_info(index, header); + let kept_names = kept_channel_names(header, None, keep); + let keeps_any = !kept_names.is_empty(); + let recorded = |name: &str| kept_names.contains(name); + let keep: &dyn Fn(&str) -> bool = &recorded; let select = Select { index, keep, seen: std::cell::Cell::new(0) }; let planes = if meta.headers.iter().any(|header| header.deep) { select.seen.set(index); @@ -966,6 +1044,7 @@ pub fn decode_part(bytes: &[u8], index: usize, keep: &dyn Fn(&str) -> bool, limi read_flat_part_chunks(bytes, &meta, index, &mut reader, limits)?; reader.into_channels() } else { + check_flat_packed_lengths(bytes, &meta, index, keeps_any, limits)?; 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"))? }; @@ -998,7 +1077,7 @@ pub enum SampleDepth { Half, } -fn to_exr_compression(compression: Compression) -> ExrCompression { +pub(crate) fn to_exr_compression(compression: Compression) -> ExrCompression { match compression { Compression::None => ExrCompression::Uncompressed, Compression::Rle => ExrCompression::RLE, diff --git a/crates/exr/src/decode_tests.rs b/crates/exr/src/decode_tests.rs index 32fefa029f..59d2c08ff7 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -179,6 +179,133 @@ fn decoded_display_part_rejects_kept_subsampled_channels() { assert!(matches!(decode_display_part(&bytes, 0, &|name| name == "R", &|_| 0.0, &Limits::default()), Err(Error::Unsupported(_)))); } +#[test] +fn a_flat_chunk_s_packed_length_is_checked_before_the_crate_reads_it() { + // One 9 × 7 tile of a 1024 × 1024 tile size: the crate would reserve up to the nominal tile + // (1024 × 1024 pixels of three f32 channels, 12 MiB) for the chunk's declared length. + let list = ["B", "G", "R"].iter().map(|n| AnyChannel::new(*n, FlatSamples::F32(ramp(63, 1.0)))).collect(); + let encoding = Encoding { + compression: exr::prelude::Compression::Uncompressed, + blocks: Blocks::Tiles(exr::math::Vec2(1024, 1024)), + line_order: LineOrder::Increasing, + }; + let mut bytes = file(vec![Layer::new((9, 7), LayerAttributes::default(), encoding, AnyChannels::sort(list))], (9, 7)); + assert_eq!(decode_part(&bytes, 0, &all, &Limits::default()).unwrap().channels.len(), 3); + let mut cursor = std::io::Cursor::new(&bytes[..]); + exr::meta::MetaData::read_from_buffered(&mut cursor, false).unwrap(); + let table = cursor.position() as usize; + let chunk = u64::from_le_bytes(bytes[table..table + 8].try_into().unwrap()) as usize; + // The packed length follows the four tile coordinates. + let size_at = chunk + 16; + bytes.extend_from_slice(&[0; 2000]); + let limits = Limits { max_bytes: 1000, ..Limits::default() }; + let r = |name: &str| name == "R"; + // More bytes than the file has left after the length. + bytes[size_at..size_at + 4].copy_from_slice(&i32::MAX.to_le_bytes()); + assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::Malformed(m)) if m.contains("remain in the file"))); + assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::Malformed(m)) if m.contains("remain in the file"))); + // Inside the file, but over the byte budget. + bytes[size_at..size_at + 4].copy_from_slice(&1001i32.to_le_bytes()); + assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(_)))); + assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::LimitExceeded(_)))); + // A decode that keeps no channel reads no chunk. + let none = |_: &str| false; + assert!(decode_part(&bytes, 0, &none, &limits).unwrap().channels.is_empty()); + assert!(decode_display_part(&bytes, 0, &none, &|_| 0.0, &limits).unwrap().channels.is_empty()); +} + +#[test] +fn a_skipped_flat_chunk_s_packed_length_is_not_held_to_the_budget() { + use exr::math::RoundingMode; + use exr::prelude::Levels; + // 9 × 7 in 4 × 4 tiles with mip levels. The reader reads only the six tiles of level 0, so a + // smaller level's chunk may declare more than the budget while it fits in the file. + let sizes: Vec = exr::meta::mip_map_levels(RoundingMode::Down, exr::math::Vec2(9, 7)).map(|(_, size)| size.area()).collect(); + let levels = Levels::Mip { rounding_mode: RoundingMode::Down, level_data: sizes.iter().map(|n| FlatSamples::F32(ramp(*n, 1.0))).collect() }; + let encoding = Encoding { + compression: exr::prelude::Compression::Uncompressed, + blocks: Blocks::Tiles(exr::math::Vec2(4, 4)), + line_order: LineOrder::Increasing, + }; + let channels = AnyChannels::sort(vec![AnyChannel::new("R", levels)].into()); + let layers = vec![Layer::new((9, 7), LayerAttributes::default(), encoding, channels)]; + let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (9, 7))), layers); + let mut out = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).unwrap(); + let mut bytes = out.into_inner(); + let mut cursor = std::io::Cursor::new(&bytes[..]); + let meta = exr::meta::MetaData::read_from_buffered(&mut cursor, false).unwrap(); + let table = cursor.position() as usize; + let count = meta.headers[0].chunk_count; + assert!(count > 6, "the part has chunks beyond level 0"); + // The last chunk in the table holds the smallest level: its tile coordinates, then its level. + let last = table + (count - 1) * 8; + let chunk = u64::from_le_bytes(bytes[last..last + 8].try_into().unwrap()) as usize; + let level_x = i32::from_le_bytes(bytes[chunk + 8..chunk + 12].try_into().unwrap()); + let level_y = i32::from_le_bytes(bytes[chunk + 12..chunk + 16].try_into().unwrap()); + assert_ne!((level_x, level_y), (0, 0)); + bytes.extend_from_slice(&[0; 2000]); + bytes[chunk + 16..chunk + 20].copy_from_slice(&1500i32.to_le_bytes()); + let limits = Limits { max_bytes: 1000, ..Limits::default() }; + let r = |name: &str| name == "R"; + assert_eq!(decode_part(&bytes, 0, &all, &limits).unwrap().channels.len(), 1); + assert_eq!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits).unwrap().channels.len(), 1); + // The reader picks chunks by their place in the table, so a level-0 entry that points at the + // smaller level's chunk is read, and that chunk's length is held to the budget. + let entry = bytes[last..last + 8].to_vec(); + bytes[table..table + 8].copy_from_slice(&entry); + assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(_)))); + assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::LimitExceeded(_)))); +} + +#[test] +fn the_packed_length_check_finds_the_end_of_level_0_among_many_small_tiles() { + use exr::math::RoundingMode; + use exr::prelude::Levels; + // 64 × 48 in 1 × 1 tiles with mip levels: the 3,072 tiles of level 0 fill the first places of + // the offset table, and the smaller levels follow. + let (w, h) = (64, 48); + let sizes: Vec = exr::meta::mip_map_levels(RoundingMode::Down, exr::math::Vec2(w, h)).map(|(_, size)| size.area()).collect(); + let levels = Levels::Mip { rounding_mode: RoundingMode::Down, level_data: sizes.iter().map(|n| FlatSamples::F32(ramp(*n, 1.0))).collect() }; + let encoding = Encoding { + compression: exr::prelude::Compression::Uncompressed, + blocks: Blocks::Tiles(exr::math::Vec2(1, 1)), + line_order: LineOrder::Increasing, + }; + let channels = AnyChannels::sort(vec![AnyChannel::new("R", levels)].into()); + let layers = vec![Layer::new((w, h), LayerAttributes::default(), encoding, channels)]; + let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), layers); + let mut out = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).unwrap(); + let mut bytes = out.into_inner(); + let mut cursor = std::io::Cursor::new(&bytes[..]); + let meta = exr::meta::MetaData::read_from_buffered(&mut cursor, false).unwrap(); + let table = cursor.position() as usize; + let level_0 = w * h; + assert!(meta.headers[0].chunk_count > level_0, "the part has chunks beyond level 0"); + let chunk_at = |bytes: &[u8], place: usize| u64::from_le_bytes(bytes[table + place * 8..table + place * 8 + 8].try_into().unwrap()) as usize; + let level_of = |bytes: &[u8], chunk: usize| { + let x = i32::from_le_bytes(bytes[chunk + 8..chunk + 12].try_into().unwrap()); + let y = i32::from_le_bytes(bytes[chunk + 12..chunk + 16].try_into().unwrap()); + (x, y) + }; + let (last_read, first_skipped) = (chunk_at(&bytes, level_0 - 1), chunk_at(&bytes, level_0)); + assert_eq!(level_of(&bytes, last_read), (0, 0)); + assert_ne!(level_of(&bytes, first_skipped), (0, 0)); + // The decoded part takes 12,288 bytes, inside the budget; a declared length of 30,000 is not. + bytes.extend_from_slice(&[0; 40_000]); + let limits = Limits { max_bytes: 20_000, ..Limits::default() }; + let r = |name: &str| name == "R"; + // The first chunk past level 0 is not read, so its length is not held to the budget. + bytes[first_skipped + 16..first_skipped + 20].copy_from_slice(&30_000i32.to_le_bytes()); + assert_eq!(decode_part(&bytes, 0, &all, &limits).unwrap().channels.len(), 1); + assert_eq!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits).unwrap().channels.len(), 1); + // The last chunk of level 0 is read, so its length is. + bytes[last_read + 16..last_read + 20].copy_from_slice(&30_000i32.to_le_bytes()); + assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(_)))); + assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::LimitExceeded(_)))); +} + /// A 2x2 single-part file whose layer carries a 2x1 preview. fn with_preview() -> Vec { let mut attrs = LayerAttributes::named("rgb"); @@ -224,7 +351,16 @@ fn limits_are_checked_from_the_headers() { // is over; the 1 MiB slack always admits small pictures. assert!(ok(Limits { max_ratio: 0, ..d })); // A header claiming a huge data window over a few bytes of file is refused by the ratio. - let big = file(vec![layer(None, 4096, 4096, &["R"], false, exr::prelude::Compression::ZIP16)], (4096, 4096)); + // Only headers are read here: keep the large declared windows without encoding their pixels. + let mut big = file(vec![layer(None, 8, 4, &["R"], false, exr::prelude::Compression::ZIP16)], (8, 4)); + let window: Vec = [0i32, 0, 4095, 4095].iter().flat_map(|v| v.to_le_bytes()).collect(); + for tag in ["dataWindow\0box2i\0", "displayWindow\0box2i\0"] { + let tag = tag.as_bytes(); + let at = big.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len() + 4; + big[at..at + 16].copy_from_slice(&window); + } + // At 1024 file bytes the default ratio admits 64 MiB, but ratio 1 plus 1 MiB slack does not. + big.resize(1024, 0); assert!(ok_big(&big)); assert!(matches!(parts(&big, &Limits { max_ratio: 1, ..d }), Err(Error::LimitExceeded(_)))); } diff --git a/crates/exr/src/layer_stack.rs b/crates/exr/src/layer_stack.rs new file mode 100644 index 0000000000..2e53f4d2c9 --- /dev/null +++ b/crates/exr/src/layer_stack.rs @@ -0,0 +1,372 @@ +//! The optional `craftLayerStack` string attribute describes an editable raster layer stack. +//! The EXR remains readable as an ordinary image without this attribute. Version 1 is an +//! ASCII-safe JSON object. Layer array order is bottom-to-top within each parent. The beauty +//! image and other passes can be stored in EXR parts or channels outside the manifest. + +use std::collections::HashMap; +use std::fmt::{self, Write}; + +use serde::{Deserialize, Serialize}; + +pub const ATTRIBUTE_NAME: &str = "craftLayerStack"; +pub const MAX_ATTRIBUTE_BYTES: usize = 1 << 20; +const VERSION: u64 = 1; +const MAX_LAYERS: usize = 4096; +const MAX_GROUP_DEPTH: usize = 100; + +#[derive(Debug)] +pub enum Error { + Limit(&'static str), + Malformed(&'static str), + Json(serde_json::Error), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{ATTRIBUTE_NAME}: ")?; + match self { + Self::Limit(message) | Self::Malformed(message) => f.write_str(message), + Self::Json(error) => error.fmt(f), + } + } +} + +impl std::error::Error for Error {} + +#[derive(Debug, Clone, PartialEq)] +pub struct LayerStack { + pub layers: Vec, + /// The producer's original RGB compositing encoding. A portable profile ID or + /// `icc:` describing an ICC profile. EXR chromaticities describe the stored pixels. + pub original_blend_profile: Option, + /// The producer's document sample depth before conversion to EXR channels. + pub original_sample_depth: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SampleDepth { + U8, + U16, + F32, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Layer { + pub id: u64, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent: Option, + pub visible: bool, + /// Portable blend mode identifier. Consumers may warn and use Normal for unsupported modes. + pub blend: String, + pub opacity: f32, + pub fill_opacity: f32, + pub clipped: bool, + pub content: LayerContent, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] +pub enum LayerContent { + Group, + Raster { pixels: PixelRef, sampling: PixelSampling }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] +pub enum PixelRef { + /// A named, flat EXR part. Use part names that are unique within the file. + Part { name: String }, + /// The exact prefix of the RGB(A) channels in the zero-based flat EXR part. + /// An empty prefix selects unprefixed channels such as `R`, `G` and `B`. + ChannelGroup { part: u32, prefix: String }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PixelSampling { + /// Raster pixels from the source layer. + Raw, + /// Raster pixels derived by rendering the source layer. Transforms, effects or masks may + /// be baked into the pixels. The manifest's stack compositing properties still apply. + Baked, +} + +#[derive(Deserialize)] +struct Version { + version: u64, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Input { + version: u64, + layers: Vec, + original_blend_profile: Option, + original_sample_depth: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Output<'a> { + version: u64, + layers: &'a [Layer], + #[serde(skip_serializing_if = "Option::is_none")] + original_blend_profile: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + original_sample_depth: Option, +} + +impl LayerStack { + /// Parse the attribute, returning `None` for an unsupported version. A caller can still + /// open the EXR as a flat image in that case. + pub fn parse(text: &str) -> Result, Error> { + if text.len() > MAX_ATTRIBUTE_BYTES { + return Err(Error::Limit("attribute is too large")); + } + if !text.trim_start().starts_with('{') { + return Err(Error::Malformed("expected a JSON object")); + } + let version = serde_json::from_str::(text).map_err(Error::Json)?.version; + if version != VERSION { + return Ok(None); + } + let Input { version, layers, original_blend_profile, original_sample_depth } = serde_json::from_str(text).map_err(Error::Json)?; + if version != VERSION { + return Ok(None); + } + let stack = Self { layers, original_blend_profile, original_sample_depth }; + stack.validate()?; + Ok(Some(stack)) + } + + /// Validate and serialize version 1. Unicode layer names are escaped to keep the EXR + /// header ASCII-safe. + pub fn to_attribute(&self) -> Result { + self.validate()?; + let json = serde_json::to_string(&Output { + version: VERSION, + layers: &self.layers, + original_blend_profile: self.original_blend_profile.as_deref(), + original_sample_depth: self.original_sample_depth, + }) + .map_err(Error::Json)?; + if json.len() > MAX_ATTRIBUTE_BYTES { + return Err(Error::Limit("attribute is too large")); + } + let mut text = String::with_capacity(json.len()); + for c in json.chars() { + if c.is_ascii() { + text.push(c); + } else { + for unit in c.encode_utf16(&mut [0; 2]) { + write!(text, "\\u{unit:04x}").map_err(|_| Error::Limit("could not encode attribute text"))?; + } + } + if text.len() > MAX_ATTRIBUTE_BYTES { + return Err(Error::Limit("attribute is too large")); + } + } + Ok(text) + } + + /// Check the manifest's intrinsic constraints. Consumers check its pixel references + /// against the file headers before decoding. + pub fn validate(&self) -> Result<(), Error> { + if self.layers.len() > MAX_LAYERS { + return Err(Error::Limit("too many layers")); + } + if self.original_blend_profile.as_deref().is_some_and(|profile| !valid_profile(profile)) { + return Err(Error::Malformed("invalid original RGB blend profile")); + } + let mut text_bytes = self.original_blend_profile.as_ref().map_or(0, String::len); + let mut by_id = HashMap::with_capacity(self.layers.len()); + for layer in &self.layers { + if by_id.insert(layer.id, layer).is_some() { + return Err(Error::Malformed("duplicate layer ID")); + } + if layer.name.len() > 4096 { + return Err(Error::Limit("layer name is too large")); + } + if !valid_label(&layer.blend) { + return Err(Error::Malformed("invalid blend mode identifier")); + } + if !(0.0..=1.0).contains(&layer.opacity) || !(0.0..=1.0).contains(&layer.fill_opacity) { + return Err(Error::Malformed("opacity and fill opacity must be between zero and one")); + } + text_bytes = text_bytes.saturating_add(layer.name.len()).saturating_add(layer.blend.len()); + if let LayerContent::Raster { pixels, .. } = &layer.content { + let (name, min, max) = match pixels { + PixelRef::Part { name } => (name, 1, 255), + PixelRef::ChannelGroup { prefix, .. } => (prefix, 0, 253), + }; + if !(min..=max).contains(&name.chars().count()) || name.chars().any(|c| c.is_control() || u32::from(c) > 255) { + return Err(Error::Malformed("invalid EXR part or channel group name")); + } + text_bytes = text_bytes.saturating_add(name.len()); + } + if text_bytes > MAX_ATTRIBUTE_BYTES { + return Err(Error::Limit("attribute is too large")); + } + } + for layer in &self.layers { + let mut at = layer; + let mut depth = 0; + while let Some(parent) = at.parent { + let ancestor = by_id.get(&parent).ok_or(Error::Malformed("unknown parent layer"))?; + if ancestor.content != LayerContent::Group { + return Err(Error::Malformed("a parent layer must be a group")); + } + if ancestor.id == layer.id { + return Err(Error::Malformed("cyclic layer hierarchy")); + } + depth += 1; + if depth > MAX_GROUP_DEPTH { + return Err(Error::Limit("layer hierarchy is too deep")); + } + at = ancestor; + } + } + Ok(()) + } +} + +fn valid_label(label: &str) -> bool { + !label.trim().is_empty() && label.len() <= 128 && label.bytes().all(|b| b == b' ' || b.is_ascii_graphic()) +} + +fn valid_profile(profile: &str) -> bool { + if let Some(encoded) = profile.strip_prefix("icc:") { + if encoded.is_empty() || encoded.len() > MAX_ATTRIBUTE_BYTES || !encoded.len().is_multiple_of(4) { + return false; + } + let data = encoded.trim_end_matches('='); + !data.is_empty() && encoded.len() - data.len() <= 2 && data.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/')) + } else { + valid_label(profile) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn stack() -> LayerStack { + LayerStack { + layers: vec![ + Layer { + id: u64::MAX, + name: "東京 🎞".into(), + parent: Some(8), + visible: false, + blend: "multiply".into(), + opacity: 0.4, + fill_opacity: 0.5, + clipped: true, + content: LayerContent::Raster { pixels: PixelRef::Part { name: "Layer".into() }, sampling: PixelSampling::Baked }, + }, + Layer { + id: 8, + name: "Group".into(), + parent: None, + visible: true, + blend: "passThrough".into(), + opacity: 1.0, + fill_opacity: 1.0, + clipped: false, + content: LayerContent::Group, + }, + ], + original_blend_profile: Some("icc:AAE=".into()), + original_sample_depth: None, + } + } + + #[test] + fn unicode_and_compositing_fields_round_trip_through_an_ascii_attribute() { + let stack = stack(); + let encoded = stack.to_attribute().unwrap(); + assert!(encoded.is_ascii()); + assert_eq!(LayerStack::parse(&encoded).unwrap(), Some(stack)); + } + + #[test] + fn original_sample_depth_is_optional_in_version_one() { + let old = r#"{"version":1,"layers":[]}"#; + let stack = LayerStack::parse(old).unwrap().unwrap(); + assert_eq!(stack.original_sample_depth, None); + assert_eq!(stack.to_attribute().unwrap(), old); + + for (depth, wire) in [(SampleDepth::U8, "u8"), (SampleDepth::U16, "u16"), (SampleDepth::F32, "f32")] { + let stack = LayerStack { original_sample_depth: Some(depth), ..stack.clone() }; + let text = format!(r#"{{"version":1,"layers":[],"originalSampleDepth":"{wire}"}}"#); + assert_eq!(stack.to_attribute().unwrap(), text); + assert_eq!(LayerStack::parse(&text).unwrap(), Some(stack)); + } + assert!(LayerStack::parse(r#"{"version":1,"layers":[],"originalSampleDepth":"f16"}"#).is_err()); + } + + #[test] + fn empty_channel_group_prefix_round_trips_but_empty_part_name_is_invalid() { + let mut stack = stack(); + stack.layers[0].content = + LayerContent::Raster { pixels: PixelRef::ChannelGroup { part: 0, prefix: String::new() }, sampling: PixelSampling::Raw }; + let text = stack.to_attribute().unwrap(); + assert_eq!(LayerStack::parse(&text).unwrap(), Some(stack.clone())); + + stack.layers[0].content = LayerContent::Raster { pixels: PixelRef::Part { name: String::new() }, sampling: PixelSampling::Raw }; + assert!(matches!(stack.to_attribute(), Err(Error::Malformed(_)))); + } + + #[test] + fn supports_a_raster_inside_one_hundred_groups() { + let mut stack = stack(); + let group = stack.layers[1].clone(); + stack.layers.truncate(1); + stack.layers[0].parent = Some(100); + for id in 1..=100 { + stack.layers.push(Layer { id, parent: (id > 1).then_some(id - 1), ..group.clone() }); + } + let text = stack.to_attribute().unwrap(); + assert_eq!(LayerStack::parse(&text).unwrap(), Some(stack.clone())); + + stack.layers.push(Layer { id: 101, parent: Some(100), ..group }); + stack.layers[0].parent = Some(101); + assert!(matches!(stack.to_attribute(), Err(Error::Limit(_)))); + } + + #[test] + fn supports_flat_image_fallback_for_unknown_versions_and_rejects_bad_v1() { + assert!(LayerStack::parse(r#"{"version":2,"layout":{"different":true}}"#).unwrap().is_none()); + for text in [ + r#"{"version":1,"layers":[],"unexpected":null}"#, + r#"{"version":1,"version":2,"layers":[]}"#, + r#"{"version":1,"layers":[],"originalBlendProfile":"icc:abc?"}"#, + r#"{"version":"1","layers":[]}"#, + ] { + assert!(LayerStack::parse(text).is_err(), "{text}"); + } + assert!(matches!(LayerStack::parse(&" ".repeat(MAX_ATTRIBUTE_BYTES + 1)), Err(Error::Limit(_)))); + } + + #[test] + fn rejects_ambiguous_identity_invalid_opacity_and_bad_hierarchy() { + let mut s = stack(); + s.layers[0].id = 8; + assert!(s.to_attribute().is_err()); + let mut s = stack(); + s.layers[0].fill_opacity = f32::NAN; + assert!(s.to_attribute().is_err()); + let mut s = stack(); + s.layers[1].parent = Some(8); + assert!(s.to_attribute().is_err()); + let mut s = stack(); + s.layers[1].parent = Some(u64::MAX); + assert!(s.to_attribute().is_err()); + let mut s = stack(); + s.layers[0].parent = Some(9); + assert!(s.to_attribute().is_err()); + } +} diff --git a/crates/exr/src/lib.rs b/crates/exr/src/lib.rs index 833bd79910..5db34a65fa 100644 --- a/crates/exr/src/lib.rs +++ b/crates/exr/src/lib.rs @@ -9,6 +9,7 @@ //! and alpha. //! - [`cryptomatte`]: Cryptomatte (specification 1.2) IDs, metadata keys, manifests and rank //! channel names. +//! - [`layer_stack`]: optional layer hierarchy and compositing metadata for editable EXR exchange. //! //! Those take names and attribute text and depend on no decoder. With the `decode` feature: //! @@ -18,6 +19,7 @@ //! - `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. +//! - `write`: write flat scan-line parts from a row callback to a seekable destination. //! - `cryptomatte_samples`: a file's Cryptomatte layers and their per-pixel (ID, coverage) ranks. /// Bounded RLE expansion and inverse byte prediction for EXR blocks. @@ -53,9 +55,14 @@ pub mod deep; mod deep_tests; #[cfg(feature = "decode")] mod dwa_guard; +pub mod layer_stack; #[cfg(feature = "decode")] pub mod seek; #[cfg(all(test, feature = "decode"))] mod seek_tests; #[cfg(feature = "decode")] pub mod stream; +#[cfg(feature = "decode")] +pub mod write; +#[cfg(all(test, feature = "decode"))] +mod write_tests; diff --git a/crates/exr/src/seek.rs b/crates/exr/src/seek.rs index 03f0fa506b..0bccc7dad0 100644 --- a/crates/exr/src/seek.rs +++ b/crates/exr/src/seek.rs @@ -60,7 +60,7 @@ 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}; +use crate::decode::{Limits, MAX_HEADER_ATTRIBUTES, 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)] @@ -119,10 +119,10 @@ fn exr_error(e: exr::error::Error) -> Error { } const MAGIC: [u8; 4] = [0x76, 0x2f, 0x31, 0x01]; -/// Headers of all parts together: at most this many bytes, parts, and attributes per part. +/// Headers of all parts together: at most this many bytes and parts. Attributes per header are +/// bounded by `MAX_HEADER_ATTRIBUTES`. 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 × @@ -293,6 +293,13 @@ impl Index { self.display } + /// Stored RGB primaries and white point (red, green, blue, white in CIE xy), from the first + /// part that supplies the shared chromaticities attribute. + pub fn chromaticities(&self) -> Option<[[f32; 2]; 4]> { + let c = self.meta.headers.iter().find_map(|header| header.shared_attributes.chromaticities.as_ref())?; + Some([c.red, c.green, c.blue, c.white].map(|v| [v.0, v.1])) + } + /// 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 @@ -386,8 +393,8 @@ fn read_headers(r: &mut R, cancel: &dyn Fn() -> bool) -> Resul break; } attributes += 1; - if attributes > MAX_ATTRIBUTES { - return Err(Error::LimitExceeded("more than 4096 attributes in a header".into())); + if attributes > MAX_HEADER_ATTRIBUTES { + return Err(Error::LimitExceeded(format!("more than {MAX_HEADER_ATTRIBUTES} attributes in a header"))); } read_name(r, &mut prefix, None)?; let mut size = [0u8; 4]; @@ -606,11 +613,14 @@ pub struct Request<'a> { /// 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)], + /// Use this part's data window as the output grid, keeping samples beyond the display + /// window. Every requested channel must belong to this part. Default: the display window. + pub data_window: Option, /// 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. + /// The rows to read, counted from the output window's top row, at full resolution. + /// `None`: all rows. pub rows: Option>, /// Every `2^level`-th row and column of the display window (0: full resolution, at most 16). pub level: u32, @@ -644,7 +654,7 @@ 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: &[] } + Request { channels, data_window: None, fill: &[], rows: None, level: 0, max_bytes, workers: None, max_block_bytes: None, groups: &[] } } } @@ -657,7 +667,7 @@ pub fn level_size((width, height): (usize, usize), level: u32) -> (usize, usize) /// 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 +/// selected window's top-left corner (0, 0, whatever its absolute position): window pixels at /// level 0, every `2^level`-th pixel above. #[derive(Debug, Clone, PartialEq)] pub struct Band { @@ -761,6 +771,7 @@ struct Geometry<'a> { size: (usize, usize), out: (usize, usize), stride: i64, + in_data_window: bool, /// The display rows read. rows: Range, /// Each part's channel → the request slots that name it. @@ -771,6 +782,10 @@ struct Geometry<'a> { } impl Geometry<'_> { + fn offset(&self, part: &PartLayout) -> (i64, i64) { + if self.in_data_window { (0, 0) } else { part.offset } + } + /// 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 @@ -810,6 +825,7 @@ struct Plan { size: (usize, usize), out: (usize, usize), stride: i64, + in_data_window: bool, rows: Range, /// The chunks to read, in file order. jobs: Vec, @@ -821,7 +837,26 @@ struct Plan { 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 } + Geometry { + size: self.size, + out: self.out, + stride: self.stride, + in_data_window: self.in_data_window, + rows: self.rows.clone(), + slots: &self.slots, + units: &self.units, + } + } +} + +fn request_window(index: &Index, request: &Request) -> Result { + if let Some(part) = request.data_window { + if request.channels.iter().any(|(p, _)| *p != part) { + return Err(malformed("every channel in a data-window request must belong to that part")); + } + index.parts.get(part).map(|p| p.data_window).ok_or_else(|| malformed("no such data window part")) + } else { + Ok(index.display) } } @@ -830,7 +865,9 @@ impl Plan { 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 window = request_window(index, request)?; + let (w, h) = (window.width as usize, window.height as usize); + let in_data_window = request.data_window.is_some(); 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(); @@ -872,7 +909,7 @@ fn plan(index: &Index, request: &Request) -> Result { // (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 }; + let geometry = Geometry { size: (w, h), out, stride, in_data_window, 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 { @@ -888,7 +925,7 @@ fn plan(index: &Index, request: &Request) -> Result { continue; } for c in &part.chunks { - let top = (c.y as i64).saturating_add(part.offset.1); + let top = (c.y as i64).saturating_add(geometry.offset(part).1); if !geometry.any_wanted(top, top.saturating_add(c.rows as i64)) { continue; } @@ -914,7 +951,7 @@ fn plan(index: &Index, request: &Request) -> Result { // (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 }) + Ok(Plan { slots, size: (w, h), out, stride, in_data_window, rows, jobs, workers, units }) } impl Index { @@ -1188,7 +1225,8 @@ fn next_result(results: &Receiver<(usize, Decoded)>, cancel: &dyn Fn() -> bool) /// 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 window = request_window(index, request)?; + let (w, h) = (window.width as usize, window.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()); @@ -1451,12 +1489,13 @@ fn chunk_bands(index: &Index, pi: usize, expected: &ChunkRef, buf: &[u8], g: &Ge 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 (offset_x, offset_y) = g.offset(part); 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_map(|y| usize::try_from(y as i64 + offset_y).ok()) .filter(|ty| *ty < h && g.wanted(*ty as i64)) .map(|ty| ty / g.stride as usize) .collect(); @@ -1477,11 +1516,11 @@ fn chunk_bands(index: &Index, pi: usize, expected: &ChunkRef, buf: &[u8], g: &Ge 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 }; + let Some(ty) = usize::try_from(y as i64 + offset_y).ok().filter(|ty| *ty < h) else { continue }; if !g.wanted(ty as i64) { continue; } - let tx0 = x0 as i64 + part.offset.0; + let tx0 = x0 as i64 + offset_x; 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)); diff --git a/crates/exr/src/seek_tests.rs b/crates/exr/src/seek_tests.rs index 0f48fdb386..2bb2ddb071 100644 --- a/crates/exr/src/seek_tests.rs +++ b/crates/exr/src/seek_tests.rs @@ -14,7 +14,7 @@ use exr::prelude::{ WritableImage, }; -use super::decode::{Limits, decode_display_part}; +use super::decode::{Limits, Window, decode_display_part}; use super::seek::*; fn value(i: usize, k: usize) -> f32 { @@ -52,6 +52,29 @@ fn indexed(bytes: &[u8]) -> Index { Index::build(&mut Cursor::new(bytes), &Limits::default(), &never).unwrap() } +#[test] +fn index_finds_chromaticities_in_a_later_part_header() { + let window = Window { x: 0, y: 0, width: 1, height: 1 }; + let channels = [crate::write::Channel { name: "Y", sample: crate::decode::SampleType::F32 }]; + let first = crate::write::Part { name: Some("First"), data_window: window, channels: &channels, compression: crate::decode::Compression::None }; + let second = crate::write::Part { name: Some("Second"), ..first }; + let chromaticities = [[0.64, 0.33], [0.3, 0.6], [0.15, 0.06], [0.3127, 0.329]]; + let metadata = crate::write::Metadata { chromaticities: Some(chromaticities), ..Default::default() }; + let mut out = Cursor::new(Vec::new()); + crate::write::write_scanlines_with_metadata(&mut out, window, &[first, second], &metadata, |_, _, _, row| Ok(row.len())).unwrap(); + let mut bytes = out.into_inner(); + + // Rename the first header's attribute without shifting the second header or any offsets. + let attr = b"chromaticities\0chromaticities\0"; + let positions: Vec<_> = bytes.windows(attr.len()).enumerate().filter_map(|(offset, bytes)| (bytes == attr).then_some(offset)).collect(); + assert_eq!(positions.len(), 2); + bytes[positions[0]] = b'x'; + let headers = exr::meta::MetaData::read_from_buffered(Cursor::new(&bytes), false).unwrap().headers; + assert!(headers[0].shared_attributes.chromaticities.is_none()); + assert!(headers[1].shared_attributes.chromaticities.is_some()); + assert_eq!(indexed(&bytes).chromaticities(), Some(chromaticities)); +} + /// 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() @@ -89,6 +112,25 @@ fn only_the_requested_channels_are_returned_in_the_requested_order() { assert_eq!(read.planes, [whole[3].clone(), whole[0].clone()]); } +#[test] +fn reading_in_a_parts_data_window_keeps_off_display_tiles() { + let bytes = file( + vec![ + layer(Some("beauty"), (0, 0), (8, 6), &["R"], false, Compression::ZIP1), + layer(Some("paint"), (-2, -3), (9, 7), &["R"], true, Compression::ZIP1), + ], + (8, 6), + ); + let index = indexed(&bytes); + let request = Request { data_window: Some(1), ..Request::new(&[(1, 0)], usize::MAX) }; + let output = read_planes(&mut Cursor::new(&bytes), &index, &request, &never).unwrap(); + assert_eq!((output.width, output.height), (9, 7)); + assert_eq!(output.stats.chunks[0], 0); + assert_eq!(output.planes[0], (0..9 * 7).map(|i| value(i, 0)).collect::>()); + let wrong_part = Request { data_window: Some(1), ..Request::new(&[(0, 0)], usize::MAX) }; + assert!(index.estimate(&wrong_part).is_err()); +} + #[test] fn a_part_with_no_requested_channel_is_not_read() { let bytes = file( diff --git a/crates/exr/src/stream.rs b/crates/exr/src/stream.rs index c3d942e947..6f9ab3ef3d 100644 --- a/crates/exr/src/stream.rs +++ b/crates/exr/src/stream.rs @@ -1,6 +1,6 @@ //! Bounded block-by-block reading of one flat scan-line part (feature `decode`): a reader that //! never sizes a buffer by the whole picture. [`Decoder::new`] reads the headers (at most 8 MiB -//! and 4096 attributes) and the offset table through `Read + Seek`; [`Decoder::next_band`] then +//! and 4,096 attributes) and the offset table through `Read + Seek`; [`Decoder::next_band`] then //! returns one compression block at a time as interleaved f32 samples. A caller that writes bands //! into tiled storage can open pictures larger than memory. //! @@ -21,7 +21,7 @@ use exr::{ }; use crate::channels::{ColorLayout, color_channels}; -use crate::decode::{Error, Result}; +use crate::decode::{Error, MAX_HEADER_ATTRIBUTES, Result}; const META_BYTES: usize = 8 << 20; const BLOCK_BYTES: usize = 64 << 20; @@ -73,8 +73,8 @@ fn metadata(r: &mut impl Read, cancel: &dyn Fn() -> bool) -> Result> { break; } attributes += 1; - if attributes > 4096 { - return Err(limit("EXR metadata exceeds 4096 attributes")); + if attributes > MAX_HEADER_ATTRIBUTES { + return Err(limit(&format!("EXR metadata exceeds {MAX_HEADER_ATTRIBUTES} attributes"))); } string(r, &mut prefix)?; let length = read::<4>(r)?; diff --git a/crates/exr/src/write.rs b/crates/exr/src/write.rs new file mode 100644 index 0000000000..0e2daba2a4 --- /dev/null +++ b/crates/exr/src/write.rs @@ -0,0 +1,660 @@ +//! Incremental flat OpenEXR output (feature `decode`). +//! +//! [`write_scanlines`] asks for one typed channel row at a time. [`write_tiles`] asks for one +//! tile at a time. Both buffer a single compression block, with sample and codec scratch space, +//! metadata and one offset per chunk. + +use std::collections::HashSet; +use std::io::{Seek, SeekFrom, Write}; +use std::ops::Range; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use exr::block::writer::ChunksWriter; +use exr::block::{BlockIndex, UncompressedBlock, enumerate_ordered_header_block_indices}; +use exr::math::{RoundingMode, Vec2}; +use exr::meta::attribute::{ + AttributeValue, ChannelDescription, Chromaticities, IntegerBounds, LevelMode, LineOrder, SampleType as ExrSample, Text, TileDescription, +}; +use exr::meta::{BlockDescription, Headers, header::Header}; + +use crate::decode::{Compression, Error, MAX_HEADER_ATTRIBUTES, Result, SampleType, Window, f16, to_exr_compression}; + +const MAX_PARTS: usize = 1024; +const MAX_CHANNELS: usize = 16_384; +const MAX_CHUNKS: usize = 1 << 20; +const MAX_BLOCK_BYTES: usize = 64 << 20; +const MAX_NAME_BYTES: usize = 255; +const SHORT_NAME_BYTES: usize = 31; +const VERSION_WORD_OFFSET: u64 = 4; +const MAX_HEADER_BYTES: usize = 8 << 20; +const MAX_TEXT_ATTRIBUTES: usize = 16_384; + +/// Name and stored sample type of a full-resolution channel. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Channel<'a> { + pub name: &'a str, + pub sample: SampleType, +} + +/// The window, channels and encoding of one flat part. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Part<'a> { + /// Required and unique in a multipart file. Optional in a single-part file. + pub name: Option<&'a str>, + pub data_window: Window, + pub channels: &'a [Channel<'a>], + /// Per-part compression. + pub compression: Compression, +} + +/// One flat tiled part with a single resolution level. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TilePart<'a> { + pub part: Part<'a>, + pub tile_width: u32, + pub tile_height: u32, +} + +/// Names and values of the `string` attributes of one part. +pub type TextAttributes<'a> = &'a [(&'a str, &'a str)]; + +/// Optional file and part attributes. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Metadata<'a> { + /// CIE xy for red, green, blue and white, shared by every part. + pub chromaticities: Option<[[f32; 2]; 4]>, + /// Text attributes by input part index. An empty slice supplies no attributes. The file + /// accepts at most 16,384 text attributes and 8 MiB of estimated headers. A part's header + /// holds at most 4,096 attributes, so its text attributes leave room for the standard + /// attributes the writer adds (channels, windows, compression and the like, plus the part + /// name and type in a multipart file). + pub text_attributes: &'a [TextAttributes<'a>], +} + +/// A buffer to fill in the channel's stored type. Tiles use a contiguous, row-major channel plane. +#[derive(Debug)] +pub enum RowSamples<'a> { + F16(&'a mut [f16]), + F32(&'a mut [f32]), + U32(&'a mut [u32]), +} + +impl RowSamples<'_> { + pub fn len(&self) -> usize { + match self { + Self::F16(row) => row.len(), + Self::F32(row) => row.len(), + Self::U32(row) => row.len(), + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + fn reborrow(&mut self) -> RowSamples<'_> { + match self { + Self::F16(row) => RowSamples::F16(row), + Self::F32(row) => RowSamples::F32(row), + Self::U32(row) => RowSamples::U32(row), + } + } + + fn clear(&mut self) { + match self { + Self::F16(row) => row.fill(f16::ZERO), + Self::F32(row) => row.fill(0.0), + Self::U32(row) => row.fill(0), + } + } + + fn append_to(&self, data: &mut Vec) { + match self { + Self::F16(row) => row.iter().for_each(|sample| data.extend_from_slice(&sample.to_bits().to_ne_bytes())), + Self::F32(row) => row.iter().for_each(|sample| data.extend_from_slice(&sample.to_ne_bytes())), + Self::U32(row) => row.iter().for_each(|sample| data.extend_from_slice(&sample.to_ne_bytes())), + } + } + + fn copy_range_to(&self, range: Range, data: &mut [u8]) -> Result<()> { + fn copy(samples: &[T], range: Range, data: &mut [u8], bytes: impl Fn(&T) -> [u8; N]) -> Result<()> { + let samples = samples.get(range).ok_or_else(|| encode("invalid tile sample range"))?; + let (destinations, remainder) = data.as_chunks_mut::(); + if !remainder.is_empty() || destinations.len() != samples.len() { + return Err(encode("invalid tile channel byte length")); + } + for (sample, dest) in samples.iter().zip(destinations) { + *dest = bytes(sample); + } + Ok(()) + } + match self { + Self::F16(samples) => copy(samples, range, data, |sample| sample.to_bits().to_ne_bytes()), + Self::F32(samples) => copy(samples, range, data, |sample| sample.to_ne_bytes()), + Self::U32(samples) => copy(samples, range, data, |sample| sample.to_ne_bytes()), + } + } +} + +/// Writes one or more flat scan-line parts with a common `display_window`. +/// +/// `fill_row(part, row, channel, samples)` fills the given buffer and returns the number of +/// samples supplied. `part` and `channel` are indices into the supplied descriptors. Parts +/// follow input order and rows increase from `0` at each part's data-window top. Within a row, +/// channels are requested in file name order. A callback error stops writing and is returned. +/// +/// Pass a fresh seekable output positioned at byte zero. The caller owns buffering, truncation +/// and cleanup of partial output after an I/O or callback error. Invalid descriptors are rejected +/// before output begins. Maximums are 1,024 parts, 16,384 channels across all parts, 1,048,576 +/// chunks across all parts and 64 MiB of uncompressed samples per chunk. +pub fn write_scanlines( + out: &mut W, + display_window: Window, + parts: &[Part<'_>], + fill_row: impl FnMut(usize, usize, usize, RowSamples<'_>) -> Result, +) -> Result<()> { + write_scanlines_with_metadata(out, display_window, parts, &Metadata::default(), fill_row) +} + +/// [`write_scanlines`] with optional file and part attributes. +pub fn write_scanlines_with_metadata( + out: &mut W, + display_window: Window, + parts: &[Part<'_>], + metadata: &Metadata<'_>, + mut fill_row: impl FnMut(usize, usize, usize, RowSamples<'_>) -> Result, +) -> Result<()> { + let (headers, channel_orders) = prepare_headers(display_window, parts.iter().map(|&part| (part, Storage::ScanLines)), metadata)?; + let mut rows = SampleBuffers::new(&headers, |header| header.layer_size.0)?; + write_blocks(out, headers, |index, header| { + let order = channel_orders.get(index.layer).ok_or_else(|| encode("invalid scan-line block part"))?; + fill_block(index, header, order, &mut rows, &mut fill_row) + }) +} + +/// Writes one or more flat tiled parts with a common display window and one resolution level. +/// +/// `fill_tile(part, window, writer)` is called once per tile and supplies each channel once +/// through [`TileWriter::fill_channel`]. `part` is the input part index. `window` gives the +/// tile's absolute coordinates and its actual size, clipped to its part's data window at edges. +/// Parts follow input order and tiles are requested left to right, then top to bottom. +/// The output and block limits are as for [`write_scanlines`], with the uncompressed block +/// limit applied to the nominal tile dimensions. +pub fn write_tiles( + out: &mut W, + display_window: Window, + parts: &[TilePart<'_>], + metadata: &Metadata<'_>, + mut fill_tile: impl FnMut(usize, Window, &mut TileWriter<'_>) -> Result<()>, +) -> Result<()> { + let layouts = parts.iter().map(|part| (part.part, Storage::Tiles(part.tile_width, part.tile_height))); + let (headers, channel_orders) = prepare_headers(display_window, layouts, metadata)?; + let mut planes = SampleBuffers::new(&headers, |header| { + let Vec2(w, h) = header.max_block_pixel_size(); + w.min(header.layer_size.0).saturating_mul(h.min(header.layer_size.1)) + })?; + let layouts: Vec<_> = headers.iter().zip(&channel_orders).map(|(header, order)| tile_layout(header, order)).collect::>()?; + let mut supplied = vec![false; layouts.iter().map(Vec::len).max().unwrap_or_default()]; + write_blocks(out, headers, |index, header| { + let layout = layouts.get(index.layer).ok_or_else(|| encode("invalid tile part"))?; + let supplied = supplied.get_mut(..layout.len()).ok_or_else(|| encode("invalid tile channel count"))?; + supplied.fill(false); + let window = tile_window(index, header)?; + let bytes = block_bytes(index, header)?; + let mut data = block_buffer(bytes)?; + data.resize(bytes, 0); + let Vec2(width, height) = index.pixel_size; + let mut writer = + TileWriter { width, height, bytes_per_pixel: header.channels.bytes_per_pixel, layout, supplied, data: &mut data, planes: &mut planes }; + fill_tile(index.layer, window, &mut writer)?; + if let Some(channel) = writer.supplied.iter().position(|&supplied| !supplied) { + return Err(encode(format_args!("part {}, tile at ({}, {}): missing channel {channel}", index.layer, window.x, window.y))); + } + Ok(data) + }) +} + +/// Receives the channel planes of one tile in the caller's channel order. +pub struct TileWriter<'a> { + width: usize, + height: usize, + bytes_per_pixel: usize, + layout: &'a [TileChannel], + supplied: &'a mut [bool], + data: &'a mut [u8], + planes: &'a mut SampleBuffers, +} + +impl TileWriter<'_> { + /// Fills a typed, row-major channel plane containing one sample per pixel. The callback + /// returns the number of samples it supplied. + pub fn fill_channel(&mut self, channel: usize, fill: impl FnOnce(RowSamples<'_>) -> Result) -> Result<()> { + let layout = self.layout.get(channel).ok_or_else(|| encode(format_args!("unknown tile channel {channel}")))?; + let supplied = self.supplied.get_mut(channel).ok_or_else(|| encode("invalid tile channel bookkeeping"))?; + if *supplied { + return Err(encode(format_args!("duplicate tile channel {channel}"))); + } + let len = self.width.checked_mul(self.height).ok_or_else(|| encode("tile sample count overflow"))?; + let mut plane = self.planes.get(layout.sample, len)?; + plane.clear(); + let count = fill(plane.reborrow())?; + if count != len { + return Err(encode(format_args!("tile channel {channel}: expected {len} samples, got {count}"))); + } + let stride = self.width * self.bytes_per_pixel; + let start = self.width * layout.offset; + let end = start + self.width * layout.sample.bytes_per_sample(); + for (y, row) in self.data.chunks_exact_mut(stride).enumerate() { + let dest = row.get_mut(start..end).ok_or_else(|| encode("invalid tile channel byte range"))?; + plane.copy_range_to(y * self.width..(y + 1) * self.width, dest)?; + } + *supplied = true; + Ok(()) + } +} + +#[derive(Clone, Copy)] +struct TileChannel { + sample: ExrSample, + // Width-independent byte count of the channels preceding this one in file order. + offset: usize, +} + +fn tile_layout(header: &Header, order: &[usize]) -> Result> { + let mut channels = vec![TileChannel { sample: ExrSample::F16, offset: 0 }; order.len()]; + let mut offset = 0; + for (&input, channel) in order.iter().zip(&header.channels.list) { + let entry = channels.get_mut(input).ok_or_else(|| encode("invalid tile channel order"))?; + *entry = TileChannel { sample: channel.sample_type, offset }; + offset += channel.sample_type.bytes_per_sample(); + } + Ok(channels) +} + +fn tile_window(index: BlockIndex, header: &Header) -> Result { + let position = |start: i32, offset: usize| { + i32::try_from(offset).ok().and_then(|offset| start.checked_add(offset)).ok_or_else(|| encode("tile coordinate overflow")) + }; + let origin = header.own_attributes.layer_position; + Ok(Window { + x: position(origin.0, index.pixel_position.0)?, + y: position(origin.1, index.pixel_position.1)?, + width: u32::try_from(index.pixel_size.0).map_err(encode)?, + height: u32::try_from(index.pixel_size.1).map_err(encode)?, + }) +} + +fn write_blocks( + mut out: &mut W, + headers: Headers, + mut read_block: impl FnMut(BlockIndex, &Header) -> Result>, +) -> Result<()> { + if out.stream_position().map_err(encode)? != 0 { + return Err(encode("output must start at byte zero")); + } + let has_long_names = headers.iter().any(|header| { + header.own_attributes.layer_name.as_ref().is_some_and(|name| name.bytes().len() > SHORT_NAME_BYTES) + || header.channels.list.iter().any(|channel| channel.name.bytes().len() > SHORT_NAME_BYTES) + }); + let mut version_update = None; + let mut block_error = None; + let written = catch_unwind(AssertUnwindSafe(|| { + exr::block::write(&mut *out, headers, true, |meta, writer| { + if has_long_names && !meta.requirements.has_long_names { + version_update = Some(exr::meta::Requirements { has_long_names: true, ..meta.requirements }); + } + for (chunk_index, index) in enumerate_ordered_header_block_indices(&meta.headers) { + let data = + meta.headers.get(index.layer).ok_or_else(|| encode("invalid block part")).and_then(|header| read_block(index, header)).map_err( + |error| { + block_error = Some(error); + exr::error::Error::Aborted + }, + )?; + let chunk = UncompressedBlock { index, data }.compress_to_chunk(&meta.headers)?; + writer.write_chunk(chunk_index, chunk)?; + } + Ok(()) + }) + })); + if let Some(error) = block_error { + return Err(error); + } + written.map_err(|_| encode("block writer panicked"))?.map_err(encode)?; + // The codec can omit bit 10 when inferring requirements from channel names. Update the + // OpenEXR v2 version word in place, preserving the codec's other flags and all chunk offsets. + if let Some(requirements) = version_update { + let position = out.stream_position().map_err(encode)?; + out.seek(SeekFrom::Start(VERSION_WORD_OFFSET)).map_err(encode)?; + requirements.write(&mut out).map_err(encode)?; + out.seek(SeekFrom::Start(position)).map_err(encode)?; + } + out.flush().map_err(encode) +} + +#[derive(Clone, Copy)] +enum Storage { + ScanLines, + Tiles(u32, u32), +} + +impl Storage { + fn describe(self, size: Vec2, compression: exr::compression::Compression) -> Result<(BlockDescription, Vec2, usize)> { + match self { + Self::ScanLines => { + let rows = compression.scan_lines_per_block(); + Ok((BlockDescription::ScanLines, Vec2(size.0, rows), size.1.div_ceil(rows))) + } + Self::Tiles(width, height) => { + let dimension = |n| usize::try_from(n).ok().filter(|&n| n > 0 && n <= MAX_BLOCK_BYTES); + let (w, h) = dimension(width).zip(dimension(height)).ok_or_else(|| encode("invalid tile dimensions"))?; + let chunks = size.0.div_ceil(w).checked_mul(size.1.div_ceil(h)).ok_or_else(|| encode("tile count overflow"))?; + let tile_size = Vec2(w, h); + let tiles = TileDescription { tile_size, level_mode: LevelMode::Singular, rounding_mode: RoundingMode::Down }; + Ok((BlockDescription::Tiles(tiles), tile_size, chunks)) + } + } + } +} + +fn prepare_headers<'a>( + display_window: Window, + parts: impl ExactSizeIterator, Storage)>, + metadata: &Metadata<'_>, +) -> Result<(Headers, Vec>)> { + let part_count = parts.len(); + if part_count == 0 || part_count > MAX_PARTS { + return Err(encode("expected 1 to 1,024 parts")); + } + if !metadata.text_attributes.is_empty() && metadata.text_attributes.len() != part_count { + return Err(encode("text attributes must have one entry per part")); + } + if metadata.text_attributes.iter().map(|attributes| attributes.len()).fold(0usize, usize::saturating_add) > MAX_TEXT_ATTRIBUTES { + return Err(encode(format_args!("more than {MAX_TEXT_ATTRIBUTES} text attributes"))); + } + let chromaticities = metadata.chromaticities.map(checked_chromaticities).transpose()?; + let display = window_bounds(display_window)?; + let mut headers = Headers::new(); + let mut channel_orders = Vec::with_capacity(part_count); + let mut part_names = HashSet::new(); + let (mut channel_count, mut chunk_count) = (0usize, 0usize); + let mut max_file_bytes = 16usize; // Magic, version and header-list terminator. + let mut header_bytes = 16usize; + for (index, (part, storage)) in parts.enumerate() { + let name = part.name.map(|name| checked_name(name, "part")).transpose()?; + if let Some(name) = &name { + if !part_names.insert(name.clone()) { + return Err(encode(format_args!("duplicate part name {name}"))); + } + } else if part_count > 1 { + return Err(encode(format_args!("multipart part {index} needs a name"))); + } + + let data = window_bounds(part.data_window)?; + let (width, height) = (data.size.0, data.size.1); + channel_count = channel_count.saturating_add(part.channels.len()); + if part.channels.is_empty() || channel_count > MAX_CHANNELS { + return Err(encode(format_args!("part {index} needs channels and the file supports up to {MAX_CHANNELS} channels"))); + } + + let compression = to_exr_compression(part.compression); + let (blocks, Vec2(block_width, block_height), chunks) = storage.describe(data.size, compression)?; + chunk_count = chunk_count.saturating_add(chunks); + if chunk_count > MAX_CHUNKS { + return Err(encode(format_args!("more than {MAX_CHUNKS} blocks"))); + } + + let mut channels = Vec::with_capacity(part.channels.len()); + for (channel_index, channel) in part.channels.iter().enumerate() { + let name = checked_name(channel.name, "channel")?; + let sample = match channel.sample { + SampleType::F16 => ExrSample::F16, + SampleType::F32 => ExrSample::F32, + SampleType::U32 => ExrSample::U32, + }; + channels.push((channel_index, ChannelDescription::named(name, sample))); + } + channels.sort_unstable_by(|(_, a), (_, b)| a.name.cmp(&b.name)); + if let Some([(_, a), _]) = channels.windows(2).find(|pair| matches!(pair, [(_, a), (_, b)] if a.name == b.name)) { + return Err(encode(format_args!("duplicate channel name {} in part {index}", a.name))); + } + + let bytes_per_pixel: usize = channels.iter().map(|(_, channel)| channel.sample_type.bytes_per_sample()).sum(); + let bounded_height = if matches!(storage, Storage::ScanLines) { block_height.min(height) } else { block_height }; + if block_width.saturating_mul(bounded_height).saturating_mul(bytes_per_pixel) > MAX_BLOCK_BYTES { + return Err(encode(format_args!("a block in part {index} exceeds {MAX_BLOCK_BYTES} uncompressed bytes"))); + } + // The codec uses usize for the nominal block size and output offsets. Allow space + // beyond raw samples for standard attributes, channel entries, and chunk prefixes/offsets. + if block_width.checked_mul(block_height).and_then(|n| n.checked_mul(bytes_per_pixel)).is_none() { + return Err(encode(format_args!("a block in part {index} exceeds the codec's addressable size"))); + } + let header_estimate = 1024 + channels.iter().map(|(_, channel)| channel.name.bytes().len() + 32).sum::(); + header_bytes = header_bytes.saturating_add(header_estimate); + let attributes = metadata.text_attributes.get(index).copied().unwrap_or_default(); + let extra_bytes = text_bytes(attributes, &mut header_bytes)?; + let overhead = header_estimate + extra_bytes + chunks * 32; + max_file_bytes = width + .checked_mul(height) + .and_then(|pixels| pixels.checked_mul(bytes_per_pixel)) + .and_then(|samples| samples.checked_add(overhead)) + .and_then(|part_bytes| max_file_bytes.checked_add(part_bytes)) + .ok_or_else(|| encode("file may exceed the codec's addressable size"))?; + + let (order, descriptions) = channels.into_iter().unzip(); + let mut header = Header::new(Text::from_slice_unchecked(b""), data.size, descriptions) + .with_display_window(display) + .with_position(data.position) + .with_encoding(compression, blocks, LineOrder::Increasing); + header.own_attributes.layer_name = name; + header.shared_attributes.chromaticities = chromaticities; + set_text_attributes(&mut header, attributes)?; + let header_attributes = header.all_named_attributes().count(); + if header_attributes > MAX_HEADER_ATTRIBUTES { + return Err(encode(format_args!( + "part {index} has {header_attributes} attributes, standard ones included, and a header holds at most {MAX_HEADER_ATTRIBUTES}" + ))); + } + headers.push(header); + channel_orders.push(order); + } + Ok((headers, channel_orders)) +} + +fn checked_name(name: &str, kind: &str) -> Result { + // exr::Text stores one byte per character. Check the character count before allocating it. + if name.is_empty() || name.chars().take(MAX_NAME_BYTES + 1).count() > MAX_NAME_BYTES || name.bytes().any(|byte| byte == 0) { + return Err(encode(format_args!("invalid {kind} name: expected 1 to {MAX_NAME_BYTES} OpenEXR bytes without NUL"))); + } + Text::new_or_none(name).ok_or_else(|| encode(format_args!("invalid {kind} name: unsupported characters"))) +} + +fn checked_chromaticities(points: [[f32; 2]; 4]) -> Result { + if points.iter().flatten().any(|value| !value.is_finite()) { + return Err(encode("chromaticities must be finite")); + } + let [red, green, blue, white] = points.map(|[x, y]| Vec2(x, y)); + Ok(Chromaticities { red, green, blue, white }) +} + +fn text_bytes(attributes: TextAttributes<'_>, header_bytes: &mut usize) -> Result { + let start = *header_bytes; + if start > MAX_HEADER_BYTES { + return Err(encode("OpenEXR headers exceed 8 MiB")); + } + for &(key, value) in attributes { + *header_bytes = header_bytes.saturating_add(key.len()).saturating_add(value.len()).saturating_add(16); + if *header_bytes > MAX_HEADER_BYTES { + return Err(encode("OpenEXR headers exceed 8 MiB")); + } + } + Ok(*header_bytes - start) +} + +fn set_text_attributes(header: &mut Header, attributes: TextAttributes<'_>) -> Result<()> { + let mut seen = HashSet::new(); + for &(name, value) in attributes { + let key = checked_name(name, "attribute")?; + if !seen.insert(name) { + return Err(encode(format_args!("duplicate attribute {name}"))); + } + let value = Text::new_or_none(value).ok_or_else(|| encode(format_args!("invalid string attribute {name}: unsupported characters")))?; + if value.bytes().contains(&0) { + return Err(encode(format_args!("invalid string attribute {name}: contains NUL"))); + } + let attrs = &mut header.own_attributes; + let field = match name { + "owner" => &mut attrs.owner, + "comments" => &mut attrs.comments, + "capDate" => &mut attrs.capture_date, + "wrapmodes" => &mut attrs.wrap_mode_name, + "view" => &mut attrs.view_name, + "software" => &mut attrs.software_name, + "renderingTransform" => &mut attrs.rendering_transform_name, + "lookModTransform" => &mut attrs.look_modification_transform_name, + "channels" + | "compression" + | "dataWindow" + | "displayWindow" + | "lineOrder" + | "pixelAspectRatio" + | "screenWindowCenter" + | "screenWindowWidth" + | "name" + | "type" + | "version" + | "chunkCount" + | "tiles" + | "maxSamplesPerPixel" + | "chromaticities" + | "timeCode" + | "preview" + | "whiteLuminance" + | "adoptedNeutral" + | "xDensity" + | "utcOffset" + | "longitude" + | "latitude" + | "altitude" + | "focus" + | "expTime" + | "aperture" + | "isoSpeed" + | "envmap" + | "keyCode" + | "framesPerSecond" + | "multiView" + | "worldToCamera" + | "worldToNDC" + | "deepImageState" + | "originalDataWindow" + | "nearClipPlane" + | "farClipPlane" + | "horizontalFieldOfView" + | "verticalFieldOfView" => { + return Err(encode(format_args!("reserved attribute {name}"))); + } + _ => { + attrs.other.insert(key, AttributeValue::Text(value)); + continue; + } + }; + *field = Some(value); + } + Ok(()) +} + +fn window_bounds(window: Window) -> Result { + let axis = |position: i32, size: u32| { + // The codec works with inclusive and exclusive ends and negates the origin in i32. + let size = i32::try_from(size).ok().filter(|&size| size > 0)?; + position.checked_neg()?; + position.checked_add(size)?; + usize::try_from(size).ok() + }; + let size = axis(window.x, window.width).zip(axis(window.y, window.height)).ok_or_else(|| encode("invalid OpenEXR window dimensions"))?; + Ok(IntegerBounds::new((window.x, window.y), size)) +} + +struct SampleBuffers { + half: Vec, + float: Vec, + uint: Vec, +} + +impl SampleBuffers { + fn new(headers: &[Header], samples: impl Fn(&Header) -> usize) -> Result { + let mut lengths = (0, 0, 0); + for header in headers { + for channel in &header.channels.list { + let len = match channel.sample_type { + ExrSample::F16 => &mut lengths.0, + ExrSample::F32 => &mut lengths.1, + ExrSample::U32 => &mut lengths.2, + }; + *len = (*len).max(samples(header)); + } + } + fn zeroed(width: usize) -> Result> { + let mut samples = Vec::new(); + samples.try_reserve_exact(width).map_err(|_| encode("could not allocate sample buffer"))?; + samples.resize(width, T::default()); + Ok(samples) + } + Ok(Self { half: zeroed(lengths.0)?, float: zeroed(lengths.1)?, uint: zeroed(lengths.2)? }) + } + + fn get(&mut self, sample: ExrSample, width: usize) -> Result> { + match sample { + ExrSample::F16 => self.half.get_mut(..width).map(RowSamples::F16), + ExrSample::F32 => self.float.get_mut(..width).map(RowSamples::F32), + ExrSample::U32 => self.uint.get_mut(..width).map(RowSamples::U32), + } + .ok_or_else(|| encode("sample buffer has the wrong size")) + } +} + +fn fill_block( + index: BlockIndex, + header: &Header, + order: &[usize], + rows: &mut SampleBuffers, + fill_row: &mut impl FnMut(usize, usize, usize, RowSamples<'_>) -> Result, +) -> Result> { + let part = index.layer; + let Vec2(width, height) = index.pixel_size; + let mut data = block_buffer(block_bytes(index, header)?)?; + let first = index.pixel_position.1; + let end = first.checked_add(height).ok_or_else(|| encode("scan-line row index overflow"))?; + for row in first..end { + for (&channel, description) in order.iter().zip(&header.channels.list) { + let mut samples = rows.get(description.sample_type, width)?; + samples.clear(); + let count = fill_row(part, row, channel, samples.reborrow())?; + if count != width { + return Err(encode(format_args!("part {part}, channel {channel}, row {row}: expected {width} samples, got {count}"))); + } + samples.append_to(&mut data); + } + } + Ok(data) +} + +fn block_bytes(index: BlockIndex, header: &Header) -> Result { + let Vec2(width, height) = index.pixel_size; + width + .checked_mul(height) + .and_then(|pixels| pixels.checked_mul(header.channels.bytes_per_pixel)) + .filter(|&bytes| (1..=MAX_BLOCK_BYTES).contains(&bytes)) + .ok_or_else(|| encode("invalid block size")) +} + +fn block_buffer(bytes: usize) -> Result> { + let mut data = Vec::new(); + data.try_reserve_exact(bytes).map_err(|_| encode("could not allocate block buffer"))?; + Ok(data) +} + +fn encode(message: impl std::fmt::Display) -> Error { + Error::Encode(message.to_string()) +} diff --git a/crates/exr/src/write_tests.rs b/crates/exr/src/write_tests.rs new file mode 100644 index 0000000000..a9c2737441 --- /dev/null +++ b/crates/exr/src/write_tests.rs @@ -0,0 +1,453 @@ +use std::cell::Cell; +use std::io::{self, Cursor, Seek, SeekFrom, Write}; + +use crate::decode::{self, Compression, Error, Limits, MAX_HEADER_ATTRIBUTES, SampleType, Samples, Window, f16}; +use crate::seek::{Index, Request, read_planes}; +use crate::write::{Channel, Metadata, Part, RowSamples, TilePart, TileWriter, write_scanlines, write_scanlines_with_metadata, write_tiles}; + +const WINDOW: Window = Window { x: -3, y: -5, width: 64, height: 35 }; +const HALF: Channel<'_> = Channel { name: "R", sample: SampleType::F16 }; +const FLOAT: Channel<'_> = Channel { name: "Z", sample: SampleType::F32 }; +const UINT: Channel<'_> = Channel { name: "ID", sample: SampleType::U32 }; + +fn half_value(row: usize, channel: usize, x: usize) -> f16 { + f16::from_f32((row * 8 + channel * 32 + x / 8) as f32 / 16.0) +} + +fn depth_value(row: usize, x: usize) -> f32 { + f32::from_bits(0x3f80_0001 + (row * 8 + x / 8) as u32) +} + +fn id_value(row: usize, x: usize) -> u32 { + u32::MAX - (row * 8 + x / 8) as u32 +} + +fn sample_row(_: usize, row: usize, channel: usize, mut samples: RowSamples<'_>) -> decode::Result { + match &mut samples { + RowSamples::F16(values) => values.iter_mut().enumerate().for_each(|(x, value)| *value = half_value(row, channel, x)), + RowSamples::F32(values) => values.iter_mut().enumerate().for_each(|(x, value)| *value = depth_value(row, x)), + RowSamples::U32(values) => values.iter_mut().enumerate().for_each(|(x, value)| *value = id_value(row, x)), + } + Ok(samples.len()) +} + +fn whole_plane(window: Window, sample: impl Fn(usize, usize) -> T) -> Vec { + (0..window.height as usize).flat_map(|row| (0..window.width as usize).map(move |x| (row, x))).map(|(row, x)| sample(row, x)).collect() +} + +fn fill_tile(part: TilePart<'_>, window: Window, tile: &mut TileWriter<'_>) -> decode::Result<()> { + let x0 = (window.x - part.part.data_window.x) as usize; + let y0 = (window.y - part.part.data_window.y) as usize; + let width = window.width as usize; + // Supply in reverse descriptor order to exercise channel placement independent of callback order. + for channel in (0..part.part.channels.len()).rev() { + tile.fill_channel(channel, |mut samples| { + let at = |i: usize| (y0 + i / width, x0 + i % width); + match &mut samples { + RowSamples::F16(values) => values.iter_mut().enumerate().for_each(|(i, value)| { + let (y, x) = at(i); + *value = half_value(y, channel, x); + }), + RowSamples::F32(values) => values.iter_mut().enumerate().for_each(|(i, value)| { + let (y, x) = at(i); + *value = depth_value(y, x); + }), + RowSamples::U32(values) => values.iter_mut().enumerate().for_each(|(i, value)| { + let (y, x) = at(i); + *value = id_value(y, x); + }), + } + Ok(samples.len()) + })?; + } + Ok(()) +} + +#[test] +fn tiled_lossless_round_trips_all_sample_types_and_clips_edge_tiles() { + for (compression, name) in [ + (Compression::None, "Uncompressed"), + (Compression::Rle, "RLE"), + (Compression::Zip1, "ZIP1"), + (Compression::Zip16, "ZIP16"), + (Compression::Piz, "PIZ"), + ] { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT, HALF, UINT], compression }; + let tiled = TilePart { part, tile_width: 30, tile_height: 18 }; + let mut out = Cursor::new(Vec::new()); + let mut windows = Vec::new(); + write_tiles(&mut out, WINDOW, &[tiled], &Metadata::default(), |part, window, tile| { + assert_eq!(part, 0); + windows.push(window); + fill_tile(tiled, window, tile) + }) + .unwrap(); + assert_eq!(windows.len(), 6); + assert_eq!(windows[0], Window { width: 30, height: 18, ..WINDOW }); + assert_eq!(windows[5], Window { x: WINDOW.x + 60, y: WINDOW.y + 18, width: 4, height: 17 }); + + let decoded = decode::decode_part(out.get_ref(), 0, &|_| true, &Limits::default()).unwrap(); + assert!(decoded.info.tiled); + assert_eq!(decoded.info.compression, name); + assert_eq!(decoded.info.data_window, WINDOW); + assert_eq!(decoded.channel("Z").unwrap().samples, Samples::F32(whole_plane(WINDOW, depth_value))); + assert_eq!(decoded.channel("R").unwrap().samples, Samples::F16(whole_plane(WINDOW, |y, x| half_value(y, 1, x)))); + assert_eq!(decoded.channel("ID").unwrap().samples, Samples::U32(whole_plane(WINDOW, id_value))); + } +} + +#[test] +fn tiled_multipart_keeps_distinct_tile_sizes_and_metadata() { + let depth = Part { name: Some("Depth"), data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let beauty = Part { name: Some("Beauty"), data_window: WINDOW, channels: &[HALF], compression: Compression::Piz }; + let parts = [TilePart { part: depth, tile_width: 16, tile_height: 14 }, TilePart { part: beauty, tile_width: 31, tile_height: 20 }]; + let chromaticities = [[0.64, 0.33], [0.3, 0.6], [0.15, 0.06], [0.3127, 0.329]]; + let text = [&[("craftLayerStack", "{\"version\":1}"), ("comments", "Preview")][..], &[("passLabel", "Beauty")][..]]; + let metadata = Metadata { chromaticities: Some(chromaticities), text_attributes: &text }; + let mut out = Cursor::new(Vec::new()); + write_tiles(&mut out, WINDOW, &parts, &metadata, |part, window, tile| fill_tile(parts[part], window, tile)).unwrap(); + let mut source = Cursor::new(out.into_inner()); + let index = Index::build(&mut source, &Limits::default(), &|| false).unwrap(); + let info = index.parts(); + assert_eq!(info[0].name.as_deref(), Some("Depth")); + assert_eq!(info[1].name.as_deref(), Some("Beauty")); + assert!(info.iter().all(|part| part.tiled)); + assert_eq!(info[0].text("craftLayerStack"), Some("{\"version\":1}")); + assert_eq!(info[1].text("craftLayerStack"), None); + assert_eq!(info[1].text("passLabel"), Some("Beauty")); + let headers = exr::meta::MetaData::read_from_buffered(Cursor::new(source.get_ref()), true).unwrap().headers; + assert_eq!(headers[0].own_attributes.comments.as_ref().unwrap().to_string(), "Preview"); + for header in &headers { + let c = header.shared_attributes.chromaticities.unwrap(); + assert_eq!([[c.red.0, c.red.1], [c.green.0, c.green.1], [c.blue.0, c.blue.1], [c.white.0, c.white.1]], chromaticities); + } + let requested_row = 31; + let request = Request { rows: Some(requested_row..requested_row + 1), ..Request::new(&[(0, 0), (1, 0)], usize::MAX) }; + let read = read_planes(&mut source, &index, &request, &|| false).unwrap(); + assert_eq!(read.stats.chunks, [4, 3]); + let requested_row = requested_row as usize; + assert_eq!(read.planes[0], whole_plane(WINDOW, |y, x| if y == requested_row { depth_value(y, x) } else { 0.0 })); + assert_eq!(read.planes[1], whole_plane(WINDOW, |y, x| if y == requested_row { half_value(y, 0, x).to_f32() } else { 0.0 })); +} + +#[test] +fn scanline_metadata_round_trips_a_custom_string() { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let text = [&[("cryptomatte/abc1234/name", "CryptoObject")][..]]; + let metadata = Metadata { text_attributes: &text, ..Metadata::default() }; + let mut out = Cursor::new(Vec::new()); + write_scanlines_with_metadata(&mut out, WINDOW, &[part], &metadata, sample_row).unwrap(); + let parts = decode::parts(out.get_ref(), &Limits::default()).unwrap(); + assert_eq!(parts[0].text("cryptomatte/abc1234/name"), Some("CryptoObject")); +} + +#[test] +fn channel_names_set_the_long_name_flag_at_the_openexr_byte_boundary() { + let window = Window { width: 1, height: 1, ..WINDOW }; + for len in [31, 32, 255] { + let name = "Z".repeat(len); + let part = Part { name: None, data_window: window, channels: &[Channel { name: &name, ..FLOAT }], compression: Compression::None }; + let mut out = Cursor::new(Vec::new()); + write_scanlines(&mut out, window, &[part], sample_row).unwrap(); + assert_eq!(u32::from_le_bytes(out.get_ref()[4..8].try_into().unwrap()), 2 | if len > 31 { 0x400 } else { 0 }); + assert_eq!(decode::parts(out.get_ref(), &Limits::default()).unwrap()[0].channels[0].name, name); + + let tiled = TilePart { part, tile_width: 1, tile_height: 1 }; + let mut out = Cursor::new(Vec::new()); + write_tiles(&mut out, window, &[tiled], &Metadata::default(), |_, window, tile| fill_tile(tiled, window, tile)).unwrap(); + assert_eq!(u32::from_le_bytes(out.get_ref()[4..8].try_into().unwrap()), 0x202 | if len > 31 { 0x400 } else { 0 }); + let decoded = decode::decode_part(out.get_ref(), 0, &|_| true, &Limits::default()).unwrap(); + assert_eq!(decoded.channel(&name).unwrap().samples, Samples::F32(vec![depth_value(0, 0)])); + } +} + +#[test] +fn long_part_names_set_the_flag_in_multipart_files() { + let window = Window { width: 1, height: 1, ..WINDOW }; + let part = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::None }; + for len in [31, 32, 255] { + let name = "P".repeat(len); + let mut out = Cursor::new(Vec::new()); + write_scanlines(&mut out, window, &[part, Part { name: Some(&name), ..part }], sample_row).unwrap(); + assert_eq!(u32::from_le_bytes(out.get_ref()[4..8].try_into().unwrap()), 0x1002 | if len > 31 { 0x400 } else { 0 }); + assert_eq!(decode::parts(out.get_ref(), &Limits::default()).unwrap()[1].name.as_deref(), Some(name.as_str())); + } +} + +#[test] +fn invalid_tile_dimensions_and_metadata_fail_before_output() { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let tiled = TilePart { part, tile_width: 16, tile_height: 16 }; + let no_metadata = Metadata::default(); + let duplicate = [&[("pass", "Z"), ("pass", "depth")][..]]; + let reserved = [&[("tiles", "unexpected")][..]]; + let invalid_chromaticities = Metadata { chromaticities: Some([[f32::NAN; 2]; 4]), ..no_metadata }; + for (part, metadata) in [ + (TilePart { tile_width: 0, ..tiled }, no_metadata), + (TilePart { tile_width: 16_384, tile_height: 16_384, ..tiled }, no_metadata), + (tiled, invalid_chromaticities), + (tiled, Metadata { text_attributes: &duplicate, ..no_metadata }), + (tiled, Metadata { text_attributes: &reserved, ..no_metadata }), + ] { + let mut out = Cursor::new(Vec::new()); + let result = write_tiles(&mut out, WINDOW, &[part], &metadata, |_, _, _| panic!("invalid descriptors reached callback")); + assert!(matches!(result, Err(Error::Encode(_))), "{result:?}"); + assert!(out.get_ref().is_empty()); + } +} + +// Chunk count, channels, compression, line order, display and data windows, pixel aspect ratio, +// screen window centre and width, block type and part name +const MULTIPART_SCANLINE_ATTRIBUTES: usize = 11; + +fn numbered_attributes(count: usize) -> Vec<(String, String)> { + (0..count).map(|n| (format!("pass{n}"), format!("value{n}"))).collect() +} + +fn borrowed(attributes: &[(String, String)]) -> Vec<(&str, &str)> { + attributes.iter().map(|(name, value)| (name.as_str(), value.as_str())).collect() +} + +#[test] +fn multipart_header_at_the_attribute_limit_round_trips() { + let window = Window { width: 2, height: 2, ..WINDOW }; + let beauty = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::Zip16 }; + let depth = Part { name: Some("Depth"), ..beauty }; + let user_attributes = numbered_attributes(MAX_HEADER_ATTRIBUTES - MULTIPART_SCANLINE_ATTRIBUTES); + let borrowed_attributes = borrowed(&user_attributes); + let text = [&borrowed_attributes[..], &[("passLabel", "Depth")][..]]; + let metadata = Metadata { text_attributes: &text, ..Metadata::default() }; + let mut out = Cursor::new(Vec::new()); + + write_scanlines_with_metadata(&mut out, window, &[beauty, depth], &metadata, sample_row).unwrap(); + + let index = Index::build(&mut out, &Limits::default(), &|| false).unwrap(); + let last = user_attributes.len() - 1; + assert_eq!(index.parts()[0].text("pass0"), Some("value0")); + assert_eq!(index.parts()[0].text(&format!("pass{last}")), Some(format!("value{last}").as_str())); + assert_eq!(index.parts()[1].text("passLabel"), Some("Depth")); +} + +#[test] +fn multipart_header_over_the_attribute_limit_is_refused_before_output() { + let window = Window { width: 2, height: 2, ..WINDOW }; + let beauty = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::Zip16 }; + let depth = Part { name: Some("Depth"), ..beauty }; + let user_attributes = numbered_attributes(MAX_HEADER_ATTRIBUTES - MULTIPART_SCANLINE_ATTRIBUTES + 1); + let borrowed_attributes = borrowed(&user_attributes); + let text = [&[][..], &borrowed_attributes[..]]; + let metadata = Metadata { text_attributes: &text, ..Metadata::default() }; + let mut out = Cursor::new(Vec::new()); + + let result = write_scanlines_with_metadata(&mut out, window, &[beauty, depth], &metadata, |_, _, _, _| panic!("reached callback")); + + assert!(matches!(&result, Err(Error::Encode(message)) if message.contains("part 1") && message.contains("4096")), "{result:?}"); + assert!(out.get_ref().is_empty()); +} + +#[test] +fn tiled_header_with_chromaticities_counts_them_against_the_attribute_limit() { + let window = Window { width: 2, height: 2, ..WINDOW }; + let part = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::Zip16 }; + let tiled = TilePart { part, tile_width: 2, tile_height: 2 }; + let chromaticities = Some([[0.64, 0.33], [0.3, 0.6], [0.15, 0.06], [0.3127, 0.329]]); + // The scan-line set plus the tile description and the shared chromaticities + let user_count = MAX_HEADER_ATTRIBUTES - MULTIPART_SCANLINE_ATTRIBUTES - 2; + let user_attributes = numbered_attributes(user_count); + let borrowed_attributes = borrowed(&user_attributes); + let text = [&borrowed_attributes[..]]; + let metadata = Metadata { chromaticities, text_attributes: &text }; + let mut out = Cursor::new(Vec::new()); + + write_tiles(&mut out, window, &[tiled], &metadata, |_, window, tile| fill_tile(tiled, window, tile)).unwrap(); + + Index::build(&mut out, &Limits::default(), &|| false).unwrap(); + let over_attributes = numbered_attributes(user_count + 1); + let borrowed_over = borrowed(&over_attributes); + let over_text = [&borrowed_over[..]]; + let over = Metadata { chromaticities, text_attributes: &over_text }; + let mut refused = Cursor::new(Vec::new()); + let result = write_tiles(&mut refused, window, &[tiled], &over, |_, _, _| panic!("reached callback")); + assert!(matches!(result, Err(Error::Encode(_))), "{result:?}"); + assert!(refused.get_ref().is_empty()); +} + +#[test] +fn incomplete_tiles_are_rejected() { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let tiled = TilePart { part, tile_width: 4, tile_height: 5 }; + let result = write_tiles(&mut Cursor::new(Vec::new()), WINDOW, &[tiled], &Metadata::default(), |_, _, _| Ok(())); + assert!(matches!(result, Err(Error::Encode(message)) if message.contains("missing channel 0"))); + + let short = write_tiles(&mut Cursor::new(Vec::new()), WINDOW, &[tiled], &Metadata::default(), |_, _, tile| { + tile.fill_channel(0, |plane| Ok(plane.len() - 1)) + }); + assert!(matches!(short, Err(Error::Encode(message)) if message.contains("expected 20 samples, got 19"))); + + let duplicate = write_tiles(&mut Cursor::new(Vec::new()), WINDOW, &[tiled], &Metadata::default(), |_, _, tile| { + tile.fill_channel(0, |plane| Ok(plane.len()))?; + tile.fill_channel(0, |plane| Ok(plane.len())) + }); + assert!(matches!(duplicate, Err(Error::Encode(message)) if message.contains("duplicate tile channel 0"))); +} + +#[test] +fn single_part_lossless_round_trips_all_sample_types() { + for (compression, name) in [ + (Compression::None, "Uncompressed"), + (Compression::Rle, "RLE"), + (Compression::Zip1, "ZIP1"), + (Compression::Zip16, "ZIP16"), + (Compression::Piz, "PIZ"), + ] { + let mut out = Cursor::new(Vec::new()); + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT, HALF, UINT], compression }; + write_scanlines(&mut out, WINDOW, &[part], sample_row).unwrap(); + let limits = Limits::default(); + let bytes = out.get_ref(); + assert_eq!(decode::parts(bytes, &limits).unwrap().len(), 1); + let decoded = decode::decode_part(bytes, 0, &|_| true, &limits).unwrap(); + assert_eq!(decoded.info.name, None); + assert_eq!(decoded.info.compression, name); + assert_eq!(decoded.info.data_window, WINDOW); + assert_eq!(decoded.channel("Z").unwrap().samples, Samples::F32(whole_plane(WINDOW, depth_value))); + assert_eq!(decoded.channel("R").unwrap().samples, Samples::F16(whole_plane(WINDOW, |row, x| half_value(row, 1, x)))); + assert_eq!(decoded.channel("ID").unwrap().samples, Samples::U32(whole_plane(WINDOW, id_value))); + } +} + +#[test] +fn lossy_encodings_preserve_integer_ids() { + for compression in [Compression::Pxr24, Compression::B44, Compression::B44a, Compression::Dwaa, Compression::Dwab] { + let mut out = Cursor::new(Vec::new()); + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT, HALF, UINT], compression }; + write_scanlines(&mut out, WINDOW, &[part], sample_row).unwrap(); + let decoded = decode::decode_part(out.get_ref(), 0, &|_| true, &Limits::default()).unwrap(); + assert_eq!(decoded.channel("ID").unwrap().samples, Samples::U32(whole_plane(WINDOW, id_value)), "{compression:?}"); + } +} + +#[test] +fn named_parts_round_trip_and_support_selective_reads() { + let beauty = [HALF, Channel { name: "G", ..HALF }, Channel { name: "B", ..HALF }, Channel { name: "A", ..HALF }]; + let depth_window = Window { x: WINDOW.x + 1, y: WINDOW.y + 2, width: WINDOW.width - 1, height: WINDOW.height - 2 }; + let parts = [ + Part { name: Some("Depth"), data_window: depth_window, channels: &[FLOAT], compression: Compression::Zip1 }, + Part { name: Some("Beauty"), data_window: WINDOW, channels: &beauty, compression: Compression::Zip16 }, + ]; + let mut out = Cursor::new(Vec::new()); + write_scanlines(&mut out, WINDOW, &parts, sample_row).unwrap(); + let limits = Limits::default(); + let mut source = Cursor::new(out.into_inner()); + let index = Index::build(&mut source, &limits, &|| false).unwrap(); + let headers = index.parts(); + assert_eq!(headers.iter().map(|part| part.name.as_deref().unwrap()).collect::>(), ["Depth", "Beauty"]); + assert_eq!(decode::pick_part(headers), Some(1)); + assert_eq!((&*headers[0].compression, &*headers[1].compression), ("ZIP1", "ZIP16")); + assert_eq!(headers[0].data_window, depth_window); + assert!(headers.iter().all(|part| part.display_window == WINDOW)); + let beauty = &headers[1].channels; + assert_eq!(beauty.iter().map(|channel| channel.name.as_str()).collect::>(), ["A", "B", "G", "R"]); + assert!(beauty.iter().all(|channel| channel.sample == SampleType::F16)); + assert_eq!(headers[0].channels[0].sample, SampleType::F32); + let depth = decode::decode_part(source.get_ref(), 0, &|_| true, &limits).unwrap(); + assert_eq!(depth.channel("Z").unwrap().samples, Samples::F32(whole_plane(depth_window, depth_value))); + + let row = 17; + let request = Request { rows: Some(row..row + 1), fill: &[-1.0, -2.0], ..Request::new(&[(1, 3), (0, 0)], usize::MAX) }; + let read = read_planes(&mut source, &index, &request, &|| false).unwrap(); + assert_eq!(read.stats.chunks, [1, 1]); + let row = row as usize; + for (plane, expected) in [ + (&read.planes[0], whole_plane(WINDOW, |y, x| if y == row { half_value(y, 0, x).to_f32() } else { -1.0 })), + (&read.planes[1], whole_plane(WINDOW, |y, x| if y == row && x > 0 { depth_value(y - 2, x - 1) } else { -2.0 })), + ] { + assert_eq!(plane, &expected); + } +} + +#[test] +fn bad_descriptors_fail_before_writing_or_requesting_rows() { + let part = Part { name: Some("Depth"), data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let duplicate = [FLOAT, FLOAT]; + let bad_channel = [Channel { name: "Z\0hidden", ..FLOAT }]; + let long_name = "Z".repeat(256); + let long_channel = [Channel { name: &long_name, ..FLOAT }]; + let empty_name = [Channel { name: "", ..FLOAT }]; + for parts in [ + vec![], + vec![part, part], + vec![part, Part { name: None, ..part }], + vec![Part { name: Some("🎞"), ..part }], + vec![Part { channels: &duplicate, ..part }], + vec![Part { channels: &bad_channel, ..part }], + vec![Part { channels: &long_channel, ..part }], + vec![Part { channels: &empty_name, ..part }], + vec![Part { channels: &[], ..part }], + vec![Part { data_window: Window { width: 0, ..WINDOW }, ..part }], + vec![Part { data_window: Window { x: i32::MAX, ..WINDOW }, ..part }], + vec![Part { data_window: Window { width: 1 << 27, ..WINDOW }, ..part }], + vec![Part { data_window: Window { height: 1 << 21, ..WINDOW }, compression: Compression::Zip1, ..part }], + ] { + let mut out = Cursor::new(Vec::new()); + let result = write_scanlines(&mut out, WINDOW, &parts, |_, _, _, _| panic!("invalid descriptors reached callback")); + assert!(matches!(result, Err(Error::Encode(_))), "{parts:?}: {result:?}"); + assert!(out.get_ref().is_empty()); + } +} + +#[test] +fn short_rows_and_callback_errors_stop_writing() { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let mut calls = 0; + let short = write_scanlines(&mut Cursor::new(Vec::new()), WINDOW, &[part], |_, _, _, row| { + calls += 1; + Ok(row.len() - 1) + }); + assert!(matches!(short, Err(Error::Encode(message)) if message.contains("expected 64 samples, got 63"))); + assert_eq!(calls, 1); + + let stopped = Error::Encode("source became unavailable".into()); + let result = write_scanlines(&mut Cursor::new(Vec::new()), WINDOW, &[part], |_, _, _, _| Err(stopped.clone())); + assert_eq!(result, Err(stopped)); +} + +struct LimitedOutput<'a> { + cursor: Cursor>, + limit: &'a Cell, +} + +impl Write for LimitedOutput<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if self.cursor.position() + bytes.len() as u64 > self.limit.get() { + return Err(io::Error::other("synthetic full disk")); + } + self.cursor.write(bytes) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl Seek for LimitedOutput<'_> { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.cursor.seek(position) + } +} + +#[test] +fn chunks_are_written_before_requesting_more_rows() { + let limit = Cell::new(u64::MAX); + let mut out = LimitedOutput { cursor: Cursor::new(Vec::new()), limit: &limit }; + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let mut rows = 0; + let result = write_scanlines(&mut out, WINDOW, &[part], |_, _, _, row| { + rows += 1; + // Let the header and offset placeholders through, then fail the first block write. + limit.set(0); + Ok(row.len()) + }); + assert!(matches!(result, Err(Error::Encode(message)) if message.contains("synthetic full disk"))); + assert!(rows > 0 && rows < WINDOW.height, "received {rows} rows before first block write"); +} diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index bae6ecb65d..4911e2f2b1 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -529,6 +529,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { wrap: None, index: None, group: None, + item: p.props.list_item.filter(|_| list.is_none()).map(|l| l.min(8)), }; if opts.paras { out.extra = para_extra(doc, &p.props); @@ -579,6 +580,8 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { wrap: None, index: None, group: None, + // A list item's further paragraph, each piece of it. + item: out.item, }; let prev = std::mem::replace(&mut out, next); if prev.inlines.is_empty() { @@ -952,9 +955,50 @@ fn kept_index(doc: &Document, bl: &Blocks, i: usize) -> Option<(usize, std::sync (paras.len() == *n && craft_wordmodel::kept::run_fingerprint(paras.into_iter()) == *run).then(|| (*n, xml.clone())) } +/// Where the text of each level's last numbered paragraph starts, points. +type ItemText = [Option; 9]; + +/// The flow paragraphs of `p`, a list item's further paragraph only while it still sits at its +/// item's text: one moved out of it (Enter, then Decrease Indent to the margin, the ruler, the +/// Paragraph dialog…) is body text after the list. Asked of the paragraph itself, so whichever +/// command moved it, the paragraph is where it shows. +fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemText) -> Vec { + let rp = doc.styles.resolve_para(&p.props); + // (Its own indent, or its style's.) + let left = rp.indent_left; + let mut paras = flow_paras_in(doc, p, opts); + if let Some(n) = rp.numbering.filter(|n| n.num != 0) { + // The paragraph's own indent, else its level's, else its style's (as Word places it). + let level = doc.numbering.level(n.num, n.level).map(|l| l.indent); + // Nonzero character indents override point indents, including an explicit zero. + let text = if rp.indent_chars[0] != 0.0 { left } else { p.props.indent_left.or(level).unwrap_or(left) }; + if let Some(t) = at.get_mut(usize::from(n.level)) { + *t = Some(text); + } + } else if let Some(l) = p.props.list_item { + // Before any numbered paragraph, an explicit header has no prior baseline to outdent from. + let kept = match at.get(usize::from(l)).copied().flatten() { + Some(text) => left >= text - 0.5, + None => true, + }; + if !kept { + for q in &mut paras { + q.item = None; + } + // Moved out of its item, it is body text: the lists before it have ended. + *at = [None; 9]; + } + } else { + // Body text: the lists before it have ended, and where their items' text was with them. + *at = [None; 9]; + } + paras +} + fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> Vec { let mut out = Vec::new(); let mut skip = 0usize; + let mut at: ItemText = [None; 9]; for (i, b) in bl.iter().enumerate() { if skip > 0 { skip -= 1; @@ -969,7 +1013,7 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> let from = out.len(); for b in bl.get(i..i + ix.0).unwrap_or(&[]) { if let Block::Para(p) = &**b { - out.extend(flow_paras_in(doc, p, tracked).into_iter().map(FBlock::Para)); + out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para)); } } let n = out.len() - from; @@ -980,7 +1024,7 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> continue; } match &**b { - Block::Para(p) => out.extend(flow_paras_in(doc, p, tracked).into_iter().map(FBlock::Para)), + Block::Para(p) => out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para)), Block::Table(t) if depth < MAX_DEPTH => out.push(FBlock::Table(flow_table(doc, t, depth, tracked))), Block::Table(t) => { for r in &t.rows { @@ -1105,6 +1149,8 @@ fn with_cell_text(doc: &Document, blocks: &Blocks, chr: &CharProps, align: Optio if !table.is_empty() { let mut props = doc.styles.table_para_patch(&p.props, &table); props.overlay(&p.props); + // Direct only, so no overlay carries it: a list item's further paragraph stays one. + props.list_item = p.props.list_item; p.props = props; } Arc::new(Block::Para(p)) diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 7dc83c99d8..238a455fb8 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -26,6 +26,7 @@ mod media; pub mod odf_object; mod to_doc; mod types; +pub use types::continues_list; pub use color::parse_color; pub use from_doc::{ @@ -210,4 +211,149 @@ mod tests { p.trim(); assert_eq!(p.inlines, vec![Inline::Text("a ".into(), i), Inline::Text("b".into(), b)]); } + + /// Paragraphs of `text` in order, each with its props set by `set`. + fn doc_of(paras: &[(&str, &dyn Fn(&mut craft_wordmodel::ParaProps))]) -> craft_wordmodel::Document { + let mut doc = craft_wordmodel::Document::new(); + doc.body = paras + .iter() + .map(|(t, set)| { + let mut p = craft_wordmodel::Paragraph::with_text(t, Default::default()); + set(&mut p.props); + std::sync::Arc::new(craft_wordmodel::Block::Para(p)) + }) + .collect(); + doc + } + + /// The text and `item` of each flow paragraph, a table cell's included. + fn items(blocks: &[FBlock]) -> Vec<(String, Option)> { + let mut out = Vec::new(); + for b in blocks { + match b { + FBlock::Para(p) => out.push((p.text(), p.item)), + FBlock::Table(t) => { + for c in t.rows.iter().flatten() { + out.extend(items(&c.blocks)); + } + } + } + } + out + } + + #[test] + fn character_indents_set_the_list_continuation_baseline() { + let mut doc = craft_wordmodel::Document::new(); + let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered); + let numbered = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(0.0); + p.indent_left_chars = Some(6.0); + }; + let outdented = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(0.0); + }; + doc.body = doc_of(&[("One", &numbered), ("Out", &outdented)]).body; + let got = items(&from_doc(&doc).blocks); + assert_eq!(got.iter().find(|r| r.0 == "Out").map(|r| r.1), Some(None)); + } + + #[test] + fn a_zero_indent_header_keeps_its_explicit_list_membership() { + let header = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(0.0); + }; + let doc = doc_of(&[("Header", &header)]); + assert_eq!(items(&from_doc(&doc).blocks), [("Header".into(), Some(0))]); + } + + /// A list item's further paragraph cut by a page break is that paragraph on both pages: the + /// text after the break stays in the item too. + #[test] + fn a_further_paragraph_stays_in_its_item_past_a_page_break() { + let cont = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(36.0); + }; + let doc = doc_of(&[("Before\u{c}After", &cont)]); + let got = items(&from_doc(&doc).blocks); + assert_eq!(got, [("Before".to_string(), Some(0)), ("After".to_string(), Some(0))], "{got:?}"); + } + + /// Body text ends the lists before it: a list starting with a header (no number) at its text + /// is a list's paragraph however far an earlier list's text was indented. + #[test] + fn a_list_header_after_body_text_is_in_its_list() { + let mut doc = craft_wordmodel::Document::new(); + let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered); + let numbered = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(72.0); + }; + let header = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(36.0); + }; + let numbered_36 = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(36.0); + }; + let body = doc_of(&[("One", &numbered), ("Body", &|_| {}), ("Header", &header), ("Two", &numbered_36)]).body; + doc.body = body; + let got = items(&from_doc(&doc).blocks); + assert_eq!(got.iter().find(|r| r.0 == "Header").map(|r| r.1), Some(Some(0)), "{got:?}"); + } + + /// A further paragraph moved out of its item (to the margin) is body text: a list starting with + /// a header after it, less indented than the list before, keeps the header in its list. + #[test] + fn a_list_header_after_an_outdented_further_paragraph_is_in_its_list() { + let mut doc = craft_wordmodel::Document::new(); + let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered); + let numbered = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(72.0); + }; + let outdented = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(0.0); + }; + let header = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(36.0); + }; + let numbered_36 = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(36.0); + }; + let body = doc_of(&[("One", &numbered), ("Out", &outdented), ("Header", &header), ("Two", &numbered_36)]).body; + doc.body = body; + let got = items(&from_doc(&doc).blocks); + assert_eq!(got.iter().find(|r| r.0 == "Out").map(|r| r.1), Some(None), "{got:?}"); + assert_eq!(got.iter().find(|r| r.0 == "Header").map(|r| r.1), Some(Some(0)), "{got:?}"); + } + + /// A list item's further paragraph in a table cell a table style formats stays one. + #[test] + fn a_further_paragraph_in_a_styled_cell_stays_in_its_item() { + let cont = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(36.0); + }; + let mut doc = craft_wordmodel::Document::new(); + // Table Grid: paragraph formatting of its own (no space after, single spacing). + let mut t = craft_wordmodel::table::Table::new(1, 1, 200.0); + if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut()) { + c.blocks = doc_of(&[("Cont", &cont)]).body; + } + doc.body = vec![ + std::sync::Arc::new(craft_wordmodel::Block::Table(t)), + std::sync::Arc::new(craft_wordmodel::Block::Para(craft_wordmodel::Paragraph::new())), + ]; + let got = items(&from_doc_with(&doc, FlowOpts { paras: true, ..Default::default() }).blocks); + assert_eq!(got.iter().find(|r| r.0 == "Cont").map(|r| r.1), Some(Some(0)), "{got:?}"); + } } diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index 3d27d521f3..303dc022cc 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -158,6 +158,9 @@ fn para_props(p: &Para, list_num: Option) -> ParaProps { } out.numbering = Some(NumRef { num, level: li.level.min(8) }); } + if p.list.is_none() { + out.list_item = p.item.map(|l| l.min(8)); + } out.align = p.align; if p.rtl { out.bidi = Some(true); @@ -766,6 +769,12 @@ impl<'a> Builder<'a> { fn blocks(&mut self, blocks: &[FBlock], depth: usize) -> Blocks { let mut out = Blocks::new(); + // Each list the source numbers, all of it in these blocks: a run of it after a paragraph + // it doesn't number may be the first to use a level. + let mut of_list: std::collections::HashMap> = std::collections::HashMap::new(); + for li in blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { p.list } else { None }).filter(|li| li.list != 0) { + of_list.entry(li.list).or_default().push(li); + } let mut i = 0; while let Some(b) = blocks.get(i) { match b { @@ -779,7 +788,14 @@ impl<'a> Builder<'a> { let mut top: Option = None; let id = p.list.map_or(0, |l| l.list); while let Some(FBlock::Para(q)) = blocks.get(j) { - let Some(li) = q.list else { break }; + let Some(li) = q.list else { + // An item's further paragraph is in the list: it goes on after it. + if super::continues_list(blocks, j).is_some() { + j += 1; + continue; + } + break; + }; if li.list != id { break; } @@ -795,7 +811,9 @@ impl<'a> Builder<'a> { let num = match self.lists.get(&id) { Some(num) if id != 0 => *num, _ => { - let num = self.new_list(&group); + // First met here, so this is the only time it's asked for. + let all = if id == 0 { group } else { of_list.remove(&id).unwrap_or(group) }; + let num = self.new_list(&all); if id != 0 { self.lists.insert(id, num); } diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index 7def87e344..357c9c6ff4 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -716,6 +716,9 @@ pub struct Para { pub index: Option, usize)>>, /// The group of paragraphs its markup kept as read belongs to (see [`Group`]). pub group: Option>, + /// A list item's further paragraph, with no number of its own (`list` is `None`): the level + /// of the item it belongs to. + pub item: Option, } /// Paragraphs whose markup kept as read ties them together (a comment from one to another, a @@ -1107,3 +1110,14 @@ pub fn ruby_as_text(inlines: &[Inline]) -> std::borrow::Cow<'_, [Inline]> { pub fn clean_text(s: &str) -> String { s.chars().filter(|c| *c != OBJ && (!c.is_control() || matches!(c, '\t' | '\n' | '\u{000C}' | '\u{000E}'))).collect() } + +/// Whether the paragraph at `i` in `blocks` is a list item's further paragraph, and the level of +/// its item: HTML and Markdown keep it in its item, so the list doesn't start again after it. +/// A plain paragraph or a heading (ODF's `text:h` may sit in a list item); the writers have no +/// way to put the other kinds in an item. +pub fn continues_list(blocks: &[FBlock], i: usize) -> Option { + match blocks.get(i) { + Some(FBlock::Para(p)) if p.list.is_none() && matches!(p.kind, Kind::Normal | Kind::Heading(_)) => p.item.map(|l| l.min(8)), + _ => None, + } +} diff --git a/crates/font-catalog/README.md b/crates/font-catalog/README.md index bbc13c3af7..13f2d5758f 100644 --- a/crates/font-catalog/README.md +++ b/crates/font-catalog/README.md @@ -54,6 +54,7 @@ Each face (`FaceInfo`) has its family and style, legacy family and style, family - `family(name)` and `resolve(name, style)` accept any name of a family: its own name ignoring ASCII case, its names in other languages and its legacy names ignoring case and anything but letters and digits. `resolve` also accepts a legacy family with its legacy style (`Roboto Light` / `Regular`), a full name, and a PostScript name. - Within a family, `resolve` matches the style by name (any of its names). Otherwise it picks the nearest weight, with italic differing counting as 1000, then the nearest width. It returns `Match::Exact` or `Match::NearestStyle`, so the app decides about substitutes. - `by_postscript_name(name)`. +- `generic_family(Generic::SansSerif)` (also `Serif`, `Monospace` and `SystemUi`) names the installed family to use when a document names no family or one that is not installed. With the `system` feature it takes the first family the font service lists for it that the catalog has (fontconfig's configured aliases on Linux and FreeBSD). Otherwise, or when the catalog has none of those, it takes the first installed family of a fixed list for the catalog's platform (`Arial` for sans-serif on Windows, `Helvetica` on macOS, `DejaVu Sans` on Linux), then of the other platforms' lists. `SystemUi` tries the platform's sans-serif families before the other platforms' lists. It returns `None` when none of them is installed. - `faces()`, `families()` and the lookups list each face once: of faces with the same family, style, PostScript name and variations they keep the first (added faces, then installed files by path), except that the font store's face wins over a scanned copy elsewhere, such as one in the OS font folder. `versions(face)` gives the face from every file that has it, for an app that offers another version of a font. `scanned_faces()` lists every face the scan found, the same font in two places included, for telling copies apart (craft-font-store's conflict check). - `read_faces(path, source)` reads one file's faces, named instances included, as a scan does, without a catalog. diff --git a/crates/font-catalog/examples/fonts.rs b/crates/font-catalog/examples/fonts.rs index 772ad51599..b728d2c35b 100644 --- a/crates/font-catalog/examples/fonts.rs +++ b/crates/font-catalog/examples/fonts.rs @@ -8,7 +8,7 @@ use std::time::{Duration, Instant}; -use craft_font_catalog::{Catalog, font_dirs, font_store_dir}; +use craft_font_catalog::{Catalog, Generic, font_dirs, font_store_dir}; fn main() { let catalog = Catalog::global(); @@ -18,6 +18,9 @@ fn main() { let faces = catalog.faces(); println!("{} families, {} faces, first scan {:?}", families.len(), faces.len(), start.elapsed()); println!("font store: {:?}", font_store_dir(catalog.env())); + for generic in Generic::ALL { + println!("{}: {:?}", generic.css_name(), catalog.generic_family(generic)); + } for dir in font_dirs(catalog.env()).iter().filter(|d| d.is_dir()) { println!("folder: {}", dir.display()); } diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index bee23bf041..d2027c029f 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -574,6 +574,11 @@ impl Catalog { self.config.read().unwrap_or_else(PoisonError::into_inner) } + /// Whether scans ask the platform's font service ([`Catalog::with_font_service`]). + pub(crate) fn uses_font_service(&self) -> bool { + self.read_config().font_service + } + /// The environment the catalog was made for. pub fn env(&self) -> &FontEnv { &self.env diff --git a/crates/font-catalog/src/generic.rs b/crates/font-catalog/src/generic.rs new file mode 100644 index 0000000000..67d655a88b --- /dev/null +++ b/crates/font-catalog/src/generic.rs @@ -0,0 +1,124 @@ +//! Generic families: the installed family to use for sans-serif, serif, monospace or interface +//! text when a caller has no family name, or the name it has is not installed. + +use crate::{Catalog, Os}; + +/// A generic family ([`Catalog::generic_family`]), as CSS names them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Generic { + /// `sans-serif`. + SansSerif, + /// `serif`. + Serif, + /// `monospace`. + Monospace, + /// `system-ui`: the face the platform draws its own interface with. + SystemUi, +} + +impl Generic { + /// Every generic family. + pub const ALL: [Generic; 4] = [Generic::SansSerif, Generic::Serif, Generic::Monospace, Generic::SystemUi]; + + /// The CSS keyword (`sans-serif`, `serif`, `monospace`, `system-ui`). + pub fn css_name(self) -> &'static str { + match self { + Generic::SansSerif => "sans-serif", + Generic::Serif => "serif", + Generic::Monospace => "monospace", + Generic::SystemUi => "system-ui", + } + } +} + +/// The platforms in the order their lists are tried after the catalog's own. +const OSES: [Os; 4] = [Os::Windows, Os::MacOs, Os::Unix, Os::Haiku]; + +/// The families tried for `generic` on `os`, most likely first. +fn names(generic: Generic, os: Os) -> &'static [&'static str] { + match (generic, os) { + (Generic::SansSerif, Os::Windows) => &["Arial", "Segoe UI", "Tahoma", "Verdana"], + (Generic::SansSerif, Os::MacOs) => &["Helvetica", "Helvetica Neue", "Arial"], + (Generic::SansSerif, Os::Unix) => &["DejaVu Sans", "Noto Sans", "Liberation Sans", "Cantarell", "Ubuntu", "FreeSans"], + (Generic::SansSerif, Os::Haiku) => &["Noto Sans", "DejaVu Sans"], + (Generic::Serif, Os::Windows) => &["Times New Roman", "Cambria", "Georgia"], + (Generic::Serif, Os::MacOs) => &["Times", "Times New Roman", "New York"], + (Generic::Serif, Os::Unix) => &["DejaVu Serif", "Noto Serif", "Liberation Serif", "FreeSerif"], + (Generic::Serif, Os::Haiku) => &["Noto Serif", "DejaVu Serif"], + (Generic::Monospace, Os::Windows) => &["Consolas", "Cascadia Mono", "Courier New"], + (Generic::Monospace, Os::MacOs) => &["Menlo", "SF Mono", "Monaco", "Courier", "Courier New"], + (Generic::Monospace, Os::Unix) => &["DejaVu Sans Mono", "Noto Sans Mono", "Liberation Mono", "FreeMono"], + (Generic::Monospace, Os::Haiku) => &["Noto Sans Mono", "DejaVu Sans Mono"], + (Generic::SystemUi, Os::Windows) => &["Segoe UI", "Tahoma"], + (Generic::SystemUi, Os::MacOs) => &[".SF NS", "SF Pro", "SF Pro Text", "Helvetica Neue", "Lucida Grande"], + (Generic::SystemUi, Os::Unix) => &["Cantarell", "Ubuntu", "Noto Sans", "DejaVu Sans"], + (Generic::SystemUi, Os::Haiku) => &["Noto Sans"], + (_, Os::None) => &[], + } +} + +/// The names [`Catalog::generic_family`] tries, in order: the font service's (`service`) and the +/// list for `os`, then the other platforms' lists. For [`Generic::SystemUi`], the font service's +/// and `os`'s sans-serif names (`sans_service`) come before the other platforms' lists, and their +/// sans-serif lists come last. +fn candidates<'a>(generic: Generic, os: Os, service: &'a [String], sans_service: &'a [String]) -> Vec<&'a str> { + let others = |generic: Generic| OSES.into_iter().filter(move |o| *o != os).flat_map(move |o| names(generic, o).iter().copied()); + let mut out: Vec<&str> = service.iter().map(String::as_str).chain(names(generic, os).iter().copied()).collect(); + if generic == Generic::SystemUi { + out.extend(sans_service.iter().map(String::as_str).chain(names(Generic::SansSerif, os).iter().copied())); + out.extend(others(generic).chain(others(Generic::SansSerif))); + } else { + out.extend(others(generic)); + } + out +} + +impl Catalog { + /// The installed family for `generic`, as the catalog names it. + /// + /// With the font service on ([`Catalog::with_font_service`]), the families the platform's + /// service lists for `generic` come first (fontconfig's configured aliases on Linux and + /// FreeBSD, fixed names on macOS and Windows). A fixed list for the catalog's platform + /// ([`crate::FontEnv::os`]) follows, then the other platforms' lists. [`Generic::SystemUi`] + /// tries the service's and the platform's sans-serif families before the other platforms' + /// lists. The first of these names that [`Catalog::resolve`] finds wins, so a legacy family + /// name finds its family. Faces added with [`Catalog::add_bytes`] or [`Catalog::add_file`] + /// count as installed. Returns `None` when none of the names is installed. Pass the family + /// to [`Catalog::resolve`] for a face in a style. + pub fn generic_family(&self, generic: Generic) -> Option { + let service = |generic| if self.uses_font_service() { crate::system::generic_family_names(generic) } else { Vec::new() }; + let (own, sans) = (service(generic), if generic == Generic::SystemUi { service(Generic::SansSerif) } else { Vec::new() }); + candidates(generic, self.env().os, &own, &sans).into_iter().find_map(|name| self.resolve(name, "").map(|(face, _)| face.family)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn candidates_put_the_service_first_then_this_platform_then_the_others() { + let service = ["Configured Sans".to_string()]; + let tried = candidates(Generic::SansSerif, Os::Unix, &service, &[]); + assert_eq!(&tried[..3], ["Configured Sans", "DejaVu Sans", "Noto Sans"]); + let windows = tried.iter().position(|n| *n == "Arial"); + let mac = tried.iter().position(|n| *n == "Helvetica"); + assert!(windows.is_some() && mac.is_some() && windows < mac, "the other platforms' lists follow in a fixed order"); + let ui = candidates(Generic::SystemUi, Os::Windows, &[], &service); + assert_eq!(&ui[..4], ["Segoe UI", "Tahoma", "Configured Sans", "Arial"], "this platform's sans-serif names follow its system-ui names"); + let (cantarell, dejavu) = (ui.iter().position(|n| *n == "Cantarell"), ui.iter().rposition(|n| *n == "DejaVu Sans")); + assert!(cantarell < dejavu, "the other platforms' system-ui names come before their sans-serif names"); + assert!(candidates(Generic::Serif, Os::None, &[], &[]).contains(&"Times New Roman")); + } + + #[test] + fn every_generic_has_names_on_every_platform_with_font_folders() { + for generic in Generic::ALL { + for os in OSES { + assert!(!names(generic, os).is_empty(), "{generic:?} on {os:?}"); + } + assert!(names(generic, Os::None).is_empty()); + } + assert_eq!(Generic::ALL.map(Generic::css_name), ["sans-serif", "serif", "monospace", "system-ui"]); + } +} diff --git a/crates/font-catalog/src/lib.rs b/crates/font-catalog/src/lib.rs index b9feb95776..f912dd11c7 100644 --- a/crates/font-catalog/src/lib.rs +++ b/crates/font-catalog/src/lib.rs @@ -27,6 +27,7 @@ mod env; mod face_data; mod fallback; mod fontconfig; +mod generic; mod ligature; mod line_break; mod outline; @@ -47,6 +48,7 @@ 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 generic::Generic; pub use ligature::ligature_caret_stops; pub use line_break::settle_line_break; pub use outline::{FontOutline, GlyphPen, OutlineError}; diff --git a/crates/font-catalog/src/system.rs b/crates/font-catalog/src/system.rs index 4f19186b5f..31f642e8d1 100644 --- a/crates/font-catalog/src/system.rs +++ b/crates/font-catalog/src/system.rs @@ -13,7 +13,7 @@ mod imp { use std::path::{Path, PathBuf}; use std::sync::{Mutex, PoisonError}; - use fontique::{Collection, CollectionOptions, SourceKind}; + use fontique::{Collection, CollectionOptions, GenericFamily, SourceKind}; use crate::{FontEnv, font_store_dir}; @@ -160,6 +160,19 @@ mod imp { }) } + pub fn generic_family_names(generic: crate::Generic) -> Vec { + let generic = match generic { + crate::Generic::SansSerif => GenericFamily::SansSerif, + crate::Generic::Serif => GenericFamily::Serif, + crate::Generic::Monospace => GenericFamily::Monospace, + crate::Generic::SystemUi => GenericFamily::SystemUi, + }; + with(false, |s| { + let ids: Vec<_> = s.collection.generic_families(generic).collect(); + ids.into_iter().filter_map(|id| s.collection.family_name(id).map(str::to_owned)).collect() + }) + } + #[cfg(test)] mod tests { use super::*; @@ -241,6 +254,10 @@ mod imp { pub fn font_files(_refresh: bool) -> Vec { Vec::new() } + + pub fn generic_family_names(_generic: crate::Generic) -> Vec { + Vec::new() + } } #[cfg(all(feature = "system", not(target_arch = "wasm32")))] @@ -269,3 +286,9 @@ pub fn refresh() { pub(crate) fn font_files(refresh: bool) -> Vec { imp::font_files(refresh) } + +/// The families the platform's font service lists for `generic`, most preferred first; none +/// without the `system` feature. +pub(crate) fn generic_family_names(generic: crate::Generic) -> Vec { + imp::generic_family_names(generic) +} diff --git a/crates/font-catalog/src/tests.rs b/crates/font-catalog/src/tests.rs index 1c7397578c..54c044fd0b 100644 --- a/crates/font-catalog/src/tests.rs +++ b/crates/font-catalog/src/tests.rs @@ -390,6 +390,39 @@ fn a_family_loads_once_for_every_thread() { assert!(cat.load_family("Missing").is_empty()); } +#[test] +fn generic_families_follow_the_platforms_list_then_the_others() { + let root = temp("generic"); + let dir = root.join("listed"); + write(&dir.join("Arial.ttf"), font(&spec("Arial", "Regular", 400))); + write(&dir.join("NotoSans.ttf"), font(&spec("Noto Sans", "Regular", 400))); + write(&dir.join("Mono.ttf"), font(&spec("DEJAVU SANS MONO", "Regular", 400))); + write(&dir.join("Times.ttf"), font(&Spec { legacy: Some(("Times New Roman", "Regular")), ..spec("Times New Roman Pro", "Regular", 400) })); + write(&dir.join("DejaVuSans.ttf"), font(&Spec { outlines: false, ..spec("DejaVu Sans", "Regular", 400) })); + let catalog = |os: Os| { + let listed = dir.clone(); + Catalog::new(FontEnv { os, ..linux_env(&root) }).with_font_service(false).with_lister(Arc::new(move || vec![listed.clone()])) + }; + // Linux: DejaVu Sans has no outlines, so Noto Sans; the family's own spelling comes back. + let linux = catalog(Os::Unix); + assert_eq!(linux.generic_family(Generic::SansSerif).as_deref(), Some("Noto Sans")); + assert_eq!(linux.generic_family(Generic::Monospace).as_deref(), Some("DEJAVU SANS MONO")); + // A legacy family name finds its family. + assert_eq!(linux.generic_family(Generic::Serif).as_deref(), Some("Times New Roman Pro")); + assert_eq!(linux.generic_family(Generic::SystemUi).as_deref(), Some("Noto Sans")); + // Windows tries Arial before the Linux names. + let windows = catalog(Os::Windows); + assert_eq!(windows.generic_family(Generic::SansSerif).as_deref(), Some("Arial")); + // Nothing of macOS's system-ui list: sans-serif's answer. + assert_eq!(catalog(Os::MacOs).generic_family(Generic::SystemUi).as_deref(), Some("Arial")); + // An added face counts; with nothing installed there is no answer. + let empty = Catalog::new(linux_env(&root.join("empty"))).with_font_service(false); + assert_eq!(empty.generic_family(Generic::Monospace), None); + empty.add_bytes(font(&spec("Liberation Mono", "Regular", 400)), Source::Document, &Limits::default()).unwrap(); + assert_eq!(empty.generic_family(Generic::Monospace).as_deref(), Some("Liberation Mono")); + assert_eq!(empty.generic_family(Generic::Serif), None); +} + #[test] fn repeated_name_records_are_bounded_before_pairing() { // Thousands of legacy family and style records in one language: pairing them all would diff --git a/crates/font-manager/Cargo.toml b/crates/font-manager/Cargo.toml index fbaa419991..dcc2db8025 100644 --- a/crates/font-manager/Cargo.toml +++ b/crates/font-manager/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true reads = [ "crates/ui-contract/fonts/inter/Inter-Regular.ttf", "crates/ui-contract/fonts/inter/Inter-SemiBold.ttf", + "crates/font-subset/tests/data/orbitron/Orbitron[wght].ttf", "crates/font-subset/tests/data/sarabun/Sarabun-Regular.ttf", "crates/ui-contract/tests/fonts/NotoSansCJKsc-test.otf", ] diff --git a/crates/font-manager/README.md b/crates/font-manager/README.md index e5a30b4507..0adca059e1 100644 --- a/crates/font-manager/README.md +++ b/crates/font-manager/README.md @@ -32,13 +32,22 @@ The layout follows Adobe Fonts' and Google Fonts' browse pages. Preview, Installed, a progress bar while downloading, Couldn't install with Retry, "Not curated" for a source the user added), and a large sample in the face below. The list is virtual: only the cards on screen are laid out, and their faces load - as they come into view. The arrow keys step through the cards and Enter opens one. -- **Sample toolbar**: a preset (a sentence in the language filtered by, or in the family's own - script when it has no Latin; the alphabet; numerals), the sample text, and the size. + as they come into view. With a preview service set, families that aren't installed draw from + small subsets of their face: the sample for the cards on screen, then one screen above and two + below, then ASCII for the Latin cards on screen; typed text outside those asks for its own + characters once typing pauses. A card the service draws offers no Preview; one whose subset + failed does, and so does its details sheet. The arrow keys step through the cards and Enter + opens one. +- **Sample toolbar**: a preset (a sentence in the language filtered by, else the family's own + sample from the index, by its `sample_script`; the alphabet; numerals), the sample text, and the + size. - **Details sheet** over the list: every style in its own face with Install or Remove for each, Install all (with the same menu) and Remove all, whether the family is available to all apps with the switch that changes it, the source, designer, licence, scripts and languages, and what a - preview downloads. + preview downloads. With a preview service, styles not installed draw with its subsets: a static + file's sample, and one subset of each variable file with every axis kept, drawn at each named + instance and at the values of its axis sliders. The copyright and the upstream link, and + an Apache family's NOTICE and, on request, the licence text, read through the store. - **Installed**: system and font store fonts as the same cards, filtered by source. Only font store families can be removed; system fonts are removed with the system's own tools. - **Sources** (`sources_ui`, for a host's settings page): the built-in sources, the index URLs the @@ -81,6 +90,10 @@ panel.ui(ui); | `set_look(look)` | The host's palettes (dark and light) and font families, and whether labels are set in capitals | | `settings()` | The panel's `FontsPanelSettings`: the sample text, preset and size, and whether the downloads note was closed. The panel reads them from the Host's `fonts_panel` section on its first frame and writes the section when they change; without a Host they stay in memory | | `downloads_allowed()`, `set_downloads_allowed(on)` | The download consent, for a host's settings page. It is the font store's own setting, shared by every Craft app | +| `use_default_filters(language)` | Starts the catalogue on sans-serif families in the host's interface language (English when the index has none for it). Called once, after building the panel | +| `with_previews(previews)` | The preview service's client (craft-font-store's `preview::Previews`), for a host that builds its own (native only) | +| `reload_preview_settings()` | Reads the preview service and the previews setting again, after a host's settings page changed them. The panel also reads them when it first shows and when its window regains focus | +| `loading_previews()` | Whether previews are being fetched | | `show_downloads_switch(false)` | For a host with the switch in its own settings | | `sources_ui(ui)` | The font sources, for a host's settings page | | `set_index(index)` | The indexes, after the host fetched them | @@ -88,17 +101,30 @@ panel.ui(ui); ## Network use -Nothing is downloaded until the user allows it. Downloads are off by default; the first Install or -Preview asks first. Files come from each source's repositories at the commit or tag its index +No font is installed or downloaded whole until the user allows it. Downloads are off by default; the +first Install or Preview asks first. With a preview service set and previews on (a user setting, on by +default), the panel fetches the small preview subsets of the fonts it shows without asking; with +previews off it uses only those in the disk cache. Files come from each source's repositories at the commit or tag its index records, through jsDelivr (raw GitHub as the fallback), and each is checked against the index's size and sha256 before use. Previews stay in memory and are never installed. A source the user adds is an index at an https URL; its families are never curated. ## Strings -Every interface string goes through craft-i18n with the English text as the key. The panel embeds -its own Japanese and Arabic catalogs (`src/panel/catalogs/`) until its rows are part of -craft-i18n; style and weight names, licence names and product names stay in English. +Every interface string is a word of the Host's `I18n` (`craft_ui::words!`), so the panel is in the Host's +language when the app's catalogs have its rows and in English where they have none. `CATALOGS` holds the +Japanese and Arabic rows, until they are part of craft-i18n's shared catalog, as data the app passes to +its Host's `I18n`: + +```rust +// An app with no shared catalog of its own; one with a shared catalog joins the rows to it for +// `I18n::from_owned`. +let (i18n, problems) = craft_i18n::I18n::new(craft_font_manager::CATALOGS, &["ja", "ar"]); +let lang = i18n.match_tag(language).unwrap_or(craft_i18n::Lang::EN); +Host::builder(app).i18n(Arc::new(i18n)).lang(lang).install(ctx); +``` + +Style and weight names, licence names and product names stay in English. ## Testing diff --git a/crates/font-manager/src/axes/sliders.rs b/crates/font-manager/src/axes/sliders.rs index cb760a9839..a15cafd080 100644 --- a/crates/font-manager/src/axes/sliders.rs +++ b/crates/font-manager/src/axes/sliders.rs @@ -25,13 +25,14 @@ craft_ui::words! { width: "axisSliders.width" = "Width"; slant: "axisSliders.slant" = "Slant"; italic: "axisSliders.italic" = "Italic"; + optical_size: "axisSliders.opticalSize" = "Optical size"; style: "axisSliders.style" = "Style"; custom: "axisSliders.custom" = "Custom"; } } /// The label of an axis: its name when the font gives one, else the registered tag's -/// (`Weight`, `Width`, `Slant`, `Italic`), else the tag itself. +/// (`Weight`, `Width`, `Slant`, `Italic`, `Optical size`), else the tag itself. pub fn axis_label(axis: &FontAxis) -> String { label_in(axis, &AxisSlidersWords::default()) } @@ -45,6 +46,7 @@ fn label_in(axis: &FontAxis, labels: &AxisSlidersWords) -> String { b"wdth" => labels.width.as_str().to_owned(), b"slnt" => labels.slant.as_str().to_owned(), b"ital" => labels.italic.as_str().to_owned(), + b"opsz" => labels.optical_size.as_str().to_owned(), tag => Tag::new(tag).to_string(), } } @@ -70,9 +72,21 @@ fn set_value(values: &mut AxisValues, tag: [u8; 4], value: f32) { } } -/// The axes the sliders show: not hidden, not `opsz`, with a finite, non-empty range. -fn shown_axes(axes: &[FontAxis]) -> impl Iterator { - axes.iter().filter(|a| !a.hidden && a.tag != *b"opsz" && a.min.is_finite() && a.max.is_finite() && a.min < a.max) +/// Where the optical size axis (`opsz`) takes its value from. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum OpticalSize { + /// The text layout sets it from the font size: it has no slider. + #[default] + FontSize, + /// Its own slider, as any axis: for text drawn only to look at the face. + Slider, +} + +/// The axes the sliders show: not hidden, `opsz` only where it has a slider, with a finite, non-empty range. +pub(crate) fn shown_axes(axes: &[FontAxis], optical_size: OpticalSize) -> impl Iterator { + let slides = move |a: &FontAxis| a.tag != *b"opsz" || optical_size == OpticalSize::Slider; + axes.iter().filter(move |a| !a.hidden && slides(a) && a.min.is_finite() && a.max.is_finite() && a.min < a.max) } /// What changed in the sliders this pass. @@ -108,8 +122,8 @@ struct Drawn { } /// One slider field per visible axis (label, slider, number field with the axis's range), plus a `Select` of named -/// instances above them when the face has any. Hidden axes, `opsz` (the text layout sets the optical size from the -/// font size) and axes with an empty or non-finite range are left out. Values are the current coordinates; an axis +/// instances above them when the face has any. Hidden axes, `opsz` ([`OpticalSize::FontSize`]) and axes with an empty or +/// non-finite range are left out. Values are the current coordinates; an axis /// without one shows what the layout draws (its style's weight and italic; else its default). Axes whose range is 10 wide /// or more step by whole units, the others by hundredths. A drag is one edit; an instance sets every axis in one /// edit. @@ -128,6 +142,9 @@ pub struct AxisSliders<'a> { /// Whether the style is italic: an unset `ital` axis then shows its maximum, once a weight is given. #[prop] italic: bool, + /// Whether the `opsz` axis has a slider. + #[prop] + optical_size: OpticalSize, /// The axes (by tag) the selection mixes: each shows `Mixed` and is left out of the edit's held values. #[prop] #[allow(dead_code)] // P3(type-w3): ty.X21a @@ -137,12 +154,21 @@ pub struct AxisSliders<'a> { impl<'a> AxisSliders<'a> { /// Sliders named `label` over the `axes` of a face, editing the coordinates `values`. pub fn new(label: impl Into