diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 66897e207a..b80d10d34c 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -70,6 +70,7 @@ workflows: - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' '.github/workflows/nightly.yml': [] + '.github/workflows/pbr.yml': [] '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' diff --git a/.github/workflows/pbr.yml b/.github/workflows/pbr.yml new file mode 100644 index 0000000000..51c3a62daa --- /dev/null +++ b/.github/workflows/pbr.yml @@ -0,0 +1,29 @@ +name: PBR feature tests + +on: + workflow_dispatch: + push: + branches: [main, next] + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + pull_request: + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + +permissions: + contents: read + +jobs: + features: + name: PBR ${{ matrix.mode }} tests + strategy: + fail-fast: false + matrix: + include: + - { mode: serial, arguments: '' } + - { mode: parallel, arguments: '--features parallel' } + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest"]' + craft-fonts-ref: '' + require-craft-fonts: false + timeout-minutes: 30 + command: cargo test -p craft-pbr --locked ${{ matrix.arguments }} diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 112bfe4e93..009f7f7119 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -27,6 +27,7 @@ author, source and license. Library code and original assets are under the repos | `crates/text/assets/hyphen/en-us.pat` | DesignCraft contributors, trained from the Moby Hyphenator II list | `crates/text/examples/hyphgen.rs` | CC0-1.0 | | Patterns embedded through `hypher` (optional `craft-text` language features) | hyph-utf8 authors, per language | [tex-hyphen](https://github.com/hyphenation/tex-hyphen), as packaged in [hypher](https://github.com/typst/hypher/tree/main/patterns) | Per file header: LPPL, MIT, BSD-3-Clause, Unlicense or a permit-any-use notice (or a choice including one); Slovak (`hyph-sk.tex`, embedded whenever `hypher/slovak` is on: feature `slovak-gpl`, or another dependency through feature unification) is GPL-2.0-or-later; Spanish (`hyph-es.tex` 5.0, Javier Bezos, CervanTeX) is MIT | | Word-break dictionaries and LSTM models embedded through `icu_segmenter_data` (optional `craft-text` features `thai`, `lao`, `khmer`, `burmese`) | Unicode, Inc. and ICU4X contributors | [ICU4X](https://github.com/unicode-org/icu4x) | Unicode-3.0 | +| MikkTSpace tangent generation compiled in through `mikktspace` (`craft-mesh-ops`) | Benjamin Wasty, David Harvey-Macaulay and Layl Bongers; translated from the C original by Morten S. Mikkelsen | [mikktspace 0.3.0](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field); its `src/generated.rs` also carries the C original's 2011 notice, reproduced in [`crates/mesh-ops/ATTRIBUTION.md`](crates/mesh-ops/ATTRIBUTION.md) | | `crates/ui/tests/fonts/NotoSansArabic-test.ttf` (subset to the test strings, default weight set to 100, width axis dropped) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) | | `crates/ui/tests/fonts/NotoSansCJKsc-test.otf` (subset to the test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) | | `crates/imaging/tests/fonts/NotoSansArabic-digits.ttf` (instance at weight 400 and width 100, subset to the Arabic-Indic digits and separators U+0660–U+066C) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) | @@ -174,6 +175,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. `crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. +## GPU device selection + +`crates/gpu-device`'s adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both. + ## Dalvik DEX inspection `crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained. diff --git a/Cargo.lock b/Cargo.lock index 1eb7e98ead..07c3fd7ab8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1819,9 +1819,11 @@ dependencies = [ "craft-geom", "craft-gif", "craft-gpu", + "craft-gpu-device", "craft-gpu-null", "craft-gpu-providers", "craft-gpu-wgpu", + "craft-gpu-yuv", "craft-gridcraft-format", "craft-gzip", "craft-har", @@ -1863,6 +1865,7 @@ dependencies = [ "craft-media-source", "craft-menu", "craft-mesh", + "craft-mesh-ops", "craft-metadata", "craft-metafile", "craft-midi", @@ -1905,6 +1908,7 @@ dependencies = [ "craft-review", "craft-rtf", "craft-sbs", + "craft-scopes", "craft-score", "craft-scraft-format", "craft-settings", @@ -2284,7 +2288,6 @@ dependencies = [ "craft-flags", "craft-platform", "dirs", - "getrandom 0.3.4", "log", "proptest", "serde", @@ -2297,6 +2300,7 @@ dependencies = [ name = "craft-control-protocol" version = "0.1.0" dependencies = [ + "getrandom 0.3.4", "serde_json", "subtle", ] @@ -2502,6 +2506,7 @@ dependencies = [ "chrono", "craft-cfb", "craft-drawingml", + "craft-flow", "craft-math", "craft-offcrypto", "craft-opc", @@ -2920,6 +2925,18 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-gpu-device" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "log", + "pollster 0.4.0", + "serde", + "serde_json", + "wgpu", +] + [[package]] name = "craft-gpu-null" version = "0.1.0" @@ -2945,6 +2962,17 @@ dependencies = [ "wgpu", ] +[[package]] +name = "craft-gpu-yuv" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-null", + "pollster 0.4.0", + "wgpu", + "yuv", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" @@ -3418,6 +3446,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mesh-ops" +version = "0.1.0" +dependencies = [ + "glam 0.30.10", + "mikktspace", + "rayon", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-metadata" version = "0.1.0" @@ -3580,6 +3619,8 @@ version = "0.1.0" name = "craft-pbr" version = "0.1.0" dependencies = [ + "craft-materialx", + "craft-mesh", "craft-pbr", "craft-texture", "glam 0.30.10", @@ -4041,6 +4082,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-scopes" +version = "0.1.0" +dependencies = [ + "craft-color", + "serde", + "serde_json", +] + [[package]] name = "craft-score" version = "0.1.0" @@ -4294,7 +4344,14 @@ dependencies = [ name = "craft-testkit" version = "0.1.0" dependencies = [ + "libc", + "png 0.18.1", "rustix 1.1.6", + "serde_json", + "sha2 0.10.9", + "skrifa 0.47.0", + "tempfile", + "toml", ] [[package]] @@ -4328,8 +4385,12 @@ name = "craft-texture" version = "0.1.0" dependencies = [ "bytemuck", + "craft-exr", + "craft-hdr", + "craft-image-codecs", "dds", "half", + "png 0.18.1", "rayon", "thiserror 2.0.21", ] @@ -4931,9 +4992,14 @@ name = "craft-xtask" version = "0.1.0" dependencies = [ "craft-atomic", + "flate2", "libc", "serde_json", + "sha2 0.10.9", + "tar", "tempfile", + "toml_edit", + "unicode-normalization", ] [[package]] @@ -6807,6 +6873,12 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glam" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b" + [[package]] name = "glam" version = "0.25.0" @@ -6818,6 +6890,9 @@ name = "glam" version = "0.30.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9" +dependencies = [ + "serde_core", +] [[package]] name = "glifo" @@ -8346,8 +8421,6 @@ dependencies = [ [[package]] name = "kurbo" version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" dependencies = [ "arrayvec", "euclid", @@ -8663,6 +8736,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74" +[[package]] +name = "mikktspace" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d0b56b403871a8f992ca626d52cc0a690d4841baea8955dc4af6304ac62f8b0" +dependencies = [ + "glam 0.15.2", +] + [[package]] name = "mime" version = "0.3.17" @@ -15036,6 +15118,15 @@ dependencies = [ "synstructure 0.14.0", ] +[[package]] +name = "yuv" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d109d1eacc7b034329873d2d848039b365c65ab7d751b19ee84e4921c62c607" +dependencies = [ + "num-traits", +] + [[package]] name = "zbus" version = "5.19.0" diff --git a/Cargo.toml b/Cargo.toml index 3af86eaf40..136df2be6f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" members = ["crates/*"] -exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"] +exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"] [workspace.package] version = "0.1.0" @@ -37,7 +37,9 @@ acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } +craft-gpu-device = { path = "crates/gpu-device" } craft-wasm = { path = "crates/wasm" } +craft-gpu-yuv = { path = "crates/gpu-yuv" } craft-platform = { path = "crates/platform" } craft-png = { path = "crates/png" } craft-aep = { path = "crates/aep" } @@ -82,6 +84,7 @@ craft-cloud = { path = "crates/cloud" } craft-cloud-local = { path = "crates/cloud-local" } craft-cloud-ui = { path = "crates/cloud-ui" } craft-color = { path = "crates/color" } +craft-scopes = { path = "crates/scopes" } craft-color-ui = { path = "crates/color-ui" } craft-color-transform = { path = "crates/color-transform" } craft-frame = { path = "crates/frame" } @@ -133,6 +136,7 @@ craft-gcode = { path = "crates/gcode" } craft-gif = { path = "crates/gif" } craft-hdr = { path = "crates/hdr" } craft-mesh = { path = "crates/mesh" } +craft-mesh-ops = { path = "crates/mesh-ops" } craft-html = { path = "crates/html" } craft-ipp = { path = "crates/ipp" } craft-heif = { path = "crates/heif" } @@ -321,6 +325,7 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } +kurbo = { path = "vendor/kurbo" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } diff --git a/NOTICE b/NOTICE index 4a2d1084e4..baa994eb47 100644 --- a/NOTICE +++ b/NOTICE @@ -63,6 +63,10 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +mikktspace 0.3.0 (https://crates.io/crates/mikktspace/0.3.0), a dependency of crates/mesh-ops, + is MIT OR Apache-2.0. Its src/generated.rs, a translation of Morten S. Mikkelsen's C + MikkTSpace, carries that original's 2011 zlib-style notice, which must not be removed or + altered; crates/mesh-ops/ATTRIBUTION.md reproduces it in full. crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer. crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists) 2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/. @@ -229,6 +233,17 @@ 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 mesh operations in crates/mesh-ops are moved from: +- TextureCraft, crates/geom (src/mesh.rs, bvh.rs, primitives.rs, gbuffer.rs, unwrap.rs, + camera.rs and their tests), revision 386630ee85cb22679295b24013575d1aecb39ad2. + https://github.com/storytold/texturecraft + Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors. +- MaterialCraft, crates/geom/src/mesh.rs (subdivision and its test), revision + 3133062968b8a1566eda12a357cb06062db16687. + https://github.com/storytold/materialcraft + Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors. + All licensed MIT OR Apache-2.0. + 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. @@ -288,11 +303,18 @@ applications retain their own document-font selection and licensing policy. 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/segments.rs, 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 with its upstream license files and local changes. 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. +changes and the files left out. + +kurbo + +kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR +Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to +src/stroke.rs. Its source files carry "Copyright the Kurbo Authors" lines (2018 to 2026), +and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and +vendor/kurbo/SOURCE.json for provenance and the local patches. Platform lifecycle source provenance diff --git a/README.md b/README.md index 6e841b7157..8169bedf9a 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-automation`](crates/automation/README.md): drive a running app from tests, agents and the CLI: control channel, screenshot queue, frame profiler and trace (native only); recorded actions, their playback and the Actions panel (every target). - [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite. -- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft. +- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), the asset attribution check, an optional slot lock held across processes, an optional per-step JSON report, and PNG images packed into `.ico` and `.icns` files. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft; icon packing for DeckCraft, CADCraft, craft-launcher and MaterialCraft. - [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral 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 @@ -211,6 +211,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit every frame's position, delay, disposal and transparent colour, the loop count and the first frame's colour table, without decompressing pixels. Tells an animation from a still and whether a file can hold the picture it declares before a decoder runs. +- [`craft-gpu-yuv`](crates/gpu-yuv/README.md): the `craft.yuv` GPU provider. It converts RGBA to + NV12, P010 and I420, scaled to the output size, in BT.601, BT.709 and BT.2020 at limited or full + range, through the `craft-gpu` job registry on the null context or on a device. Each output texel + averages the part of the source it covers. The crate also has the render passes for a caller's + own encoder, read-back layouts with unpacking to a packed frame, and the same conversion on the + CPU. Encoders and scopes stay in each app. +- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto, + low power, a named adapter that survives a reordered list and a driver update, or software; + corrections for drivers that crash; the next adapter and then a software one when a device fails + to open; a capability report; device-loss and error recording without panics; and what to reopen + after a loss. Settings pages and the window stay in each app. - [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook (`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept unread and written back into a list. The workbook model and what follows a read stay in GridCraft. @@ -318,6 +329,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY, glTF 2.0 / GLB, FBX and 3MF, one feature each. Readers are bounded by `Limits`, never open a file themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft. +- [`craft-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals, + MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a + BVH for ray casts, and an orbit camera. From TextureCraft and MaterialCraft. - [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and 2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per quarter note. From SoundCraft. @@ -412,11 +426,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit reference picking, selection statistics, error tags and filter buttons (`ui` feature). - [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals - 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. Its `rng` - module holds two seeded generators for repeatable test input. Not published. + out of range, and `std::time::Instant` in code the web build runs. Its `fonts` module makes test fonts + from font bytes the caller supplies: a face with a renamed family and a TrueType collection. 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. Its `rng` module holds two seeded generators for repeatable test input. Its `skip` module + prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the + test when the variable the caller names is `1`. Any other value of that variable except empty fails + the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder + against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures + under `target/fixtures` and publishes each one under a lock. 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 @@ -424,8 +444,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit (ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find` (regex) are features. - [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with - nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are - bounded by `Limits`. From MaterialCraft. + nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and + (optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float + samples. Sizes are bounded by `Limits`. From MaterialCraft. - [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates, timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE, CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel, diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index ce6724bb8e..48daa625b1 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -12,8 +12,19 @@ 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, a loudness meter, and a pitch shifter for a live voice with 10 ms - of latency. + dither, a signal generator, a loudness meter, a pitch shifter for a live voice with 10 ms of + latency, a formant shifter for a live voice with 10.7 ms of latency, and noise suppression for + a live voice with 5.3 ms of latency that follows the noise floor without first learning it. + These latencies are at 48 kHz (the STFT sizes depend on the sample rate; `latency()` reports + them in samples). The pitch shifter's Keep Formants switch adds the formant shifter's latency, + and `latency()` reports it while the switch is on. A ring modulator for robotic and metallic + voices (ring, frequency modulation, and positive or negative comb resonators, with the + frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency, and + neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits, + or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. A vibrato + that swings the pitch by up to 100 cents through a delay moved by a sine or triangle LFO adds + no latency either: the delay is 0 at the start of each cycle, except while it glides to new + settings. - `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 @@ -28,6 +39,14 @@ and contains no `unsafe` code. - `biquad` and `design`: biquad filters with their magnitude response, and IIR filter design from Butterworth, Bessel, Chebyshev and elliptic prototypes. +`noise_suppression` estimates the noise floor from minimum spectral power over 1.5 s. The first +noise estimate after a reset starts from the median bin's power. Each bin's value is clamped +between 30 dB below its own estimate and its own estimate. Windows that overlap a run of at +least one hop of zeros (64 samples at 48 kHz) do not enter the noise estimate. The gain floor +moves from 0 dB toward the attenuation set by `reduction` during the first search window +of sound. Continuous voiced or tonal audio present from startup can enter the noise estimate +and be attenuated afterward. + ## Conventions Audio is planar `f32`: one slice per channel, all the same length. `AudioEffect::process`, @@ -79,7 +98,8 @@ The crate combines two crates from the ArtCraft apps, with changes: 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`). + shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`), and the + ring modulator (`src/plugins/modulation.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 42ec2261ce..0ea9055b1f 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -1,6 +1,7 @@ //! Audio effects and their registry. pub(crate) mod channel; +pub(crate) mod character; pub(crate) mod declick; pub(crate) mod dither; pub(crate) mod dynamics; @@ -15,11 +16,13 @@ pub(crate) mod restoration; pub(crate) mod reverbs; pub(crate) mod special; mod stft; +pub(crate) mod suppress; pub(crate) mod time; pub(crate) mod util; pub(crate) mod voice; pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing}; +pub use character::{Bitcrusher, RingMod, Tremolo, Vibrato}; pub(crate) use declick::ClickRemover; pub use dither::Dither; pub use dynamics::{Compressor, Gate, Limiter, Maximizer}; @@ -35,8 +38,9 @@ pub(crate) use restoration::{DeHum, DeNoise}; pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb}; pub use special::LoudnessMeterFx; pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer}; +pub use suppress::NoiseSuppression; pub(crate) use time::{Delay, Reverb}; -pub use voice::VoicePitch; +pub use voice::{VoiceFormant, VoicePitch}; use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate}; @@ -125,8 +129,10 @@ static REGISTRY: &[EffectInfo] = &[ }, entry!("dehum", "DeHum", Restoration, DeHum), entry!("denoise", "DeNoise", Restoration, DeNoise), + entry!("noise_suppression", "Noise Suppression", Restoration, NoiseSuppression), entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter), entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch), + entry!("voice_formant", "Voice Formant", Pitch, VoiceFormant), entry!("deesser", "DeEsser", Restoration, DeEsser), entry!("dereverb", "DeReverb", Restoration, DeReverb), entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance), @@ -144,6 +150,9 @@ static REGISTRY: &[EffectInfo] = &[ entry!("chorus_flanger", "Chorus/Flanger", Modulation, ChorusFlanger), entry!("flanger", "Flanger", Modulation, Flanger), entry!("phaser", "Phaser", Modulation, Phaser), + entry!("ring_mod", "Ring Modulator", Modulation, RingMod), + entry!("tremolo", "Tremolo", Modulation, Tremolo), + entry!("vibrato", "Vibrato", Modulation, Vibrato), entry!("analog_delay", "Analog Delay", Time, AnalogDelay), entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay), entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb), @@ -151,6 +160,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("click_remover", "Automatic Click Remover", Restoration, ClickRemover), entry!("channel_mixer", "Channel Mixer", Channel, ChannelMixer), entry!("distortion", "Distortion", Special, Distortion), + entry!("bitcrusher", "Bitcrusher", Special, Bitcrusher), entry!("guitar_suite", "GuitarSuite", Special, GuitarSuite), entry!("mastering", "Mastering", Special, Mastering), entry!("vocal_enhancer", "Vocal Enhancer", Special, VocalEnhancer), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index 662046f75c..6433aa26c7 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -132,9 +132,11 @@ fn every_effect_is_deterministic_and_latency_is_constant() { f }; let lat0 = (e.create)(SR, 2).latency(); + // Keep Formants adds voice_pitch's formant stage; no other parameter changes a latency. + let want = if e.id == "voice_pitch" { lat0 + voice::VoiceFormant::new(SR, 2).latency() } else { lat0 }; let mut a = mk(); let mut b = mk(); - assert_eq!(a.latency(), lat0, "{}: latency depends on parameters", e.id); + assert_eq!(a.latency(), want, "{}: latency depends on parameters", e.id); let ya = run(a.as_mut(), &l, &r); let yb = run(b.as_mut(), &l, &r); assert!(ya.0 == yb.0 && ya.1 == yb.1, "{}: not deterministic", e.id); @@ -147,7 +149,14 @@ 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)]), ("voice_pitch", vec![])] { + for (id, p) in [ + ("fft_filter", vec![]), + ("convolution_reverb", vec![("mix", 0.0)]), + ("voice_pitch", vec![]), + ("voice_pitch", vec![("formant_follow", 1.0)]), + ("voice_formant", vec![]), + ("noise_suppression", vec![("reduction", 0.0)]), + ] { let mut e = fx(id, &p); let lat = e.latency(); assert!(lat > 0, "{id}"); @@ -906,6 +915,8 @@ fn delays_and_reverbs_report_their_tails() { ("chorus_flanger", &[("mode", 1.0), ("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]), ("chorus_flanger", &[("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]), ("flanger", &[("final_delay", 20.0), ("feedback", 100.0), ("mix", 100.0)][..]), + ("ring_mod", &[("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)][..]), + ("ring_mod", &[("effect", 3.0), ("frequency", 60.0), ("resonance", 95.0), ("mod_source", 1.0), ("mod_depth", 100.0)][..]), ] { let mut e = fx(id, params); let tail = e.tail_samples(); @@ -977,6 +988,12 @@ fn direct_constructors_cap_the_channel_count() { filters::FullParametricEq, pitch::PitchShifter, voice::VoicePitch, + voice::VoiceFormant, + suppress::NoiseSuppression, + character::RingMod, + character::Bitcrusher, + character::Tremolo, + character::Vibrato, ); } diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs new file mode 100644 index 0000000000..eb623f0870 --- /dev/null +++ b/crates/audio-dsp/src/effects/character.rs @@ -0,0 +1,1487 @@ +//! Character effects for a live voice. None of them adds latency. +//! +//! The ring modulator (`ring_mod`) has four effects: +//! +//! - Ring multiplies the input by a sine carrier at the frequency, which moves each partial of a +//! voice to the sum and the difference of its frequency and the carrier's. +//! - Frequency Mod reads the input through a delay that the carrier swings between 2 samples and +//! 2 samples plus 2 ms. +//! - Resonator + and Resonator - feed the output back after one period of the frequency, with a +//! positive or a negative sign, so the input rings at the frequency and its multiples (Resonator +//! +) or at its odd half multiples (Resonator -). The output is scaled by `1 - resonance`, so the +//! peak gain at resonance is unity. +//! +//! An LFO, an envelope follower (5 ms attack, 100 ms release) or a sample-and-hold source moves the +//! frequency by up to two octaves either way at 100 % depth. The envelope follower moves it up +//! only. +//! +//! The bitcrusher (`bitcrusher`) takes one input sample every `rate_divide` samples, holds it until +//! the next one, and rounds it to a word length of 1 to 16 bits. +//! +//! The tremolo (`tremolo`) lowers the gain of every channel by up to `depth` once per cycle of a +//! sine, triangle or square LFO at `rate`. +//! +//! The vibrato (`vibrato`) reads the input through a delay that grows from 0 and shrinks back once +//! per cycle of a sine or triangle LFO at `rate`, so the pitch swings by up to `depth` cents. While +//! no glide to new settings is in progress, the delay is 0 at the start of each cycle. + +use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail, uni_sine, uni_tri}; +use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; +use std::f64::consts::TAU; + +fn blend(dry: f64, wet: f64, mix: f64) -> f64 { + (1.0 - mix) * dry + mix * wet +} + +/// Smoothing time of the frequency, resonance, depth and mix, in ms. +const SM: f32 = 20.0; +const RING_EFFECTS: &[&str] = &["Ring", "Frequency Mod", "Resonator +", "Resonator -"]; +const RING_SOURCES: &[&str] = &["LFO", "Envelope", "Sample & Hold"]; +/// Lowest frequency the control reaches. +const MIN_HZ: f32 = 20.0; +/// Octaves the frequency moves at full modulation depth. +const MOD_OCTAVES: f32 = 2.0; +/// Peak delay swing of Frequency Mod, in ms. +const FM_SWING_MS: f32 = 1.0; +/// Shortest delay of Frequency Mod, in samples (room for the interpolated read). +const FM_BASE: f32 = 2.0; +/// Sample-and-hold seed (the same sequence after every reset). +const SEED: u64 = 0x5EED_1234; +/// Highest frequency the modulation reaches, as a fraction of the sample rate. +const MAX_FRACTION: f32 = 0.45; +const TREMOLO_SHAPES: &[&str] = &["Sine", "Triangle", "Square"]; +/// Length of each edge of the tremolo's square, in ms. +const EDGE_MS: f64 = 2.0; +const VIBRATO_SHAPES: &[&str] = &["Sine", "Triangle"]; +/// Lowest rate of the vibrato, in Hz. +const VIBRATO_MIN_RATE: f32 = 1.0; +/// Greatest depth of the vibrato, in cents. +const VIBRATO_MAX_CENTS: f32 = 100.0; +/// Most the vibrato's glide moves the delay per sample on top of the curve. +const VIBRATO_GLIDE_SLOPE: f32 = 1.0 / 32.0; + +/// Ring modulation, frequency modulation and positive or negative comb resonators, with the +/// frequency moved by an LFO, an envelope follower or a sample-and-hold source. +pub struct RingMod { + pv: ParamValues, + sr: f32, + lines: Vec, + carrier: Lfo, + lfo: Lfo, + rng: Prng, + env: Envelope, + env_attack: f32, + env_release: f32, + held: f32, + hold_left: usize, + /// Effect the lines hold state for. + effect: usize, + freq: Smoothed, + res: Smoothed, + depth: Smoothed, + mix: Smoothed, +} + +impl RingMod { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::choice("effect", "Effect", RING_EFFECTS, 0), + ParamSpec::log("frequency", "Frequency", MIN_HZ, 5000.0, 440.0, Unit::Hertz), + ParamSpec::new("resonance", "Resonance", 0.0, 95.0, 50.0, Unit::Percent), + ParamSpec::choice("mod_source", "Mod Source", RING_SOURCES, 0), + ParamSpec::log("mod_rate", "Mod Rate", 0.05, 20.0, 1.0, Unit::Hertz), + ParamSpec::new("mod_depth", "Mod Depth", 0.0, 100.0, 0.0, Unit::Percent), + ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + // One period of the lowest frequency the modulation reaches, or the widest Frequency Mod + // delay, whichever is longer. + let longest_ms = (1000.0 / (MIN_HZ * (-MOD_OCTAVES).exp2())).max(2.0 * FM_SWING_MS) + 1.0; + let len = delay_line_len(longest_ms, sample_rate, ch); + let sm = |v| Smoothed::with_ms(v, sample_rate, SM); + let mut s = RingMod { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + lines: vec![DelayLine::new(len); ch], + carrier: Lfo::default(), + lfo: Lfo::default(), + rng: Prng::new(SEED), + env: Envelope::default(), + env_attack: coef(5.0, sample_rate), + env_release: coef(100.0, sample_rate), + held: 0.0, + hold_left: 0, + effect: 0, + freq: sm(440.0), + res: sm(0.0), + depth: sm(0.0), + mix: sm(1.0), + }; + s.apply_params(true); + s.effect = s.pv.idx("effect"); + s + } + + fn apply_params(&mut self, snap: bool) { + self.freq.set(self.pv.v("frequency")); + self.res.set(self.pv.v("resonance") / 100.0); + self.depth.set(self.pv.v("mod_depth") / 100.0); + self.mix.set(self.pv.v("mix") / 100.0); + if snap { + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.snap(); + } + } + } + + /// One period of the lowest frequency the modulation reaches, in ms, from the settings and from + /// the values still ramping toward them. The envelope follower moves the frequency up only, so + /// with it the lowest is the frequency. The frequency is held within the same range as in + /// [`AudioEffect::process`]. + fn longest_period_ms(&self) -> f32 { + let down = if self.pv.idx("mod_source") == 1 { 0.0 } else { self.depth.value().max(self.depth.target()) }; + let lowest = self.freq.value().min(self.freq.target()) * (-MOD_OCTAVES * down).exp2(); + 1000.0 / lowest.clamp(1.0, self.sr * MAX_FRACTION) + } +} + +impl AudioEffect for RingMod { + param_plumbing!("ring_mod"); + /// Ring has no tail. Frequency Mod holds up to its widest delay. The resonators ring until + /// the feedback has fallen by 60 dB at the longest period the modulation reaches, at the higher + /// of the resonance setting and the value still ramping toward it. + fn tail_samples(&self) -> usize { + match self.pv.idx("effect") { + 1 => (FM_BASE + 2.0 * FM_SWING_MS * 0.001 * self.sr).ceil() as usize + 1, + 2 | 3 => echo_tail(self.longest_period_ms(), self.res.value().max(self.res.target()), self.sr), + _ => 0, + } + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(DelayLine::reset); + self.carrier.reset(); + self.lfo.reset(); + self.rng = Prng::new(SEED); + self.env.env = 0.0; + self.held = 0.0; + self.hold_left = 0; + self.effect = self.pv.idx("effect"); + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.snap(); + } + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + return; + } + let nch = channels.len().min(self.lines.len()); + let effect = self.pv.idx("effect"); + if effect != self.effect { + // The lines hold the previous effect's state. + self.lines.iter_mut().for_each(DelayLine::reset); + self.effect = effect; + } + let source = self.pv.idx("mod_source"); + let rate = self.pv.v("mod_rate"); + let hold = ((self.sr / rate.max(0.05)) as usize).max(1); + // A faster rate cuts the value being held short, instead of holding it for the old length. + self.hold_left = self.hold_left.min(hold); + let highest = self.sr * MAX_FRACTION; + let swing = FM_SWING_MS * 0.001 * self.sr; + let sign = if effect == 3 { -1.0 } else { 1.0 }; + for i in 0..n { + let level = channels[..nch].iter().map(|c| c[i]).filter(|x| x.is_finite()).fold(0.0f32, |m, x| m.max(x.abs())); + let env = self.env.tick(self.env_attack, self.env_release, level); + let m = match source { + 1 => env.min(1.0), + 2 => { + if self.hold_left == 0 { + self.held = self.rng.uniform(); + self.hold_left = hold; + } + self.hold_left -= 1; + self.held + } + _ => (TAU * self.lfo.phase(0.0)).sin() as f32, + }; + self.lfo.advance(rate, self.sr); + let f = (self.freq.tick() * (MOD_OCTAVES * self.depth.tick() * m).exp2()).clamp(1.0, highest); + let fb = self.res.tick(); + let mix = self.mix.tick(); + let carrier = (TAU * self.carrier.phase(0.0)).sin() as f32; + self.carrier.advance(f, self.sr); + // The read happens before this sample's push, so one period back is `period - 1`. + let back = self.sr / f - 1.0; + for (ch, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is taken as silence. A channel the block leaves out is fed + // silence, so it holds none of its earlier audio when it comes back. + let dry = match channels.get(ch).filter(|_| ch < nch) { + Some(c) if c[i].is_finite() => c[i], + _ => 0.0, + }; + let wet = match effect { + 1 => { + line.push(dry); + // The read interpolates in f64, as Vibrato's does, so neighboring samples + // near the f32 limit with opposite signs do not overflow. + let d = (FM_BASE + swing * (1.0 + carrier)).clamp(0.0, line.max_delay()); + let (di, frac) = (d.floor() as usize, f64::from(d - d.floor())); + let (a, b) = (f64::from(line.tap(di)), f64::from(line.tap(di + 1))); + (a + (b - a) * frac) as f32 + } + 2 | 3 => { + let y = flush32(dry + sign * fb * line.read(back)); + line.push(y); + y * (1.0 - fb) + } + _ => dry * carrier, + }; + if ch < nch { + let (dry, wet) = (dry as f64, wet as f64); + channels[ch][i] = blend(dry, wet, f64::from(mix)) as f32; + } + } + } + } +} + +/// Bit-depth and sample-rate reduction. The input is sampled once every `rate_divide` samples and +/// held in between; a fractional value alternates between the two nearest whole hold lengths, so +/// the holds average it. Each held sample is rounded to the nearest multiple of the step +/// `2^(1 - bits)`, so silence stays silence and the range -1 ..= 1 takes `2^bits + 1` levels; +/// fractional bits give steps between the whole-bit ones. Bits and Rate Divide take effect from +/// the next sample: a new Bits rounds the sample being held again, and a shorter hold cuts the +/// one in progress short. Mix moves to a new value over 20 ms. +pub struct Bitcrusher { + pv: ParamValues, + /// The input sample each channel holds, before rounding. + held: Vec, + /// Samples since the last capture, counted so that a capture happens when it reaches the hold + /// length. Infinite after a reset, so the next sample is captured. + since: f64, + mix: Smoothed, +} + +impl Bitcrusher { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::new("bits", "Bits", 1.0, 16.0, 8.0, Unit::None), + ParamSpec::new("rate_divide", "Rate Divide", 1.0, 50.0, 4.0, Unit::None), + ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent), + ]; + + 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 mut s = Bitcrusher { + pv: ParamValues::new(Self::PARAMS), + held: vec![0.0; ch], + since: f64::INFINITY, + mix: Smoothed::with_ms(1.0, sample_rate, SM), + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, snap: bool) { + self.mix.set(self.pv.v("mix") / 100.0); + if snap { + self.mix.snap(); + } + } +} + +impl AudioEffect for Bitcrusher { + param_plumbing!("bitcrusher"); + /// A held sample lasts at most the hold length rounded up, so it sounds for up to that many + /// samples less one after the input ends. + fn tail_samples(&self) -> usize { + (self.pv.v("rate_divide").ceil() as usize).saturating_sub(1) + } + fn reset(&mut self) { + self.held.fill(0.0); + self.since = f64::INFINITY; + self.mix.snap(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + let nch = channels.len().min(self.held.len()); + let hold = f64::from(self.pv.v("rate_divide")); + // The rounding and the mix run in f64, so a finite input near the f32 limit stays finite. + let step = (1.0 - f64::from(self.pv.v("bits"))).exp2(); + let limit = f64::from(f32::MAX); + for i in 0..n { + let capture = self.since >= hold; + if capture { + // On schedule, less than one sample is left over. More is left after a reset or + // after the hold got shorter; the new holds then count from this capture. + let left = self.since - hold; + self.since = if left < 1.0 { left } else { 0.0 }; + } + self.since += 1.0; + let mix = f64::from(self.mix.tick()); + for (ch, held) in self.held.iter_mut().enumerate() { + // A non-finite sample is taken as silence. A channel the block leaves out holds + // silence from its first left-out sample on, so it holds none of its earlier audio + // when it comes back. + let dry = match channels.get(ch).filter(|_| ch < nch) { + Some(c) if c[i].is_finite() => f64::from(c[i]), + _ => 0.0, + }; + if capture || ch >= nch { + *held = dry as f32; + } + if ch < nch { + // The held input is rounded at the current step, so a change of Bits also + // applies to the hold in progress. + let crushed = ((f64::from(*held) / step).round() * step).clamp(-limit, limit); + channels[ch][i] = blend(dry, crushed, mix) as f32; + } + } + } + } +} + +/// Amplitude modulation. The gain is `1 - depth * m`, where the LFO value `m` runs from 0 at the +/// start of each cycle to 1 at its middle and back, as a sine, a triangle or a square. The square +/// holds 0 and 1 for half a cycle each and moves between them along a raised-cosine edge 2 ms long, +/// centered on the quarter and three-quarter points, so it does not click. Rate takes effect from +/// the next sample with the phase kept. A change of Shape, or of Rate while the shape is the +/// square, glides from the last LFO value to the new curve over 20 ms, with the value kept within +/// 0 ..= 1. Depth moves to a new value over 20 ms. +pub struct Tremolo { + pv: ParamValues, + sr: f32, + channels: usize, + lfo: Lfo, + /// Shape the LFO value follows. + shape: usize, + /// Length of the square's edges, in cycles, for the rate of the last block. + edge: f64, + /// LFO value of the last sample. + last: f32, + /// Difference between the last LFO value and the new curve at a change of Shape, or of the + /// square's edges. It fades to zero over `glide_len` samples. + glide: f32, + glide_left: usize, + glide_len: usize, + depth: Smoothed, +} + +impl Tremolo { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::log("rate", "Rate", 0.1, 20.0, 5.0, Unit::Hertz), + ParamSpec::new("depth", "Depth", 0.0, 100.0, 50.0, Unit::Percent), + ParamSpec::choice("shape", "Shape", TREMOLO_SHAPES, 0), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let mut s = Tremolo { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + channels: crate::sane_channels(channels), + lfo: Lfo::default(), + shape: 0, + edge: 0.0, + last: 0.0, + glide: 0.0, + glide_left: 0, + glide_len: ((SM * 0.001 * sample_rate) as usize).max(1), + depth: Smoothed::with_ms(0.5, sample_rate, SM), + }; + s.apply_params(true); + s.shape = s.pv.idx("shape"); + s.edge = s.edge_len(); + s + } + + /// Length of the square's edges at the current rate, in cycles. + fn edge_len(&self) -> f64 { + (EDGE_MS * 0.001 * f64::from(self.pv.v("rate"))).clamp(1e-9, 0.25) + } + + fn apply_params(&mut self, snap: bool) { + self.depth.set(self.pv.v("depth") / 100.0); + if snap { + self.depth.snap(); + } + } + + /// LFO value of `shape` at phase `p` (cycles), with square edges `edge` cycles long. + fn shape_value(shape: usize, p: f64, edge: f64) -> f32 { + match shape { + 1 => uni_tri(p), + 2 => { + // The triangle crosses 1/2 at the edges' centers with a slope of 2 per cycle, so an + // edge `edge` cycles long spans `2 * edge` of it. + let tri = if p < 0.5 { 2.0 * p } else { 2.0 - 2.0 * p }; + let u = ((tri - 0.5) / (2.0 * edge) + 0.5).clamp(0.0, 1.0); + (0.5 - 0.5 * (std::f64::consts::PI * u).cos()) as f32 + } + _ => uni_sine(p), + } + } +} + +impl AudioEffect for Tremolo { + param_plumbing!("tremolo"); + fn reset(&mut self) { + self.lfo.reset(); + self.shape = self.pv.idx("shape"); + self.edge = self.edge_len(); + self.last = 0.0; + self.glide = 0.0; + self.glide_left = 0; + self.depth.snap(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + // No sample used the current settings, so a glide in progress goes on unchanged. + return; + } + let nch = channels.len().min(self.channels); + let rate = self.pv.v("rate"); + let edge = self.edge_len(); + let shape = self.pv.idx("shape"); + if shape != self.shape || (shape == 2 && edge != self.edge) { + self.glide = self.last - Self::shape_value(shape, self.lfo.phase(0.0), edge); + self.glide_left = self.glide_len; + self.shape = shape; + } + self.edge = edge; + for i in 0..n { + let mut m = Self::shape_value(shape, self.lfo.phase(0.0), edge); + if self.glide_left > 0 { + m = (m + self.glide * self.glide_left as f32 / self.glide_len as f32).clamp(0.0, 1.0); + self.glide_left -= 1; + } + self.last = m; + self.lfo.advance(rate, self.sr); + let gain = 1.0 - self.depth.tick() * m; + for c in channels[..nch].iter_mut() { + // A non-finite sample is taken as silence. + c[i] = if c[i].is_finite() { c[i] * gain } else { 0.0 }; + } + } + } +} + +/// Pitch modulation. The input is read through a delay of `swing * m` samples, where the LFO value +/// `m` runs from 0 at the start of each cycle to 1 at its middle and back, as a sine or a triangle. +/// The swing is set so that the pitch falls by `depth` cents while the delay grows, and rises by a +/// little less while it shrinks: the read moves at `1 -/+ d` samples per sample, with +/// `d = 1 - 2^(-depth / 1200)`. A sine reaches `d` at its steepest point, and a triangle holds it +/// for each half of the cycle. While no glide is in progress, the delay is 0 at the start of each +/// cycle. Rate takes effect from the next sample with the phase kept. A change of Rate, Depth or +/// Shape glides the delay from its last value to the new curve, moving it by at most 1/32 sample +/// per sample on top of the curve, so the output neither clicks nor jumps in pitch. A glide can run +/// past the start of a cycle, and the delay there stays above 0 until the glide ends. +pub struct Vibrato { + pv: ParamValues, + sr: f32, + lines: Vec, + lfo: Lfo, + /// Shape the delay follows. + shape: usize, + /// Peak delay of the curve, in samples, for the settings of the last block. + swing: f32, + /// Delay of the last sample, in samples. + last: f32, + /// Difference between the last delay and the new curve at a change of the settings. It fades + /// to zero over `glide_len` samples. + glide: f32, + glide_left: usize, + glide_len: usize, +} + +impl Vibrato { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::log("rate", "Rate", VIBRATO_MIN_RATE, 14.0, 6.0, Unit::Hertz), + ParamSpec::new("depth", "Depth (cents)", 0.0, VIBRATO_MAX_CENTS, 40.0, Unit::None), + ParamSpec::choice("shape", "Shape", VIBRATO_SHAPES, 0), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + // The widest swing is the triangle's at the lowest rate and the greatest depth. A glide + // can add up to one more swing on top of the curve. + let widest_ms = (1000.0 * Self::slope(VIBRATO_MAX_CENTS) / (2.0 * f64::from(VIBRATO_MIN_RATE))) as f32; + let len = delay_line_len(2.0 * widest_ms + 1.0, sample_rate, ch); + let mut s = Vibrato { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + lines: vec![DelayLine::new(len); ch], + lfo: Lfo::default(), + shape: 0, + swing: 0.0, + last: 0.0, + glide: 0.0, + glide_left: 0, + glide_len: 1, + }; + s.shape = s.pv.idx("shape"); + s.swing = s.swing_len(); + s + } + + fn apply_params(&mut self, _snap: bool) {} + + /// Samples the read moves per sample, away from 1, at a depth of `cents`. + fn slope(cents: f32) -> f64 { + 1.0 - (-f64::from(cents) / 1200.0).exp2() + } + + /// Peak delay of the curve for the current settings, in samples. + fn swing_len(&self) -> f32 { + let (d, rate, sr) = (Self::slope(self.pv.v("depth")), f64::from(self.pv.v("rate")), f64::from(self.sr)); + // The sine's delay `swing * (1 - cos(2 pi p)) / 2` moves by at most `swing * pi * rate / sr` + // per sample, and the triangle's moves by `swing * 2 * rate / sr`. + let swing = if self.pv.idx("shape") == 1 { d * sr / (2.0 * rate) } else { d * sr / (std::f64::consts::PI * rate) }; + (swing as f32).min(self.max_delay()) + } + + fn max_delay(&self) -> f32 { + self.lines.first().map_or(0.0, DelayLine::max_delay) + } + + /// LFO value of `shape` at phase `p` (cycles). + fn shape_value(shape: usize, p: f64) -> f32 { + if shape == 1 { uni_tri(p) } else { uni_sine(p) } + } +} + +impl AudioEffect for Vibrato { + param_plumbing!("vibrato"); + /// The input sounds until the delay has passed it. The delay reaches at most the new curve's + /// swing plus the last delay, so the tail covers both. + fn tail_samples(&self) -> usize { + (self.swing_len() + self.last).min(self.max_delay()).ceil() as usize + 1 + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(DelayLine::reset); + self.lfo.reset(); + self.shape = self.pv.idx("shape"); + self.swing = self.swing_len(); + self.last = 0.0; + self.glide = 0.0; + self.glide_left = 0; + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + // No sample uses the new settings, so no glide starts. + return; + } + let nch = channels.len().min(self.lines.len()); + let rate = self.pv.v("rate"); + let shape = self.pv.idx("shape"); + let swing = self.swing_len(); + if shape != self.shape || swing != self.swing { + self.glide = self.last - swing * Self::shape_value(shape, self.lfo.phase(0.0)); + self.glide_len = ((self.glide.abs() / VIBRATO_GLIDE_SLOPE).ceil() as usize).max(1); + self.glide_left = if self.glide == 0.0 { 0 } else { self.glide_len }; + self.shape = shape; + self.swing = swing; + } + let max = self.max_delay(); + for i in 0..n { + let mut d = swing * Self::shape_value(shape, self.lfo.phase(0.0)); + if self.glide_left > 0 { + d = (d + self.glide * self.glide_left as f32 / self.glide_len as f32).clamp(0.0, max); + self.glide_left -= 1; + } + self.last = d; + self.lfo.advance(rate, self.sr); + // The read interpolates in f64, so neighboring samples near the f32 limit with opposite + // signs do not overflow. + let d = if d.is_nan() { 0.0 } else { d.clamp(0.0, max) }; + let (di, frac) = (d.floor() as usize, f64::from(d - d.floor())); + for (ch, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is taken as silence. A channel the block leaves out is fed + // silence, so it holds none of its earlier audio when it comes back. + let dry = match channels.get(ch).filter(|_| ch < nch) { + Some(c) if c[i].is_finite() => c[i], + _ => 0.0, + }; + line.push(dry); + if ch < nch { + let (a, b) = (f64::from(line.tap(di)), f64::from(line.tap(di + 1))); + channels[ch][i] = (a + (b - a) * frac) as f32; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn ring(params: &[(&str, f32)], channels: usize) -> RingMod { + let mut r = RingMod::new(SR, channels); + for (id, v) in params { + assert!(r.set_param(id, *v), "{id}"); + } + r.reset(); + r + } + + /// Ring moves a tone to the sum and the difference of its frequency and the carrier's, each + /// at half the tone's amplitude, and leaves nothing at the tone's own frequency. + #[test] + fn ring_moves_a_tone_to_the_sum_and_difference_frequencies() { + let mut r = ring(&[("frequency", 300.0)], 1); + let mut x = sine(1000.0, 0.5, SR as f64, SR as usize, 0.0); + r.process(&mut [&mut x]); + for (f, want) in [(700.0, 0.25), (1300.0, 0.25), (1000.0, 0.0), (300.0, 0.0)] { + let a = tone_amplitude(&x, f, SR as f64); + assert!((a - want).abs() < 0.005, "{f} Hz: {a}, want {want}"); + } + } + + /// Resonator + repeats an impulse once per period of its frequency, each repeat lower by the + /// resonance, and Resonator - flips the sign of each repeat. + #[test] + fn resonators_repeat_an_impulse_once_per_period() { + for (effect, sign) in [(2.0, 1.0f32), (3.0, -1.0)] { + let mut r = ring(&[("effect", effect), ("frequency", 500.0), ("resonance", 80.0)], 1); + let mut x = vec![0.0f32; 1000]; + x[10] = 1.0; + r.process(&mut [&mut x]); + // 96 samples per period at 500 Hz. + for k in 0..8 { + let i = 10 + 96 * k; + let want = 0.2 * (sign * 0.8).powi(k as i32); + assert!((x[i] - want).abs() < 1e-5, "effect {effect}, repeat {k} at {i}: {}, want {want}", x[i]); + } + let others = x.iter().enumerate().filter(|(i, _)| *i < 10 || (*i - 10) % 96 != 0).fold(0.0f32, |m, (_, v)| m.max(v.abs())); + assert!(others < 1e-5, "effect {effect}: {others} between the repeats"); + } + } + + /// Frequency Mod delays the input by 2 samples to 2 samples plus 2 ms, swinging across the + /// whole range at the carrier's rate. + #[test] + fn frequency_mod_swings_the_delay_by_two_ms() { + let mut r = ring(&[("effect", 1.0), ("frequency", 440.0)], 1); + let slope = 1e-4f32; + let mut x: Vec = (0..4800).map(|i| i as f32 * slope).collect(); + r.process(&mut [&mut x]); + let delays: Vec = x.iter().enumerate().skip(200).map(|(i, y)| (i as f32 * slope - y) / slope).collect(); + let (lo, hi) = delays.iter().fold((f32::MAX, f32::MIN), |(lo, hi), d| (lo.min(*d), hi.max(*d))); + assert!((1.99..2.1).contains(&lo), "shortest delay {lo}"); + assert!((97.9..=98.01).contains(&hi), "longest delay {hi}"); + } + + /// With the envelope as the source, a steady input at full level moves the frequency up by + /// the depth: two octaves at 100 %. + #[test] + fn envelope_moves_the_frequency_up_with_the_level() { + let mut r = ring(&[("frequency", 100.0), ("mod_source", 1.0), ("mod_depth", 100.0)], 1); + let n = SR as usize; + let mut x = vec![1.0f32; n]; + r.process(&mut [&mut x]); + let tail = &x[n / 2..]; + assert!(tone_amplitude(tail, 400.0, SR as f64) > 0.99, "400 Hz: {}", tone_amplitude(tail, 400.0, SR as f64)); + assert!(tone_amplitude(tail, 100.0, SR as f64) < 0.01, "100 Hz: {}", tone_amplitude(tail, 100.0, SR as f64)); + } + + /// A resonator's tail covers the longest period the modulation reaches: four times as long at + /// full depth with the LFO or sample and hold, which move the frequency down two octaves, and + /// unchanged with the envelope, which moves it up only. + #[test] + fn resonator_tail_follows_the_lowest_frequency_the_modulation_reaches() { + let tail = |source: f32, depth: f32| { + ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 90.0), ("mod_source", source), ("mod_depth", depth)], 1).tail_samples() as f32 + }; + let still = tail(0.0, 0.0); + for source in [0.0, 2.0] { + let ratio = tail(source, 100.0) / still; + assert!((ratio - 4.0).abs() < 0.01, "source {source}: {ratio}"); + } + assert_eq!(tail(1.0, 100.0), still); + } + + /// While the resonance ramps down to a new setting, the tail still covers the higher value, + /// and it shrinks to the new setting's tail once the ramp has ended. + #[test] + fn resonator_tail_covers_a_resonance_still_ramping_down() { + let mut r = ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 95.0)], 1); + let high = r.tail_samples(); + assert!(r.set_param("resonance", 0.0)); + assert_eq!(r.tail_samples(), high); + let mut x = vec![0.0f32; 4800]; + r.process(&mut [&mut x]); + let low = ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 0.0)], 1).tail_samples(); + assert_eq!(r.tail_samples(), low); + assert!(low * 10 < high, "{low} vs {high}"); + } + + /// At a low sample rate the resonators ring at the highest frequency processing reaches, not + /// at the setting above it, and the tail covers that ring. A setting below that frequency + /// keeps the tail of its own period. + #[test] + fn resonator_tail_covers_a_frequency_held_at_the_rate_limit() { + let sr = 1000.0f32; + let mut r = RingMod::new(sr, 1); + for (id, v) in [("effect", 2.0), ("frequency", 5000.0), ("resonance", 95.0)] { + assert!(r.set_param(id, v), "{id}"); + } + r.reset(); + let tail = r.tail_samples(); + let mut x = vec![0.0f32; tail + 200]; + x[0] = 1.0; + r.process(&mut [&mut x]); + let after = x[tail + 1..].iter().fold(0.0f32, |m, v| m.max(v.abs())); + assert!(after <= 1e-3 * x[0].abs(), "tail {tail}: {after} after it, against {} at the impulse", x[0]); + let mut below = RingMod::new(sr, 1); + for (id, v) in [("effect", 2.0), ("frequency", 400.0), ("resonance", 95.0)] { + assert!(below.set_param(id, v), "{id}"); + } + below.reset(); + assert_eq!(below.tail_samples(), echo_tail(1000.0 / 400.0, 0.95, sr)); + } + + /// Frequency Mod reads between two of the largest samples of opposite sign without + /// overflowing. + #[test] + fn frequency_mod_reads_between_huge_samples_of_opposite_sign() { + let mut r = ring(&[("effect", 1.0), ("frequency", 500.0)], 1); + let mut x = vec![0.0f32; 200]; + x[6] = -f32::MAX; + x[7] = f32::MAX; + r.process(&mut [&mut x]); + assert!(x.iter().all(|v| v.is_finite()), "{:?}", x.iter().position(|v| !v.is_finite())); + } + + #[test] + fn frequency_mod_full_mix_keeps_a_small_delayed_sample() { + let mut r = ring(&[("effect", 1.0), ("frequency", 500.0), ("mix", 100.0)], 1); + let mut x = vec![0.5f32; 600]; + x[500] = f32::MAX; + r.process(&mut [&mut x]); + assert_eq!(x[500], 0.5, "the delayed sample was lost at full mix"); + } + + /// Mixing a dry and a wet sample of opposite sign at the largest level stays finite: a mix of + /// 0 gives the input, and every mix gives the result at a level of 1 scaled up. + #[test] + fn mixing_huge_samples_of_opposite_sign_stays_finite() { + for mix in [0.0f32, 50.0, 100.0] { + let run = |level: f32| { + let mut r = ring(&[("frequency", 5000.0), ("mix", mix)], 1); + let mut x = vec![level; 480]; + r.process(&mut [&mut x]); + x + }; + let (huge, unit) = (run(f32::MAX), run(1.0)); + assert!(huge.iter().all(|v| v.is_finite()), "mix {mix}"); + for (i, (h, u)) in huge.iter().zip(&unit).enumerate() { + let want = *u as f64 * f32::MAX as f64; + assert!((*h as f64 - want).abs() <= 1e-5 * f32::MAX as f64, "mix {mix}, sample {i}: {h} against {want}"); + } + if mix == 0.0 { + assert!(huge.iter().all(|v| *v == f32::MAX)); + } + } + } + + /// At a mix of 100% the output is the wet sample even when the dry sample is far larger. + #[test] + fn full_mix_keeps_a_small_wet_sample_beside_a_huge_dry_one() { + let mut c = crush(&[("mix", 100.0), ("bits", 16.0), ("rate_divide", 4.0)], 1); + let mut y = vec![0.5, f32::MAX, f32::MAX, f32::MAX, 0.25]; + c.process(&mut [&mut y]); + assert_eq!(y[1], 0.5, "the held sample was lost at full mix: {y:?}"); + } + + /// Raising the sample-and-hold rate takes effect within one new hold, instead of after the + /// value already held at the slow rate runs out. + #[test] + fn sample_and_hold_follows_a_faster_rate_at_once() { + let mut r = ring(&[("mod_source", 2.0), ("mod_rate", 0.05), ("mod_depth", 100.0)], 1); + let mut x = vec![0.0f32; 480]; + r.process(&mut [&mut x]); + let first = r.held; + assert!(r.set_param("mod_rate", 20.0)); + // A hold lasts 2,400 samples at 20 Hz and 960,000 at 0.05 Hz. + let mut x = vec![0.0f32; 4800]; + r.process(&mut [&mut x]); + assert_ne!(r.held, first, "the slow hold kept its value"); + } + + /// At a mix of 0 every effect passes the input through unchanged. + #[test] + fn mix_zero_passes_the_input_through() { + for effect in 0..4 { + let mut r = ring(&[("effect", effect as f32), ("mix", 0.0), ("mod_depth", 50.0)], 2); + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let (mut l, mut rr) = (x.clone(), x.clone()); + r.process(&mut [&mut l, &mut rr]); + assert!(l == x && rr == x, "effect {effect}"); + } + } + + /// A block that leaves a channel out feeds it silence, so a resonator's ring on that channel + /// keeps decaying instead of waiting for the channel to come back. + #[test] + fn channels_a_block_leaves_out_are_fed_silence() { + let p = [("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)]; + let (mut left_out, mut silent) = (ring(&p, 2), ring(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + for r in [&mut left_out, &mut silent] { + let (mut l, mut rr) = (x.clone(), x.clone()); + r.process(&mut [&mut l, &mut rr]); + } + for _ in 0..10 { + let mut l = vec![0.0f32; 480]; + left_out.process(&mut [&mut l]); + let (mut l, mut rr) = (vec![0.0f32; 480], vec![0.0f32; 480]); + silent.process(&mut [&mut l, &mut rr]); + } + let (mut la, mut ra) = (vec![0.0f32; 4800], vec![0.0f32; 4800]); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (vec![0.0f32; 4800], vec![0.0f32; 4800]); + silent.process(&mut [&mut lb, &mut rb]); + assert!(rms(&rb) > 1e-3, "the ring has already died out: {}", rms(&rb)); + let worst = ra.iter().zip(&rb).fold(0.0f32, |m, (a, b)| m.max((a - b).abs())); + assert!(worst < 1e-6, "the left-out channel differs by {worst}"); + assert_eq!(la, lb); + } + + /// A non-finite input sample comes out as silence and leaves no NaN in the resonator. + #[test] + fn a_non_finite_sample_leaves_the_state_finite() { + for effect in 0..4 { + let mut r = ring(&[("effect", effect as f32), ("resonance", 95.0)], 1); + let mut x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + x[100] = f32::NAN; + x[200] = f32::INFINITY; + r.process(&mut [&mut x]); + assert!(x.iter().all(|v| v.is_finite()), "effect {effect}"); + } + } + + /// An empty block does not take up a change of effect, so a resonator switched away from and + /// back before the next sample keeps its ring. + #[test] + fn an_empty_block_keeps_the_resonator_ring() { + let p = [("effect", 2.0), ("frequency", 500.0), ("resonance", 80.0)]; + let (mut r, mut still) = (ring(&p, 1), ring(&p, 1)); + for f in [&mut r, &mut still] { + let mut x = vec![0.0f32; 50]; + x[10] = 1.0; + f.process(&mut [&mut x]); + } + assert!(r.set_param("effect", 0.0)); + let mut empty: [f32; 0] = []; + r.process(&mut [&mut empty[..]]); + r.process(&mut []); + assert!(r.set_param("effect", 2.0)); + let (mut a, mut b) = (vec![0.0f32; 500], vec![0.0f32; 500]); + r.process(&mut [&mut a]); + still.process(&mut [&mut b]); + assert!(rms(&b) > 1e-3, "the ring has already died out"); + assert_eq!(a, b); + } + + /// Neighboring samples at the f32 limit with opposite signs come out finite from every effect + /// at every mix, through Frequency Mod's fractional and whole-sample reads, and a mix of 0 + /// passes them through unchanged. + #[test] + fn samples_at_the_f32_limit_stay_finite() { + let edge: Vec = (0..4800).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + for effect in 0..4 { + for mix in [0.0, 50.0, 100.0] { + let mut r = ring(&[("effect", effect as f32), ("frequency", 5000.0), ("mix", mix)], 1); + let mut y = edge.clone(); + r.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite()), "effect {effect}, mix {mix}"); + if mix == 0.0 { + assert_eq!(y, edge, "effect {effect}"); + } + } + } + // At 48 kHz Frequency Mod's first read is 50 samples back, a whole number, and the next + // ones fall between samples. + let mut r = ring(&[("effect", 1.0)], 1); + let mut y = edge.clone(); + r.process(&mut [&mut y]); + assert!(y[60..].iter().any(|v| v.abs() > 1e30 && v.abs() < f32::MAX), "no fractional read near the limit"); + } + + fn crush(params: &[(&str, f32)], channels: usize) -> Bitcrusher { + let mut c = Bitcrusher::new(SR, channels); + for (id, v) in params { + assert!(c.set_param(id, *v), "{id}"); + } + c.reset(); + c + } + + /// Indices of the samples where the output changes, with the first sample counted. + fn changes(x: &[f32]) -> Vec { + (0..x.len()).filter(|&i| i == 0 || x[i] != x[i - 1]).collect() + } + + /// Every output sample is the multiple of `2^(1 - bits)` nearest the input, and silence stays + /// silence. + #[test] + fn bitcrusher_rounds_to_the_word_length() { + for (bits, step) in [(1.0, 1.0f32), (3.0, 0.25), (5.5, 2f32.powf(-4.5))] { + let mut c = crush(&[("bits", bits), ("rate_divide", 1.0)], 1); + let x: Vec = (0..2000).map(|i| -1.0 + i as f32 / 1000.0).collect(); + let mut y = x.clone(); + c.process(&mut [&mut y]); + for (a, b) in x.iter().zip(&y) { + let k = b / step; + assert!((k - k.round()).abs() < 1e-3, "bits {bits}: {b} is not a multiple of {step}"); + assert!((a - b).abs() <= step / 2.0 + 1e-6, "bits {bits}: {a} became {b}"); + } + let mut z = vec![0.0f32; 480]; + c.process(&mut [&mut z]); + assert!(z.iter().all(|v| *v == 0.0), "bits {bits}"); + } + } + + /// The input is taken once every `rate_divide` samples and held: a whole value holds each + /// sample for exactly that many samples, and 2.5 alternates holds of 3 and 2. + #[test] + fn bitcrusher_holds_each_sample_for_the_rate_divide() { + let x: Vec = (0..200).map(|i| (i + 1) as f32 / 1024.0).collect(); + for (divide, want) in [(1.0, vec![1usize]), (5.0, vec![5]), (2.5, vec![3, 2])] { + let mut c = crush(&[("bits", 16.0), ("rate_divide", divide)], 1); + let mut y = x.clone(); + c.process(&mut [&mut y]); + let mut expected = vec![0usize]; + while let Some(&last) = expected.last() { + let next = last + want[(expected.len() - 1) % want.len()]; + if next >= x.len() { + break; + } + expected.push(next); + } + assert_eq!(changes(&y), expected, "divide {divide}"); + assert!(expected.iter().all(|&i| y[i] == x[i]), "divide {divide}: a hold does not start with the input"); + } + } + + /// A shorter rate divide cuts the hold in progress short, and the holds after it have the new + /// length from the first one on. + #[test] + fn bitcrusher_follows_a_shorter_hold_at_once() { + let mut c = crush(&[("bits", 16.0), ("rate_divide", 50.0)], 1); + let mut a: Vec = (0..10).map(|i| (i + 1) as f32 / 1024.0).collect(); + c.process(&mut [&mut a]); + assert!(c.set_param("rate_divide", 2.0)); + let input: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + let mut b = input.clone(); + c.process(&mut [&mut b]); + // `changes` counts the first sample whatever it holds, so the capture is checked apart. + assert_eq!(b[0], input[0], "the hold in progress was not cut short"); + assert_eq!(changes(&b), (0..30).step_by(2).collect::>()); + assert!((0..30).step_by(2).all(|i| b[i] == input[i])); + } + + /// A new Bits rounds the sample being held again from the next sample on, from the input it + /// took rather than from its rounded value, and the hold keeps its length. + #[test] + fn bitcrusher_rounds_the_hold_in_progress_at_new_bits() { + let mut c = crush(&[("bits", 16.0), ("rate_divide", 4.0)], 1); + let mut a = [0.3f32]; + c.process(&mut [&mut a]); + assert!((a[0] - 0.3).abs() < 1e-4); + assert!(c.set_param("bits", 1.0)); + let mut b = [0.9f32]; + c.process(&mut [&mut b]); + assert_eq!(b[0], 0.0, "1 bit did not round the held 0.3 to 0"); + assert!(c.set_param("bits", 16.0)); + let mut d = [0.9f32, 0.9, 0.7]; + c.process(&mut [&mut d]); + assert!((d[0] - 0.3).abs() < 1e-4 && d[0] == d[1], "the held input was lost: {d:?}"); + assert_eq!(changes(&[a[0], b[0], d[0], d[1], d[2]]), vec![0, 1, 2, 4], "the hold did not keep its length"); + } + + /// A channel left out of one block of a single sample, between two captures, holds silence + /// when it comes back instead of the sample it held before. + #[test] + fn bitcrusher_clears_a_channel_left_out_for_one_sample() { + let mut c = crush(&[("bits", 8.0), ("rate_divide", 4.0)], 2); + let (mut l, mut r) = ([1.0f32], [1.0f32]); + c.process(&mut [&mut l, &mut r]); + assert_eq!(r[0], 1.0); + let mut l = [0.0f32]; + c.process(&mut [&mut l]); + let (mut l, mut r) = ([0.0f32; 2], [0.0f32; 2]); + c.process(&mut [&mut l, &mut r]); + assert_eq!(r, [0.0, 0.0], "the channel came back with its earlier hold"); + assert_eq!(l, [1.0, 1.0], "the channel kept in the block lost its hold"); + } + + /// A held sample sounds for no longer than the tail reports after the input ends. + #[test] + fn bitcrusher_tail_covers_the_hold() { + for divide in [1.0, 4.0, 7.5, 50.0] { + let mut c = crush(&[("bits", 4.0), ("rate_divide", divide)], 1); + let tail = c.tail_samples(); + let mut x = vec![0.0f32; 200]; + x[0] = 0.5; + c.process(&mut [&mut x]); + let last = x.iter().rposition(|v| *v != 0.0).unwrap_or(0); + assert_eq!(last, tail, "divide {divide}"); + } + } + + /// A block that leaves a channel out feeds it silence, so the channel holds none of its earlier + /// audio when it comes back. + #[test] + fn bitcrusher_feeds_channels_a_block_leaves_out_silence() { + let p = [("bits", 6.0), ("rate_divide", 7.0)]; + let (mut left_out, mut silent) = (crush(&p, 2), crush(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 4801, 0.0); + for c in [&mut left_out, &mut silent] { + let (mut l, mut r) = (x.clone(), x.clone()); + c.process(&mut [&mut l, &mut r]); + } + let mut l = x[..10].to_vec(); + left_out.process(&mut [&mut l]); + let (mut l, mut r) = (x[..10].to_vec(), vec![0.0f32; 10]); + silent.process(&mut [&mut l, &mut r]); + let (mut la, mut ra) = (vec![0.0f32; 480], vec![0.0f32; 480]); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (vec![0.0f32; 480], vec![0.0f32; 480]); + silent.process(&mut [&mut lb, &mut rb]); + assert_eq!(ra, rb); + assert_eq!(la, lb); + } + + /// At a mix of 0 the input passes through unchanged, and a non-finite sample comes out finite. + #[test] + fn bitcrusher_mix_zero_and_non_finite_input() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut c = crush(&[("mix", 0.0), ("bits", 2.0), ("rate_divide", 9.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + c.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut c = crush(&[("bits", 2.0), ("rate_divide", 3.0)], 1); + let mut y = x.clone(); + y[99] = f32::NAN; + y[200] = f32::INFINITY; + c.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite())); + } + + /// Finite samples at the f32 limit, held while the input swings to the other limit, come out + /// finite at every mix. + #[test] + fn bitcrusher_keeps_samples_at_the_f32_limit_finite() { + for mix in [0.0, 50.0, 100.0] { + for bits in [1.0, 7.3, 16.0] { + let mut c = crush(&[("mix", mix), ("bits", bits), ("rate_divide", 3.0)], 1); + let mut y: Vec = (0..30).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + c.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite()), "mix {mix}, bits {bits}: {y:?}"); + } + } + } + + fn tremolo(params: &[(&str, f32)], channels: usize) -> Tremolo { + let mut t = Tremolo::new(SR, channels); + for (id, v) in params { + assert!(t.set_param(id, *v), "{id}"); + } + t.reset(); + t + } + + /// The gain of a tremolo over `n` samples, read from a constant input of 1. + fn gains(t: &mut Tremolo, n: usize) -> Vec { + let mut x = vec![1.0f32; n]; + t.process(&mut [&mut x]); + x + } + + /// At full depth the gain is 1 at the start of each cycle and 0 at its middle. The sine and the + /// triangle follow their curves, the square holds each level for most of half a cycle, and + /// half depth swings the gain between 1 and 1/2. + #[test] + fn tremolo_gain_follows_the_shape() { + let period = 9600; + for shape in 0..3 { + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", shape as f32)], 1); + let g = gains(&mut t, 2 * period); + for (i, v) in g.iter().enumerate() { + let p = (i % period) as f64 / period as f64; + let want = match shape { + 0 => 0.5 + 0.5 * (TAU * p).cos(), + 1 => 1.0 - 2.0 * p.min(1.0 - p), + _ if !(0.24..=0.26).contains(&p) && !(0.74..=0.76).contains(&p) => { + if (0.25..0.75).contains(&p) { + 0.0 + } else { + 1.0 + } + } + _ => continue, + }; + assert!((f64::from(*v) - want).abs() < 1e-4, "shape {shape} at {i}: {v}, want {want}"); + } + let mut t = tremolo(&[("rate", 5.0), ("depth", 50.0), ("shape", shape as f32)], 1); + let g = gains(&mut t, period); + let (lo, hi) = g.iter().fold((f32::MAX, f32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + assert!((lo - 0.5).abs() < 1e-4 && (hi - 1.0).abs() < 1e-6, "shape {shape}: {lo} ..= {hi}"); + } + } + + /// The square's edges are 2 ms raised-cosine ramps at every rate, centered on the quarter and + /// three-quarter points of the cycle. + #[test] + fn tremolo_square_edges_do_not_click() { + let edge = (0.002 * SR) as usize; + for rate in [0.1f32, 1.0, 20.0] { + let mut t = tremolo(&[("rate", rate), ("depth", 100.0), ("shape", 2.0)], 1); + let g = gains(&mut t, (SR / rate) as usize); + let worst = g.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0f32, f32::max); + // A raised cosine over `edge` samples moves at most pi / 2 / edge per sample. + assert!(worst <= std::f32::consts::FRAC_PI_2 / edge as f32 * 1.01, "rate {rate}: step {worst}"); + let moving = g.windows(2).filter(|w| w[1] != w[0]).count(); + assert!(moving <= 2 * edge + 2, "rate {rate}: the gain moves on {moving} samples"); + let quarter = (SR / rate / 4.0) as usize; + assert!((g[quarter] - 0.5).abs() < 0.02, "rate {rate}: {} at the quarter point", g[quarter]); + } + } + + /// A new rate takes effect from the next sample, with the phase kept. + #[test] + fn tremolo_rate_change_keeps_the_phase() { + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0)], 1); + let a = gains(&mut t, 2400); + assert!(t.set_param("rate", 10.0)); + let b = gains(&mut t, 2400); + // A quarter of a cycle at 5 Hz, then a quarter at 10 Hz ends at the middle of the cycle. + assert!((a[2399] - 0.5).abs() < 1e-3 && (b[0] - a[2399]).abs() < 1e-3, "{} then {}", a[2399], b[0]); + assert!(b[1199] < 1e-3 && b[1201] < 1e-3, "{} {}", b[1199], b[1201]); + } + + /// A change of shape glides from where the old shape was to the new one over 20 ms, so the + /// gain does not jump, and the new shape is followed exactly afterward. + #[test] + fn tremolo_shape_change_glides() { + let glide = (0.02 * SR) as usize; + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + let mut s = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 2.0)], 1); + // 2,000 samples in, the sine has the gain at 0.63 and the square at 1. + let a = gains(&mut t, 2000); + gains(&mut s, 2000); + assert!(t.set_param("shape", 2.0)); + let b = gains(&mut t, 2 * glide); + let want = gains(&mut s, 2 * glide); + // The square's own edge moves the gain by up to pi / 2 / 96 (0.0164) per sample. + let step = (b[0] - a[1999]).abs(); + assert!(step < 0.02, "the gain jumped by {step}"); + assert!(b.windows(2).all(|w| (w[1] - w[0]).abs() < 0.02), "the glide jumped"); + assert_eq!(b[glide..], want[glide..]); + assert!((b[0] - want[0]).abs() > 0.2, "{} {}", b[0], want[0]); + } + + /// A shape that only an empty block saw does not restart a glide in progress: the glide goes + /// on as if the shape had not changed. + #[test] + fn tremolo_empty_block_keeps_the_glide() { + let glide = (0.02 * SR) as usize; + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + let mut s = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + for fx in [&mut t, &mut s] { + gains(fx, 2000); + assert!(fx.set_param("shape", 2.0)); + gains(fx, 100); + } + assert!(t.set_param("shape", 1.0)); + let mut empty: [f32; 0] = []; + t.process(&mut [&mut empty[..]]); + assert!(t.set_param("shape", 2.0)); + assert_eq!(gains(&mut t, 2 * glide), gains(&mut s, 2 * glide)); + } + + /// A new rate moves the square's edges to a new share of the cycle. Changed just before an + /// edge, from 0.1 Hz (where the edge is still ahead) to 20 Hz (where the phase is inside it), + /// the gain glides instead of jumping. + #[test] + fn tremolo_square_rate_change_glides() { + let mut t = tremolo(&[("rate", 0.1), ("depth", 100.0), ("shape", 2.0)], 1); + // Phase 0.249 at 0.1 Hz. + let a = gains(&mut t, 119_520); + assert_eq!(a[119_519], 1.0); + assert!(t.set_param("rate", 20.0)); + let b = gains(&mut t, 2000); + let step = (b[0] - a[119_519]).abs(); + assert!(step < 0.02, "the gain jumped by {step}"); + assert!(b.windows(2).all(|w| (w[1] - w[0]).abs() < 0.02), "the glide jumped"); + } + + /// At zero depth the input passes unchanged, a non-finite sample comes out as silence, and a + /// channel past the configured count is left alone. + #[test] + fn tremolo_depth_zero_non_finite_and_extra_channels() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut t = tremolo(&[("depth", 0.0), ("shape", 2.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + t.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut t = tremolo(&[("depth", 100.0)], 1); + let (mut l, mut r) = (x.clone(), x.clone()); + l[99] = f32::NAN; + l[200] = f32::INFINITY; + t.process(&mut [&mut l, &mut r]); + assert!(l[99] == 0.0 && l[200] == 0.0 && l.iter().all(|v| v.is_finite())); + assert_eq!(r, x); + } + + /// A glide keeps the LFO value within 0 ..= 1, so the gain stays between 1 - depth and 1 and + /// never inverts the input, even when the new curve moves away from the glide's offset. + #[test] + fn tremolo_glide_keeps_the_gain_in_range() { + for (from, to) in [(1.0, 2.0), (2.0, 1.0), (0.0, 2.0), (2.0, 0.0)] { + for start in [240, 480, 1680, 1900] { + let mut t = tremolo(&[("rate", 20.0), ("depth", 100.0), ("shape", from)], 1); + gains(&mut t, start); + assert!(t.set_param("shape", to)); + let g = gains(&mut t, 2400); + assert!(g.iter().all(|v| (0.0..=1.0).contains(v)), "{from} to {to} at {start}: {g:?}"); + } + } + } + + /// An empty block does not take up a change of shape, so a shape changed and restored before + /// the next sample starts no glide. + #[test] + fn tremolo_empty_block_starts_no_glide() { + let p = [("rate", 5.0), ("depth", 100.0), ("shape", 0.0)]; + let (mut t, mut still) = (tremolo(&p, 1), tremolo(&p, 1)); + gains(&mut t, 1000); + gains(&mut still, 1000); + assert!(t.set_param("shape", 1.0)); + let mut empty: [f32; 0] = []; + t.process(&mut [&mut empty[..]]); + t.process(&mut []); + assert!(t.set_param("shape", 0.0)); + assert_eq!(gains(&mut t, 2000), gains(&mut still, 2000)); + } + + fn vibrato(params: &[(&str, f32)], channels: usize) -> Vibrato { + let mut v = Vibrato::new(SR, channels); + for (id, x) in params { + assert!(v.set_param(id, *x), "{id}"); + } + v.reset(); + v + } + + /// Slope of the ramp the delay tests feed in, per sample. + const RAMP: f32 = 1e-3; + /// Most the delay moves per sample during a glide at a depth of 100 cents: the curve's + /// steepest slope plus the glide's, with room for the rounding of the ramp. + const GLIDE_STEP: f32 = 0.0562 + 1.0 / 32.0 + 0.002; + + /// The delay of a vibrato over `n` samples, read from a ramp that starts at `start` samples. + fn delays(v: &mut Vibrato, start: usize, n: usize) -> Vec { + let x: Vec = (start..start + n).map(|i| i as f32 * RAMP).collect(); + let mut y = x.clone(); + v.process(&mut [&mut y]); + x.iter().zip(&y).map(|(a, b)| (a - b) / RAMP).collect() + } + + /// Largest change of the delay between neighboring samples, averaged over 2 * `k` samples to + /// smooth out the rounding of the ramp. + fn steepest(d: &[f32], k: usize) -> f32 { + (k..d.len() - k).map(|i| (d[i + k] - d[i - k]).abs() / (2 * k) as f32).fold(0.0, f32::max) + } + + /// The delay is 0 at the start of each cycle and follows the sine or the triangle, and its + /// steepest slope lowers the pitch by the depth: 100 cents at a depth of 100 for both shapes. + #[test] + fn vibrato_delay_follows_the_shape_and_the_depth() { + let d_max = 1.0 - 2f32.powf(-100.0 / 1200.0); + for (shape, rate) in [(0, 6.0f32), (1, 6.0), (0, 1.0), (1, 14.0)] { + let mut v = vibrato(&[("rate", rate), ("depth", 100.0), ("shape", shape as f32)], 1); + let period = (SR / rate) as usize; + let swing = v.swing; + let d = delays(&mut v, 0, 2 * period); + for (i, got) in d.iter().enumerate() { + let p = (i as f64 * f64::from(rate) / f64::from(SR)).fract(); + let want = swing * if shape == 1 { uni_tri(p) } else { uni_sine(p) }; + assert!((got - want).abs() < 0.05, "shape {shape} at {rate} Hz, sample {i}: {got}, want {want}"); + } + assert!(d[0].abs() < 0.05 && d[period].abs() < 0.05, "shape {shape}: {} {}", d[0], d[period]); + let slope = steepest(&d, 40); + let cents = 1200.0 * (1.0 - slope).log2(); + assert!((cents + 100.0).abs() < 2.0, "shape {shape} at {rate} Hz: the pitch falls by {cents} cents"); + assert!((slope - d_max).abs() < 0.002, "shape {shape} at {rate} Hz: slope {slope}"); + } + } + + /// A lower depth set at the middle of the cycle, where the delay is longest, glides the delay + /// down to the new curve without jumping, and afterward the output matches a vibrato that had + /// the new depth from the start. + #[test] + fn vibrato_depth_change_glides_to_the_new_curve() { + let half = 4000; + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0)], 1); + let mut w = vibrato(&[("rate", 6.0), ("depth", 10.0)], 1); + let a = delays(&mut v, 0, half); + delays(&mut w, 0, half); + assert!(v.set_param("depth", 10.0)); + let b = delays(&mut v, half, 16_000); + let want = delays(&mut w, half, 16_000); + // The new curve moves by up to 0.0058 per sample, and the glide by 1/32 more. + let step = (b[0] - a[half - 1]).abs(); + assert!(step < 0.04, "the delay jumped by {step}"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < 0.04), "the glide moved too fast"); + assert!(b[100] > want[100] + 100.0, "{} {}", b[100], want[100]); + let glide = v.glide_len; + assert!(glide < b.len() / 2, "the glide has not ended: {glide}"); + assert_eq!(b[glide..], want[glide..]); + } + + /// A new rate takes effect from the next sample with the phase kept, the delay glides to the + /// new curve without jumping, and afterward follows it. + #[test] + fn vibrato_rate_change_keeps_the_phase_and_glides() { + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0)], 1); + // A quarter of a cycle at 6 Hz. + let a = delays(&mut v, 0, 2000); + assert!(v.set_param("rate", 3.0)); + let swing = v.swing_len(); + let b = delays(&mut v, 2000, 12000); + let step = (b[0] - a[1999]).abs(); + assert!(step < GLIDE_STEP, "the delay jumped by {step}"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < GLIDE_STEP), "the glide moved too fast"); + let glide = v.glide_len; + assert!(glide < b.len() / 2, "the glide has not ended: {glide}"); + for (k, got) in b.iter().enumerate().skip(glide) { + let p = (0.25 + k as f64 * 3.0 / f64::from(SR)).fract(); + let want = swing * uni_sine(p); + assert!((got - want).abs() < 0.05, "sample {k}: {got}, want {want}"); + } + } + + /// A change of shape glides from the last delay to the new curve without jumping. + #[test] + fn vibrato_shape_change_glides() { + for (from, to) in [(0.0, 1.0), (1.0, 0.0)] { + for start in [600, 2000, 4000, 7000] { + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0), ("shape", from)], 1); + let a = delays(&mut v, 0, start); + assert!(v.set_param("shape", to)); + let b = delays(&mut v, start, 8000); + assert!((b[0] - a[start - 1]).abs() < GLIDE_STEP, "{from} to {to} at {start}: jumped"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < GLIDE_STEP), "{from} to {to} at {start}: the glide moved too fast"); + assert!(b.iter().all(|d| *d > -0.05), "{from} to {to} at {start}: the delay went below 0"); + } + } + } + + /// An empty block does not take up a change of depth, so a depth changed and restored before + /// the next sample starts no glide. + #[test] + fn vibrato_empty_block_starts_no_glide() { + let p = [("rate", 6.0), ("depth", 100.0)]; + let (mut v, mut still) = (vibrato(&p, 1), vibrato(&p, 1)); + delays(&mut v, 0, 1000); + delays(&mut still, 0, 1000); + assert!(v.set_param("depth", 10.0)); + let mut empty: [f32; 0] = []; + v.process(&mut [&mut empty[..]]); + v.process(&mut []); + assert!(v.set_param("depth", 100.0)); + assert_eq!(delays(&mut v, 1000, 4000), delays(&mut still, 1000, 4000)); + } + + /// After the input ends, the output falls silent within the reported tail, for every shape and + /// for a depth lowered just before the end, while the delay is still gliding down. + #[test] + fn vibrato_tail_covers_the_delay() { + for (rate, depth, shape, lower) in + [(1.0f32, 100.0f32, 1.0f32, false), (14.0, 50.0, 0.0, false), (1.0, 100.0, 1.0, true), (2.0, 100.0, 0.0, true)] + { + for len in [5000usize, 12000, 24000] { + let mut v = vibrato(&[("rate", rate), ("depth", depth), ("shape", shape)], 1); + let mut x = vec![0.5f32; len]; + v.process(&mut [&mut x]); + if lower { + assert!(v.set_param("depth", 0.0)); + } + let tail = v.tail_samples(); + let mut z = vec![0.0f32; 96_000]; + v.process(&mut [&mut z]); + let last = z.iter().rposition(|s| *s != 0.0).map_or(0, |i| i + 1); + assert!(last <= tail, "{rate} Hz {depth} ct shape {shape} lower {lower} len {len}: sound until {last} after a tail of {tail}"); + } + } + } + + /// At zero depth the input passes unchanged, a non-finite sample comes out as silence, and a + /// channel past the configured count is left alone. + #[test] + fn vibrato_depth_zero_non_finite_and_extra_channels() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut v = vibrato(&[("depth", 0.0), ("shape", 1.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + v.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut v = vibrato(&[("depth", 0.0)], 1); + let (mut l, mut r) = (x.clone(), x.clone()); + l[99] = f32::NAN; + l[200] = f32::INFINITY; + v.process(&mut [&mut l, &mut r]); + assert!(l[99] == 0.0 && l[200] == 0.0 && l.iter().all(|s| s.is_finite())); + assert_eq!(r, x); + let mut v = vibrato(&[("depth", 100.0)], 1); + let mut l = x.clone(); + l[99] = f32::NAN; + v.process(&mut [&mut l]); + assert!(l.iter().all(|s| s.is_finite())); + // Neighboring samples at the f32 limit with opposite signs stay finite. + let edge: Vec = (0..4800).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + for depth in [0.0, 100.0] { + let mut v = vibrato(&[("depth", depth)], 1); + let mut l = edge.clone(); + v.process(&mut [&mut l]); + assert!(l.iter().all(|s| s.is_finite()), "depth {depth}"); + if depth == 0.0 { + assert_eq!(l, edge); + } + } + } + + /// A block that leaves a channel out feeds it silence, so the channel holds none of its earlier + /// audio when it comes back. + #[test] + fn vibrato_feeds_channels_a_block_leaves_out_silence() { + let p = [("rate", 1.0), ("depth", 100.0), ("shape", 1.0)]; + let (mut left_out, mut silent) = (vibrato(&p, 2), vibrato(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 12_000, 0.0); + for v in [&mut left_out, &mut silent] { + let (mut l, mut r) = (x.clone(), x.clone()); + v.process(&mut [&mut l, &mut r]); + } + let mut l = x[..2000].to_vec(); + left_out.process(&mut [&mut l]); + let (mut l, mut r) = (x[..2000].to_vec(), vec![0.0f32; 2000]); + silent.process(&mut [&mut l, &mut r]); + let (mut la, mut ra) = (x[..4800].to_vec(), x[..4800].to_vec()); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (x[..4800].to_vec(), x[..4800].to_vec()); + silent.process(&mut [&mut lb, &mut rb]); + assert_eq!(ra, rb); + assert_eq!(la, lb); + } +} diff --git a/crates/audio-dsp/src/effects/stft.rs b/crates/audio-dsp/src/effects/stft.rs index c4b9ed7070..14d1003dbb 100644 --- a/crates/audio-dsp/src/effects/stft.rs +++ b/crates/audio-dsp/src/effects/stft.rs @@ -402,7 +402,7 @@ mod tests { #[test] fn paired_effects_match_mono_on_transients() { use crate::AudioEffect; - use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter}; + use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter}; const SR: f32 = 48_000.0; let len = 48_000; let material = |f: f64, amp: f32, phase: f64, click_every: usize, click_at: usize, noise: f32, seed: u64| -> Vec { @@ -427,6 +427,7 @@ mod tests { "DeReverb" => Box::new(DeReverb::new(SR, ch)), "FftFilter" => Box::new(FftFilter::new(SR, ch)), "DeNoise" => Box::new(DeNoise::new(SR, ch)), + "NoiseSuppression" => Box::new(NoiseSuppression::new(SR, ch)), _ => Box::new(PitchShifter::new(SR, ch)), }; if name == "PitchShifter" { @@ -445,7 +446,7 @@ mod tests { y }; let mut failures = Vec::new(); - for name in ["PitchShifter", "DeNoise", "DeReverb", "FftFilter"] { + for name in ["PitchShifter", "DeNoise", "NoiseSuppression", "DeReverb", "FftFilter"] { for (label, src) in [("identical", &identical), ("different", &different)] { let joint = run(name, src); for (ch, chan) in src.iter().enumerate() { @@ -502,17 +503,18 @@ mod tests { #[test] fn non_finite_sample_stays_in_its_channel() { use crate::AudioEffect; - use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter}; + use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter}; const SR: f32 = 48_000.0; let len = 24_000; let mut rng = Rng::new(5); let clean_a: Vec = crate::testutil::sine(440.0, 0.4, SR as f64, len, 0.0).iter().map(|v| v + 0.05 * rng.uniform()).collect(); let clean_b: Vec = crate::testutil::sine(1250.0, 0.4, SR as f64, len, 0.3).iter().map(|v| v + 0.05 * rng.uniform()).collect(); type Make = fn() -> Box; - let make: [(&str, Make, usize); 4] = [ + let make: [(&str, Make, usize); 5] = [ ("DeReverb", || Box::new(DeReverb::new(SR, 2)), 1), ("FftFilter", || Box::new(FftFilter::new(SR, 2)), 1), ("DeNoise", || Box::new(DeNoise::new(SR, 2)), 1), + ("NoiseSuppression", || Box::new(NoiseSuppression::new(SR, 2)), 1), ("PitchShifter", || Box::new(PitchShifter::new(SR, 2)), 1), ]; let mono = |name: &str, src: &[f32]| -> Vec { @@ -520,6 +522,7 @@ mod tests { "DeReverb" => Box::new(DeReverb::new(SR, 1)), "FftFilter" => Box::new(FftFilter::new(SR, 1)), "DeNoise" => Box::new(DeNoise::new(SR, 1)), + "NoiseSuppression" => Box::new(NoiseSuppression::new(SR, 1)), _ => Box::new(PitchShifter::new(SR, 1)), }; if name == "PitchShifter" { diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs new file mode 100644 index 0000000000..eff764db08 --- /dev/null +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -0,0 +1,1022 @@ +//! Noise suppression for a live voice (`noise_suppression`), with 256 samples (5.3 ms) of latency +//! at 48 kHz. +//! +//! The effect runs a short STFT: 256 points at up to 50 kHz (twice that for each doubling of the +//! rate above it), a hop of a quarter of the size, and square-root Hann windows. Each bin's noise +//! power is the smallest value of its smoothed power over the last 1.5 s (minimum statistics, +//! R. Martin, 2001), so the estimate follows a noise floor that changes and needs no "learn noise" +//! step. Each bin's gain is a Wiener gain on the decision-directed a priori SNR (Ephraim and Malah, +//! 1984), held at or above the floor that `reduction` sets, and averaged with its neighbors. At a +//! reduction of 0 every gain is 1 and the effect is a plain delay. +//! +//! A frame enters the noise estimate only after the next four frames have arrived. A frame of +//! digital silence (a mute or a gate) drops the frames still waiting, and the four frames after +//! it do not enter either, so no frame that shares a sample with the silence lowers the estimate +//! and lets the noise pass when the sound resumes, wherever between two hops the silence ends. +//! A mute too short to fill a frame keeps every frame that holds a sample of it out too, down to +//! a run of zeros one hop long (64 samples at 48 kHz); a shorter run of zeros counts as sound. +//! Nor does a frame more than 15 dB below the estimate, until such frames have lasted a whole +//! search window without digital silence between them (the floor has really fallen). +//! The noise power the gains are computed from falls at once and rises by at most 10 dB a +//! second, so a vowel or a note held for longer than the search window keeps its level for a few +//! seconds more, and a noise floor that rises by 12 dB is suppressed again within 3 s. +//! After a reset the gain floor moves from 0 dB toward the attenuation set by `reduction` over +//! the first search window of sound. The first noise estimate after a reset starts from the +//! median bin's power. Each bin's value is clamped between 30 dB below its own estimate and its +//! own estimate. The noise power then rises by at most 10 dB a second. A vowel held from the +//! first sample keeps its level for a few seconds, like one held after a stretch of noise, while +//! steady noise of an even spectrum is suppressed as soon as the floor allows; noise whose +//! spectrum is uneven takes up to 3 s more in the bins well above the median. Continuous voiced +//! or tonal audio present from startup can eventually enter the noise estimate and be attenuated. + +use super::stft::{Pairing, Plan, Spectral, StftChannel, stream}; +use crate::{AudioEffect, MAX_CHANNELS, ParamSpec, ParamValues, Unit, block_len, db_to_gain, flush32, param_plumbing}; + +/// Length of the minimum-statistics search, and the number of sub-windows it rotates through. +const SEARCH_S: f32 = 1.5; +const SUBWINDOWS: usize = 8; +/// Time constant of the smoothing of each bin's power. +const POWER_MS: f32 = 10.0; +/// Time constant of the decision-directed a priori SNR. +const PRIORI_MS: f32 = 80.0; +/// Ratio of the mean noise power to the minimum of its smoothed power with these windows (see +/// `the_noise_estimate_follows_white_noise`). +const BIAS: f32 = 3.25; +/// Smallest noise power a bin is divided by, so digital silence keeps its gain at the floor. +const MIN_NOISE: f32 = 1.0e-30; +/// A frame whose power is below the estimated noise power by this ratio (15 dB) is quiet. +const QUIET: f32 = 1.0 / 32.0; +/// Frames that share a sample with any one frame: the hop is a quarter of the STFT size. +const OVERLAP: usize = 4; +/// Lowest the first noise power of a bin starts against the bin's own estimate (30 dB). +const SEED_SPAN: f32 = 1.0e-3; +/// Fastest rise of the noise power a bin's gain is computed from, in dB per second. +const RISE_DB_S: f32 = 10.0; + +/// STFT size: 256 at up to 50 kHz (5.3 ms at 48 kHz), doubled for each doubling of the rate above +/// it, up to 8192. +fn suppress_size(sample_rate: f32) -> usize { + let (mut n, mut top) = (256, 50_000.0); + while sample_rate > top && n < 8192 { + n *= 2; + top *= 2.0; + } + n +} + +/// Smoothing and floor shared by every frame, from the parameters and the frame rate. +#[derive(Clone, Copy, Debug)] +struct Coefs { + /// Lowest gain a bin gets. + floor: f32, + /// Weight of the previous smoothed power. + smooth: f32, + /// Weight of the previous frame's clean power in the a priori SNR. + priori: f32, + /// Frames in one minimum-statistics sub-window. + sub_frames: usize, + /// Frames in the whole search window. + window: usize, + /// Largest ratio of one frame's noise power to the previous frame's (`RISE_DB_S`). + rise: f32, +} + +/// One channel's noise estimate and gains. Every buffer is sized at creation. +#[derive(Clone, Debug)] +struct Bins { + /// Smoothed power of each bin. + power: Vec, + /// Smallest smoothed power in the current sub-window. + min: Vec, + /// Smallest smoothed power of each of the last `SUBWINDOWS` sub-windows. + ring: Vec, + slot: usize, + frames: usize, + /// Power the previous frame kept (gain² × power). + clean: Vec, + gains: Vec, + /// Smallest smoothed power of the search window for each bin, for the frame being processed. + est: Vec, + /// Noise power of each bin that the gains are computed from: `est` times the bias, rising by + /// at most `RISE_DB_S`. + noise: Vec, + /// Power of each bin of the frames waiting to enter the estimate, `OVERLAP` frames of + /// `bins` values, the oldest at `head`. + queue: Vec, + /// Total power of each waiting frame, and whether it may enter the estimate. + queue_total: [f32; OVERLAP], + queue_ok: [bool; OVERLAP], + /// Whether a mute began between a waiting frame and the one before it. + queue_cut: [bool; OVERLAP], + /// Whether a mute began since the last frame was queued. + cut_pending: bool, + head: usize, + queued: usize, + /// Whether a frame has entered the estimate since the last reset. + started: bool, + /// Frames that entered the estimate since the last reset, up to a search window. + heard: usize, + /// Frames with sound since the last frame of digital silence, up to `OVERLAP + 1`. It starts + /// at 1: the zeros the STFT starts with end on a hop boundary, so `OVERLAP` frames clear them. + since_zero: usize, + /// Quiet frames in a row since the last frame of digital silence, up to a search window. + quiet_run: usize, + /// Whether `noise` has been set from a first estimate since the last reset. + seeded: bool, + /// Room to find the median bin of the first estimate. + scratch: Vec, + /// Zero samples in a row up to the last sample, up to a hop. + zero_run: usize, + /// Samples since the last sample of a mute (a run of at least a hop of zeros), or `usize::MAX` + /// when there has been none since the last reset. + since_mute: usize, + /// Samples since the last frame. + since_frame: usize, +} + +impl Bins { + fn new(bins: usize) -> Self { + Bins { + power: vec![0.0; bins], + min: vec![f32::INFINITY; bins], + ring: vec![f32::INFINITY; bins * SUBWINDOWS], + slot: 0, + frames: 0, + clean: vec![0.0; bins], + gains: vec![1.0; bins], + est: vec![f32::INFINITY; bins], + noise: vec![f32::INFINITY; bins], + queue: vec![0.0; bins * OVERLAP], + queue_total: [0.0; OVERLAP], + queue_ok: [false; OVERLAP], + queue_cut: [false; OVERLAP], + cut_pending: false, + head: 0, + queued: 0, + started: false, + heard: 0, + since_zero: 1, + quiet_run: 0, + seeded: false, + scratch: vec![0.0; bins], + zero_run: 0, + since_mute: usize::MAX, + since_frame: 0, + } + } + + fn reset(&mut self) { + self.power.fill(0.0); + self.min.fill(f32::INFINITY); + self.ring.fill(f32::INFINITY); + self.clean.fill(0.0); + self.gains.fill(1.0); + self.est.fill(f32::INFINITY); + self.noise.fill(f32::INFINITY); + self.slot = 0; + self.frames = 0; + self.head = 0; + self.queued = 0; + self.cut_pending = false; + self.started = false; + self.heard = 0; + self.since_zero = 1; + self.quiet_run = 0; + self.seeded = false; + self.zero_run = 0; + self.since_mute = usize::MAX; + self.since_frame = 0; + } + + /// Takes one input sample before the STFT does, to find mutes too short to give a frame of + /// digital silence. Once `hop` zeros run in a row, the frame still waiting that holds the first + /// of them leaves the queue, and so does every later frame that holds a sample of the run. + fn sample(&mut self, x: f32, hop: usize) { + self.since_frame += 1; + self.zero_run = if x == 0.0 { (self.zero_run + 1).min(hop) } else { 0 }; + if self.zero_run < hop { + self.since_mute = self.since_mute.saturating_add(1); + return; + } + if self.since_mute != 0 { + // The run has just reached a hop. It started `hop - 1` samples ago, so of the frames + // waiting only the newest can hold it: when it ended less than a hop ago. + if self.queued > 0 && self.since_frame < hop { + self.queue_ok[(self.head + self.queued - 1) % OVERLAP] = false; + } + self.cut_pending = true; + } + self.since_mute = 0; + } + + /// Noise power of bin `k` for the frame last processed: the smallest smoothed power of the + /// search window times the bias, rising by at most `RISE_DB_S`. + fn noise(&self, k: usize) -> f32 { + self.noise[k].max(MIN_NOISE) + } + + /// Moves the oldest waiting frame into the noise estimate, unless it shares a sample with + /// digital silence, or it is quiet and quiet frames have not yet lasted a search window. + fn commit(&mut self, c: &Coefs) { + let bins = self.power.len(); + let at = self.head; + self.head = (at + 1) % OVERLAP; + self.queued -= 1; + if self.queue_cut[at] { + self.quiet_run = 0; + } + if !self.queue_ok[at] { + return; + } + let noise_total = self.est.iter().map(|e| e * BIAS).sum::(); + let quiet = noise_total.is_finite() && self.queue_total[at] < noise_total * QUIET; + self.quiet_run = if quiet { (self.quiet_run + 1).min(c.window) } else { 0 }; + if quiet && self.quiet_run < c.window { + return; + } + let a = if self.started { c.smooth } else { 0.0 }; + for k in 0..bins { + let p = self.queue[at * bins + k]; + self.power[k] = flush32(a * self.power[k] + (1.0 - a) * p); + self.min[k] = self.min[k].min(self.power[k]); + self.est[k] = self.est[k].min(self.power[k]); + } + self.frames += 1; + if self.frames == c.sub_frames { + for k in 0..bins { + self.ring[self.slot * bins + k] = self.min[k]; + self.min[k] = f32::INFINITY; + } + self.slot = (self.slot + 1) % SUBWINDOWS; + self.frames = 0; + } + self.started = true; + self.heard = (self.heard + 1).min(c.window); + } + + /// Takes one frame's half spectrum, updates the noise estimate and the gains, and writes the + /// gains averaged with their neighbors to `out`. A frame with a non-finite bin leaves the + /// state as it is and repeats the last gains. + fn frame(&mut self, re: &[f32], im: &[f32], c: &Coefs, out: &mut [f32]) { + let bins = self.power.len(); + self.since_frame = 0; + let finite = re.iter().zip(im).fold(true, |ok, (a, b)| ok & (a * a + b * b).is_finite()); + if finite { + for k in 0..bins { + self.est[k] = (0..SUBWINDOWS).fold(self.min[k], |m, u| m.min(self.ring[u * bins + k])); + } + let total = (0..bins).map(|k| re[k] * re[k] + im[k] * im[k]).sum::(); + if total == 0.0 { + // Digital silence: the frames still waiting share a sample with it, and so do the + // next `OVERLAP - 1` frames, or the next `OVERLAP` when the silence ends between + // two hops. A quiet run ends here too. + self.queued = 0; + self.cut_pending = false; + self.since_zero = 0; + self.quiet_run = 0; + } else { + self.since_zero = (self.since_zero + 1).min(OVERLAP + 1); + if self.queued == OVERLAP { + self.commit(c); + } + let at = (self.head + self.queued) % OVERLAP; + for k in 0..bins { + self.queue[at * bins + k] = re[k] * re[k] + im[k] * im[k]; + } + self.queue_total[at] = total; + self.queue_cut[at] = std::mem::take(&mut self.cut_pending); + // A frame holds the last STFT size of samples, `2 * (bins - 1)`. + self.queue_ok[at] = self.since_zero > OVERLAP && self.since_mute >= 2 * (bins - 1); + self.queued += 1; + } + if self.started && !self.seeded { + // The first estimate: a bin well above the median bin, such as a harmonic of a + // vowel held from the start, starts from the median and rises from there. + self.seeded = true; + self.scratch.copy_from_slice(&self.est); + let median = *self.scratch.select_nth_unstable_by(bins / 2, f32::total_cmp).1 * BIAS; + for k in 0..bins { + let own = self.est[k] * BIAS; + self.noise[k] = own.min(median.max(own * SEED_SPAN)); + } + } + // The floor moves from 1 to `c.floor` (in dB) over the first search window of sound. + let floor = c.floor.powf(self.heard as f32 / c.window as f32); + for k in 0..bins { + let p = re[k] * re[k] + im[k] * im[k]; + // The noise power falls at once and rises by at most `c.rise` a frame, so a sound + // held longer than the search window is not taken for the noise at once. + self.noise[k] = (self.est[k] * BIAS).min(self.noise[k].max(MIN_NOISE) * c.rise); + let noise = self.noise(k); + let excess = (p / noise - 1.0).max(0.0); + let xi = c.priori * self.clean[k] / noise + (1.0 - c.priori) * excess; + // `1 - 1 / (1 + xi)` is `xi / (1 + xi)`, and stays 1 for an infinite `xi`. + let g = (1.0 - 1.0 / (1.0 + xi)).max(floor); + self.gains[k] = g; + self.clean[k] = flush32(g * g * p); + } + } + for k in 0..bins { + let lo = self.gains[k.saturating_sub(1)]; + let hi = self.gains[(k + 1).min(bins - 1)]; + out[k] = 0.25 * lo + 0.5 * self.gains[k] + 0.25 * hi; + } + } +} + +/// Noise suppression for a live voice: lowers steady background noise (fans, hiss, room tone) by +/// up to `reduction` dB, with no step that learns the noise first. Its latency is the STFT size, +/// 256 samples (5.3 ms) at 48 kHz. Continuous voiced or tonal audio present from startup can +/// enter the noise estimate and be attenuated after the initial search window. +pub struct NoiseSuppression { + pv: ParamValues, + n: usize, + hop: usize, + spec: Spectral, + stft: Vec, + bins: Vec, + /// Gains of the frame being processed, averaged with their neighbors. + smoothed: Vec, + coefs: Coefs, + sample_rate: f32, + /// Samples since the last frame, the same in every channel. + pos: usize, +} + +impl NoiseSuppression { + pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("reduction", "Reduction", 0.0, 40.0, 24.0, Unit::Decibels)]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let n = suppress_size(sample_rate); + let bins = n / 2 + 1; + let ch = crate::sane_channels(channels); + let mut s = NoiseSuppression { + pv: ParamValues::new(Self::PARAMS), + n, + hop: n / OVERLAP, + spec: Spectral::new(n, true), + stft: vec![StftChannel::new(n); ch], + bins: vec![Bins::new(bins); ch], + smoothed: vec![1.0; bins], + coefs: Coefs { floor: 1.0, smooth: 0.0, priori: 0.0, sub_frames: 1, window: SUBWINDOWS, rise: 1.0 }, + sample_rate, + pos: 0, + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, _snap: bool) { + let frame_s = self.hop as f32 / self.sample_rate; + let sub_frames = ((SEARCH_S / frame_s / SUBWINDOWS as f32).round() as usize).max(1); + self.coefs = Coefs { + floor: db_to_gain(-self.pv.v("reduction")), + smooth: (-frame_s * 1000.0 / POWER_MS).exp(), + priori: (-frame_s * 1000.0 / PRIORI_MS).exp(), + sub_frames, + window: sub_frames * SUBWINDOWS, + // A power ratio: twice the dB of an amplitude ratio. + rise: db_to_gain(2.0 * RISE_DB_S * frame_s), + }; + } +} + +impl AudioEffect for NoiseSuppression { + param_plumbing!("noise_suppression"); + fn latency(&self) -> usize { + self.n + } + fn tail_samples(&self) -> usize { + self.n + } + fn reset(&mut self) { + self.stft.iter_mut().for_each(StftChannel::reset); + self.bins.iter_mut().for_each(Bins::reset); + self.pos = 0; + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + let nch = channels.len().min(self.stft.len()); + // A non-finite sample is taken as silence, so it never reaches the output. + for c in channels.iter_mut().take(nch) { + c[..len].iter_mut().for_each(|v| *v = flush32(*v)); + } + let (n, hop, coefs) = (self.n, self.hop, self.coefs); + let scale = 1.0 / (n as f32 * 2.0); + let plan = Plan { hop, scale, pairing: Pairing::SynthesisOnly }; + // The block runs in pieces that end at the next frame, so each channel's noise estimate + // takes every sample of a frame before the STFT frames it. + let mut start = 0; + while start < len { + let end = len.min(start + hop - self.pos); + for (b, c) in self.bins.iter_mut().zip(channels.iter()).take(nch) { + c[start..end].iter().for_each(|&x| b.sample(x, hop)); + } + let mut piece: [&mut [f32]; MAX_CHANNELS] = std::array::from_fn(|_| <&mut [f32]>::default()); + for (p, c) in piece.iter_mut().zip(channels.iter_mut()).take(nch) { + *p = &mut c[start..end]; + } + let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); + stream(&mut self.stft, &mut self.spec, &mut piece[..nch], end - start, plan, &mut |ch, _, re, im| { + bins[ch].frame(re, im, &coefs, smoothed); + for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { + *r *= g; + *i *= g; + } + }); + self.pos = (self.pos + end - start) % hop; + start = end; + } + // A channel the block leaves out is fed silence, so it holds none of its earlier audio + // when it comes back. + let half = n / 2 + 1; + let (spec, smoothed) = (&mut self.spec, &mut self.smoothed); + for (st, b) in self.stft.iter_mut().zip(self.bins.iter_mut()).skip(nch) { + for _ in 0..len { + b.sample(0.0, hop); + st.tick(0.0, hop, &mut |input, out| { + spec.analyze(input); + b.frame(&spec.re[..half], &spec.im[..half], &coefs, smoothed); + for k in 0..half { + spec.re[k] *= smoothed[k]; + spec.im[k] *= smoothed[k]; + } + spec.synthesize_add(out, scale); + }); + } + } + // A huge finite input can overflow the inverse FFT. + for c in channels.iter_mut().take(nch) { + c[..len].iter_mut().for_each(|v| *v = flush32(*v)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn suppressor(reduction: f32) -> NoiseSuppression { + let mut s = NoiseSuppression::new(SR, 1); + assert!(s.set_param("reduction", reduction)); + s.reset(); + s + } + + fn white(seed: u64, n: usize, amp: f32) -> Vec { + let mut r = Rng::new(seed); + (0..n).map(|_| r.uniform() * amp).collect() + } + + /// Voiced syllables (seven harmonics of a gliding pitch from 110 to 230 Hz under a sine + /// envelope) with pauses between them, at a peak level of about 0.5. + fn voiced(sr: f64, secs: f64, seed: u64) -> Vec { + let n = (sr * secs) as usize; + let mut rng = Rng::new(seed); + let mut out = vec![0.0f32; n]; + let mut i = 0usize; + while i < n { + let len = ((0.12 + 0.2 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; + let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); + let glide = 1.0 + 0.3 * rng.uniform() as f64; + let amp = 0.1 + 0.1 * (rng.uniform() * 0.5 + 0.5); + for k in 0..len.min(n - i) { + let t = k as f64 / sr; + let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; + let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); + let v: f32 = (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum(); + out[i + k] = v * env * amp; + } + i += len + ((rng.uniform() * 0.5 + 0.5) * 0.25 * sr as f32) as usize; + } + out + } + + /// Runs the suppressor's gains, computed from `speech + noise`, on the speech and the noise + /// apart, so the SNR before and after can be measured. Returns the processed mix, speech and + /// noise. + fn shadow(speech: &[f32], noise: &[f32], reduction: f32) -> (Vec, Vec, Vec) { + let s = suppressor(reduction); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let mut spec = Spectral::new(n, true); + let half = n / 2 + 1; + let scale = 1.0 / (n as f32 * 2.0); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lanes = [StftChannel::new(n), StftChannel::new(n), StftChannel::new(n)]; + let mut out = [vec![0.0f32; speech.len()], vec![0.0f32; speech.len()], vec![0.0f32; speech.len()]]; + for i in 0..speech.len() { + let x = [speech[i] + noise[i], speech[i], noise[i]]; + bins.sample(x[0], hop); + for (lane, (st, o)) in lanes.iter_mut().zip(out.iter_mut()).enumerate() { + o[i] = st.tick(x[lane], hop, &mut |input, frame_out| { + spec.analyze(input); + if lane == 0 { + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + } + for k in 0..half { + spec.re[k] *= gains[k]; + spec.im[k] *= gains[k]; + } + spec.synthesize_add(frame_out, scale); + }); + } + } + let [mix, speech, noise] = out; + (mix, speech, noise) + } + + fn energy(x: &[f32]) -> f64 { + x.iter().map(|&v| v as f64 * v as f64).sum() + } + + /// SNR before and after the suppressor at a reduction of 24 dB, and the change of the voice's + /// own level, in dB, measured from 3 s on (the noise estimate has settled by then). + fn snr_gain(speech: &[f32], noise_amp: f32) -> (f64, f64, f64) { + let len = speech.len(); + let noise = white(17, len, noise_amp); + let (mix, ys, yv) = shadow(speech, &noise, 24.0); + let mut real: Vec = speech.iter().zip(&noise).map(|(a, b)| a + b).collect(); + suppressor(24.0).process(&mut [&mut real]); + assert!(real.iter().zip(&mix).all(|(a, b)| (a - b).abs() < 1e-5), "the shadow run differs from the effect"); + let lat = 256; + let (from, to) = (SR as usize * 3, len - lat); + let after = from + lat..to + lat; + let snr_in = db((energy(&speech[from..to]) / energy(&noise[from..to])).sqrt()); + let snr_out = db((energy(&ys[after.clone()]) / energy(&yv[after.clone()])).sqrt()); + let kept = db((energy(&ys[after]) / energy(&speech[from..to])).sqrt()); + (snr_in, snr_out - snr_in, kept) + } + + /// Voiced syllables in white noise come out with an SNR at least 15 dB higher at an input SNR + /// of 7 dB (13 dB higher at 17 dB), and the voice's level changes by less than 3 dB. + #[test] + fn the_voice_gains_15_db_of_snr_and_keeps_its_level() { + let speech = voiced(SR as f64, 12.0, 4); + for (noise_amp, want) in [(0.06f32, 15.0), (0.02, 13.0)] { + let (snr_in, gain, kept) = snr_gain(&speech, noise_amp); + assert!(gain >= want, "input SNR {snr_in:.1} dB: SNR gain {gain:.1} dB"); + assert!(kept.abs() < 3.0, "input SNR {snr_in:.1} dB: voice level changed by {kept:.2} dB"); + } + } + + /// Speech with consonants (bursts of broadband noise at the level of the vowels) keeps its + /// level within 3 dB and still gains SNR. Bins where a consonant covers the noise keep both. + #[test] + fn speech_with_consonants_keeps_its_level() { + let speech = speechy(SR as f64, 12.0, 4); + for noise_amp in [0.06f32, 0.02] { + let (snr_in, gain, kept) = snr_gain(&speech, noise_amp); + assert!(gain >= 4.0, "input SNR {snr_in:.1} dB: SNR gain {gain:.1} dB"); + assert!(kept.abs() < 3.0, "input SNR {snr_in:.1} dB: speech level changed by {kept:.2} dB"); + } + } + + /// Steady noise falls by close to the reduction setting, at 44.1, 48, 96 and 192 kHz, and the + /// latency is 256 samples up to 50 kHz and doubles with each doubling of the rate above it. + #[test] + fn steady_noise_falls_by_the_reduction() { + for (sr, lat) in [(44_100.0f32, 256), (48_000.0, 256), (96_000.0, 512), (192_000.0, 1024)] { + for reduction in [6.0f32, 12.0, 24.0, 40.0] { + let mut s = NoiseSuppression::new(sr, 1); + assert!(s.set_param("reduction", reduction)); + assert_eq!(s.latency(), lat); + let n = sr as usize * 4; + let x = white(5, n, 0.05); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let tail = n - sr as usize..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + // At 40 dB the Wiener gains of noise-only bins sit above the floor. + let limit = if reduction == 40.0 { 28.0 } else { reduction as f64 - 2.0 }; + assert!(got >= limit && got <= reduction as f64 + 1.0, "{sr} Hz, reduction {reduction}: noise fell by {got:.1} dB"); + } + } + } + + /// At a reduction of 0 the output is the input delayed by the latency. + #[test] + fn zero_reduction_is_a_delay() { + let mut s = suppressor(0.0); + let lat = s.latency(); + let x = speechy(SR as f64, 2.0, 8); + let mut y = x.clone(); + s.process(&mut [&mut y]); + for i in lat..x.len() { + assert!((y[i] - x[i - lat]).abs() < 1e-5, "{i}: {} vs {}", y[i], x[i - lat]); + } + } + + /// The noise estimate follows a noise floor that rises by 12 dB within 3 s, and one that falls + /// by 12 dB at once. + #[test] + fn the_estimate_follows_a_changing_noise_floor() { + let level = |amps: [f32; 2], at: f32| -> f64 { + let mut s = suppressor(24.0); + let n = SR as usize * 8; + let mut rng = Rng::new(31); + let x: Vec = (0..n).map(|i| rng.uniform() * if i < n / 2 { amps[0] } else { amps[1] }).collect(); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let from = n / 2 + (at * SR) as usize; + let range = from..from + SR as usize / 4; + -db(rms(&y[range.clone()]) / rms(&x[range])) + }; + let up = level([0.02, 0.08], 3.0); + assert!(up >= 20.0, "rise: noise fell by {up:.1} dB 3 s later"); + let down = level([0.08, 0.02], 0.25); + assert!(down >= 20.0, "fall: noise fell by {down:.1} dB 0.25 s later"); + } + + /// Noise that starts after digital silence is suppressed again within the search window. + #[test] + fn noise_after_silence_is_suppressed_again() { + let mut s = suppressor(24.0); + let n = SR as usize * 6; + let mut x = white(41, n, 0.05); + x[..SR as usize * 2].fill(0.0); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let tail = n - SR as usize / 2..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// Noise that resumes after a pause of digital silence, or of noise 40 dB lower, is suppressed + /// from the start: the pause does not enter the noise estimate. + #[test] + fn noise_after_a_pause_is_suppressed_at_once() { + for pause_amp in [0.0f32, 0.0005] { + let mut s = suppressor(24.0); + let lat = s.latency(); + let n = SR as usize * 5; + let (pause, resume) = (SR as usize * 3, SR as usize * 4); + let mut x = white(43, n, 0.05); + x[pause..resume].iter_mut().for_each(|v| *v *= pause_amp / 0.05); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let range = resume + lat + SR as usize / 50..resume + lat + SR as usize / 2; + let got = -db(rms(&y[range.clone()]) / rms(&x[range.start - lat..range.end - lat])); + assert!(got >= 20.0, "pause level {pause_amp}: noise fell by {got:.1} dB after the pause"); + } + } + + /// No frame that shares a sample with digital silence enters the noise estimate: not the + /// frames that run into a mute, nor those that run out of it, whether or not the mute starts + /// or ends on a frame boundary. At most two frames per mute that hold no silence are dropped + /// with them. + #[test] + fn frames_that_touch_a_mute_stay_out_of_the_estimate() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + for offset in [0usize, 17, 40, 63] { + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let len = SR as usize; + let mut x = white(29, len, 0.05); + let mutes = [(SR as usize * 3 / 10 + offset, SR as usize * 4 / 10 + offset), (SR as usize * 7 / 10 + offset, SR as usize * 8 / 10)]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + let mut frames = 0usize; + // A frame enters the estimate when the frame `OVERLAP` after it arrives, which is when + // `heard` grows. + let mut entered = Vec::new(); + for &v in &x { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + let heard = bins.heard; + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + frames += 1; + if bins.heard > heard { + entered.push(frames - OVERLAP); + } + }); + } + // Frame `j` (from 1) holds samples `j * hop - n .. j * hop`; samples before 0 are + // the zeros the STFT starts with. + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), bins.heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(bins.heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", bins.heard); + } + } + + /// A mute too short to fill a frame, from one hop long up, keeps the frames that hold a sample + /// of it out of the estimate too, wherever it starts and ends between two hops. + #[test] + fn frames_that_touch_a_short_mute_stay_out_of_the_estimate() { + for offset in [0usize, 17, 40, 63] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut x = white(31, SR as usize / 2, 0.05); + // The last mute is one STFT size long and holds no whole frame unless it starts on a hop. + let mutes = [ + (192 + offset, 256 + offset), + (6000 + offset, 6100 + offset), + (12_000 + offset, 12_200 + offset), + (17_984 + offset, 17_984 + offset + n), + ]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + // One hop per block, so each block ends with a frame. A frame enters the estimate when + // the frame `OVERLAP` after it arrives, which is when `heard` grows. + let mut entered = Vec::new(); + for (k, chunk) in x.chunks(hop).enumerate() { + let heard = s.bins[0].heard; + let mut y = chunk.to_vec(); + s.process(&mut [&mut y]); + if s.bins[0].heard > heard { + entered.push(k + 1 - OVERLAP); + } + } + let frames = x.len() / hop; + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < s.coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), s.bins[0].heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(s.bins[0].heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", s.bins[0].heard); + } + } + + /// Quiet stretches that a mute separates do not add up to a search window: the estimate stays + /// at the noise before them, and falls only after a whole search window of quiet in a row. + #[test] + fn a_mute_ends_a_quiet_run() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let window = coefs.window * hop; + let amp = 0.05f32; + let (loud, quiet, mute) = (SR as usize * 2, window * 6 / 10, SR as usize / 5); + let mut x = white(47, loud + 2 * quiet + mute + window + quiet, amp); + x[loud..].iter_mut().for_each(|v| *v *= 0.01); + x[loud + quiet..loud + quiet + mute].fill(0.0); + let want = amp * amp / 3.0 * n as f32 / 2.0; + let mut feed = |part: &[f32]| -> f64 { + for &v in part { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + }); + } + (1..half - 1).map(|k| db((bins.est[k] as f64 * BIAS as f64 / want as f64).sqrt())).sum::() / (half - 2) as f64 + }; + let split = loud + 2 * quiet + mute; + let kept = feed(&x[..split]); + assert!(kept > -6.0, "after two quiet stretches split by a mute the estimate fell by {:.1} dB", -kept); + let fell = feed(&x[split..]); + assert!(fell < -20.0, "after a search window of quiet the estimate fell by only {:.1} dB", -fell); + } + + /// A mute of one hop, which leaves no frame of digital silence, ends the quiet run where it + /// falls in the stream: the quiet frames waiting before it still count, and only the frames + /// after the mute that may enter the estimate start the next run. + #[test] + fn a_short_mute_ends_the_quiet_run_in_queue_order() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let im = vec![0.0f32; half]; + let (loud, quiet) = (vec![1.0f32; half], vec![0.001f32; half]); + let mut step = |bins: &mut Bins, sample: f32, spectrum: &[f32]| { + for _ in 0..hop { + bins.sample(sample, hop); + } + bins.frame(spectrum, &im, &coefs, &mut gains); + }; + for _ in 0..40 { + step(&mut bins, 0.1, &loud); + } + for _ in 0..OVERLAP + 3 { + step(&mut bins, 0.001, &quiet); + } + assert!(bins.quiet_run > 0, "the quiet frames before the mute did not count"); + step(&mut bins, 0.0, &quiet); + let mut eligible = 0; + for _ in 0..2 * n / hop { + step(&mut bins, 0.001, &quiet); + let newest = (bins.head + bins.queued - 1) % OVERLAP; + eligible += usize::from(bins.queue_ok[newest]); + } + let waiting = (0..bins.queued).filter(|j| bins.queue_ok[(bins.head + j) % OVERLAP]).count(); + assert_eq!(waiting, bins.queued, "a frame waiting after the mute may not enter the estimate"); + assert!(eligible + 3 < coefs.window, "the test needs the run below its cap"); + assert_eq!(bins.quiet_run, eligible - waiting, "frames from before the mute counted in the new run"); + } + + #[test] + fn a_short_mute_ends_the_queued_quiet_run() { + for offset in [0, 17] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut loud = white(47, SR as usize * 2, 0.05); + s.process(&mut [&mut loud]); + let mut quiet = white(51, 20 * hop + offset, 0.0005); + s.process(&mut [&mut quiet]); + assert!(s.bins[0].quiet_run > 0); + let mute_end = loud.len() + quiet.len() + hop; + let first_clean_frame = (mute_end + n).div_ceil(hop); + let commit_end = (first_clean_frame + OVERLAP) * hop; + let mut after = white(53, commit_end - loud.len() - quiet.len(), 0.0005); + after[..hop].fill(0.0); + let before_mute = s.bins[0].quiet_run; + s.process(&mut [&mut after[..hop]]); + assert_eq!(s.bins[0].quiet_run, before_mute + 1, "offset {offset}: queued pre-mute frames lost their quiet run"); + s.process(&mut [&mut after[hop..]]); + assert_eq!(s.bins[0].quiet_run, 1, "offset {offset}: pre-mute quiet frames contributed to the new run"); + } + } + + /// A voice that starts with the stream keeps its level within 3 dB over its first 0.25 s and + /// its first 1.5 s, while the suppressor has no noise estimate yet. One of the voices starts on + /// its first sample with a vowel held for 0.25 s. + #[test] + fn a_voice_at_the_start_keeps_its_level() { + let mut abrupt = voiced(SR as f64, 2.0, 7); + let vowel = SR as usize / 4; + let len = abrupt.len(); + abrupt.copy_within(..len - vowel, vowel); + for (i, v) in abrupt[..vowel].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + for speech in [abrupt, voiced(SR as f64, 2.0, 6), speechy(SR as f64, 2.0, 6)] { + let noise = white(19, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + for to in [SR as usize / 4, SR as usize * 3 / 2] { + let kept = db((energy(&ys[lat..to + lat]) / energy(&speech[..to])).sqrt()); + assert!(kept.abs() < 3.0, "voice level changed by {kept:.2} dB in the first {to} samples"); + } + } + } + + /// A steady vowel held for 3 s in noise, longer than the search window, keeps its level within + /// 3 dB over its last second. + #[test] + fn a_held_vowel_keeps_its_level() { + let (lead, held) = (SR as usize * 2, SR as usize * 3); + let mut speech = vec![0.0f32; lead + held + SR as usize / 2]; + for (i, v) in speech[lead..lead + held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + let fade = (i as f32 / 480.0).min(1.0); + *v = fade * (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum::(); + } + let noise = white(37, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + let last = lead + held - SR as usize..lead + held; + let kept = db((energy(&ys[last.start + lat..last.end + lat]) / energy(&speech[last])).sqrt()); + assert!(kept.abs() < 3.0, "the held vowel's level changed by {kept:.2} dB in its last second"); + } + + /// A steady vowel held from the first sample, with no noise before it, keeps its level within + /// 3 dB over its first 2 s, after the floor has reached the reduction. + #[test] + fn a_vowel_held_from_the_start_keeps_its_level() { + let held = SR as usize * 3; + let mut speech = vec![0.0f32; held + SR as usize / 2]; + for (i, v) in speech[..held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + let noise = white(53, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + for range in [0..SR as usize * 2, SR as usize * 3 / 2..SR as usize * 2] { + let kept = db((energy(&ys[range.start + lat..range.end + lat]) / energy(&speech[range.clone()])).sqrt()); + assert!(kept.abs() < 3.0, "the vowel's level changed by {kept:.2} dB over {range:?}"); + } + } + + #[test] + fn a_hop_periodic_startup_vowel_keeps_its_level_at_16_khz() { + let sr = 16_000.0; + let held = sr as usize * 3; + let mut speech = vec![0.0f32; held + sr as usize / 2]; + for (i, v) in speech[..held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 250.0 * i as f64 / sr as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + let mut s = NoiseSuppression::new(sr, 1); + assert!(s.set_param("reduction", 24.0)); + s.reset(); + assert_eq!(s.hop, sr as usize / 250); + let lat = s.latency(); + let mut y = speech.clone(); + s.process(&mut [&mut y]); + for range in [0..sr as usize * 2, sr as usize * 3 / 2..sr as usize * 2] { + let kept = db((energy(&y[range.start + lat..range.end + lat]) / energy(&speech[range.clone()])).sqrt()); + assert!(kept.abs() < 3.0, "the 250 Hz startup vowel at 16 kHz changed by {kept:.2} dB over {range:?}"); + } + } + + /// Steady noise whose spectrum falls with frequency (white noise through a one-pole low-pass + /// at 500 Hz) is suppressed by at least 20 dB from 4 s on. + #[test] + fn steady_low_passed_noise_falls_by_the_reduction() { + let mut s = suppressor(24.0); + let n = SR as usize * 5; + let a = (-std::f32::consts::TAU * 500.0 / SR).exp(); + let mut state = 0.0f32; + let x: Vec = white(59, n, 0.2) + .into_iter() + .map(|v| { + state = a * state + (1.0 - a) * v; + state + }) + .collect(); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let lat = s.latency(); + let from = SR as usize * 4; + let got = -db(rms(&y[from + lat..n]) / rms(&x[from..n - lat])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// NaN, infinite and the largest finite samples give finite output, and the noise is still + /// suppressed afterwards. + #[test] + fn non_finite_and_huge_samples_give_finite_output() { + let mut s = suppressor(24.0); + let n = SR as usize * 4; + let x = white(13, n, 0.05); + let mut y = x.clone(); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + y[3000 + i * 1500] = bad; + y[3001 + i * 1500] = bad; + } + s.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite())); + let tail = n - SR as usize / 2..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// A block that leaves channels out feeds them silence, so when they come back without a + /// reset none of their earlier audio sounds. + #[test] + fn channels_left_out_of_a_block_come_back_silent() { + let noise = white(23, 4_000, 0.5); + let mut s = NoiseSuppression::new(SR, 3); + let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone()); + s.process(&mut [&mut a, &mut b, &mut c]); + // The first channel is silent too, so the paired inverse FFT carries none of its audio + // into the second channel. + let mut a = vec![0.0f32; 4_000]; + s.process(&mut [&mut a]); + let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + s.process(&mut [&mut a, &mut b, &mut c]); + assert!(b.iter().chain(&c).all(|v| *v == 0.0), "earlier audio came back"); + } + + /// On steady white noise, the noise estimate, averaged over the bins, lands within 1 dB of the + /// noise's mean power once the search window has filled. + #[test] + fn the_noise_estimate_follows_white_noise() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let amp = 0.1f32; + let x = white(3, SR as usize * 4, amp); + for &v in &x { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + }); + } + // uniform noise of amplitude `amp` has a variance of amp²/3; each bin of the + // square-root-Hann windowed FFT gets n/2 of that + let want = amp * amp / 3.0 * n as f32 / 2.0; + let mean = (1..half - 1).map(|k| db((bins.noise(k) as f64 / want as f64).sqrt())).sum::() / (half - 2) as f64; + assert!(mean.abs() < 1.0, "the noise estimate is {mean:.2} dB from the mean power"); + } +} diff --git a/crates/audio-dsp/src/effects/util.rs b/crates/audio-dsp/src/effects/util.rs index eb19d70d72..e16654994e 100644 --- a/crates/audio-dsp/src/effects/util.rs +++ b/crates/audio-dsp/src/effects/util.rs @@ -81,7 +81,14 @@ impl DelayLine { let i0 = self.w + len - 1 - di as usize; let i0 = if i0 >= len { i0 - len } else { i0 }; let i1 = if i0 == 0 { len - 1 } else { i0 - 1 }; - self.buf[i0] + (self.buf[i1] - self.buf[i0]) * frac + let (a, b) = (self.buf[i0], self.buf[i1]); + let y = a + (b - a) * frac; + if y.is_finite() { + y + } else { + // Two large samples of opposite sign overflow `b - a` in f32. + (a as f64 + (b as f64 - a as f64) * frac as f64) as f32 + } } /// Integer read (`d` samples ago, 0 = newest). #[inline] diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs index af487cdbbb..4b059b67b3 100644 --- a/crates/audio-dsp/src/effects/voice.rs +++ b/crates/audio-dsp/src/effects/voice.rs @@ -1,5 +1,8 @@ -//! 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. +//! Effects for a live voice: a pitch shifter with 10 ms of latency and a formant shifter with +//! 10.7 ms of latency (at 48 kHz). +//! +//! The pitch shifter (`voice_pitch`) has two read taps that 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 @@ -11,8 +14,21 @@ //! 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. +//! +//! The formant shifter (`voice_formant`) moves the spectral envelope of the voice up or down while +//! its harmonics stay where they are. It runs a short STFT (512 points at up to 50 kHz, hop 128). +//! For each frame it fits a linear predictor (one coefficient per kHz plus 2, at most 96) to the +//! last two frame lengths of input (1,024 samples at 48 kHz), which end with the frame and add no +//! latency, and takes the +//! envelope from the predictor. It then multiplies every bin by the envelope read at +//! `bin / ratio` over the envelope at the bin, with at most 24 dB of boost. Its latency is the +//! STFT size. `voice_pitch` uses the same stage for Keep Formants: the stage moves the shifted +//! voice's envelope back by the inverse of the pitch ratio, so the pitch changes and the formants +//! stay, and the latency grows by the STFT size. +use super::stft::{Spectral, StftChannel, fft_size}; use crate::biquad::{Biquad, Coeffs, FilterType}; +use crate::fft::Fft; use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, flush32, param_plumbing}; use std::f64::consts::PI; @@ -33,13 +49,31 @@ const MARGIN: f64 = 2.0; 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; +/// Fewest and most predictor coefficients of the formant envelope (one per kHz plus 2 between). +const MIN_ORDER: usize = 8; +const MAX_ORDER: usize = 96; +/// Width of the Gaussian lag window, which widens each envelope peak to about this many hertz. +const LAG_HZ: f64 = 40.0; +/// White noise added to the autocorrelation (60 dB down), so a pure tone still gives a stable +/// predictor. +const WHITE: f64 = 1.0e-6; +/// Largest boost the envelope warp gives one bin: ln 16, about 24 dB. +const MAX_BOOST: f64 = 2.772_588_722_239_781; + +/// STFT size of the formant stage: 512 at up to 50 kHz (10.7 ms at 48 kHz), 1024 up to 100 kHz, +/// 2048 above. +fn formant_size(sample_rate: f32) -> usize { + fft_size(sample_rate) / 4 +} /// 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. +/// It keeps two copies: the mean of the channels, and one channel alone. A frame whose mean holds +/// less than a quarter of that channel's energy (channels of opposite polarity cancel in the +/// mean) is analyzed on that channel. The channel is the first one until another channel holds +/// over four times its energy through one hop; the tracker then moves to the loudest channel, and +/// analyzes that channel's copy only once a whole frame of it has come in. #[derive(Clone, Debug)] struct Tracker { /// Input samples per analysis sample. @@ -56,10 +90,16 @@ struct Tracker { max_tau: usize, /// Period in input samples, or `None` when the last frame was unvoiced. period: Option, + /// Channel the second copy holds. + channel: usize, + /// Energy of each channel's clipped input since the last analysis. + energy: Vec, + /// Analysis samples of `channel` in the second copy, up to the frame length. + filled: usize, } impl Tracker { - fn new(sample_rate: f32) -> Self { + fn new(sample_rate: f32, channels: usize) -> 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); @@ -82,6 +122,10 @@ impl Tracker { min_tau, max_tau, period: None, + channel: 0, + energy: vec![0.0; channels.max(1)], + // The zeros the copy starts with are the first channel's silence. + filled: len, } } @@ -91,12 +135,23 @@ impl Tracker { self.at = 0; self.since = 0; self.period = None; + self.channel = 0; + self.energy.fill(0.0); + self.filled = self.frame.len(); } - /// 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)); + /// Adds one input sample of channel `c` to that channel's energy. + fn measure(&mut self, c: usize, x: f32) { + if let Some(e) = self.energy.get_mut(c) { + let x = (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP); + *e += x * x; + } + } + + /// Takes one input sample, as the mean of the channels and the sample of the channel in + /// `self.channel`; runs an analysis every `hop` analysis samples. + fn push(&mut self, mean: f32, single: f32) { + let clipped = [mean, single].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); } @@ -110,16 +165,34 @@ impl Tracker { feed.ring[self.at] = feed.last as f32; } self.at = (self.at + 1) & mask; + self.filled = (self.filled + 1).min(self.frame.len()); self.since += 1; if self.since >= self.hop { self.since = 0; self.analyze(); + self.choose_channel(); } } + /// Moves the second copy to the loudest channel when that channel held over four times the + /// energy of the one in use since the last analysis. The first of equally loud channels wins. + fn choose_channel(&mut self) { + let loudest = (0..self.energy.len()).fold(0, |b, c| if self.energy[c] > self.energy[b] { c } else { b }); + if self.energy[self.channel] < 0.25 * self.energy[loudest] { + self.channel = loudest; + self.feeds[1].reset(); + self.filled = 0; + } + self.energy.fill(0.0); + } + 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 [mean, single] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::()); + if mean < 0.25 * single && self.filled < self.frame.len() { + // The channel's copy holds less than a frame since the move: keep the last period. + return; + } + let feed = if mean < 0.25 * single { &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]; @@ -229,10 +302,16 @@ struct Taps { delay_b: f64, } -/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). +/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). Keep Formants +/// (`formant_follow`) adds the formant stage's latency, 10.7 ms at 48 kHz, and `latency` reports +/// it while the switch is on. pub struct VoicePitch { pv: ParamValues, latency: usize, + /// Formant stage of Keep Formants, and the share of its output against the shifted voice. + follow: Stage, + follow_mix: f64, + follow_on: bool, /// Widest tap spacing that keeps both taps inside the line, in samples. max_spacing: f64, lines: Vec>, @@ -252,6 +331,7 @@ 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), + ParamSpec::new("formant_follow", "Keep Formants", 0.0, 1.0, 0.0, Unit::Toggle), ]; pub fn new(sample_rate: f32, channels: usize) -> Self { @@ -262,11 +342,14 @@ impl VoicePitch { let mut s = VoicePitch { pv: ParamValues::new(Self::PARAMS), latency, + follow: Stage::new(sample_rate, ch), + follow_mix: 0.0, + follow_on: false, max_spacing: latency as f64 - MARGIN, lines: vec![vec![0.0; len]; ch], mask: len - 1, pos: 0, - tracker: Tracker::new(sample_rate), + tracker: Tracker::new(sample_rate, ch), ratio: 1.0, phase: 0.5, spacing: latency as f64 - MARGIN, @@ -280,11 +363,17 @@ impl VoicePitch { 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); + self.follow_on = self.pv.v("formant_follow") >= 0.5; if snap { self.wet = self.target_wet(); + self.follow_mix = self.follow_target(); } } + fn follow_target(&self) -> f64 { + if self.follow_on { 1.0 } else { 0.0 } + } + fn target_wet(&self) -> f64 { if self.ratio == 1.0 { 0.0 } else { 1.0 } } @@ -341,12 +430,13 @@ impl VoicePitch { impl AudioEffect for VoicePitch { param_plumbing!("voice_pitch"); fn latency(&self) -> usize { - self.latency + self.latency + if self.follow_on { self.follow.n } else { 0 } } 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 + // more, which is twice the latency in all. Keep Formants spreads a frame over up to the + // formant stage's size more. A render drains `latency() + tail_samples()` samples. + self.latency + if self.follow_on { self.follow.n } else { 0 } } fn reset(&mut self) { self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|v| *v = 0.0)); @@ -355,23 +445,43 @@ impl AudioEffect for VoicePitch { self.phase = 0.5; self.spacing = self.max_spacing; self.wet = self.target_wet(); + self.follow.reset(); + self.follow_mix = self.follow_target(); } fn process(&mut self, channels: &mut [&mut [f32]]) { let len = block_len(channels); - let ch = channels.len().min(self.lines.len()); + let ch = self.lines.len(); let dry_at = self.mask + 1 - self.latency; + let follow_target = self.follow_target(); + // The formant stage moves the envelope by the inverse of the pitch ratio. + let back = (1.0 / self.ratio) as f32; 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]); + for (c, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is stored as silence, so it never reaches the output. A + // channel the block leaves out is stored as silence too while its line advances, + // so after a gap of at least `latency() + tail_samples()` samples it holds none of + // its earlier audio; after a shorter gap, audio still in the line can sound. + let x = channels.get(c).map_or(0.0, |io| flush32(io[i])); line[self.pos] = x; sum += x; + self.tracker.measure(c, x); } - let first = self.lines[0][self.pos]; - self.tracker.push(sum / ch as f32, first); + let single = self.lines[self.tracker.channel][self.pos]; + self.tracker.push(sum / ch as f32, single); let t = self.advance(); - for (line, io) in self.lines.iter().zip(channels.iter_mut()) { + let mix = if self.follow_mix < follow_target { + (self.follow_mix + self.wet_step).min(follow_target) + } else { + (self.follow_mix - self.wet_step).max(follow_target) + }; + self.follow_mix = mix; + // While Keep Formants is off and faded out, the stage's frames copy the shifted voice, + // so switching it on crossfades from a delayed copy instead of from silence. + let warp = if mix > 0.0 { back } else { 1.0 }; + // A channel the block leaves out still reads its line into the formant stage, so the + // audio its line holds reaches the stage on time; only its output is dropped. + for (c, line) in self.lines.iter().enumerate() { let dry = line[(self.pos + dry_at) & self.mask] as f64; let y = if t.wet == 0.0 { dry @@ -380,13 +490,290 @@ impl AudioEffect for VoicePitch { 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; + let y = y.clamp(-f32::MAX as f64, f32::MAX as f64); + let z = self.follow.tick(c, y as f32, warp); + // The stage's output is `n` samples later than `y`, so a switch fades one out + // before the other comes in instead of mixing them. + let out = if mix < 0.5 { (1.0 - 2.0 * mix) * y } else { (2.0 * mix - 1.0) * z as f64 }; + if let Some(io) = channels.get_mut(c) { + io[i] = out.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + } } self.pos = (self.pos + 1) & self.mask; } } } +/// Spectral envelope of the recent input from linear prediction, and the warp that moves it. +/// Every buffer is sized at creation. +#[derive(Clone, Debug)] +struct Envelope { + fft: Fft, + /// Hann window over the analyzed history. + window: Vec, + /// Gaussian lag window, one value per autocorrelation lag (`order + 1`). + lags: Vec, + frame: Vec, + r: Vec, + /// Predictor coefficients, `a[0] = 1`. + a: Vec, + prev: Vec, + re: Vec, + im: Vec, + /// Natural log of the envelope's magnitude, bins 0..=n/2 of the STFT. + log: Vec, +} + +impl Envelope { + /// An envelope for STFT frames of `n` points, read from the last `2 n` samples. + fn new(n: usize, sample_rate: f32) -> Self { + let order = ((sample_rate / 1000.0).round() as usize + 2).clamp(MIN_ORDER, MAX_ORDER); + let w = 2 * n; + let window = (0..w).map(|i| 0.5 - 0.5 * (2.0 * PI * (i as f64 + 0.5) / w as f64).cos()).collect(); + let lags = (0..=order) + .map(|i| { + let x = 2.0 * PI * LAG_HZ * i as f64 / sample_rate as f64; + (-0.5 * x * x).exp() + }) + .collect(); + Envelope { + fft: Fft::new(n), + window, + lags, + frame: vec![0.0; w], + r: vec![0.0; order + 1], + a: vec![0.0; order + 1], + prev: vec![0.0; order + 1], + re: vec![0.0; n], + im: vec![0.0; n], + log: vec![0.0; n / 2 + 1], + } + } + + /// Reads the envelope of the newest `2 n` samples of `history`. Returns `false` for silence, + /// which has no envelope. + fn measure(&mut self, history: &History) -> bool { + let mask = history.ring.len() - 1; + for (i, (v, w)) in self.frame.iter_mut().zip(&self.window).enumerate() { + *v = history.ring[(history.pos + i) & mask] as f64 * w; + } + let len = self.frame.len(); + self.r[0] = dot(&self.frame, &self.frame) * self.lags[0]; + if !(self.r[0] > 0.0 && self.r[0].is_finite()) { + return false; + } + for (lag, (r, w)) in self.r.iter_mut().zip(&self.lags).enumerate().skip(1) { + *r = dot(&self.frame[..len - lag], &self.frame[lag..]) * w; + } + self.r[0] *= 1.0 + WHITE; + levinson(&self.r, &mut self.a, &mut self.prev); + // The envelope is 1 / |A| on the bins of the STFT. + self.re.fill(0.0); + self.im.fill(0.0); + for (v, a) in self.re.iter_mut().zip(&self.a) { + *v = *a as f32; + } + self.fft.forward(&mut self.re, &mut self.im); + for (l, (re, im)) in self.log.iter_mut().zip(self.re.iter().zip(&self.im)) { + *l = (-0.5 * (*re as f64 * *re as f64 + *im as f64 * *im as f64 + 1e-30).ln()) as f32; + } + true + } + + /// Multiplies the half spectrum `re`/`im` (bins 0..=n/2) by the envelope read at `bin / + /// ratio` over the envelope at the bin, so the envelope moves up by `ratio` and the + /// harmonics stay. A frame with a non-finite bin is replaced with silence. + fn warp(&self, re: &mut [f32], im: &mut [f32], ratio: f32) { + let half = self.log.len(); + let (re, im) = (&mut re[..half], &mut im[..half]); + if !re.iter().chain(im.iter()).fold(true, |ok, v| ok & v.is_finite()) { + re.fill(0.0); + im.fill(0.0); + return; + } + let last = (half - 1) as f32; + for k in 0..half { + let src = (k as f32 / ratio).min(last); + let i = src as usize; + let e = match self.log.get(i + 1) { + Some(next) => self.log[i] + (src - i as f32) * (next - self.log[i]), + None => self.log[i], + }; + let g = ((e - self.log[k]) as f64).min(MAX_BOOST).exp() as f32; + re[k] *= g; + im[k] *= g; + } + } +} + +/// Dot product of two slices of the same length, in four running sums so it vectorizes. +fn dot(a: &[f64], b: &[f64]) -> f64 { + let mut sums = [0.0f64; 4]; + let ((ca, ra), (cb, rb)) = (a.as_chunks::<4>(), b.as_chunks::<4>()); + for (x, y) in ca.iter().zip(cb) { + for ((s, x), y) in sums.iter_mut().zip(x).zip(y) { + *s += x * y; + } + } + let rest: f64 = ra.iter().zip(rb).map(|(x, y)| x * y).sum(); + (sums[0] + sums[1]) + (sums[2] + sums[3]) + rest +} + +/// Levinson-Durbin recursion: the predictor `a` (`a[0] = 1`) of the autocorrelation `r`. It +/// stops at the first reflection coefficient that would make the predictor unstable. +fn levinson(r: &[f64], a: &mut [f64], prev: &mut [f64]) { + a.fill(0.0); + a[0] = 1.0; + let mut err = r[0]; + for i in 1..a.len() { + let acc = r[i] + (1..i).map(|j| a[j] * r[i - j]).sum::(); + let k = -acc / err; + // NaN (from a zero error) also stops the recursion. + if k.is_nan() || k.abs() >= 1.0 { + return; + } + prev[..i].copy_from_slice(&a[..i]); + for j in 1..i { + a[j] = prev[j] + k * prev[i - j]; + } + a[i] = k; + err *= 1.0 - k * k; + } +} + +/// The newest samples of one channel, for the envelope. +#[derive(Clone, Debug)] +struct History { + ring: Vec, + /// Where the next sample goes, which is also the oldest sample. + pos: usize, +} + +impl History { + fn push(&mut self, x: f32) { + self.ring[self.pos] = x; + self.pos = (self.pos + 1) & (self.ring.len() - 1); + } + + fn reset(&mut self) { + self.ring.fill(0.0); + self.pos = 0; + } +} + +/// STFT stage that moves each channel's envelope, fed one sample at a time: the formant +/// shifter, and the formant stage of `voice_pitch`'s Keep Formants. +#[derive(Clone, Debug)] +struct Stage { + n: usize, + hop: usize, + scale: f32, + spec: Spectral, + stft: Vec, + history: Vec, + env: Envelope, +} + +impl Stage { + fn new(sample_rate: f32, channels: usize) -> Self { + let n = formant_size(sample_rate); + Stage { + n, + hop: n / 4, + // √Hann on both sides is Hann, which sums to 2 at a hop of n/4; the inverse FFT is + // unscaled. + scale: 1.0 / (2 * n) as f32, + spec: Spectral::new(n, true), + stft: vec![StftChannel::new(n); channels], + history: vec![History { ring: vec![0.0; 2 * n], pos: 0 }; channels], + env: Envelope::new(n, sample_rate), + } + } + + fn reset(&mut self) { + self.stft.iter_mut().for_each(StftChannel::reset); + self.history.iter_mut().for_each(History::reset); + } + + /// Pushes one sample of a channel and returns the stage's output for it, `n` samples later. + /// A frame moves the envelope by `ratio`, which can spread a sound over the frame, so the + /// output can go on for up to `n` samples more (the tail). At a ratio of 1, and for silence, a frame only + /// windows and adds its input, which needs no FFT. + fn tick(&mut self, channel: usize, x: f32, ratio: f32) -> f32 { + let Stage { n, hop, scale, spec, stft, history, env } = self; + let half = *n / 2 + 1; + history[channel].push(x); + let history = &history[channel]; + let z = stft[channel].tick(x, *hop, &mut |input, out| { + if ratio != 1.0 && env.measure(history) { + spec.analyze(input); + env.warp(&mut spec.re[..half], &mut spec.im[..half], ratio); + spec.synthesize_add(out, *scale); + } else { + for ((o, x), w) in out.iter_mut().zip(input).zip(&spec.window) { + *o += x * w * w * 0.5; + } + } + }); + // A huge finite input can overflow the inverse FFT. + flush32(z) + } +} + +/// Formant shifter for a live voice: moves the spectral envelope by -12 to +12 semitones (a ratio +/// of 0.5 to 2) and keeps the harmonics. Its latency is the STFT size, 512 samples (10.7 ms) at +/// 48 kHz. +pub struct VoiceFormant { + pv: ParamValues, + stage: Stage, + ratio: f32, +} + +impl VoiceFormant { + pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("semitones", "Formant Shift", -12.0, 12.0, 0.0, Unit::Semitones)]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let mut s = VoiceFormant { pv: ParamValues::new(Self::PARAMS), stage: Stage::new(sample_rate, crate::sane_channels(channels)), ratio: 1.0 }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, _snap: bool) { + self.ratio = 2f32.powf(self.pv.v("semitones") / 12.0); + } +} + +impl AudioEffect for VoiceFormant { + param_plumbing!("voice_formant"); + fn latency(&self) -> usize { + self.stage.n + } + fn tail_samples(&self) -> usize { + self.stage.n + } + fn reset(&mut self) { + self.stage.reset(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + for i in 0..len { + for c in 0..self.stage.stft.len() { + // A non-finite sample is taken as silence, so it never reaches the output. A + // channel the block leaves out is fed silence while its state advances, so after + // a gap of at least `latency() + tail_samples()` samples it holds none of its + // earlier audio; after a shorter gap, audio still pending can sound. + match channels.get_mut(c) { + Some(io) => io[i] = self.stage.tick(c, flush32(io[i]), self.ratio), + None => { + self.stage.tick(c, 0.0, self.ratio); + } + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -455,6 +842,24 @@ mod tests { } } + /// With a silent first channel, a voice on the other two channels in opposite polarity is + /// still tracked from one of them and crossfades without beating. + #[test] + fn opposite_polarity_beside_a_silent_first_channel_is_still_tracked() { + let mut p = VoicePitch::new(SR, 3); + assert!(p.set_param("semitones", 7.0)); + p.reset(); + let n = SR as usize * 2; + let mut silent = vec![0.0f32; n]; + let mut l = sine(220.0, 0.5, SR as f64, n, 0.0); + let mut r: Vec = l.iter().map(|v| -v).collect(); + p.process(&mut [&mut silent, &mut l, &mut r]); + assert!(silent.iter().all(|v| *v == 0.0)); + 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"); + } + /// A voice whose two channels have opposite polarity, which cancel in their mean, is still /// tracked and crossfades without beating. #[test] @@ -557,18 +962,357 @@ mod tests { assert!(db(rms(tail) / (0.5 / std::f64::consts::SQRT_2)).abs() < 1.0, "level {}", rms(tail)); } + /// Two-pole resonance magnitude at `f`, 1 at `center`. + fn resonance(f: f64, center: f64, bandwidth: f64) -> f64 { + center * bandwidth / ((center * center - f * f).powi(2) + (f * bandwidth).powi(2)).sqrt() + } + + /// A vowel: harmonics of `f0` up to 6 kHz shaped by two formants (`f1` with an 80 Hz + /// bandwidth, `f2` with 120 Hz and half the level) over a floor 34 dB down. + fn vowel(f0: f64, f1: f64, f2: f64, sr: f64, n: usize) -> Vec { + let harmonics: Vec<(f64, f64)> = (1..) + .map(|k| k as f64 * f0) + .take_while(|f| *f < 6000.0) + .map(|f| (f, 0.02 + resonance(f, f1, 80.0) + 0.5 * resonance(f, f2, 120.0))) + .collect(); + (0..n) + .map(|i| { + let t = i as f64 / sr; + (0.08 * harmonics.iter().map(|(f, a)| a * (2.0 * std::f64::consts::PI * f * t).sin()).sum::()) as f32 + }) + .collect() + } + + /// The envelope peak of `y` between `lo` and `hi` Hz, read from the amplitudes of the + /// harmonics of `f0` with a parabola through the strongest one and its neighbors (in dB). + fn envelope_peak(y: &[f32], f0: f64, lo: f64, hi: f64, sr: f64) -> f64 { + let amp = |k: usize| tone_amplitude(y, k as f64 * f0, sr).max(1e-12).ln(); + let ks = (lo / f0).ceil() as usize..=(hi / f0).floor() as usize; + let k = ks.max_by(|a, b| amp(*a).total_cmp(&(*b))).unwrap_or(1); + let (a, b, c) = (amp(k - 1), amp(k), amp(k + 1)); + 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 }; + (k as f64 + shift) * f0 + } + + /// The second of `y` after its first half second, at the rate `sr`. + fn settled_at(y: &[f32], sr: f64) -> &[f32] { + &y[sr as usize / 2..sr as usize * 3 / 2] + } + + /// The two formants of the vowel test signal (600 and 2000 Hz) in `y`, each looked for within + /// a window moved by `ratio`, with `y`'s harmonics at multiples of `f0`. + fn formants(y: &[f32], f0: f64, ratio: f64, sr: f64) -> (f64, f64) { + let tail = settled_at(y, sr); + (envelope_peak(tail, f0, 400.0 * ratio, 1000.0 * ratio, sr), envelope_peak(tail, f0, 1400.0 * ratio, 3000.0 * ratio, sr)) + } + + /// Level of everything off the harmonics of `f0` in `y`'s settled second, against the whole, + /// in dB. + fn off_harmonics_db(y: &[f32], f0: f64, sr: f64) -> f64 { + let tail = settled_at(y, sr); + let total = rms(tail).powi(2); + let on: f64 = (1..).map(|k| k as f64 * f0).take_while(|f| *f < sr / 2.0 - f0).map(|f| tone_amplitude(tail, f, sr).powi(2) / 2.0).sum(); + 10.0 * ((total - on).max(1e-30) / total).log10() + } + + /// A formant shift moves both formants of a vowel by the ratio, within a tenth of the move for + /// the first and 5% for the second, while every partial stays on the harmonics of the + /// unchanged fundamental. Checked at three voice pitches and three sample rates. + #[test] + fn a_formant_shift_moves_the_envelope_and_keeps_the_harmonics() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + for f0 in [110.0, 150.0, 220.0] { + let x = vowel(f0, 600.0, 2000.0, sr, sr as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + for semis in [-4.0f32, 4.0] { + let mut f = VoiceFormant::new(sr as f32, 1); + assert!(f.set_param("semitones", semis)); + let mut y = x.clone(); + f.process(&mut [&mut y]); + let r = 2f64.powf(semis as f64 / 12.0); + let (q1, q2) = formants(&y, f0, r, sr); + let at = format!("{sr} Hz, f0 {f0}, {semis:+} st: formants {p1:.0} and {p2:.0} moved to {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * r) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * r) - 1.0).abs() < 0.05, "{at}"); + let off = off_harmonics_db(&y, f0, sr); + assert!(off < -30.0, "{at}: {off:.1} dB off the harmonics"); + } + } + } + } + + /// Keep Formants: the pitch moves up a fourth, and the formants of the vowel stay where they + /// were (where without it they move with the pitch). + #[test] + fn keep_formants_holds_the_envelope_while_the_pitch_moves() { + let (sr, f0) = (SR as f64, 150.0); + let x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + let r = 2f64.powf(5.0 / 12.0); + for keep in [false, true] { + let mut p = shifter(5.0, 0.0); + assert!(p.set_param("formant_follow", if keep { 1.0 } else { 0.0 })); + p.reset(); + let y = run(&mut p, &x); + let want = if keep { 1.0 } else { r }; + let (q1, q2) = formants(&y, f0 * r, want, sr); + let at = format!("keep {keep}: formants {p1:.0} and {p2:.0} read {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * want) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * want) - 1.0).abs() < 0.05, "{at}"); + assert!(cents(peak_hz(settled(&y), f0 * r * 0.98, f0 * r * 1.02), f0 * r).abs() < 2.0, "keep {keep}: pitch"); + } + } + + /// Keep Formants adds the formant shifter's latency to the pitch shifter's while it is on, at + /// each rate. + #[test] + fn the_latency_reports_the_formant_stage() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + let n = VoiceFormant::new(sr, 2).latency(); + assert!(n > 0, "{sr}"); + let mut p = VoicePitch::new(sr, 2); + let base = p.latency(); + assert!(p.set_param("formant_follow", 1.0)); + assert_eq!(p.latency(), base + n, "{sr}"); + assert!(p.set_param("formant_follow", 0.0)); + assert_eq!(p.latency(), base, "{sr}"); + } + } + + /// After a burst of noise ends, the formant shifter and the pitch shifter with Keep Formants + /// fall silent within `latency + tail_samples`, so an offline render that drains that long + /// keeps all of the output. + #[test] + fn formant_output_ends_within_the_reported_tail() { + let (n, at, len) = (12_000, 1_777, 1_000); + let mut rng = Rng::new(17); + let mut x = vec![0.0f32; n]; + x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform()); + let mut f = VoiceFormant::new(SR, 1); + assert!(f.set_param("semitones", 7.0)); + let mut p = shifter(-5.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + p.reset(); + let fxs: [&mut dyn AudioEffect; 2] = [&mut f, &mut p]; + for fx in fxs { + let mut y = x.clone(); + fx.process(&mut [&mut y]); + let end = at + len + fx.latency() + fx.tail_samples(); + assert!(y[end..].iter().all(|v| *v == 0.0), "{}: output after {end}", fx.id()); + } + } + + /// Switching Keep Formants on fades the shifter's own output out over 10 ms and then fades the + /// formant stage's output, 512 samples later, in over 10 ms: the two never sound together, + /// so their different delays cannot comb-filter the voice. Checked at a shift of 0, where the + /// stage passes the voice unchanged. + #[test] + fn switching_keep_formants_fades_through_silence() { + let x = vowel(170.0, 650.0, 1900.0, SR as f64, 12_000); + let at = 4_000; + let mut plain = shifter(0.0, 0.0); + let y = run(&mut plain, &x); + let mut p = shifter(0.0, 0.0); + let mut out = x.clone(); + p.process(&mut [&mut out[..at]]); + assert!(p.set_param("formant_follow", 1.0)); + p.process(&mut [&mut out[at..]]); + let n = p.follow.n; + let step = 1.0 / (SR as f64 * BYPASS_MS as f64 / 1000.0); + for i in at..x.len() { + let m = ((i - at + 1) as f64 * step).min(1.0); + let want = if m < 0.5 { (1.0 - 2.0 * m) * y[i] as f64 } else { (2.0 * m - 1.0) * y[i - n] as f64 }; + assert!((out[i] as f64 - want).abs() < 1e-4, "sample {i}: {} against {want}", out[i]); + } + } + + /// The formant shifter with a shift change part way, and the pitch shifter with Keep Formants + /// switched on and off part way, give the same output however the stream is cut into blocks. + #[test] + fn formant_output_does_not_depend_on_how_the_stream_is_cut() { + let n = 40_000; + let x = vowel(130.0, 700.0, 1800.0, SR as f64, n); + let changes: [(usize, &str, f32); 3] = [(9_001, "semitones", 3.0), (17_321, "formant_follow", 1.0), (29_999, "formant_follow", 0.0)]; + let run_cut = |make: &dyn Fn() -> Box, sizes: &mut dyn FnMut() -> usize| { + let mut fx = make(); + let mut y = x.clone(); + let mut pos = 0; + while pos < n { + for (at, id, v) in changes { + if pos == at { + fx.set_param(id, v); + } + } + let next = changes.iter().map(|c| c.0).find(|at| *at > pos).unwrap_or(n); + let len = sizes().min(next - pos); + fx.process(&mut [&mut y[pos..pos + len]]); + pos += len; + } + y + }; + let makers: [&dyn Fn() -> Box; 2] = [ + &|| { + let mut f = VoiceFormant::new(SR, 1); + f.set_param("semitones", -5.0); + Box::new(f) + }, + &|| Box::new(shifter(-3.0, 0.0)), + ]; + for make in makers { + let whole = run_cut(make, &mut || usize::MAX); + let mut rng = Rng::new(13); + let cut = run_cut(make, &mut || (rng.next_u64() % 700) as usize); + assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits())); + assert!(whole.iter().any(|v| v.abs() > 0.05)); + } + } + + /// NaN, infinite and the largest finite samples in a vowel give finite output from the formant + /// shifter and from Keep Formants, and the formants are still moved afterwards. + #[test] + fn formant_stage_output_stays_finite() { + let (sr, f0) = (SR as f64, 150.0); + let mut x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + 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 mut f = VoiceFormant::new(SR, 2); + assert!(f.set_param("semitones", 4.0)); + let (mut l, mut r) = (x.clone(), x.clone()); + f.process(&mut [&mut l, &mut r]); + assert!(l.iter().chain(&r).all(|v| v.is_finite())); + let ratio = 2f64.powf(4.0 / 12.0); + let (q1, _) = formants(&l, f0, ratio, sr); + assert!((q1 / (p1 * ratio) - 1.0).abs() < 0.12, "{q1}"); + let mut p = shifter(-7.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + let y = run(&mut p, &x); + assert!(y.iter().all(|v| v.is_finite())); + assert!(rms(settled(&y)) > 0.01); + let shifted_f0 = f0 * 2f64.powf(-7.0 / 12.0); + let (q1, q2) = formants(&y, shifted_f0, 1.0, sr); + assert!((q1 / p1 - 1.0).abs() < 0.12, "Keep Formants: {p1} read {q1}"); + assert!((q2 / p2 - 1.0).abs() < 0.05, "Keep Formants: {p2} read {q2}"); + } + + /// A block that leaves channels out feeds them silence, so when they come back without a + /// reset, after a gap at least as long as the latency and the tail, none of their earlier + /// audio sounds. Checked for the formant shifter and for the pitch shifter with and without + /// Keep Formants. + #[test] + fn channels_left_out_of_a_block_come_back_silent() { + let mut rng = Rng::new(19); + let noise: Vec = (0..4_000).map(|_| 0.5 * rng.uniform()).collect(); + let mut f = VoiceFormant::new(SR, 3); + assert!(f.set_param("semitones", 4.0)); + let mut plain = VoicePitch::new(SR, 3); + assert!(plain.set_param("semitones", 5.0)); + plain.reset(); + let mut keep = VoicePitch::new(SR, 3); + assert!(keep.set_param("semitones", 5.0) && keep.set_param("formant_follow", 1.0)); + keep.reset(); + let fxs: [&mut dyn AudioEffect; 3] = [&mut f, &mut plain, &mut keep]; + for fx in fxs { + assert!(fx.latency() + fx.tail_samples() <= noise.len(), "{}: the gap is shorter than the latency and the tail", fx.id()); + let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone()); + fx.process(&mut [&mut a, &mut b, &mut c]); + let mut a = noise.clone(); + fx.process(&mut [&mut a]); + let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + fx.process(&mut [&mut a, &mut b, &mut c]); + assert!(b.iter().chain(&c).all(|v| *v == 0.0), "{}: earlier audio came back", fx.id()); + } + } + + /// With Keep Formants on, a channel left out of a short block while its line still holds an + /// impulse passes that impulse to the formant stage, so after it comes back its output matches + /// a channel that was never left out. + #[test] + fn a_short_gap_keeps_the_formant_stage_fed() { + for semitones in [0.0, 5.0] { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("semitones", semitones) && p.set_param("formant_follow", 1.0)); + p.reset(); + let (mut a, mut b) = (vec![0.0f32; 480], vec![0.0f32; 480]); + a[0] = 1.0; + b[0] = 1.0; + p.process(&mut [&mut a, &mut b]); + // The impulse leaves the delay line during samples 480 to 735, while `b` is left out. + let mut a = vec![0.0f32; 256]; + p.process(&mut [&mut a]); + let (mut a, mut b) = (vec![0.0f32; 2_000], vec![0.0f32; 2_000]); + p.process(&mut [&mut a, &mut b]); + assert!(a.iter().any(|v| v.abs() > 0.01), "{semitones}: the impulse never came out"); + assert_eq!(a, b, "{semitones}: the left-out channel lost the impulse"); + } + } + + /// A block that leaves a channel out gives the same output, once the channel is back, as a + /// block that holds silence for it: with Keep Formants on, an impulse just before the block + /// still sounds afterward. + #[test] + fn a_channel_left_out_of_a_block_runs_as_silence() { + let mut out = Vec::new(); + for omit in [false, true] { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("formant_follow", 1.0)); + p.reset(); + let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]); + r[479] = 1.0; + p.process(&mut [&mut l, &mut r]); + let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]); + if omit { + p.process(&mut [&mut l]); + } else { + p.process(&mut [&mut l, &mut r]); + } + let (mut l, mut r) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + p.process(&mut [&mut l, &mut r]); + assert!(r.iter().any(|v| *v != 0.0), "omit {omit}: the impulse did not sound"); + out.push((l, r)); + } + assert!(out[0] == out[1], "leaving the channel out changed the output"); + } + + /// Leaving a silent third channel out of a block does not change the pitch the tracker finds, + /// so a shifted voice comes out the same on the channels that remain. + #[test] + fn a_silent_channel_left_out_keeps_the_tracked_pitch() { + let n = SR as usize; + let (low, high) = (sine(187.5, 0.2, SR as f64, n, 0.0), sine(375.0, 0.24, SR as f64, n, 0.0)); + let left: Vec = low.iter().zip(&high).map(|(a, b)| a + b).collect(); + let right: Vec = low.iter().zip(&high).map(|(a, b)| -a + b).collect(); + let mut out = Vec::new(); + for omit in [false, true] { + let mut p = VoicePitch::new(SR, 3); + assert!(p.set_param("semitones", 5.0)); + p.reset(); + let (mut l, mut r, mut s) = (left.clone(), right.clone(), vec![0.0f32; n]); + if omit { + p.process(&mut [&mut l, &mut r]); + } else { + p.process(&mut [&mut l, &mut r, &mut s]); + } + out.push((l, r)); + } + assert!(out[0] == out[1], "leaving a silent channel out changed the tracked pitch"); + } + /// 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); + let mut t = Tracker::new(SR, 1); 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); + let mut t = Tracker::new(SR, 1); (0..SR as usize / 4).for_each(|_| t.push(0.0, 0.0)); assert!(t.period.is_none()); } diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index 59bfaa1741..42018ade17 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -171,8 +171,10 @@ pub trait AudioEffect: Send { /// Parameter descriptions (same as the registry entry's). fn params(&self) -> &'static [ParamSpec]; /// Set a parameter by id; the value is clamped to its range. Returns `false` for unknown ids. - /// Takes effect from the next processed sample. Gains, mix amounts and equalizer bands move to - /// the new value smoothly; the crate documentation lists which other parameters change at once. + /// Updates the target immediately. Sample-based effects use the target from the next processed + /// sample. Frame-based effects may apply it at the next frame callback while earlier output + /// remains queued. Gains, mix amounts and equalizer bands move to the new value smoothly; the + /// crate documentation lists which other parameters change at once. fn set_param(&mut self, id: &str, value: f32) -> bool; /// Current (target) value of a parameter. fn param(&self, id: &str) -> Option; @@ -182,7 +184,11 @@ pub trait AudioEffect: Send { /// Process one block in place. All channel slices must have the same length (the shortest /// length is used otherwise). Zero-length blocks are allowed. fn process(&mut self, channels: &mut [&mut [f32]]); - /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. + /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. It does + /// not change with the parameters, except for `voice_pitch`'s `formant_follow` (Keep + /// Formants), which adds the formant stage's latency while it is on. The value changes as + /// soon as the switch changes, while the output crossfades between the two delays over the + /// next 20 ms, so during that fade the output does not match the reported latency. fn latency(&self) -> usize { 0 } @@ -197,7 +203,13 @@ pub trait AudioEffect: Send { None } /// How long the output keeps sounding after the input stops, in samples (reverb and delay - /// tails), so an offline render can run past the end of its input. + /// tails), so an offline render can run past the end of its input. The count starts after + /// the latency: a render that keeps the tail runs `latency() + tail_samples()` samples past + /// the end of its input. An effect whose output decays without reaching zero (a feedback + /// delay, a resonator) reports where the decay falls below a cutoff, 60 dB under its start + /// for the feedback delays and resonators, so quieter output can still follow that point. + /// Those effects also cap the tail they report at 60 s, which is what a feedback of 1 or more + /// reports. fn tail_samples(&self) -> usize { 0 } @@ -460,6 +472,37 @@ pub(crate) mod testutil { } } + /// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope), + /// noise bursts (consonants) and pauses. + pub fn speechy(sr: f64, secs: f64, seed: u64) -> Vec { + let n = (sr * secs) as usize; + let mut rng = Rng::new(seed); + let mut out = vec![0.0f32; n]; + let mut i = 0usize; + while i < n { + let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; + let kind = rng.uniform(); + let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); + let glide = 1.0 + 0.3 * rng.uniform() as f64; + let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5); + for k in 0..len.min(n - i) { + let t = k as f64 / sr; + let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; + let v = if kind > 0.3 { + let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); + (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::() + } else if kind > -0.4 { + rng.uniform() + } else { + 0.0 + }; + out[i + k] = v * env * amp; + } + i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize; + } + out + } + pub fn sine(freq: f64, amp: f64, sr: f64, n: usize, phase: f64) -> Vec { (0..n).map(|i| (amp * (2.0 * std::f64::consts::PI * freq * i as f64 / sr + phase).sin()) as f32).collect() } diff --git a/crates/audio-dsp/src/sync.rs b/crates/audio-dsp/src/sync.rs index d117ecba3f..2ea3b75aac 100644 --- a/crates/audio-dsp/src/sync.rs +++ b/crates/audio-dsp/src/sync.rs @@ -354,38 +354,7 @@ pub fn find_offset(a: &[f32], b: &[f32], sample_rate: u32, opts: &SyncOptions) - #[cfg(test)] mod tests { use super::*; - use crate::testutil::Rng; - - /// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope), - /// noise bursts (consonants) and pauses. - fn speechy(sr: f64, secs: f64, seed: u64) -> Vec { - let n = (sr * secs) as usize; - let mut rng = Rng::new(seed); - let mut out = vec![0.0f32; n]; - let mut i = 0usize; - while i < n { - let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; - let kind = rng.uniform(); - let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); - let glide = 1.0 + 0.3 * rng.uniform() as f64; - let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5); - for k in 0..len.min(n - i) { - let t = k as f64 / sr; - let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; - let v = if kind > 0.3 { - let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); - (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::() - } else if kind > -0.4 { - rng.uniform() - } else { - 0.0 - }; - out[i + k] = v * env * amp; - } - i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize; - } - out - } + use crate::testutil::{Rng, speechy}; /// `x` delayed by `delay` samples (fractional: windowed-sinc interpolation), scaled by `gain`, /// optionally colored by a zero-phase low-pass (`[k, 1-2k, k]`, so the delay stays exact), with diff --git a/crates/audio/README.md b/crates/audio/README.md index 75f5694f66..69e9d247c0 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -31,7 +31,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | | `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | -| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | +| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `repair_wav` (size fields of a WAV left unfinished by a crash); `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 and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` | @@ -218,8 +218,10 @@ target, call `reset()`, decode from there, and drop the output before the target 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. +`vorbis::layout(channels)` gives the speakers of the result. `opus::wav_order` applies only to +mapping family 1. Family 0 is mono or stereo, which is already in WAV order. For other families, +`TrackDecoder` assigns no conventional speaker mapping and leaves channels in stream order. +`ac3::Decoder` and `mpa::Decoder` output WAV order. ### Encode a file diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index d57baa6b59..f7e69692d4 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -19,9 +19,9 @@ //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar //! `f32` in WAV channel order. //! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also -//! gives [`wav_float_header`]), FLAC (feature `flac-encode`), AAC-LC and ALAC in M4A -//! (`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 +//! gives [`wav_float_header`], [`wav_float_header_with_bwf`] and [`repair_wav`]), FLAC (feature +//! `flac-encode`), AAC-LC and ALAC in M4A (`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, @@ -209,8 +209,6 @@ pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; feature = "eac3-encode" ))] pub use write::FileEncoder; -#[cfg(feature = "pcm-encode")] -pub use write::wav_float_header; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -223,6 +221,8 @@ pub use write::wav_float_header; ))] pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] +pub use write::{WavRepair, repair_wav, wav_float_header, wav_float_header_with_bwf}; +#[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; /// Errors from probing, decoding and encoding. diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index 2cc5202780..44b2e56423 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -3,12 +3,9 @@ use super::source::Src; use crate::pcm::{PcmKind, le_u16, le_u32, le_u64, tag}; -use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; +use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; use crate::{AudioError, AudioInfo, BwfInfo, ChannelLayout, CodecId, Container, Result, SampleFormat}; -/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well. -const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]; - /// Parsed WAV layout (no sample data decoded yet). pub(crate) struct WavLayout { pub info: AudioInfo, @@ -359,7 +356,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { ixml_time = ixml_time_reference(&small(IXML_MAX as u64)); } } - b"ds64" => ds64_data = le_u64(&small(64), 8), + // The sizes come from the first `ds64` chunk that holds them. + b"ds64" if ds64_data.is_none() => ds64_data = le_u64(&small(64), 8), _ => {} } } diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs index 205741c529..09f5d6a4c3 100644 --- a/crates/audio/src/s302m.rs +++ b/crates/audio/src/s302m.rs @@ -53,6 +53,9 @@ pub struct Header { 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 { + if !matches!(self.channels, 2 | 4 | 6 | 8) { + return 0; + } let pair_bytes = match self.bits { 16 => 5, 20 => 6, @@ -243,6 +246,17 @@ mod tests { assert_eq!(h.frame_bytes(), 0); } + #[test] + fn header_frame_bytes_rejects_unsupported_channels() { + for bits in [16, 20, 24] { + for channels in [0, 1, 3, 5, 7, 9, 10, usize::MAX] { + let header = Header { channels, channel_id: 0, bits, alignment: 0, audio_bytes: 0 }; + assert!(Encoder::new(channels, bits).is_err()); + assert_eq!(header.frame_bytes(), 0, "{channels} channels, {bits} bits"); + } + } + } + #[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 }; diff --git a/crates/audio/src/wav.rs b/crates/audio/src/wav.rs index 61e32593a1..2a208d68bb 100644 --- a/crates/audio/src/wav.rs +++ b/crates/audio/src/wav.rs @@ -5,3 +5,5 @@ pub(crate) const WAVE_FORMAT_IEEE_FLOAT: u16 = 3; pub(crate) const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE; /// Tail of the KSDATAFORMAT_SUBTYPE_* GUIDs (bytes 2..16); bytes 0..2 hold the format tag. pub(crate) const GUID_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; +/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well. +pub(crate) const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 18beab7872..6f24e3bd1e 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -449,8 +449,99 @@ impl EncodeOptions { /// ``` #[cfg(feature = "pcm-encode")] pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result> { + float_header(sample_rate, channels, None, frames) +} + +/// [`wav_float_header`] with a BWF `bext` chunk holding `bwf` before the format chunk. The length +/// still doesn't depend on `frames`, so the header is rewritten in place the same way. +/// +/// ``` +/// use craft_audio::{BwfInfo, wav_float_header_with_bwf}; +/// +/// let bwf = BwfInfo::default().with_originator("Recorder").with_time_reference(48_000 * 3_600); +/// let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); +/// let samples = [0.25f32, -0.25, 0.5, -0.5]; +/// file.extend(samples.iter().flat_map(|s| s.to_le_bytes())); +/// let header = wav_float_header_with_bwf(48_000, 2, 2, &bwf).unwrap(); +/// file[..header.len()].copy_from_slice(&header); +/// assert!(header.windows(4).any(|id| id == b"bext")); +/// ``` +#[cfg(feature = "pcm-encode")] +pub fn wav_float_header_with_bwf(sample_rate: u32, channels: u16, frames: u64, bwf: &crate::BwfInfo) -> Result> { + float_header(sample_rate, channels, Some(bwf), frames) +} + +#[cfg(feature = "pcm-encode")] +fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, frames: u64) -> Result> { if channels == 0 || sample_rate == 0 { return Err(AudioError::Encode("a WAV needs channels and a sample rate".into())); } - wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false) + wav::header(usize::from(channels), sample_rate, (32, true), bwf, None, frames, false) +} + +/// What [`repair_wav`] wrote into a file. +#[cfg(feature = "pcm-encode")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct WavRepair { + /// The whole frames the data chunk holds. + pub frames: u64, + /// The length of the repaired file. Bytes past it are a partial last frame; truncate the + /// file to this length (`File::set_len`) to drop them. + pub len: u64, +} + +/// Rewrites the size fields of a PCM or float WAV whose writer stopped before finishing it, such +/// as a recorder's file after a crash, for the whole frames the file holds. The file must end in +/// its data chunk: everything after the data chunk's header counts as samples, whatever its size +/// field says. +/// +/// It writes these fields and leaves every other byte before the samples as it is, `fmt `, `bext` +/// and unknown chunks included: +/// +/// - the RIFF size and the data chunk's size (both `0xFFFF_FFFF` in an RF64 file); +/// - the frame count, the first field of the first `fact` chunk (`0xFFFF_FFFF` past `u32::MAX` frames); +/// - in an RF64 file, the RIFF size, data size and frame count at the start of the first `ds64` chunk; +/// - the pad byte after an odd data length. +/// +/// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that +/// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk +/// becomes a `ds64` chunk with an empty table. A RIFF file whose 28-byte chunk there already has the +/// `ds64` id, left by an earlier repair that stopped before writing `RF64`, becomes RF64 the same way. +/// +/// Errors: +/// +/// - [`AudioError::Malformed`] when `file` is not a RIFF or RF64 WAVE file, has no data chunk within +/// its first 100,000 chunks, has its data chunk before its `fmt ` chunk, has a `fmt ` chunk shorter +/// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size +/// other than the channels times the bytes per sample, has an extensible `fmt ` chunk with a cbSize +/// below 22 or more valid bits than bits per sample, or is RF64 without a `ds64` chunk or with a +/// first `ds64` chunk of 16 to 27 bytes (the WAV reader takes the data size from that chunk). +/// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format +/// whose subformat is neither, a sample width the WAV reader does not decode (PCM above 32 bits, +/// float other than 32 or 64 bits), and unfinished 8-bit mono data of even length (its last byte +/// may be a sample or a pad byte). +/// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` or +/// `ds64` chunk. +/// - [`AudioError::Io`] when reading, writing or seeking `file` fails. +/// +/// ``` +/// use craft_audio::{repair_wav, wav_float_header}; +/// use std::io::Cursor; +/// +/// // A recorder wrote the header for 0 frames, then 2 frames and part of a third, then stopped. +/// let mut bytes = wav_float_header(48_000, 2, 0).unwrap(); +/// bytes.extend([0.25f32, -0.25, 0.5, -0.5, 0.75].iter().flat_map(|s| s.to_le_bytes())); +/// let mut file = Cursor::new(bytes); +/// let repaired = repair_wav(&mut file).unwrap(); +/// assert_eq!(repaired.frames, 2); +/// let mut bytes = file.into_inner(); +/// bytes.truncate(repaired.len as usize); +/// let header = wav_float_header(48_000, 2, 2).unwrap(); +/// assert_eq!(bytes[..header.len()], header[..]); +/// ``` +#[cfg(feature = "pcm-encode")] +pub fn repair_wav(file: &mut F) -> Result { + let (frames, len) = wav::repair(file)?; + Ok(WavRepair { frames, len }) } diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index 96ba532510..496bb95801 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -2,9 +2,9 @@ //! specification, `bext` per EBU Tech 3285, `ds64` per EBU Tech 3306). use super::pcm::{Quantizer, sample_format, validate_buffer, validate_layout, write_interleaved}; -use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; +use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; use crate::{AudioBuffer, AudioError, BitDepth, BwfInfo, Result}; -use std::io::{Cursor, Seek, SeekFrom, Write}; +use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write}; const BEXT_MIN_LEN: usize = 602; @@ -239,3 +239,175 @@ pub(crate) fn header( head.extend_from_slice(&(if rf64 { u32::MAX } else { data_len as u32 }).to_le_bytes()); Ok(head) } + +/// Where the size fields of a WAV sit, from a walk of its chunks up to `data`. +struct Layout { + rf64: bool, + /// The body of the `ds64` chunk of an RF64 file, or in a RIFF file the body of the 28-byte + /// `JUNK` or `ds64` chunk right after `WAVE` that can become one. + ds64: Option, + junk: bool, + fact: Option, + block_align: u64, + data: u64, +} + +fn read_at(file: &mut F, pos: u64, buf: &mut [u8]) -> Result { + file.seek(SeekFrom::Start(pos))?; + match file.read_exact(buf) { + Ok(()) => Ok(true), + Err(e) if e.kind() == ErrorKind::UnexpectedEof => Ok(false), + Err(e) => Err(e.into()), + } +} + +fn write_at(file: &mut F, pos: u64, bytes: &[u8]) -> Result<()> { + file.seek(SeekFrom::Start(pos))?; + file.write_all(bytes)?; + Ok(()) +} + +/// The block size of a PCM or float `fmt ` chunk body at `pos` of `size` bytes. +fn pcm_block_align(file: &mut F, pos: u64, size: u32) -> Result { + let mut fmt = [0u8; 40]; + let n = if size >= 40 { 40 } else { 16 }; + if size < 16 || !read_at(file, pos, &mut fmt[..n])? { + return Err(AudioError::Malformed("WAV fmt chunk is cut short".into())); + } + let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]); + let mut tag = field(0); + if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 { + // The extensible fields the reader checks. + if field(16) < 22 || field(18) > field(14) { + return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk has a cbSize below 22 or too many valid bits".into())); + } + if fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL { + tag = field(24); + } + } + if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT { + return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x}"))); + } + let (channels, align, bits) = (field(2), field(12), field(14)); + if channels == 0 || bits == 0 || u32::from(align) != u32::from(channels) * u32::from(bits.div_ceil(8)) { + return Err(AudioError::Malformed(format!("WAV block size {align} does not fit {channels} channels of {bits} bits"))); + } + // The widths the WAV reader decodes. + if !matches!((tag, bits), (WAVE_FORMAT_PCM, 1..=32) | (WAVE_FORMAT_IEEE_FLOAT, 32 | 64)) { + return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x} with {bits} bits per sample"))); + } + Ok(u64::from(align)) +} + +fn layout(file: &mut F, len: u64) -> Result { + let mut riff = [0u8; 12]; + if !read_at(file, 0, &mut riff)? || !(riff.starts_with(b"RIFF") || riff.starts_with(b"RF64")) || &riff[8..] != b"WAVE" { + return Err(AudioError::Malformed("not a WAV file".into())); + } + let rf64 = riff.starts_with(b"RF64"); + let (mut ds64, mut junk, mut fact, mut block_align) = (None, false, None, None); + let mut pos = 12u64; + let mut chunk = [0u8; 8]; + // The same bound as the reader's, so a file of tiny chunks can't spin forever. + for _ in 0..100_000 { + if pos >= len || !read_at(file, pos, &mut chunk)? { + break; + } + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); + let body = pos + 8; + match &chunk[..4] { + b"data" => { + let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?; + return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body }); + } + // The first `ds64` and `fact` chunks take the sizes; later ones are left as they are. + // The WAV reader takes the data size from the first `ds64` chunk of 16 bytes or more. + b"ds64" if rf64 && size >= 16 && ds64.is_none() => { + if size < 28 { + return Err(AudioError::Malformed("RF64 ds64 chunk is shorter than 28 bytes".into())); + } + ds64 = Some(body); + } + // A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id. + b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true), + b"fact" if size >= 4 && fact.is_none() => fact = Some(body), + b"fmt " => block_align = Some(pcm_block_align(file, body, size)?), + _ => {} + } + pos = body + u64::from(size) + u64::from(size & 1); + } + Err(AudioError::Malformed("WAV has no data chunk".into())) +} + +/// The data size the header records: the `ds64` field of an RF64 file, else the data chunk's. +fn stored_data_len(file: &mut F, l: &Layout) -> Result> { + let mut size = [0u8; 8]; + Ok(match (l.rf64, l.ds64) { + (true, Some(at)) => read_at(file, at + 8, &mut size)?.then(|| u64::from_le_bytes(size)), + (true, None) => None, + (false, _) => read_at(file, l.data - 4, &mut size[..4])? + .then(|| u32::from_le_bytes([size[0], size[1], size[2], size[3]])) + .filter(|&s| s != u32::MAX) + .map(u64::from), + }) +} + +/// Rewrites the size fields of a WAV that ends in its data chunk for the whole frames it holds. +/// Returns the frame count and the length the file should have; bytes past it are a partial frame. +pub(crate) fn repair(file: &mut F) -> Result<(u64, u64)> { + let len = file.seek(SeekFrom::End(0))?; + let l = layout(file, len)?; + let held = len.saturating_sub(l.data); + // A finished file's own size, which also tells its pad byte from a frame of one byte. + let stored = stored_data_len(file, &l)?.filter(|&s| s % l.block_align == 0 && s.checked_add(s & 1) == Some(held)); + if stored.is_none() && l.block_align == 1 && held > 0 && held % 2 == 0 { + // The last byte may be a sample or the pad byte after an odd count of them. + return Err(AudioError::Unsupported("repairing 8-bit mono WAV data of even length: a pad byte reads as a sample".into())); + } + let frames = stored.unwrap_or(held) / l.block_align; + let data_len = frames * l.block_align; + let pad = data_len & 1; + let new_len = l.data + data_len + pad; + let riff_len = new_len - 8; + let rf64 = l.rf64 || u32::try_from(riff_len).is_err(); + let ds64 = match (rf64, l.ds64) { + (false, _) => None, + (true, Some(at)) if l.rf64 || l.junk => Some(at), + (true, _) if l.rf64 => return Err(AudioError::Malformed("RF64 file has no ds64 chunk".into())), + (true, _) => return Err(AudioError::TooLarge("WAV past 4 GiB has no room for a ds64 chunk".into())), + }; + if let Some(at) = l.fact { + write_at(file, at, &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes())?; + } + match ds64 { + Some(at) => { + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&riff_len.to_le_bytes()); + body.extend_from_slice(&data_len.to_le_bytes()); + body.extend_from_slice(&frames.to_le_bytes()); + if !l.rf64 { + // The `JUNK` chunk's last 4 bytes become the table length: no table entries. + body.extend_from_slice(&0u32.to_le_bytes()); + } + write_at(file, at, &body)?; + if !l.rf64 { + write_at(file, at - 8, b"ds64")?; + write_at(file, 0, b"RF64")?; + } + write_at(file, l.data - 4, &u32::MAX.to_le_bytes())?; + write_at(file, 4, &u32::MAX.to_le_bytes())?; + } + None => { + write_at(file, l.data - 4, &(data_len as u32).to_le_bytes())?; + write_at(file, 4, &(riff_len as u32).to_le_bytes())?; + } + } + // The pad byte goes last: until it is written, 8-bit mono data keeps an odd length that a + // repeated repair can count. + if pad == 1 { + write_at(file, l.data + data_len, &[0])?; + } + file.seek(SeekFrom::Start(new_len))?; + file.flush()?; + Ok((frames, new_len)) +} diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 2e58cd6332..803d85f293 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -1,4 +1,7 @@ -use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe}; +use craft_audio::{ + AudioBuffer, BitDepth, BwfInfo, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe, wav_float_header, + wav_float_header_with_bwf, +}; fn sine(sr: u32, channels: usize, frames: usize) -> AudioBuffer { let mut b = AudioBuffer::new(sr, channels as u16, frames); @@ -64,3 +67,335 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() { } } } + +/// A file that stopped growing before its header was rewritten: the header for 0 frames, the +/// samples of `buf`, then `extra` bytes of a frame that was never finished. +fn unfinished_wav(buf: &AudioBuffer, opts: &EncodeOptions, extra: usize) -> (Vec, Vec) { + let finished = encode(buf, opts).unwrap(); + let mut file = encode(&AudioBuffer::new(buf.sample_rate, buf.num_channels(), 0), opts).unwrap(); + let head = file.len(); + let sample_bytes = match opts.bit_depth { + BitDepth::Int16 => 2, + BitDepth::Int24 => 3, + _ => 4, + }; + let data_len = buf.frames() * usize::from(buf.num_channels()) * sample_bytes; + file.extend_from_slice(&finished[head..head + data_len]); + file.extend(std::iter::repeat_n(0x55, extra)); + (file, finished) +} + +#[test] +fn repair_wav_rewrites_the_sizes_of_an_unfinished_file() { + let bwf = BwfInfo::default().with_description("take 3").with_time_reference(48_000 * 3600); + let cases = [ + (sine(48_000, 2, 1_000), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()), 5), + // 3 bytes a frame and an odd frame count: the data needs a pad byte. + (sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf.clone()), 2), + (sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf), 0), + (sine(48_000, 6, 300), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true), 11), + (sine(48_000, 2, 0), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16), 3), + ]; + for (buf, opts, extra) in cases { + let (file, finished) = unfinished_wav(&buf, &opts, extra); + assert_ne!(file, finished); + let mut file = std::io::Cursor::new(file); + let repaired = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(repaired.frames, buf.frames() as u64); + let mut file = file.into_inner(); + assert!(file.len() as u64 >= repaired.len); + file.truncate(repaired.len as usize); + assert_eq!(file, finished, "{opts:?}"); + // A finished file stays as it is. + let mut again = std::io::Cursor::new(file.clone()); + assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired); + assert_eq!(again.into_inner(), file); + } +} + +/// A file whose data is all zeros past `head`, `len` bytes long, without holding them in memory. +struct SparseWav { + head: Vec, + len: u64, + pos: u64, +} + +impl std::io::Read for SparseWav { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = (self.len.saturating_sub(self.pos)).min(buf.len() as u64) as usize; + for (i, b) in buf[..n].iter_mut().enumerate() { + *b = self.head.get(self.pos as usize + i).copied().unwrap_or(0); + } + self.pos += n as u64; + Ok(n) + } +} + +impl std::io::Write for SparseWav { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let end = self.pos as usize + buf.len(); + if end <= self.head.len() { + self.head[self.pos as usize..end].copy_from_slice(buf); + } else { + assert!(buf.iter().all(|&b| b == 0), "only padding is written past the header"); + } + self.pos += buf.len() as u64; + self.len = self.len.max(self.pos); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl std::io::Seek for SparseWav { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + self.pos = match to { + std::io::SeekFrom::Start(p) => p, + std::io::SeekFrom::End(d) => self.len.checked_add_signed(d).unwrap(), + std::io::SeekFrom::Current(d) => self.pos.checked_add_signed(d).unwrap(), + }; + Ok(self.pos) + } +} + +#[test] +fn repair_wav_turns_a_file_past_4_gib_into_rf64() { + let frames = 600_000_000u64; // 4.8 GB of stereo float + let head = wav_float_header(48_000, 2, 0).unwrap(); + let len = head.len() as u64 + frames * 8 + 3; + let mut file = SparseWav { head: head.clone(), len, pos: 0 }; + let repaired = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!((repaired.frames, repaired.len), (frames, len - 3)); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // A JUNK chunk holding other bytes becomes a ds64 chunk with an empty table. + let mut dirty = head.clone(); + assert_eq!(&dirty[12..16], b"JUNK"); + dirty[20..48].fill(0xAA); + let mut file = SparseWav { head: dirty, len, pos: 0 }; + craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // A repair that stopped after naming the ds64 chunk but before writing RF64 finishes next time. + let mut half = head.clone(); + half[12..16].copy_from_slice(b"ds64"); + let mut file = SparseWav { head: half, len, pos: 0 }; + assert_eq!(craft_audio::repair_wav(&mut file).unwrap(), repaired); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // In a RIFF file only the chunk right after WAVE becomes ds64; a later ds64 chunk is left as it is. + let at = head.windows(4).position(|w| w == b"data").unwrap(); + let later: Vec = [&b"ds64"[..], &28u32.to_le_bytes(), &[0xBB; 28]].concat(); + let mut two = head.clone(); + two.splice(at..at, later.iter().copied()); + let mut file = SparseWav { head: two, len: len + 36, pos: 0 }; + assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, frames); + assert_eq!((&file.head[..4], &file.head[12..16]), (&b"RF64"[..], &b"ds64"[..])); + assert_eq!(file.head[at..at + 36], later[..]); + + // In an RF64 file the ds64 chunk right after WAVE takes the sizes; a later ds64 chunk is left as it is. + let finished = wav_float_header(48_000, 2, frames).unwrap(); + assert_eq!((&finished[..4], &finished[12..16]), (&b"RF64"[..], &b"ds64"[..])); + let mut stale = finished.clone(); + stale[20..44].fill(0); + stale.splice(at..at, later.iter().copied()); + let mut file = SparseWav { head: stale, len: len + 36, pos: 0 }; + let r = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!((r.frames, r.len), (frames, len + 33)); + let field = |at: usize| u64::from_le_bytes(file.head[at..at + 8].try_into().unwrap()); + assert_eq!((field(20), field(28), field(36)), (len + 25, frames * 8, frames)); + assert_eq!(file.head[at..at + 36], later[..]); + + // A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB. + let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16); + assert_eq!(&bare[12..16], b"fmt "); + let len = bare.len() as u64 + (1u64 << 32); + let mut file = SparseWav { head: bare, len, pos: 0 }; + assert!(matches!(craft_audio::repair_wav(&mut file), Err(craft_audio::AudioError::TooLarge(_)))); +} + +#[test] +fn repair_wav_writes_the_frame_count_into_the_first_fact_chunk() { + let mut file = wav_float_header(48_000, 2, 0).unwrap(); + let fact = file.windows(4).position(|w| w == b"fact").unwrap() + 8; + let at = file.windows(4).position(|w| w == b"data").unwrap(); + let later: Vec = [&b"fact"[..], &4u32.to_le_bytes(), &[0xCC; 4]].concat(); + file.splice(at..at, later.iter().copied()); + file.extend(std::iter::repeat_n(0, 100 * 8)); + let mut file = std::io::Cursor::new(file); + assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, 100); + let file = file.into_inner(); + assert_eq!(file[fact..fact + 4], 100u32.to_le_bytes()); + assert_eq!(file[at..at + 12], later[..]); +} + +#[test] +fn rf64_data_size_comes_from_the_ds64_chunk_after_wave() { + let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true); + let wav = encode(&sine(48_000, 2, 300), &opts).unwrap(); + assert_eq!(&wav[12..16], b"ds64"); + // A later ds64 chunk that gives the data 4 bytes, one frame. + let mut body = [0u8; 28]; + body[8..16].copy_from_slice(&4u64.to_le_bytes()); + let later = [&b"ds64"[..], &28u32.to_le_bytes(), &body].concat(); + let at = wav.windows(4).position(|w| w == b"data").unwrap(); + let mut two = wav.clone(); + two.splice(at..at, later); + let (info, buf) = decode(&two, Some("wav")).unwrap(); + assert_eq!((info.frames, buf.frames()), (300, 300)); + + // A 16-byte first ds64 chunk gives the reader the data size, so repair does not use the later one. + let mut short = two; + short[16..20].copy_from_slice(&16u32.to_le_bytes()); + short[28..36].copy_from_slice(&4u64.to_le_bytes()); + short[36..44].copy_from_slice(&[&b"JUNK"[..], &4u32.to_le_bytes()].concat()); + assert_eq!(decode(&short, Some("wav")).unwrap().1.frames(), 1); + let repaired = craft_audio::repair_wav(&mut std::io::Cursor::new(short)); + assert!(matches!(repaired, Err(craft_audio::AudioError::Malformed(_))), "{repaired:?}"); +} + +/// A file whose writes fail once `writes` of them have gone through. +struct FailingWrites { + file: std::io::Cursor>, + writes: usize, +} + +impl std::io::Read for FailingWrites { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + std::io::Read::read(&mut self.file, buf) + } +} + +impl std::io::Write for FailingWrites { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.writes == 0 { + return Err(std::io::Error::other("disk full")); + } + self.writes -= 1; + std::io::Write::write(&mut self.file, buf) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl std::io::Seek for FailingWrites { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + std::io::Seek::seek(&mut self.file, to) + } +} + +#[test] +fn repair_wav_runs_again_after_a_write_error() { + let mut u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8); + u8_mono.extend([0x80; 3]); + let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24); + let (int24, _) = unfinished_wav(&sine(44_100, 1, 999), &opts, 2); + for (file, frames) in [(u8_mono, 3), (int24, 999)] { + let mut whole = std::io::Cursor::new(file.clone()); + let repaired = craft_audio::repair_wav(&mut whole).unwrap(); + assert_eq!(repaired.frames, frames); + for writes in 0.. { + let mut failing = FailingWrites { file: std::io::Cursor::new(file.clone()), writes }; + if craft_audio::repair_wav(&mut failing).is_ok() { + break; + } + let mut again = failing.file; + assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired, "stopped after {writes} writes"); + assert_eq!(again.into_inner(), *whole.get_ref(), "stopped after {writes} writes"); + } + } +} + +#[test] +fn repair_wav_refuses_what_it_cannot_repair() { + use craft_audio::AudioError; + let repair = |bytes: Vec| craft_audio::repair_wav(&mut std::io::Cursor::new(bytes)); + let wav = encode(&sine(48_000, 1, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16)).unwrap(); + assert!(matches!(repair(b"not a wave file at all".to_vec()), Err(AudioError::Malformed(_)))); + // Every cut inside the header is an error, not a panic. + let data = wav.windows(4).position(|w| w == b"data").unwrap(); + for cut in 0..data + 8 { + assert!(repair(wav[..cut].to_vec()).is_err(), "cut at {cut}"); + } + // A compressed format (format tag 2, Microsoft ADPCM) has no fixed frame size to count by. + let fmt = wav.windows(4).position(|w| w == b"fmt ").unwrap() + 8; + let mut adpcm = wav.clone(); + adpcm[fmt..fmt + 2].copy_from_slice(&2u16.to_le_bytes()); + assert!(matches!(repair(adpcm), Err(AudioError::Unsupported(_)))); + // The chunk walk stops, as the reader's does, after 100,000 chunks. + let mut many = wav[..12].to_vec(); + many.extend(b"JUNK\0\0\0\0".repeat(100_001)); + many.extend_from_slice(&wav[12..]); + assert!(matches!(repair(many), Err(AudioError::Malformed(_)))); + // 8-bit mono: an even data length could end in a sample or in the pad after an odd count. + let u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8); + for (samples, ok) in [(3, true), (4, false)] { + let mut file = u8_mono.clone(); + file.extend(std::iter::repeat_n(0x80, samples)); + assert_eq!(repair(file.clone()).map(|r| r.frames).ok(), ok.then_some(3), "{samples} bytes"); + if ok { + // Once repaired, the size settles it. + let mut file = std::io::Cursor::new(file); + let r = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(repair(file.into_inner()).unwrap(), r); + } + } + // A block size that is not channels × sample bytes would count the wrong frames. + let mut odd_align = wav.clone(); + odd_align[fmt + 12..fmt + 14].copy_from_slice(&4u16.to_le_bytes()); + assert!(matches!(repair(odd_align), Err(AudioError::Malformed(_)))); + // Widths the reader does not decode: 16-bit float and 40-bit PCM, each with a block size that fits. + let mut float16 = wav.clone(); + float16[fmt..fmt + 2].copy_from_slice(&3u16.to_le_bytes()); + let mut pcm40 = wav.clone(); + pcm40[fmt + 12..fmt + 16].copy_from_slice(&[5, 0, 40, 0]); + for bad in [float16, pcm40] { + assert!(craft_audio::decode(&bad, Some("wav")).is_err()); + assert!(matches!(repair(bad), Err(AudioError::Unsupported(_)))); + } + // An extensible file whose subformat is PCM's tag under another GUID is not PCM. + let ext = encode(&sine(48_000, 2, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap(); + let fmt = ext.windows(4).position(|w| w == b"fmt ").unwrap() + 8; + assert!(repair(ext.clone()).is_ok()); + let mut other_guid = ext.clone(); + other_guid[fmt + 39] ^= 0xFF; + assert!(matches!(repair(other_guid), Err(AudioError::Unsupported(_)))); + // Extensible fields the reader refuses: a cbSize below 22 and more valid bits than the sample holds. + let mut short_cb = ext.clone(); + short_cb[fmt + 16..fmt + 18].copy_from_slice(&21u16.to_le_bytes()); + let mut wide_valid = ext.clone(); + wide_valid[fmt + 18..fmt + 20].copy_from_slice(&25u16.to_le_bytes()); + for bad in [short_cb, wide_valid] { + assert!(craft_audio::decode(&bad, Some("wav")).is_err()); + assert!(matches!(repair(bad), Err(AudioError::Malformed(_)))); + } + // The Ambisonic PCM subformat {00000001-0721-11D3-8644-C8C1CA000000}, which the reader reads as PCM. + let mut ambisonic = ext; + ambisonic[fmt + 26..fmt + 40].copy_from_slice(&[0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]); + assert_eq!(repair(ambisonic).unwrap().frames, 100); +} + +#[test] +fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() { + let take = sine(48_000, 2, 1_000); + let bwf = BwfInfo::default() + .with_description("take 3") + .with_originator("recorder") + .with_origination("2026-11-20", "18:30:00") + .with_time_reference(48_000 * 66_600); + let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); + let len = file.len(); + assert!(len > wav_float_header(48_000, 2, 0).unwrap().len()); + file.extend(take.interleaved().iter().flat_map(|s| s.to_le_bytes())); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 600, &bwf).unwrap()); + let (info, decoded) = decode(&file, None).unwrap(); + assert_eq!((info.bwf.as_ref(), decoded.frames()), (Some(&bwf), 600)); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 1_000, &bwf).unwrap()); + let opts = EncodeOptions::default().with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()); + assert_eq!(file, encode(&take, &opts).unwrap()); + let big = wav_float_header_with_bwf(48_000, 2, 600_000_000, &bwf).unwrap(); + assert_eq!((&big[..4], big.len()), (&b"RF64"[..], len)); + assert!(wav_float_header_with_bwf(48_000, 0, 0, &bwf).is_err()); +} diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index 46687dae3b..8a767ddd21 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -103,10 +103,8 @@ fn an_unasked_line_makes_the_connection_unusable_before_sending() { let mut client = ControlClient::connect(addr, TOKEN).unwrap(); assert!(client.is_usable(), "an idle connection with nothing pending is usable"); said.send(()).unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while client.is_usable() && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(5)); - } + // A blocking peek (under the client's read timeout) returns once the line has arrived. + assert!(client.stream.peek(&mut [0]).unwrap() > 0, "the unasked line arrived"); assert!(!client.is_usable(), "the unasked line makes the connection unusable"); assert_eq!(client.call("next", json!({})), Err("connection closed".to_string())); assert!(client.is_broken(), "the unusable connection is closed"); diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 8e75f07ecd..180a331752 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -487,20 +487,40 @@ pub fn configure_stream(stream: &std::net::TcpStream) -> std::io::Result<()> { stream.set_write_timeout(Some(IO_TIMEOUT)) } +/// The time an [`AuthDeadlineStream`] reads its deadline against: [`Instant::now`] in a server, or a time a test sets +/// by hand. +pub type DeadlineClock = std::sync::Arc Instant + Send + Sync>; + +/// The real clock, [`Instant::now`]. +pub fn real_clock() -> DeadlineClock { + std::sync::Arc::new(Instant::now) +} + /// A read wrapper that fails once [`AUTH_DEADLINE`] passes without [`Self::authenticated`] being /// called, whatever the client sends meanwhile; after that only [`IO_TIMEOUT`] applies. -#[derive(Debug)] pub struct AuthDeadlineStream { inner: std::net::TcpStream, deadline: Option, + clock: DeadlineClock, +} + +impl std::fmt::Debug for AuthDeadlineStream { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AuthDeadlineStream").field("inner", &self.inner).field("deadline", &self.deadline).finish_non_exhaustive() + } } impl AuthDeadlineStream { /// Wraps `inner`; reads fail once `auth_deadline` has passed unauthenticated. pub fn new(inner: std::net::TcpStream, auth_deadline: Duration) -> Self { + Self::with_clock(inner, auth_deadline, real_clock()) + } + + /// [`Self::new`] with the deadline read against `clock` instead of the real clock. + pub fn with_clock(inner: std::net::TcpStream, auth_deadline: Duration, clock: DeadlineClock) -> Self { // A limit too large to represent expires at once rather than never. - let now = Instant::now(); - Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)) } + let now = clock(); + Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)), clock } } /// The handshake succeeded: lift the deadline and restore the idle timeout. @@ -513,7 +533,7 @@ impl AuthDeadlineStream { impl std::io::Read for AuthDeadlineStream { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { if let Some(deadline) = self.deadline { - let left = deadline.saturating_duration_since(Instant::now()); + let left = deadline.saturating_duration_since((self.clock)()); if left.is_zero() { return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "not authenticated in time")); } diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index 2716fc24c2..2d3625c0a7 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -170,6 +170,37 @@ fn server_token_sources_and_validation() { ); } +// An unauthenticated connection's reads succeed while its deadline is ahead, however much it sends, and fail once the +// deadline has passed even with input waiting; after `authenticated` the deadline no longer applies. +#[trial] +fn the_authentication_deadline_holds_whatever_the_client_sends() { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (server, _) = listener.accept().unwrap(); + server.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let start = Instant::now(); + let at = std::sync::Arc::new(std::sync::Mutex::new(start)); + let read_at = std::sync::Arc::clone(&at); + let clock: DeadlineClock = std::sync::Arc::new(move || *read_at.lock().unwrap()); + let mut stream = AuthDeadlineStream::with_clock(server.try_clone().unwrap(), Duration::from_secs(10), clock); + let mut byte = [0]; + // Blank lines and partial frames, each read while the deadline is ahead. + for (step, sent) in [b"\n", b" ", b"{", b"\n"].into_iter().enumerate() { + *at.lock().unwrap() = start + Duration::from_secs(3 * step as u64); + client.write_all(sent).unwrap(); + assert_eq!(stream.read(&mut byte).unwrap(), 1, "read {step} is before the deadline"); + } + *at.lock().unwrap() = start + Duration::from_secs(10); + client.write_all(b"\n").unwrap(); + let late = stream.read(&mut byte).unwrap_err(); + assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "the input sent did not move the deadline: {late}"); + + stream.authenticated().unwrap(); + *at.lock().unwrap() = start + Duration::from_secs(60); + assert_eq!(stream.read(&mut byte).unwrap(), 1, "an authenticated connection reads past the deadline"); +} + // A token file create that runs out of time fails with its own error, even when it left a file at // the path: that file is not read as another process's. A create that another process beat to the // path reads that process's token. diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index c6808156d7..e913cf3b4c 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -16,8 +16,8 @@ use serde_json::{Value, json}; use crate::control::{ControlRequest, REPLY_DEADLINE}; use crate::protocol::write_reply; use crate::security::{ - AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream, - read_bounded_line, repeat_auth_reply, + AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, DeadlineClock, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, + configure_stream, read_bounded_line, real_clock, repeat_auth_reply, }; /// A running control server. Dropping it stops accepting connections and returns once the port is @@ -72,6 +72,36 @@ pub fn serve_with_deadline( host: WindowHost, auth_deadline: Duration, ) -> std::io::Result<(Receiver, Listening)> { + serve_with(listener, token, host, ServeOptions { auth_deadline, ..ServeOptions::default() }) +} + +/// What a test sets on a server [`serve_with`] starts. +#[doc(hidden)] +pub struct ServeOptions { + /// How long a connection has to authenticate ([`AUTH_DEADLINE`] in [`serve`]). + pub auth_deadline: Duration, + /// The clock the authentication deadline is read against. + pub clock: DeadlineClock, + /// Sent `()` each time a connection has ended: its request sender is dropped and its place under + /// [`MAX_CONNECTIONS`] is free again. + pub ended: Option>, +} + +impl Default for ServeOptions { + fn default() -> Self { + Self { auth_deadline: AUTH_DEADLINE, clock: real_clock(), ended: None } + } +} + +/// [`serve`] with the authentication deadline, its clock and a signal for each ended connection set by a test. +#[doc(hidden)] +pub fn serve_with( + listener: TcpListener, + token: String, + host: WindowHost, + options: ServeOptions, +) -> std::io::Result<(Receiver, Listening)> { + let ServeOptions { auth_deadline, clock, ended } = options; let (tx, rx) = channel::(); let addr = listener.local_addr()?; // `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept @@ -95,13 +125,19 @@ pub fn serve_with_deadline( let tx = tx.clone(); let host = host.clone(); let token = Arc::clone(&token); + let clock = Arc::clone(&clock); + let ended = ended.clone(); std::thread::spawn(move || { - serve_connection(stream, &token, &tx, &host, auth_deadline); + serve_connection(stream, &token, &tx, &host, auth_deadline, clock); + drop(tx); // What the last client held down would otherwise stay held with no one left to // release it; while another connection is live, its input is left alone. if permit.release() { host.end_injection(); } + if let Some(ended) = ended { + let _ = ended.send(()); + } }); } })?; @@ -110,12 +146,12 @@ pub fn serve_with_deadline( /// Serve one connection: it must authenticate ([`ServerHandshake`]) within `auth_deadline` of /// connecting, however much it sends meanwhile; after that only the idle timeout applies. -fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration) { +fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration, clock: DeadlineClock) { if configure_stream(&stream).is_err() { return; } let Ok(read) = stream.try_clone() else { return }; - let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline)); + let mut reader = BufReader::new(AuthDeadlineStream::with_clock(read, auth_deadline, clock)); let mut out = stream; let mut line = String::new(); let mut handshake = ServerHandshake::new(); diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 6cca4325a2..9238151b96 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -3,8 +3,8 @@ use std::net::TcpListener; use std::path::PathBuf; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, mpsc}; use std::time::Duration; use craft_automation::agents::AgentLinkStatus; @@ -17,7 +17,6 @@ use craft_automation::ui::agents::AgentsPage; use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles}; use craft_ui::contract::Role; use craft_ui::patterns::preferences::SettingsDraft; -use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use craft_ui::testing::Fixture; use craft_ui::testing::trial; @@ -29,16 +28,40 @@ fn temp_dir(tag: &str) -> tempfile::TempDir { tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") } -/// Waits up to five seconds for `done`. -fn wait_for(mut done: impl FnMut() -> bool) -> bool { - let started = motion::now(); - while !done() { - if started.elapsed() > Duration::from_secs(5) { - return false; +/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns once the thread has +/// finished it and waits for the next. +struct Ticks { + tick: mpsc::SyncSender<()>, + waiting: mpsc::Receiver<()>, +} + +impl Ticks { + /// The clock and the `tick` to give [`AgentSwitch::watch_with`]. + fn new() -> (Self, impl FnMut() -> bool + Send + 'static) { + let (tick, ticks) = mpsc::sync_channel(0); + let (waits, waiting) = mpsc::channel(); + let wait = move || { + let _ = waits.send(()); + ticks.recv().is_ok() + }; + (Self { tick, waiting }, wait) + } + + /// Blocks until the watch thread waits for its next poll; `false` once the thread has ended. + fn waiting(&self) -> bool { + // A hang guard only: the thread answers at once, so the limit is never reached by a run that works. + match self.waiting.recv_timeout(Duration::from_secs(60)) { + Ok(()) => true, + Err(mpsc::RecvTimeoutError::Disconnected) => false, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"), } - std::thread::sleep(Duration::from_millis(5)); + } + + /// Runs one poll; `false` when the thread ended in it instead of waiting for the next one. + fn poll(&self) -> bool { + self.tick.send(()).unwrap(); + self.waiting() } - true } /// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. @@ -52,8 +75,8 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() { assert!(!AgentSwitch::fixed(false, true).allows(false)); } -/// The switch follows the launcher's list within a poll, wakes the app once per change rather than once per poll, and -/// its thread ends once the last clone is dropped. +/// The switch follows the launcher's list at the next poll, wakes the app once per change rather than once per poll, +/// and its thread ends at the first poll after the last clone is dropped. #[trial] fn the_switch_wakes_once_per_change() { let launcher = Arc::new(AtomicBool::new(false)); @@ -72,28 +95,35 @@ fn the_switch_wakes_once_per_change() { wakes.fetch_add(1, Ordering::Relaxed); } }; - let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let (ticks, tick) = Ticks::new(); + let switch = AgentSwitch::watch_with(true, probe, tick, wake); let clone = switch.clone(); + assert!(ticks.waiting()); assert!(!switch.launcher()); + assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start"); launcher.store(true, Ordering::Relaxed); - assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(ticks.poll()); + assert!(clone.launcher(), "the switch follows the launcher"); assert!(switch.allows(false)); // Many polls with nothing changed. - let polled = probes.load(Ordering::Relaxed); - assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + for _ in 0..10 { + assert!(ticks.poll()); + } + assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll"); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll"); launcher.store(false, Ordering::Relaxed); - assert!(wait_for(|| !switch.launcher())); - assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert!(ticks.poll()); + assert!(!switch.launcher()); assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); drop(switch); + assert!(ticks.poll(), "a clone keeps the watch"); drop(clone); - // The thread sees the switch gone at its next poll and stops probing. - std::thread::sleep(Duration::from_millis(50)); - let after_drop = probes.load(Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(50)); - assert_eq!(probes.load(Ordering::Relaxed), after_drop, "the watch ended with the last switch"); + // The thread probes once more, sees the switch gone and ends, so nothing probes after it. + assert!(!ticks.poll(), "the watch ended with the last switch"); + assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended"); + assert_eq!(wakes.load(Ordering::Relaxed), 2); } /// A published connection reads back in its documented shape, and only the process that wrote it removes it. diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index 913d02d16a..6e1dc700fc 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -2,14 +2,15 @@ use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; -use std::sync::mpsc::{Receiver, channel}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use craft_automation::client::ControlClient; use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error}; use craft_automation::protocol::MAX_RESPONSE_BYTES; use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; -use craft_automation::server; +use craft_automation::server::{self, ServeOptions}; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use craft_ui::testing::trial; @@ -101,39 +102,90 @@ fn host() -> WindowHost { /// sent is dispatched. #[trial] fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { - // A short deadline, so the test does not wait out the real one. - let deadline = Duration::from_millis(400); - let listener = TcpListener::bind("127.0.0.1:0").expect("bound"); - let (rx, server) = server::serve_with_deadline(listener, TOKEN.into(), host(), deadline).expect("started"); - // Blank lines and partial frames, one byte every 20 ms: each read succeeds long before the idle timeout. + let start = motion::now(); + let at = Arc::new(Mutex::new(start)); + let read_at = Arc::clone(&at); + let (ended, connection_ended) = channel(); + // Each read of the clock is announced, so the test moves it only after the connection has set its deadline. + let (read, clock_read) = channel(); + let clock = Arc::new(move || { + let now = *read_at.lock().expect("the clock"); + let _ = read.send(()); + now + }); + let options = ServeOptions { auth_deadline: Duration::from_secs(10), clock, ended: Some(ended) }; + let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); let mut stream = TcpStream::connect(server.addr).expect("connected"); - let started = motion::now(); - let mut closed = false; - for i in 0..1000 { - let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " }; - if stream.write_all(byte).is_err() { - closed = true; - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - let served = started.elapsed(); - assert!(closed, "the trickle did not keep the connection open"); - assert!(served < deadline + Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}"); - assert!(rx.try_recv().is_err(), "nothing was dispatched"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + clock_read.recv_timeout(Duration::from_secs(5)).expect("the connection set its deadline"); + // Blank lines and the start of a line, sent while the deadline is ahead: none is a frame the handshake refuses. + stream.write_all(b"\n \n ").expect("written"); + *at.lock().expect("the clock") = start + Duration::from_secs(10); + // The server may already have closed when this is written; if not, it wakes the server's read. + let _ = stream.write_all(b" "); + assert!(is_closed(&mut reader), "the input sent did not keep the connection open past the deadline"); + assert!(nothing_more_dispatched(&rx, server, &connection_ended, 1), "nothing was dispatched"); } -/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error. +/// Whether the server closed the connection: the next read is the end of the stream, or an error other than a timeout. +/// A server that closes with input still unread makes the kernel send a reset, so the read fails with +/// `ConnectionReset` or `ConnectionAborted` instead of returning the end of the stream (mostly on Windows). fn is_closed(reader: &mut impl BufRead) -> bool { let mut line = String::new(); - matches!(reader.read_line(&mut line), Ok(0)) + match reader.read_line(&mut line) { + Ok(read) => read == 0, + Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), + } +} + +/// A reader whose every read fails with the given error kind. +struct Failing(std::io::ErrorKind); + +impl std::io::Read for Failing { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(self.0.into()) + } +} + +/// A reset or aborted connection counts as closed; a read timeout does not. +#[trial] +fn a_reset_connection_counts_as_closed() { + use std::io::ErrorKind::{ConnectionAborted, ConnectionReset, TimedOut, WouldBlock}; + assert!(is_closed(&mut BufReader::new(Failing(ConnectionReset))), "a reset is a close"); + assert!(is_closed(&mut BufReader::new(Failing(ConnectionAborted))), "an abort is a close"); + assert!(!is_closed(&mut BufReader::new(Failing(TimedOut))), "a timeout is not a close"); + assert!(!is_closed(&mut BufReader::new(Failing(WouldBlock))), "a timeout is not a close"); +} + +/// A server whose `ended` receiver gets `()` each time one of its connections has ended. Its clock stands still, so no +/// connection reaches the authentication deadline: only the client or a refusal ends one. The frozen clock does not +/// stop the socket's read timeout, which runs on real time and is the time left to the deadline capped at the idle +/// timeout. The deadline is a minute, so a waiting connection's read times out after the 30-second idle timeout +/// instead of after 10 seconds. +fn serve_counting_ends() -> (Receiver, server::Listening, Receiver<()>) { + let (ended, connection_ended) = channel(); + let start = motion::now(); + let options = ServeOptions { auth_deadline: Duration::from_secs(60), clock: Arc::new(move || start), ended: Some(ended) }; + let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); + (rx, server, connection_ended) +} + +/// Stops `server` and waits for its `connections` connections to end, so the request receiver `rx` is disconnected +/// once every request that reached it has been taken: `rx` then answers whether anything more was dispatched. +fn nothing_more_dispatched(rx: &Receiver, server: server::Listening, ended: &Receiver<()>, connections: usize) -> bool { + drop(server); + for _ in 0..connections { + ended.recv_timeout(Duration::from_secs(5)).expect("a connection ended"); + } + rx.recv_timeout(Duration::from_secs(5)).err() == Some(RecvTimeoutError::Disconnected) } /// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of /// the open ones ends, its place serves a new connection. #[trial] fn connections_past_the_limit_are_refused_with_the_reason() { - let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (rx, server, ended) = serve_counting_ends(); let connect = || { let stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); @@ -150,20 +202,14 @@ fn connections_past_the_limit_are_refused_with_the_reason() { drop(open.pop()); // The server frees the place when it reads the close; a new connection is served once it has. - let started = motion::now(); - let served = loop { - let (mut stream, mut reader) = connect(); - writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); - let reply = read_json(&mut reader).expect("a reply"); - if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) { - break reply; - } - assert_eq!(reply["error"], "connection limit reached", "{reply}"); - std::thread::sleep(Duration::from_millis(20)); - }; + ended.recv_timeout(Duration::from_secs(5)).expect("the closed connection ended"); + let (mut stream, mut reader) = connect(); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); + let served = read_json(&mut reader).expect("a reply"); assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}"); - assert!(rx.try_recv().is_err(), "nothing was dispatched"); + drop((stream, reader)); drop(open); + assert!(nothing_more_dispatched(&rx, server, &ended, MAX_CONNECTIONS), "nothing was dispatched"); } /// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the @@ -191,9 +237,8 @@ fn a_refused_first_frame_closes_the_connection() { /// and the connection closed, so neither the body's `auth` nor a request after it reaches the app. #[trial] fn a_browser_post_never_reaches_the_app() { - // Far longer than the trial, so the close comes from the refusal, not the deadline. - let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) - .expect("started"); + // The server's clock stands still, so the close comes from the refusal, not the deadline. + let (rx, server, ended) = serve_counting_ends(); let mut stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); @@ -211,7 +256,8 @@ fn a_browser_post_never_reaches_the_app() { Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), }; assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}"); - assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app"); + drop((stream, reader)); + assert!(nothing_more_dispatched(&rx, server, &ended, 1), "nothing reached the app"); } /// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed. @@ -325,19 +371,19 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() { let mut client = ControlClient::connect(addr, TOKEN).expect("connected"); capture_state(&mut client, &client_doc, &client_doc["states"][0], "new") }); - let mut channel = ControlChannel::new(requests); + // Each request is waited for as it arrives and then taken through the channel, as the app's frame takes it. + let (forward, forwarded) = channel(); + let mut channel = ControlChannel::new(forwarded); let mut seen: Vec = Vec::new(); - let started = motion::now(); - while seen.len() < 4 && started.elapsed() < Duration::from_secs(10) { - while let Some(req) = channel.next_request() { - seen.push(format!("{} {}", req.method, req.params)); - let reply = match req.method.as_str() { - "ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))), - _ => Reply::from_result(Ok(Value::Null)), - }; - channel.settle(req, reply, None, 0.0); - } - std::thread::sleep(Duration::from_millis(5)); + while seen.len() < 4 { + forward.send(requests.recv_timeout(Duration::from_secs(10)).expect("a request")).expect("forwarded"); + let req = channel.next_request().expect("the forwarded request is dispatched"); + seen.push(format!("{} {}", req.method, req.params)); + let reply = match req.method.as_str() { + "ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))), + _ => Reply::from_result(Ok(Value::Null)), + }; + channel.settle(req, reply, None, 0.0); } let reply = client.join().expect("client ran").expect("the capture replied"); assert_eq!( @@ -440,12 +486,12 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() { /// and shut its end down) still reaches the app and is answered: a client cannot know it was dropped. #[trial] fn a_complete_json_request_at_eof_can_reach_the_app() { - let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (rx, server, ended) = serve_counting_ends(); let handler = std::thread::spawn(move || { let req = rx.recv_timeout(Duration::from_secs(5)).expect("the request reached the app"); assert_eq!(req.method, "test.once"); req.reply.send(json!({"ok": true, "result": "once"})).expect("replied"); - assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "it ran exactly once"); + rx }); let (mut stream, mut reader) = authenticated(server.addr); stream.write_all(json!({"id": 3, "method": "test.once"}).to_string().as_bytes()).expect("written"); @@ -454,7 +500,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() { assert_eq!((&reply["id"], &reply["result"]), (&json!(3), &json!("once"))); let mut rest = String::new(); assert_eq!(reader.read_line(&mut rest).expect("closed, not timed out"), 0, "closed after the last request: {rest:?}"); - handler.join().expect("handler ran"); + let rx = handler.join().expect("handler ran"); + assert!(nothing_more_dispatched(&rx, server, &ended, 1), "it ran exactly once"); } /// Ported from WordCraft (#7317). Connections that never authenticate cannot fill the server: past the limit a new @@ -462,9 +509,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() { #[trial] fn idle_unauthenticated_connections_are_limited() { use craft_automation::security::MAX_CONNECTIONS; - // Far longer than the trial, so only the limit refuses. - let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) - .expect("started"); + // The server's clock stands still, so only the limit refuses. + let (rx, server, ended) = serve_counting_ends(); let idle: Vec = (0..MAX_CONNECTIONS).map(|_| TcpStream::connect(server.addr).expect("connected")).collect(); // Admission is counted by the accept thread: it is done once the next connection is answered. let refused = |addr| { @@ -477,18 +523,14 @@ fn idle_unauthenticated_connections_are_limited() { assert!(reply["error"].as_str().is_some_and(|e| e.contains("limit")), "{reply}"); drop(idle); // The freed slots go back as the closed connections are noticed. - let started = motion::now(); - loop { - let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); - let mut reader = BufReader::new(stream.try_clone().expect("cloned")); - // A refused connection may already be closed when the request is written (Windows resets it). - let auth = json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}}); - if writeln!(stream, "{auth}").is_ok() && read_json(&mut reader).is_some_and(|r| r["ok"] == true) { - break; - } - assert!(started.elapsed() < Duration::from_secs(10), "no slot came back"); - std::thread::sleep(Duration::from_millis(50)); + for _ in 0..MAX_CONNECTIONS { + ended.recv_timeout(Duration::from_secs(5)).expect("a closed connection ended"); } - assert!(rx.try_recv().is_err()); + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written"); + assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true, "a freed slot is admitted again"); + drop((stream, reader)); + assert!(nothing_more_dispatched(&rx, server, &ended, 1)); } diff --git a/crates/behavior/src/geometry/crop.rs b/crates/behavior/src/geometry/crop.rs index 7fa0422777..4704686970 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -544,7 +544,7 @@ const INV_PHI: f64 = 0.618_033_988_749_894_9; const PHI: f64 = 1.0 + INV_PHI; /// The composition guide drawn inside a crop frame, in Photoshop's menu order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropGuide { @@ -727,7 +727,7 @@ fn golden_spiral() -> Vec<[f64; 2]> { } /// When the guide shows. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum GuideShow { diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index e83b868ce2..4251b79efb 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -351,7 +351,9 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { 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()) { + if !first_lines.is_empty() + && head.lines().map(str::trim_start).filter(|line| !line.trim().is_empty()).take(3).all(|line| vplayer::split_line(line).is_some()) + { return Some(Format::VPlayer); } if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { diff --git a/crates/captions/src/vplayer.rs b/crates/captions/src/vplayer.rs index 169e4f24a0..bcc834f58a 100644 --- a/crates/captions/src/vplayer.rs +++ b/crates/captions/src/vplayer.rs @@ -49,7 +49,7 @@ pub fn parse(text: &str) -> Result { if line.trim().is_empty() { continue; } - match split_line(line.trim()) { + match split_line(line.trim_start()) { 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"))); @@ -121,6 +121,38 @@ pub fn write(doc: &Document) -> String { mod tests { use super::*; + #[test] + fn empty_clearing_lines_keep_each_separator() { + for separator in [":", "=", " "] { + for indent in ["", " \t"] { + let input = format!("{indent}00:00:01{separator} hello \n{indent}00:00:02{separator} \n"); + assert_eq!(crate::detect(input.as_bytes(), None), Some(crate::Format::VPlayer), "{input:?}"); + let doc = parse(&input).unwrap(); + assert_eq!(doc.cues.len(), 1, "{input:?}"); + assert_eq!(doc.cues[0].text, "hello", "{input:?}"); + assert_eq!(doc.cues[0].end, ms_to_tick(2000), "{input:?}"); + assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); + } + } + } + + #[test] + fn detection_keeps_clearing_lines_at_each_sampled_position() { + for separator in [":", "=", " "] { + for at in 0..3 { + let mut lines = ["00:00:01=one".to_owned(), "00:00:02=two".to_owned(), "00:00:03=three".to_owned()]; + lines[at] = format!(" \t00:00:0{}{separator} \t", at + 1); + let input = format!("\u{feff}\n \t\n{}\n", lines.join("\n")); + let format = crate::detect(input.as_bytes(), None).unwrap(); + assert_eq!(format, crate::Format::VPlayer, "{input:?}"); + let document = crate::parse(input.as_bytes(), format).unwrap(); + assert_eq!(document.cues.len(), 2, "{input:?}"); + assert!(document.warnings.is_empty(), "{:?}", document.warnings); + } + } + assert_eq!(crate::detect(b"00:00:01 hello\n00:00:02\n", None), None); + } + #[test] fn short_duration_cue_preserves_positive_duration_on_write_and_read() { let mut doc = Document::default(); diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 8200a763f6..e29d443fea 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -2,7 +2,7 @@ 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. The `.cmx` writer -(`src/cmx_write.rs`) writes in them, with R74 for what only it needs ("Written fields" lists each +(`src/cmx_write.rs`) writes in them, with R74 and R77 for what only it needs ("Written fields" lists each field it sets). Code cites a row by its id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here. @@ -56,9 +56,16 @@ Sources: https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs, was read for the order of fields that the notes do not spell out (the table entries, the rendering attributes and the curve body); no code was copied from it +- **LC**: the `.cmx` reader of libcdr (MPL-2.0), `src/lib/CMXParser.cpp`, `src/lib/CMXParser.h` + and `src/lib/CMXDocumentStructure.h` at commit `b5211a57af37dac59a04f6041822a07f4a7cf7d6`, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.cpp, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.h + and https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXDocumentStructure.h, + read for the header's offsets, the index chunks and the fields of a color entry; no code was + copied from it Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks -confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; +confirmed that no CX file shows), `public-reader` (a layout LC reads), `unconfirmed` (a point no source states and no sample file shows; listed so it can be checked against a file, with what the reader does when it is wrong). The "Written fields" table also uses `own` (a value the reader does not read, set as the synthetic test files of `src/synth_cmx.rs` set it) and `the writer's choice` (a value the reader does not read and @@ -129,7 +136,7 @@ file is committed. | 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) | +| 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`); LC `CMXParser.cpp` L1698-L1749 (a file with 32-bit coordinates: the model byte and a byte in tag 1, the values in tag 2, other tags passed over), L2254-L2371 (the values of each model: 2 and 3 four bytes, 5 red, green and blue, 9 one byte), `CMXDocumentStructure.h` L138-L139 (the tags); S: every color of the nine CX files is model 2 in the older fields, with the second byte of field 1 5 | sample (model 2), public-reader (the tags and the values of models 2, 5 and 9), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | | R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | | R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample | | R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | @@ -148,24 +155,26 @@ file is committed. | 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) | | R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample | +| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `cont` bytes 96 to 112 hold four i32 edges, the same bytes as the edges in the page's begin-page record, and bytes 112 to 116 a u32, the page's instruction count as begin page holds it. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none; four coordinates after them, read only for a debug message), L1011-L1019 (the four coordinates of a box), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; in each of the 9 files, `cont` bytes 96 to 116 match its one page's edges and instruction count; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records, the header's edges and instruction count), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) | ## Written fields `src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table lists every field it sets. `own` marks a value the reader does not read, which the writer sets as -the synthetic test files of `src/synth_cmx.rs` set it. The header's offsets at bytes 84 to 95, the -index chunks (`LIST indx`), the instruction counts and file offsets that the CX files also keep in -their page, layer and group records, and the bounds they keep in layer and group records are not -written: no public source describes -them, and the reader finds every chunk by its id and walks the instructions in order. +the synthetic test files of `src/synth_cmx.rs` set it. | Field written | Rows | Status | |---|---|---| | The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample | -| Chunk order: `cont`, the `page` chunks, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr` | R53 | own (the reader finds each chunk by its id) | +| Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) | | `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample | +| `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) | +| `cont`: the first page's edges at bytes 96 to 112 and its instruction count at bytes 112 to 116, as its begin-page record holds them; zeros for a file with no page | R77 | sample (one page), the writer's choice (the first page of several, and zeros) | | `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own | +| `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) | +| `rlst` for each page: its layers' numbers | R77 | sample | | Table counts and field lists | R55 | sample | +| `rclr` fields 1 and 2, before field 10: the model and 5, then four value bytes; model 2 (CMYK in percent), 5 (red, green, blue, then 0) and 9 (gray, then three zero bytes); a spot color as model 5 with its look at its tint, and the registration color as model 2 with four values of 100 | R56 | sample (the fields, model 2 and the 5), public-reader (models 5 and 9), the writer's choice (the models of spot and registration colors, the zero bytes and the order of the fields) | | `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) | | `rpen` field 1: the width | R57 | public-notes | | `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own | @@ -177,9 +186,11 @@ them, and the reader finds every chunk by its id and walks the instructions in o | `rscr`: one screen entry, its field 1 as the sample files write it | R74 | sample | | Instructions in the short form, and the long form past 65,534 bytes | R60 | sample (short form), public-notes (long form) | | Begin page, field 1: the page number (from 1), a u32 of 0, the left, top, right and bottom edges of the page's curves (of the page around its center when it has none; all 0 for a page without a size) | R61 | sample (page number 1, the edges), own (the later numbers, the edges of a page with no curves or no size) | +| Begin page, field 1 after the edges: the offset of the end-page instruction, the layer count and the instruction count | R77 | sample | | Begin page, field 4: the page's width and height | R61 | public-notes | -| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 8 zero bytes, then the name as a u16 byte count and 8-bit characters | R62 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the name), own (the 8 bytes) | +| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 4 zero bytes, the layer's instruction count, then the name as a u16 byte count and 8-bit characters | R62, R77 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the count; the name), own (the 4 bytes) | | Begin layer, field 4: the name as a u32 count of UTF-16 code units and the units | R62 | public-notes | -| Begin group with field 1 of 26 zero bytes; end layer, group and page with no fields | R60 | own (the bodies are not read) | +| Begin group, field 1: the edges of the group's curves as the page's are measured (all 0 for a group with none), the groups directly inside it, its instruction count and the offset of the instruction after its end | R77 | sample (the counts and the offset), public-reader (the order), the writer's choice (the edges where they differ from the points' edges, as for a page) | +| End layer, group and page with no fields | R60 | own (the bodies are not read) | | Curve, field 1: rendering attributes with a uniform fill (type 1, the color entry, screen entry 1) and an outline entry | R63, R74 | sample (the uniform fills of `bars.cmx`, `balloon.cmx` and `PC.CMX` name screen 1) | | Curve, field 2: the point count, the points as i32 and a type byte each, bit 2 set on every move, line and curve end node and clear on control points, bit 3 on the first and last nodes of a closed subpath that fits in one curve; a closed subpath cut into open pieces gets a line back to its start added when its last point is elsewhere; at most 7,281 points | R16, R62 | sample (the layout), own (bit 2 on the nodes the synthetic files set it on), the writer's choice (bit 2 on a closing node, which the synthetic files leave clear) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index e4d2033ffa..0bf2c8e8f8 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -107,12 +107,17 @@ corners, not stretched ones. Hidden layers, groups and shapes, guide and grid la and master layers are left out; opacity, blend modes, fill rules and locked states are not written, desktop layers are written as drawing layers, and a spot color with no name opens as a process color; every use of a named spot color takes the look of its use at the strongest tint -among the uses whose look is known. +among the uses whose look is known. Each color entry holds the color twice: as the property list +`read_cmx` reads, and as the model and value fields that other readers, such as libcdr, read. In +those fields a spot color is written as its look at its tint, and the registration color as 100 +percent cyan, magenta, yellow and black. `write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than 65,535 pages, layers on a page or different colors, pens, line types, dash patterns or outlines, a -dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, more chunks, +dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, a depth limit +of 0 (at which `read_cmx` leaves out the index list), more than 65,535 groups directly inside one +group, more chunks, objects, coordinates or dashes than a read within the limits takes, a file longer than their input size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes rounded to whole outline widths, nonzero fills that may fill differently, names that open @@ -120,12 +125,14 @@ shortened, spot colors at a tint too low to keep their look, with no name or wit (written black), uses of one ink with different looks, and what was left out or written opaque, unclipped or unlocked. -The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets -inside page, layer and group records, and the bounds inside layer and group records are not -written, so a reader must find the chunks by their ids and walk the instructions in order, as -`read_cmx` does. The record of a page with a size holds the edges of its curves, or of the page -when it has none. `PROVENANCE.md`'s "Written -fields" table lists every field the `.cmx` writer sets. +The file holds an index, so that a reader that finds the tables and pages through it, rather than +by their chunk ids, opens it: the header gives where the master index starts, the index list +(`LIST indx`) gives where each table, page, page reference list and layer starts, and the page, +layer and group records give their instruction counts. A page's record also gives where its +end-page instruction starts, and a group's record gives where the instruction after its end-group +instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or +of the page when it has none. The header repeats the first page's edges and instruction count. +`PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets. ## Writing diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs index 69de039cc1..a5c6e00058 100644 --- a/crates/cdr/src/cmx_write.rs +++ b/crates/cdr/src/cmx_write.rs @@ -2,8 +2,8 @@ //! reads: the RIFF form `CMX1` (R53), its header (R54), the color, pen, line type, dash, outline and //! arrowhead tables (R55 to R59), the screen table (R74) and one `page` chunk of instructions for //! each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills and outlines -//! (R63). `PROVENANCE.md`'s "Written fields" lists every field the writer sets and where its layout -//! comes from. +//! (R63), and the index that gives where each of them starts (R77). `PROVENANCE.md`'s "Written +//! fields" lists every field the writer sets and where its layout comes from. //! //! Rectangles and ellipses are written as curves. A clipping container is written as a group of //! its fill, the objects it clips, unclipped, and its outline. Hidden layers, groups and shapes, @@ -130,28 +130,58 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result children.push(c); Ok(()) }; - add(chunk(b"cont", &cont())?)?; - for (n, page) in drawing.pages.iter().enumerate() { - add(w.page(n, page.size.or(drawing.page_size), &page.layers)?)?; + // The header's index offset is set once the index is placed. + add(chunk(b"cont", &cont(0, PageHead::default()))?)?; + // Each page chunk and its reference list, with where they start in the file and the start and + // name of each of the page's layers. + let mut pages = Vec::new(); + let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> { + let at = w.file_bytes; + let (c, written, head) = w.page(n, size, layers)?; + add(c)?; + let refs = w.file_bytes; + let r = chunk(b"rlst", &reference_list(written.len()))?; + w.check_bytes(r.len())?; + w.file_bytes += r.len(); + add(r)?; + pages.push(PageAt { at, refs, layers: written, head }); + Ok(()) + }; + for (n, p) in drawing.pages.iter().enumerate() { + page(&mut w, n, p.size.or(drawing.page_size), &p.layers)?; } // A drawing with no pages but a page size is written as one empty page of that size. if drawing.pages.is_empty() && drawing.page_size.is_some() { - add(w.page(0, drawing.page_size, &[])?)?; + page(&mut w, 0, drawing.page_size, &[])?; } - // The reader also counts every chunk (`cont`, the pages and the seven tables), every table entry - // and the one arrowhead pair. - let pages = if drawing.pages.is_empty() { usize::from(drawing.page_size.is_some()) } else { drawing.pages.len() }; + // The reader leaves out a list as deep as its depth limit, and the index is a list. + if w.limits.depth == 0 { + return Err(Error::Limit("nesting depth")); + } + // The reader also counts every chunk (`cont`, each page and its reference list, the seven + // tables, and the index list with its three chunks and a layer table for each page), every + // table entry and the one arrowhead pair. let t = &w.tables; let entries = t.colors.entries.len() + t.pens.entries.len() + t.line_types.entries.len() + t.dashes.entries.len() + t.outlines.entries.len() + 1; - w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + pages + 7 + entries); + let index_chunks = pages.len().saturating_add(4); + w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + 2 * pages.len() + 7 + entries + index_chunks); w.read_cost.check(&w.limits)?; + // Where each table chunk starts, by its id. + let mut tables = Vec::new(); + let mut at = w.file_bytes; for c in w.tables.chunks(w.limits.input.saturating_sub(w.file_bytes))? { + let id: [u8; 4] = c[0..4].try_into().map_err(|_| Error::Limit("chunk size"))?; + tables.push((id, at)); + at = at.saturating_add(c.len()); add(c)?; } + let (list, ixmr) = index(at, &pages, &tables)?; + add(list)?; let total = usize::try_from(size).ok().and_then(|n| n.checked_add(8)).ok_or(Error::Limit("chunk size"))?; if total > w.limits.input { return Err(Error::Limit("input size")); } + children[0] = chunk(b"cont", &cont(ixmr, pages.first().map(|p| p.head).unwrap_or_default()))?; let mut bytes = Vec::new(); bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?; bytes.extend(b"RIFF"); @@ -190,16 +220,124 @@ fn chunk(id: &[u8; 4], body: &[u8]) -> Result, Error> { } /// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64 -/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files; the rest are zeros. -fn cont() -> Vec { +/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file +/// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the +/// picture of the drawing, which the file does not hold (R77). Bytes 96 to 116 hold the edges and +/// the instruction count of `first`, the first page's begin-page record (R77); the rest are zeros. +fn cont(ixmr: u32, first: PageHead) -> Vec { let mut c = vec![0u8; 180]; c[48] = b'2'; c[52] = b'4'; c[54] = b'2'; c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes()); + c[84..88].copy_from_slice(&ixmr.to_le_bytes()); + c[88..96].fill(0xFF); + for (i, v) in first.edges.iter().enumerate() { + c[96 + 4 * i..100 + 4 * i].copy_from_slice(&v.to_le_bytes()); + } + c[112..116].copy_from_slice(&first.instructions.to_le_bytes()); c } +/// What a page's begin-page record holds that the header repeats: its left, top, right and bottom +/// edges and its instruction count, begin and end page included. +#[derive(Clone, Copy, Default)] +struct PageHead { + edges: [i32; 4], + instructions: u32, +} + +/// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name. +type LayerAt = (usize, Vec); + +/// Where a page's chunks start in the file, and its layers. +struct PageAt { + at: usize, + /// The page's reference list `rlst`. + refs: usize, + layers: Vec, + /// What the header repeats of its begin-page record. + head: PageHead, +} + +/// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16 +/// values 2 and 9 and its number. +fn reference_list(layers: usize) -> Vec { + let mut r = (layers as u16).to_le_bytes().to_vec(); + for n in 1..=layers { + r.extend([2u16, 9, n as u16].map(u16::to_le_bytes).concat()); + } + r +} + +/// A file offset as the u32 the index stores. +fn offset(at: usize) -> Result { + u32::try_from(at).map_err(|_| Error::Limit("chunk size")) +} + +/// The index list `LIST indx` starting at file offset `at` (R77): a layer table `ixlr` for each +/// page, the table of layer tables `ixtl`, the page index `ixpg` and the master index `ixmr`, with +/// the file offset of `ixmr`. `tables` gives where each table chunk starts, by its id. +fn index(at: usize, pages: &[PageAt], tables: &[([u8; 4], usize)]) -> Result<(Vec, u32), Error> { + let mut body = b"indx".to_vec(); + // Where the next chunk of the list starts. + let next = |body: &Vec| at.saturating_add(8).saturating_add(body.len()); + let mut layer_tables = Vec::with_capacity(pages.len()); + for (n, p) in pages.iter().enumerate() { + layer_tables.push(next(&body)); + // The layer count and the page number, then for each layer the size of its record before + // the 0xFFFFFFFF that ends it, its begin-layer instruction and its name. + let mut t = (p.layers.len() as u16).to_le_bytes().to_vec(); + t.extend(u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?.to_le_bytes()); + for (start, name) in &p.layers { + t.extend(((8 + name.len()) as u16).to_le_bytes()); + t.extend(offset(*start)?.to_le_bytes()); + t.extend((name.len() as u16).to_le_bytes()); + t.extend(name); + t.extend(u32::MAX.to_le_bytes()); + } + body.extend(chunk(b"ixlr", &t)?); + } + // The table of layer tables: their count, the size of each record, the type 3 and the offsets. + let ixtl = next(&body); + let mut t = (pages.len() as u16).to_le_bytes().to_vec(); + t.extend(4u16.to_le_bytes()); + t.extend(3u16.to_le_bytes()); + for l in &layer_tables { + t.extend(offset(*l)?.to_le_bytes()); + } + body.extend(chunk(b"ixtl", &t)?); + // The page index: the page count, then for each page the size of its record, its page chunk, + // its layer table, 0xFFFFFFFF for a picture of the page it does not have and its reference + // list. + let ixpg = next(&body); + let mut t = (pages.len() as u16).to_le_bytes().to_vec(); + for (p, l) in pages.iter().zip(&layer_tables) { + t.extend(16u16.to_le_bytes()); + for v in [offset(p.at)?, offset(*l)?, u32::MAX, offset(p.refs)?] { + t.extend(v.to_le_bytes()); + } + } + body.extend(chunk(b"ixpg", &t)?); + // The master index: the values 1 and 24, the entry count, then an id and an offset for itself, + // the page index, the table of layer tables and each table. + let ixmr = next(&body); + let ids: [(&[u8; 4], u16); 7] = [(b"rotl", 15), (b"rott", 16), (b"rota", 17), (b"rscr", 18), (b"rpen", 19), (b"rdot", 20), (b"rclr", 21)]; + let mut entries = vec![(1u16, ixmr), (2, ixpg), (3, ixtl)]; + for (id, n) in ids { + if let Some((_, start)) = tables.iter().find(|(t, _)| t == id) { + entries.push((n, *start)); + } + } + let mut t = [1u16, 24, entries.len() as u16].map(u16::to_le_bytes).concat(); + for (n, start) in entries { + t.extend(n.to_le_bytes()); + t.extend(offset(start)?.to_le_bytes()); + } + body.extend(chunk(b"ixmr", &t)?); + Ok((chunk(b"LIST", &body)?, offset(ixmr)?)) +} + /// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). `None` when the /// data does not fit the length. fn field(tag: u8, data: &[u8]) -> Option> { @@ -397,9 +535,25 @@ fn color_key(c: &Color) -> ColorKey { } } -/// A color entry (R56): field 10 holds a property list, a u32 length then parts of a u8 kind, a u32 -/// length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, the -/// values; R14), and for a named color part 3, a u32 count and UTF-16 units. +/// The color of `k` in the fields 1 and 2 of a color entry (R56): the model and the palette 5, +/// then four value bytes. A spot color is written as its look at its tint in red, green and blue, +/// and the registration color as cyan, magenta, yellow and black at 100 percent, since the +/// models of these fields hold neither. +fn older_fields(k: &ColorKey) -> (u8, [u8; 4]) { + let [v0, v1, v2, v3] = k.values; + match k.model { + 2 => (2, [v0, v1, v2, v3]), + // Red, green and blue, where the color record holds blue, green and red. + 5 | 21 => (5, [v2, v1, v0, 0]), + 9 => (9, [v0, 0, 0, 0]), + _ => (2, [100; 4]), + } +} + +/// A color entry (R56): field 1 the model and the palette, field 2 the values, as +/// [`older_fields`] gives them, then field 10, a property list: a u32 length then parts of a u8 +/// kind, a u32 length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, +/// the values; R14), and for a named color part 3, a u32 count and UTF-16 units. fn color_entry(k: &ColorKey) -> Result, Error> { let mut list = vec![1u8]; list.extend(12u32.to_le_bytes()); @@ -416,7 +570,9 @@ fn color_entry(k: &ColorKey) -> Result, Error> { } let mut rec = (list.len() as u32).to_le_bytes().to_vec(); rec.extend(list); - Ok(fields(&[field(10, &rec).ok_or(Error::Limit("table entry size"))?])) + let (model, values) = older_fields(k); + let size = || Error::Limit("table entry size"); + Ok(fields(&[field(1, &[model, 5]).ok_or_else(size)?, field(2, &values).ok_or_else(size)?, field(10, &rec).ok_or_else(size)?])) } /// The counts [`crate::read_cmx`] holds to [`crate::Limits`] while it reads a file. @@ -462,8 +618,14 @@ struct Writer { looks: HashMap, /// The comparisons [`may_fill_differently`] may still make. crossing_budget: u64, - /// The groups open where the next instruction is written. - open_groups: usize, + /// The groups open where the next instruction is written, outermost first. + open_groups: Vec, + /// The instructions written on the current page, its begin-page instruction included. + instructions: usize, + /// For each group closed on the current page, where its end offset goes in the page's + /// instructions after the begin-page instruction, and the offset there, both counted from the + /// end of the begin-page instruction. + group_ends: Vec<(usize, usize)>, /// The smallest and largest x and y the curves written on the current page reach, in /// coordinate units. bounds: Option<[i32; 4]>, @@ -585,10 +747,17 @@ impl Writer { self.tables.colors.index(key) } - /// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60). - fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result, Error> { + /// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60), + /// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name, and + /// what the header repeats of the begin-page record. The chunk starts at the file offset + /// [`Writer::file_bytes`] gives. + fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec, Vec, PageHead), Error> { let mut out = Vec::new(); self.bounds = None; + self.instructions = 1; + self.group_ends.clear(); + // Where each layer's begin-layer instruction starts in `out`, and its 8-bit name. + let mut starts = Vec::new(); // The model holds layers and objects front to back; the file lists them back to front. let mut written = 0; for layer in layers.iter().rev() { @@ -604,19 +773,43 @@ impl Writer { // The reader also stops a layer's name at its first NUL and takes a blank name as none. let name = &layer.name; self.long_names |= shortened(name) || name.contains('\0') || (!name.is_empty() && name.trim().is_empty()); - out.extend(instr(BEGIN_LAYER, &layer_fields(n, written, &layer.name)?)); + let body = layer_fields(n, written, &layer.name)?; + let begin = instr(BEGIN_LAYER, &body); + // The layer's instruction count goes at bytes 8 to 12 of field 1, after the + // instruction's header and the field's tag and length. + let count_at = out.len() + begin.len() - body.len() + 3 + 8; + let first = self.instructions; + starts.push((out.len(), narrow_name(&layer.name))); + out.extend(begin); + self.instructions += 1; written += 1; self.objects(&layer.objects, &mut out)?; out.extend(instr(END_LAYER, &[])); + self.instructions += 1; + put_u32(&mut out, count_at, self.instructions - first)?; self.read_cost.chunks += 2; self.read_cost.check(&self.limits)?; self.check_bytes(out.len())?; } + let end = out.len(); out.extend(instr(END_PAGE, &[])); + self.instructions += 1; // The begin and end page instructions. self.read_cost.chunks += 2; self.read_cost.check(&self.limits)?; - let begin = begin_page(n, size, self.bounds.take())?; + let bounds = self.bounds.take(); + let begin_len = begin_page(n, size, bounds, PageTail::default())?.len(); + // The page's instructions after the begin-page instruction start here in the file. + let base = self.file_bytes.saturating_add(8).saturating_add(begin_len); + let tail = PageTail { + end: offset(base.saturating_add(end))?, + layers: u16::try_from(written).map_err(|_| Error::Limit("layers"))?, + instructions: u32::try_from(self.instructions).map_err(|_| Error::Limit("chunk count"))?, + }; + for (at, end) in std::mem::take(&mut self.group_ends) { + put_u32(&mut out, at, base.saturating_add(end))?; + } + let begin = begin_page(n, size, bounds, tail)?; if u32::try_from(begin.len() + out.len()).is_err() { return Err(Error::Limit("chunk size")); } @@ -624,8 +817,9 @@ impl Writer { page.extend(out); let c = chunk(b"page", &page)?; self.check_bytes(c.len())?; + let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect(); self.file_bytes += c.len(); - Ok(c) + Ok((c, layers, PageHead { edges: page_edges(size, bounds)?, instructions: tail.instructions })) } /// An [`Error::Limit`] when the file would be longer than the input size of the limits with @@ -657,7 +851,7 @@ impl Writer { self.shape(&s, out)?; } if ends { - self.end_group(out); + self.end_group(out)?; } } continue; @@ -699,20 +893,55 @@ impl Writer { /// Begin a group. A group inside as many groups as the reader opens (the depth of the /// [`crate::Limits`] written for) is an [`Error::Limit`]: the reader leaves out what it holds. fn begin_group(&mut self, out: &mut Vec) -> Result<(), Error> { - if self.open_groups >= self.limits.depth { + if self.open_groups.len() >= self.limits.depth { return Err(Error::Limit("nesting depth")); } - self.open_groups += 1; + if let Some(parent) = self.open_groups.last_mut() { + parent.groups = parent.groups.checked_add(1).ok_or(Error::Limit("groups"))?; + } + self.open_groups.push(OpenGroup { at: out.len(), first: self.instructions, groups: 0, bounds: None }); out.extend(group()); + self.instructions += 1; self.read_cost.chunks += 1; self.read_cost.objects += 1; self.read_cost.check(&self.limits) } - fn end_group(&mut self, out: &mut Vec) { - self.open_groups = self.open_groups.saturating_sub(1); + /// End the innermost open group, and fill in its begin-group record (R77): the edges of its + /// curves (all 0 when it has none), the groups directly inside it, its instructions from begin + /// to end, and where the instruction after its end starts, which [`Writer::page`] places in + /// the file. + fn end_group(&mut self, out: &mut Vec) -> Result<(), Error> { out.extend(instr(END_GROUP, &[])); + self.instructions += 1; self.read_cost.chunks += 1; + let Some(g) = self.open_groups.pop() else { return Ok(()) }; + if let (Some(parent), Some(b)) = (self.open_groups.last_mut(), g.bounds) { + parent.bounds = Some(match parent.bounds { + Some(p) => [p[0].min(b[0]), p[1].min(b[1]), p[2].max(b[2]), p[3].max(b[3])], + None => b, + }); + } + // Field 1's data starts after the instruction's 4-byte header and the field's tag and + // length. + let data = g.at + 4 + 3; + let [x0, y0, x1, y1] = g.bounds.unwrap_or_default(); + for (i, v) in [x0, y1, x1, y0].into_iter().enumerate() { + out[data + 4 * i..data + 4 * i + 4].copy_from_slice(&v.to_le_bytes()); + } + out[data + 16..data + 18].copy_from_slice(&g.groups.to_le_bytes()); + put_u32(out, data + 18, self.instructions - g.first)?; + self.group_ends.push((data + 22, out.len())); + Ok(()) + } + + /// Take in `[x0, y0, x1, y1]`, the edges of a written curve, in the page's and the innermost + /// open group's edges. + fn reach(&mut self, e: [i32; 4]) { + for b in [Some(&mut self.bounds), self.open_groups.last_mut().map(|g| &mut g.bounds)].into_iter().flatten() { + let b = b.get_or_insert(e); + *b = [b[0].min(e[0]), b[1].min(e[1]), b[2].max(e[2]), b[3].max(e[3])]; + } } /// A shape as one curve, or as a group of curves when its path holds more than @@ -802,9 +1031,7 @@ impl Writer { _ => [p.x, p.y, p.x, p.y], }; // Within the anchors and control points, which are i32, so the casts keep them. - let (x0, y0, x1, y1) = (x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32); - let b = self.bounds.get_or_insert([x0, y0, x1, y1]); - *b = [b[0].min(x0), b[1].min(y0), b[2].max(x1), b[3].max(y1)]; + self.reach([x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32]); } g.extend(c.iter().map(|(_, t)| *t)); bodies.push(field(2, &g).ok_or(Error::Limit("curve size"))?); @@ -815,10 +1042,11 @@ impl Writer { let i = instr(CURVE, &fields(&[f1.clone(), f2.clone()])); self.check_bytes(out.len().saturating_add(i.len()))?; out.extend(i); + self.instructions += 1; } } if curves.len() > 1 { - self.end_group(out); + self.end_group(out)?; } Ok(()) } @@ -912,41 +1140,61 @@ impl Writer { } } +/// A group open where the next instruction is written. +struct OpenGroup { + /// Where its begin-group instruction starts in the page's instructions after the begin-page + /// instruction. + at: usize, + /// The page's instructions written before it. + first: usize, + /// The groups directly inside it so far. + groups: u16, + /// The smallest and largest x and y its curves reach so far, in coordinate units. + bounds: Option<[i32; 4]>, +} + +/// What begin page keeps of the rest of the page (R77). +#[derive(Clone, Copy, Default)] +struct PageTail { + /// The file offset of the end-page instruction. + end: u32, + /// The layers on the page. + layers: u16, + /// The page's instructions, begin and end page included. + instructions: u32, +} + +/// Write `v` as a u32 at `at` of `out`. +fn put_u32(out: &mut [u8], at: usize, v: usize) -> Result<(), Error> { + let v = u32::try_from(v).map_err(|_| Error::Limit("chunk size"))?; + out.get_mut(at..at + 4).ok_or(Error::Limit("chunk size"))?.copy_from_slice(&v.to_le_bytes()); + Ok(()) +} + /// Begin page `n` (from 0; R61): field 1 the page number from 1, a u32 of flags and the left, /// top, right and bottom edges of `bounds`, the page's art (smallest x and y, largest x and y), -/// or of the page around its center when it has no art; field 4 its width and height. Without a -/// size the edges are all 0, which the reader takes as no size. -fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result, Error> { +/// or of the page around its center when it has no art, then `tail` (R77); field 4 its width and +/// height. Without a size the edges are all 0, which the reader takes as no size. +fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail: PageTail) -> Result, Error> { let number = u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?; let mut d = number.to_le_bytes().to_vec(); d.extend(0u32.to_le_bytes()); let mut list = Vec::new(); - let mut size_field = None; - let mut edges = [0i32; 4]; - if let Some((w, h)) = size { - // A negative or NaN side counts as 0. - let (wu, hu) = (width_units(w)?, width_units(h)?); - // A side that rounds to nothing would make the reader drop the page's whole size. - if wu == 0 || hu == 0 { - return Err(Error::Limit("page size")); + let edges = page_edges(size, bounds)?; + let size_field = match size { + Some((w, h)) => { + let mut s = width_units(w)?.to_le_bytes().to_vec(); + s.extend(width_units(h)?.to_le_bytes()); + Some(s) } - edges = match bounds { - Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], - None => { - // The page around its center; an odd size keeps its extra unit on the left and - // bottom, where the edge reaches -2^31. - let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); - let (w, h) = (i64::from(wu), i64::from(hu)); - [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] - } - }; - let mut s = wu.to_le_bytes().to_vec(); - s.extend(hu.to_le_bytes()); - size_field = Some(s); - } + None => None, + }; for v in edges { d.extend(v.to_le_bytes()); } + d.extend(tail.end.to_le_bytes()); + d.extend(tail.layers.to_le_bytes()); + d.extend(tail.instructions.to_le_bytes()); list.push(field(1, &d).ok_or(Error::Limit("page size"))?); if let Some(s) = size_field { list.push(field(4, &s).ok_or(Error::Limit("page size"))?); @@ -954,6 +1202,28 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> R Ok(instr(BEGIN_PAGE, &fields(&list))) } +/// The left, top, right and bottom edges begin page holds for a page of `size` whose art reaches +/// `bounds`, as [`begin_page`] describes. A page side that rounds to 0 is an [`Error::Limit`]. +fn page_edges(size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<[i32; 4], Error> { + let Some((w, h)) = size else { return Ok([0; 4]) }; + // A negative or NaN side counts as 0. + let (wu, hu) = (width_units(w)?, width_units(h)?); + // A side that rounds to nothing would make the reader drop the page's whole size. + if wu == 0 || hu == 0 { + return Err(Error::Limit("page size")); + } + Ok(match bounds { + Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], + None => { + // The page around its center; an odd size keeps its extra unit on the left and + // bottom, where the edge reaches -2^31. + let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); + let (w, h) = (i64::from(wu), i64::from(hu)); + [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] + } + }) +} + /// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it. fn windows_1252_byte(c: char) -> u8 { match u8::try_from(u32::from(c)) { @@ -962,16 +1232,26 @@ fn windows_1252_byte(c: char) -> u8 { } } -/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 8 zero -/// bytes, then the name as a u16 count and 8-bit characters (Windows-1252: characters the code -/// page has no byte for are written as `?`); field 4 the name as a u32 count and UTF-16 units. -/// `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers is an -/// [`Error::Limit`]. +/// Whether a layer's `name`, up to the first NUL where the reader stops, is blank: it is written +/// empty, so it opens with no name. +fn blank_name(name: &str) -> bool { + name.split('\0').next().unwrap_or_default().trim().is_empty() +} + +/// A layer's name as written in 8-bit characters (Windows-1252: characters the code page has no +/// byte for are written as `?`). +fn narrow_name(name: &str) -> Vec { + if blank_name(name) { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() } +} + +/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 4 zero +/// bytes, the layer's instruction count, which [`Writer::page`] fills in (R77), then the name as a +/// u16 count and 8-bit characters ([`narrow_name`]); field 4 the name as a u32 count and UTF-16 +/// units. `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers +/// is an [`Error::Limit`]. fn layer_fields(page: usize, n: usize, name: &str) -> Result, Error> { - // A blank name, up to the first NUL where the reader stops, is written empty in both fields, - // so it opens with no name. - let blank = name.split('\0').next().unwrap_or_default().trim().is_empty(); - let narrow: Vec = if blank { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() }; + let blank = blank_name(name); + let narrow = narrow_name(name); let page = u16::try_from(page + 1).map_err(|_| Error::Limit("pages"))?; let number = u16::try_from(n + 1).map_err(|_| Error::Limit("layers"))?; let mut d = page.to_le_bytes().to_vec(); @@ -987,7 +1267,7 @@ fn layer_fields(page: usize, n: usize, name: &str) -> Result, Error> { Ok(fields(&[f1, f4])) } -/// Begin a group: field 1 of 26 zero bytes, as the test files of `synth_cmx` hold. +/// Begin a group: field 1 of 26 bytes, which [`Writer::end_group`] fills in (R77). fn group() -> Vec { instr(BEGIN_GROUP, &fields(&[field(1, &[0; 26]).unwrap_or_default()])) } diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 523384491c..b18029fb25 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -133,8 +133,9 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { /// width, or a page side that rounds to 0; /// - more than 65,535 pages, layers on a page, or different colors, pens, line types, dash /// patterns or outlines, or a dash pattern of more than 32,765 lengths; -/// - groups nested deeper than the depth of `limits`, or more chunks, objects, coordinates or -/// dashes than a read within `limits` takes; +/// - groups nested deeper than the depth of `limits`, a depth of 0, at which the reader leaves out +/// the index list, more than 65,535 groups directly inside one group, or more chunks, objects, +/// coordinates or dashes than a read within `limits` takes; /// - a file longer than the input size of `limits`, or a chunk past what its 32-bit size holds. /// /// [`Written`] reports what the file holds differently from the drawing; its fields name each @@ -142,11 +143,18 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { /// written with round corners of its radii times the square root of the scales' product, not with /// stretched corners, and is not reported. /// -/// The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets -/// inside page, layer and group records, and the bounds inside layer and group records are not -/// written, so a reader must find the chunks by their ids and walk the instructions in order, as -/// [`read_cmx`] does. The record of a page with a size holds the edges of its curves, or of the -/// page when it has none. +/// Each color entry holds the color twice: as the property list [`read_cmx`] reads, and as the +/// model and value fields that other readers read. In those fields a spot color is written as its +/// look at its tint, and the registration color as 100 percent cyan, magenta, yellow and black. +/// +/// The file holds an index, so that a reader that finds the tables and pages through it, rather +/// than by their chunk ids, opens it: the header gives where the master index starts, the index +/// list (`LIST indx`) gives where each table, page, page reference list and layer starts, and the +/// page, layer and group records give their instruction counts. A page's record also gives where +/// its end-page instruction starts, and a group's record gives where the instruction after its +/// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of +/// its curves, or of the page when it has none. The header repeats the first page's edges and +/// instruction count. pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result { cmx_write::write(drawing, limits) } diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs index d751a04c2a..989205e635 100644 --- a/crates/cdr/tests/it/cmx_write.rs +++ b/crates/cdr/tests/it/cmx_write.rs @@ -283,9 +283,15 @@ fn pages_are_numbered_in_their_order() { assert_eq!(numbers, [1, 2]); } -/// Field 1 of each entry of the table chunk `id`: a u16 count, then a field list per entry (a tag, -/// a u16 length counting the 3 header bytes, the data; 0xff after the last field). +/// Field 1 of each entry of the table chunk `id`. fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { + table_fields(bytes, id).into_iter().map(|e| e.into_iter().find(|(tag, ..)| *tag == 1).map(|(.., data)| data).expect("field 1")).collect() +} + +/// The fields of each entry of the table chunk `id`, each its tag, where it starts in the file and +/// its data: a u16 count, then a field list per entry (a tag, a u16 length counting the 3 header +/// bytes, the data; 0xff after the last field). +fn table_fields(bytes: &[u8], id: &[u8; 4]) -> Vec)>> { let at = bytes.windows(4).position(|w| w == id).unwrap_or_else(|| panic!("no {id:?} chunk")) + 8; // The chunk's body runs for the size after its id. let end = at + u32::from_le_bytes(bytes[at - 4..at].try_into().unwrap()) as usize; @@ -294,7 +300,7 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { let mut p = at + 2; let mut out = Vec::new(); for _ in 0..count { - let mut first = None; + let mut entry = Vec::new(); loop { assert!(p < end, "entry runs past the {id:?} chunk at {p}"); if bytes[p] == 0xff { @@ -304,13 +310,11 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { let len = usize::from(u16::from_le_bytes([bytes[p + 1], bytes[p + 2]])); // A length shorter than its header, or past the chunk, would stop the walk. assert!(len >= 3 && p + len <= end, "field at {p} has length {len}"); - if bytes[p] == 1 { - first = Some(bytes[p + 3..p + len].to_vec()); - } + entry.push((bytes[p], p, bytes[p + 3..p + len].to_vec())); p += len; } p += 1; - out.push(first.expect("field 1")); + out.push(entry); } // The size counts the u16 count and the entries; the pad byte comes after it. assert_eq!(p, end, "{id:?} chunk has bytes left after its entries"); @@ -348,6 +352,61 @@ fn every_outline_names_a_screen_and_a_dash_pattern_the_file_holds() { assert_eq!(patterns, vec![(false, vec![]), (true, vec![3, 1])]); } +#[test] +fn colors_are_also_written_in_the_model_and_value_fields() { + let colors = [ + Color::Rgb([1.0, 0.2, 0.0]), + Color::Cmyk([0.6, 0.0, 0.13, 0.05]), + Color::Gray(0.75), + Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) }, + Color::Registration, + ]; + let objects = colors + .iter() + .enumerate() + .map(|(i, c)| Object::Shape(Box::new(Shape::new(square(20.0 * i as f64, 0.0, 10.0), Matrix::IDENTITY, Some(c.clone()), None)))) + .collect(); + let d = drawing(vec![Page { size: Some((200.0, 100.0)), layers: vec![layer("Art", objects)] }]); + let mut bytes = write_cmx(&d).unwrap().bytes; + let entries = table_fields(&bytes, b"rclr"); + // Each entry holds the model and the palette 5 in field 1 and four values in field 2, before + // the property list of field 10. + let mut older: Vec<(Vec, Vec)> = entries + .iter() + .map(|e| { + assert_eq!(e.iter().map(|(tag, ..)| *tag).collect::>(), [1, 2, 10]); + (e[0].2.clone(), e[1].2.clone()) + }) + .collect(); + older.sort(); + let mut want = vec![ + // Red, green and blue. + (vec![5, 5], vec![255, 51, 0, 0]), + // Cyan, magenta, yellow and black in percent. + (vec![2, 5], vec![60, 0, 13, 5]), + // Gray, 255 white. + (vec![9, 5], vec![64, 0, 0, 0]), + // The spot color's look at its tint of 40 percent. + (vec![5, 5], vec![153, 194, 235, 0]), + // The registration color as every ink at 100 percent. + (vec![2, 5], vec![100, 100, 100, 100]), + ]; + want.sort(); + assert_eq!(older, want); + // With field 10 retagged, the reader takes each color from fields 1 and 2. + for e in &entries { + bytes[e[2].1] = 11; + } + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let fills: Vec = back.pages[0].layers[0].objects.iter().map(|o| shape(o).fill.clone().unwrap()).collect(); + let opened = [colors[0].clone(), colors[1].clone(), colors[2].clone(), Color::Rgb([0.6, 0.76, 0.92]), Color::Cmyk([1.0; 4])]; + assert_eq!(fills.len(), opened.len()); + for (got, want) in fills.iter().zip(&opened) { + assert!(near_color(got, want), "{got:?} for {want:?}"); + } +} + #[test] fn an_outline_that_scales_with_its_shape_keeps_its_drawn_width() { let m = Matrix([3.0, 0.0, 0.0, 3.0, 0.0, 0.0]); @@ -657,7 +716,7 @@ fn a_page_without_a_size_still_writes_its_four_edges() { // The begin-page instruction: a u16 size, the code 9, then field 1: a tag and its length. assert_eq!(i16::from_le_bytes([bytes[at + 2], bytes[at + 3]]), 9); let len = usize::from(u16::from_le_bytes([bytes[at + 5], bytes[at + 6]])); - assert_eq!(len - 3, 2 + 4 + 16, "the page number, the flags and four edges"); + assert_eq!(len - 3, 2 + 4 + 16 + 4 + 2 + 4, "the page number, the flags, four edges, the end, the layers and the instructions"); } #[test] @@ -950,6 +1009,277 @@ fn layers_give_their_page_and_their_number() { assert_eq!(numbers, [(1, 1), (1, 2), (2, 1), (2, 2)]); } +fn u16_at(b: &[u8], at: usize) -> usize { + usize::from(u16::from_le_bytes([b[at], b[at + 1]])) +} + +fn u32_at(b: &[u8], at: usize) -> usize { + u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize +} + +/// The id of each chunk of a written file by where it starts, those inside lists included. +fn chunk_ids(b: &[u8]) -> std::collections::HashMap { + let mut ids = std::collections::HashMap::new(); + let mut stack = vec![(12, b.len())]; + while let Some((mut at, end)) = stack.pop() { + while at + 8 <= end { + let id: [u8; 4] = b[at..at + 4].try_into().unwrap(); + let size = u32_at(b, at + 4); + ids.insert(at, id); + if id == *b"LIST" { + stack.push((at + 12, at + 8 + size)); + } + at += 8 + size + size % 2; + } + } + ids +} + +/// The field list at `at` of `b`, in an instruction that ends at `end`: each field's tag and where +/// its data starts. A field shorter than its 3 header bytes, or past `end`, fails the test. +fn field_starts(b: &[u8], mut at: usize, end: usize) -> Vec<(u8, usize)> { + let mut out = Vec::new(); + while b[at] != 0xff { + let len = u16_at(b, at + 1); + assert!(len >= 3 && at + len <= end, "a field of length {len} at {at}, in an instruction that ends at {end}"); + out.push((b[at], at + 3)); + at += len; + } + out +} + +#[test] +#[should_panic(expected = "a field of length 0")] +fn a_field_of_length_0_fails_the_check() { + field_starts(&[1, 0, 0, 0xff], 0, 4); +} + +#[test] +#[should_panic(expected = "a field of length 9")] +fn a_field_past_its_instruction_fails_the_check() { + field_starts(&[1, 9, 0, 0, 0xff], 0, 5); +} + +#[test] +fn the_index_and_the_records_give_where_everything_is() { + let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let inner = Object::Group { objects: vec![plain(20.0)], flags: Flags::default() }; + let outer = Object::Group { objects: vec![plain(0.0), inner, plain(50.0)], flags: Flags::default() }; + let pages = vec![ + Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![outer]), layer("Back", vec![plain(5.0)])] }, + Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0), plain(2.0)])] }, + ]; + let b = write_cmx(&drawing(pages)).unwrap().bytes; + let page_entries = page_index(&b); + let layer_starts = layer_tables(&b, &page_entries, &[&["Back", "Front"], &["Only"]]); + let (seen_layers, groups) = page_records(&b, &page_entries); + assert_eq!(seen_layers, layer_starts); + // The inner group: itself and a curve; the outer: two curves and the inner group. + assert_eq!(groups, [(0, 3), (1, 7)]); +} + +#[test] +fn the_header_repeats_the_first_pages_edges_and_instruction_count() { + let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let pages = vec![ + Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![plain(0.0), plain(20.0)]), layer("Back", vec![plain(5.0)])] }, + Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0)])] }, + ]; + let b = write_cmx(&drawing(pages)).unwrap().bytes; + let cont = 12 + 8; + let chunk = page_index(&b)[0][0]; + let page = chunk + 8; + // Begin page's field 1: the page number, the flags, the edges, the end offset, the layer count + // and the instruction count. + let fields = field_starts(&b, page + 4, page + instruction_size(&b, page, page + u32_at(&b, chunk + 4))); + assert_eq!(fields[0].0, 1); + let f1 = fields[0].1; + assert_eq!(&b[cont + 96..cont + 112], &b[f1 + 6..f1 + 22]); + // The curves of the first page reach from 0 to 30 pt across and 0 to 10 pt down. + let edges: Vec = (0..4).map(|i| i32::from_le_bytes(b[cont + 96 + 4 * i..cont + 100 + 4 * i].try_into().unwrap())).collect(); + let unit = |pt: f64| (pt * 0.0254 / 72.0 / 1e-7).round() as i32; + assert_eq!(edges, [0, unit(10.0), unit(30.0), 0]); + // Begin and end page, two begin and end layers and three curves. + assert_eq!(u32_at(&b, cont + 112), 9); + assert_eq!(u32_at(&b, f1 + 28), 9); + // A drawing without pages leaves them 0. + let b = write_cmx(&drawing(Vec::new())).unwrap().bytes; + assert!(b[cont + 96..cont + 116].iter().all(|v| *v == 0)); +} + +/// The page index of a written file of two pages, each entry's page chunk, layer table, picture +/// and reference list, checked through the header and the master index. +fn page_index(b: &[u8]) -> Vec<[usize; 4]> { + let ids = chunk_ids(b); + let id = |at: usize| ids.get(&at).map(|i| String::from_utf8_lossy(i).into_owned()).unwrap_or_default(); + // The header names the master index, and no information list or picture. + let cont = 12 + 8; + let ixmr = u32_at(b, cont + 84); + assert_eq!(id(ixmr), "ixmr"); + assert_eq!((u32_at(b, cont + 88), u32_at(b, cont + 92)), (u32::MAX as usize, u32::MAX as usize)); + // The master index names itself, the page index, the table of layer tables and each table. + let m = ixmr + 8; + assert_eq!((u16_at(b, m), u16_at(b, m + 2)), (1, 24)); + let entries: Vec<(usize, String)> = (0..u16_at(b, m + 4)).map(|i| (u16_at(b, m + 6 + 6 * i), id(u32_at(b, m + 8 + 6 * i)))).collect(); + let want = + [(1, "ixmr"), (2, "ixpg"), (3, "ixtl"), (15, "rotl"), (16, "rott"), (17, "rota"), (18, "rscr"), (19, "rpen"), (20, "rdot"), (21, "rclr")]; + assert_eq!(entries, want.map(|(n, s)| (n, s.to_string()))); + let at_of = |n: usize| u32_at(b, m + 8 + 6 * entries.iter().position(|(k, _)| *k == n).unwrap()); + // The page index: each page chunk, its layer table, no picture and its reference list. + let pg = at_of(2) + 8; + assert_eq!(u16_at(b, pg), 2); + let page_entries: Vec<[usize; 4]> = (0..2) + .map(|i| { + let e = pg + 2 + 18 * i; + assert_eq!(u16_at(b, e), 16); + [0, 1, 2, 3].map(|k| u32_at(b, e + 2 + 4 * k)) + }) + .collect(); + for [page, layers, picture, refs] in &page_entries { + assert_eq!((id(*page), id(*layers), *picture, id(*refs)), ("page".into(), "ixlr".into(), u32::MAX as usize, "rlst".into())); + } + // The table of layer tables lists each page's. + let tl = at_of(3) + 8; + assert_eq!([u16_at(b, tl), u16_at(b, tl + 2), u16_at(b, tl + 4)], [2, 4, 3]); + assert_eq!([u32_at(b, tl + 6), u32_at(b, tl + 10)], [page_entries[0][1], page_entries[1][1]]); + page_entries +} + +/// Where each layer table of `page_entries` says the layers named `names` start, checking each +/// table and each reference list: a layer table holds its count, the page number, then each +/// layer's begin-layer instruction and name, back to front; a reference list a count, and 2, 9 and +/// the number of each layer. +fn layer_tables(b: &[u8], page_entries: &[[usize; 4]], names: &[&[&str]]) -> Vec { + let mut layer_starts = Vec::new(); + for (n, (entry, names)) in page_entries.iter().zip(names).enumerate() { + let t = entry[1] + 8; + assert_eq!((u16_at(b, t), u16_at(b, t + 2)), (names.len(), n + 1)); + let mut at = t + 4; + for name in *names { + let size = u16_at(b, at); + let start = u32_at(b, at + 2); + let len = u16_at(b, at + 6); + assert_eq!((size, &b[at + 8..at + 8 + len]), (8 + name.len(), name.as_bytes())); + assert_eq!(u32_at(b, at + 8 + len), u32::MAX as usize); + assert_eq!(u16_at(b, start + 2), 11, "a begin-layer instruction"); + layer_starts.push(start); + at += size + 4; + } + let r = entry[3] + 8; + let refs: Vec = (0..1 + 3 * names.len()).map(|i| u16_at(b, r + 2 * i)).collect(); + let want: Vec = std::iter::once(names.len()).chain((1..=names.len()).flat_map(|k| [2, 9, k])).collect(); + assert_eq!(refs, want); + } + layer_starts +} + +/// An open begin-page, begin-layer or begin-group record: its code, where its field 1 starts, the +/// instructions before it, the records found directly inside it and the edges of its curves. +type Open = (usize, usize, usize, usize, Option<[i32; 4]>); + +/// Check what the record `open` gives, now closed by the instruction of `code` and `size` at `at` +/// after `count` instructions of its page: begin page where the page ends, its layers and its +/// instructions; begin layer its instructions; begin group the edges of its curves, then its +/// groups and instructions, which are returned, and where the instruction after it starts. +fn closed_record(b: &[u8], open: Open, code: usize, at: usize, size: usize, count: usize) -> Option<(usize, usize)> { + let (opened, f1, before, inside, edges) = open; + assert_eq!(opened + 1, code); + let instructions = count - before; + match code { + 10 => { + assert_eq!(u32_at(b, f1 + 22), at, "where the page ends"); + assert_eq!(u16_at(b, f1 + 26), inside, "the page's layers"); + assert_eq!(u32_at(b, f1 + 28), instructions); + None + } + 12 => { + assert_eq!(u32_at(b, f1 + 8), instructions); + None + } + _ => { + let [x0, y0, x1, y1] = edges.unwrap(); + let stored: Vec = (0..4).map(|k| u32_at(b, f1 + 4 * k) as i32).collect(); + assert_eq!(stored, [x0, y1, x1, y0], "left, top, right and bottom"); + assert_eq!(u32_at(b, f1 + 22), at + size, "where the group ends"); + Some((u16_at(b, f1 + 16), u32_at(b, f1 + 18))) + } + } +} + +/// Walk the instructions of each page of `page_entries`, checking the begin-page, begin-layer and +/// begin-group records, and give where each begin-layer instruction starts and each group's +/// groups and instructions, in the order the groups end. +fn page_records(b: &[u8], page_entries: &[[usize; 4]]) -> (Vec, Vec<(usize, usize)>) { + let mut seen_layers = Vec::new(); + let mut groups = Vec::new(); + for entry in page_entries { + let end = entry[0] + 8 + u32_at(b, entry[0] + 4); + let mut at = entry[0] + 8; + let mut open: Vec = Vec::new(); + let mut count = 0; + while at < end { + let size = instruction_size(b, at, end); + let code = u16_at(b, at + 2); + count += 1; + match code { + 9 | 11 | 13 => { + let f1 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 1).unwrap().1; + if code == 11 { + seen_layers.push(at); + } + // A page counts its layers and a group the groups directly inside it. + if code != 9 { + open.last_mut().unwrap().3 += 1; + } + open.push((code, f1, count - 1, 0, None)); + } + 67 => { + let f2 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 2).unwrap().1; + for i in 0..u16_at(b, f2) { + let p = f2 + 2 + 8 * i; + let (x, y) = (u32_at(b, p) as i32, u32_at(b, p + 4) as i32); + for o in open.iter_mut().filter(|o| o.0 == 13) { + let e = o.4.get_or_insert([x, y, x, y]); + *e = [e[0].min(x), e[1].min(y), e[2].max(x), e[3].max(y)]; + } + } + } + 10 | 12 | 14 => groups.extend(closed_record(b, open.pop().unwrap(), code, at, size, count)), + _ => {} + } + at += size; + } + } + (seen_layers, groups) +} + +/// The size of the instruction at `at` of `b`, in a page that ends at `end`. These files hold +/// only short instructions, so the long form (0xFFFF), a size shorter than the 4-byte header or +/// one past `end` fails the test. +fn instruction_size(b: &[u8], at: usize, end: usize) -> usize { + let size = u16_at(b, at); + assert!(size != 0xFFFF && size >= 4 && at + size <= end, "an instruction of size {size} at {at}, in a page that ends at {end}"); + size +} + +#[test] +#[should_panic(expected = "an instruction of size 0")] +fn an_instruction_of_size_0_fails_the_check() { + instruction_size(&[0, 0, 67, 0], 0, 4); +} + +#[test] +#[should_panic(expected = "an instruction of size 65535")] +fn a_long_instruction_fails_the_check() { + instruction_size(&[0xff, 0xff, 67, 0, 8, 0, 0, 0], 0, 8); +} + +#[test] +#[should_panic(expected = "an instruction of size 8")] +fn an_instruction_past_its_page_fails_the_check() { + instruction_size(&[8, 0, 67, 0], 0, 4); +} + #[test] fn a_uniform_fill_names_the_screen_the_file_holds() { let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes; diff --git a/crates/cms/src/black_tests.rs b/crates/cms/src/black_tests.rs index 2d4864a990..90b7bee271 100644 --- a/crates/cms/src/black_tests.rs +++ b/crates/cms/src/black_tests.rs @@ -10,9 +10,8 @@ fn opts() -> TransformOptions { TransformOptions::default() } -/// L* of a CMYK colour under `p`, measured as the transform with `o` measures it. -fn lightness(p: &Profile, o: TransformOptions, cmyk: [f32; 4]) -> f32 { - let t = Transform::with_options(p, Builtin::LabD50.profile(), o).unwrap(); +/// L* of a CMYK colour, measured by the prebuilt transform. +fn lightness(t: &Transform, cmyk: [f32; 4]) -> f32 { let mut lab = [0.0f32; 3]; t.eval(&cmyk, &mut lab).unwrap(); lab[0] * 100.0 @@ -70,18 +69,22 @@ fn the_destination_black_matches_the_source_lightness() { for intent in [Intent::RelativeColorimetric, Intent::Perceptual] { for bpc in [true, false] { let o = TransformOptions { intent, bpc, ..opts() }; + let coated_lab = Transform::with_options(coated(), Builtin::LabD50.profile(), o).unwrap(); + let fogra_lab = Transform::with_options(fogra(), Builtin::LabD50.profile(), o).unwrap(); // Both directions for one setting; the other settings in the forward one. let directions = if intent == Intent::RelativeColorimetric && bpc { 2 } else { 1 }; - for (src, dst) in [(coated(), fogra()), (fogra(), coated())].into_iter().take(directions) { + for (src, dst, src_lab, dst_lab) in + [(coated(), fogra(), &coated_lab, &fogra_lab), (fogra(), coated(), &fogra_lab, &coated_lab)].into_iter().take(directions) + { let bp = BlackPreserving::new(src, dst, o).unwrap(); - let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]); + let dst_black = lightness(dst_lab, [0.0, 0.0, 0.0, 1.0]); for k in [0.1f32, 0.5, 0.9, 1.0] { - let want = lightness(src, o, [0.0, 0.0, 0.0, k]); + let want = lightness(src_lab, [0.0, 0.0, 0.0, k]); if want <= dst_black { assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1"); continue; } - let got = lightness(dst, o, [0.0, 0.0, 0.0, bp.map_k(k)]); + let got = lightness(dst_lab, [0.0, 0.0, 0.0, bp.map_k(k)]); assert!((got - want).abs() < 0.02, "{intent:?} bpc {bpc} k {k}: L* {got} for {want}"); } assert_eq!(bp.map_k(0.0), 0.0, "paper stays paper"); diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 1705f64002..c026896980 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -901,7 +901,7 @@ mod tests { #[test] fn oklab_profile_has_three_tables() { - let p = CmykParams { grid_a2b: 5, grid_b2a: 5, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; + let p = CmykParams { grid_a2b: 3, grid_b2a: 3, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; let profile = cmyk_profile(&p).unwrap(); let [Some(b0), Some(b1), Some(b2)] = &profile.b2a else { panic!("missing BToA tables") }; assert!(b0 != b1 && b0 != b2, "perceptual shares a table"); diff --git a/crates/color-ui/README.md b/crates/color-ui/README.md index 9c81d3d68b..a38b1f9827 100644 --- a/crates/color-ui/README.md +++ b/crates/color-ui/README.md @@ -7,3 +7,8 @@ Stories: `patterns/color/{picker-dialog, panel, swatches, eyedropper-bar, sample Without `ui`: `CmykModel` (CMYK through a craft-cms profile), swatch files (`palette`: `.aco`, `.act`, `.ase`, `.gpl`, `.css`), the display transform and its caches (`display`), and colour harmonies (`harmony`). The colour model and conversions are in `craft-theme`; profiles and transforms in `craft-cms`. + +`ColorPanel::edited` can supply a colour's native components. Editing one channel preserves the other components, +even when the host renders the colour through a different working-space transform. Current host components take +precedence over the panel's remembered values. Canceling a channel gesture restores the host's complete opening +colour, including its display colour, alpha and native components. diff --git a/crates/color-ui/src/ui/eyedropper.rs b/crates/color-ui/src/ui/eyedropper.rs index 9a238c2863..4e17c7b572 100644 --- a/crates/color-ui/src/ui/eyedropper.rs +++ b/crates/color-ui/src/ui/eyedropper.rs @@ -61,7 +61,7 @@ craft_ui::words! { } /// How many pixels around the pointer the eyedropper averages: Photoshop's Sample Size list. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SampleSize { @@ -115,7 +115,7 @@ impl SampleSize { } /// Which layers the eyedropper reads: Photoshop's Sample list. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SampleSource { @@ -172,7 +172,7 @@ impl SampleSource { } /// The Eyedropper's options bar values. -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct EyedropperOptions { diff --git a/crates/color-ui/src/ui/gradient/editor/bar.rs b/crates/color-ui/src/ui/gradient/editor/bar.rs index ba55ee2823..394dcdfeab 100644 --- a/crates/color-ui/src/ui/gradient/editor/bar.rs +++ b/crates/color-ui/src/ui/gradient/editor/bar.rs @@ -845,7 +845,7 @@ impl Component for GradientBar<'_, P> { let edge_of = |m: StopRef| { if self.selected_marker == Some(m) { style.selected - } else if !dragging && cx.hover_pos(part_of(m)).is_some() { + } else if !dragging && cx.part_if_declared(part_of(m)).is_some_and(|result| result.hovered) { style.hovered } else { cx.resolve(&style.edge) diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index 54fb837833..a13003b5c9 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -68,7 +68,7 @@ pub use paint_chip::{ PaintListEvent, PaintListOptions, PaintListOutput, PaintRow, PaintWords, }; pub use pair::{DropAccepts, PairWell, SwatchPair, SwatchPairOutput, Well}; -pub use palette::{SwatchPalette, SwatchPaletteOutput}; +pub use palette::{PaletteCell, SwatchPalette, SwatchPaletteOutput}; pub use panel::{ ColorPanel, ColorPanelAction, ColorPanelCommand, ColorPanelLayout, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, ColorPanelShown, ColorPanelState, ColorPanelWords, PanelTarget, TintRow, diff --git a/crates/color-ui/src/ui/palette.rs b/crates/color-ui/src/ui/palette.rs index b5d35ac5c0..7da075f1aa 100644 --- a/crates/color-ui/src/ui/palette.rs +++ b/crates/color-ui/src/ui/palette.rs @@ -38,6 +38,18 @@ pub struct SwatchPaletteOutput { /// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour. /// The recent row and the Other… cell do not report a swatch index. pub picked_swatch: Option, + /// The cell `picked` came from, so a host can tell apart cells that show the same color. + pub cell: Option, +} + +/// A cell of a [`SwatchPalette`] by its place in the host's lists. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum PaletteCell { + /// The swatch at this index of the palette's swatches. + Swatch(usize), + /// The color at this index of the recent row's colors. + Recent(usize), } impl Outcome for SwatchPaletteOutput { @@ -112,8 +124,8 @@ impl PaletteColor<'_> { /// What the body picked in its pass. #[derive(Clone, Copy)] enum Pick { - /// A swatch or a recent colour. - Color { color: Srgba, swatch: Option }, + /// A swatch or a recent color, and its cell. + Color(Srgba, PaletteCell), /// The Other… cell. Other, } @@ -235,7 +247,7 @@ impl<'a> SwatchPalette<'a> { // The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates // on its release, so only the activation files the request: one request for one click. pick = picked_cell(&table, ui).and_then(|at| match swatches.get(at) { - Some((_, picked)) => Some(Pick::Color { color: *picked, swatch: Some(at) }), + Some((_, picked)) => Some(Pick::Color(*picked, PaletteCell::Swatch(at))), None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other), }); } @@ -249,8 +261,8 @@ impl<'a> SwatchPalette<'a> { .space(SpaceAction::ActivateLead) .selection(Bind::bound(&mut current)) .show_all(ui); - if let Some((_, picked)) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at)) { - pick = Some(Pick::Color { color: *picked, swatch: None }); + if let Some((at, (_, picked))) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at).map(|cell| (at, cell))) { + pick = Some(Pick::Color(*picked, PaletteCell::Recent(at))); } } Some((before, pick)) @@ -265,19 +277,23 @@ impl<'a> SwatchPalette<'a> { let key = other.as_ref().map(|(key, _)| key.clone())?; Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None)) } - Pick::Color { color: after, swatch } => { + Pick::Color(after, cell) => { let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba()); let edit = (!unchanged).then(|| { color.write(cx, before, after, name.as_str()); let reported = bound.map_or(Mixed::Mixed, Mixed::Same); EditEvent::set(reported, after, Arc::from(name.as_str()), None) }); - Some((Some(after), edit, None, swatch)) + Some((Some(after), edit, None, Some(cell))) } } }) .flatten(); - let (picked, edit, pick_color, picked_swatch) = settled.unwrap_or((None, None, None, None)); - SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch } + let (picked, edit, pick_color, cell) = settled.unwrap_or((None, None, None, None)); + let picked_swatch = match cell { + Some(PaletteCell::Swatch(at)) => Some(at), + _ => None, + }; + SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch, cell } } } diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index d647c65307..dc32f707b1 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -5,7 +5,7 @@ use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::Arc; -use craft_behavior::{EditEvent, GesturePhase, IconId, Mixed}; +use craft_behavior::{EditEvent, GestureId, GesturePhase, IconId, Mixed}; use craft_cms::convert::CmykConverter; use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, RgbModel, Srgba}; use craft_ui::buttons::IconButton; @@ -414,6 +414,8 @@ struct Kept { tracks: Vec<(&'static str, usize, ModelValues)>, /// A channel gesture is running. dragging: bool, + /// The host's complete colour before a model gesture, independent of the panel's transform. + opening: Option<(GestureId, PanelTarget, PickedColor)>, /// The ramp gesture in progress picks for the colour not edited. other: bool, } @@ -450,6 +452,7 @@ pub struct ColorPanel<'a> { edited: Option>, shown: Option, recent: Option<&'a [Srgba]>, + recent_models: &'a [Option], recent_setup: Option, gamut: Option>, } @@ -474,6 +477,7 @@ struct Inputs<'a> { edited: Option<&'a Option>, shown: &'a ColorPanelShown, recent: Option<&'a [Srgba]>, + recent_models: &'a [Option], recent_setup: Option<&'a RecentSetup>, } @@ -492,6 +496,7 @@ impl<'a> ColorPanel<'a> { edited: None, shown: None, recent: None, + recent_models: &[], recent_setup: None, gamut: None, } @@ -541,6 +546,8 @@ impl<'a> ColorPanel<'a> { /// The colour the rows edit, with its model values; `None` disables the rows (mixed, None, a pattern). The edited /// well's colour by default. + /// Explicit components take precedence over remembered values for their model, including when the host uses a + /// different working-space transform to render the colour. pub fn edited(mut self, color: Option) -> Self { self.edited = Some(color); self @@ -559,6 +566,15 @@ impl<'a> ColorPanel<'a> { self } + /// The model values of each Recent Colors chip, in the order of [`recent`](Self::recent). A pick on a chip that has + /// them reports them with its color (`PickedColor::in_model`), so a CMYK recent color stays CMYK, and a chip + /// that shows the edited color's sRGB in another model still sets it. A chip with `None`, or past the end of + /// `models`, works as without this call: a pick sets its sRGB, and a pick of the color already shown sets nothing. + pub fn recent_models(mut self, models: &'a [Option]) -> Self { + self.recent_models = models; + self + } + /// The payload a Recent Colors chip drags. pub fn recent_payload(mut self, map: impl Fn(usize) -> Option

+ Send + Sync + 'static) -> Self { self.recent_setup = Some(recent_setup(map)); @@ -573,7 +589,8 @@ impl<'a> ColorPanel<'a> { /// Shows the panel and returns this pass's edits and requests. pub fn show(self, ui: &mut Ui) -> ColorPanelOutput { - let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_setup, gamut } = self; + let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_models, recent_setup, gamut } = + self; let env = Env::of(ui); let (words, dialog) = (env.words::(), env.words::()); let mut held = Held::new(state); @@ -613,6 +630,7 @@ impl<'a> ColorPanel<'a> { edited: edited.as_ref(), shown: rows.as_ref().unwrap_or(&default_rows), recent, + recent_models, recent_setup: recent_setup.as_ref(), }, now: before, @@ -1052,12 +1070,11 @@ impl Body<'_> { /// The model's values for the edited colour, unrounded: an edit of one channel leaves the others as they are. fn values(&self, model: &dyn ColorModel) -> ModelValues { let color = self.color(); - // The host's own values of the colour (typed CMYK, a working space's numbers) stand when they give the colour. - let given = self.picked().and_then(|picked| picked.model); - let kept = self.kept.values[self.target.index()] - .iter() - .chain(given.as_ref()) - .find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color)); + // Current host values are authoritative: its working-space transform may differ from the panel's. + if let Some(values) = self.picked().and_then(|picked| picked.model).filter(|values| values.model == model.id()) { + return finite_values(values); + } + let kept = self.kept.values[self.target.index()].iter().find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color)); finite_values(kept.copied().unwrap_or_else(|| self.read(model, color))) } @@ -1096,11 +1113,39 @@ impl Body<'_> { fn model_event(&mut self, model: &dyn ColorModel, event: EditEvent) { let event = event.map(finite_values); self.kept.dragging = matches!(event.phase(), Some(GesturePhase::Begin | GesturePhase::Update)); + if let EditEvent::Begin { id, .. } = &event { + self.kept.opening = self.picked().copied().map(|picked| (*id, self.target, picked)); + } if let Some(values) = event.value() { self.remember(model, *values); } let alpha = self.color().a; - let event = event.map(|values| PickedColor { color: model.to_srgb(&values.values).with_alpha(alpha), model: Some(values) }); + let mut event = event.map(|values| PickedColor { color: model.to_srgb(&values.values).with_alpha(alpha), model: Some(values) }); + let opening = self.kept.opening.filter(|(id, target, _)| Some(*id) == event.id() && *target == self.target).map(|(_, _, picked)| picked); + match &mut event { + EditEvent::Begin { before, .. } | EditEvent::Commit { before, .. } => { + if let (Mixed::Same(value), Some(picked)) = (before, opening) { + *value = picked; + } + } + EditEvent::Cancel { before: Some(Mixed::Same(value)), .. } => { + if let Some(picked) = opening { + *value = picked; + if let Some(values) = picked.model.filter(|values| values.model == model.id()) { + self.remember(model, values); + } + } + } + EditEvent::Set { before: Mixed::Same(value), .. } => { + if let Some(picked) = self.picked() { + *value = *picked; + } + } + _ => {} + } + if matches!(event.phase(), Some(GesturePhase::Commit | GesturePhase::Cancel) | None) { + self.kept.opening = None; + } self.push(self.target, event); } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index 183844b574..1e6dd88dd9 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -3,7 +3,7 @@ //! same `Body` as the Photoshop layout and shares its rows, wells, warnings and ramp helpers. use craft_behavior::{EditEvent, Mixed}; -use craft_theme::Srgba; +use craft_theme::{ModelValues, Srgba}; use craft_ui::choice::{Swatch, SwatchSpacing}; use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; use craft_ui::display::{Shade, Text}; @@ -15,7 +15,7 @@ use craft_ui::text::{HexField, TextField}; use egui::Ui; use super::{Body, ColorPanelMode, ColorPanelShown, PanelTarget, TintRow}; -use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PickedColor, RampKind, SwatchPalette}; +use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PaletteCell, PickedColor, RampKind, SwatchPalette}; impl Body<'_> { /// The layout. The options (rows, quick wells, recent colours) go when the state hides them; the proxy and the @@ -156,8 +156,8 @@ impl Body<'_> { } } - /// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list - /// is empty, where the first applied color will go. + /// The Recent Colors caption over a spaced palette; a pick sets the color, in the chip's model when the host gave it. + /// The caption shows while the host's list is empty, where the first applied color will go. // PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and // `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip). fn recent(&mut self, ui: &mut Ui) { @@ -174,13 +174,34 @@ impl Body<'_> { if let Some(setup) = self.inputs.recent_setup { palette = setup(palette); } - if let Some(event) = palette.show(ui).edit + let out = palette.show(ui); + let values = match out.cell { + Some(PaletteCell::Swatch(at)) => self.inputs.recent_models.get(at).copied().flatten(), + _ => None, + }; + if let (Some(color), Some(values)) = (out.picked, values) { + self.set_in_model(color, values); + } else if let Some(event) = out.edit && let Some(color) = event.value() { self.set_color(self.target, *color); } } + /// Sets the edited color to `color` in the model of `values`, keeping its alpha. It sets nothing when the host's + /// color already has those values and shows that color. + fn set_in_model(&mut self, color: Srgba, values: ModelValues) { + let before = self.picked().copied().unwrap_or_else(|| PickedColor::rgb(self.colors[self.target.index()])); + let after = PickedColor::in_model(color.with_alpha(before.color.a), values); + if before.model == after.model && before.color.to_rgba() == after.color.to_rgba() { + return; + } + // The rows' kept values in the chip's model would win over a host that keeps only sRGB (a grey's HSB hue). + self.kept.values[self.target.index()].retain(|v| v.model != values.model); + let name = self.words.title.as_str(); + self.push(self.target, EditEvent::set(Mixed::Same(before), after, name.into(), None)); + } + /// Sets `target`'s colour to `color`, keeping its alpha. fn set_color(&mut self, target: PanelTarget, color: Srgba) { let before = self.colors[target.index()]; diff --git a/crates/color-ui/src/ui/screen_picker/capture.rs b/crates/color-ui/src/ui/screen_picker/capture.rs index d25155f2ce..471ba62648 100644 --- a/crates/color-ui/src/ui/screen_picker/capture.rs +++ b/crates/color-ui/src/ui/screen_picker/capture.rs @@ -229,7 +229,7 @@ impl Component for CaptureView<'_> { .get_or_put(ctx, self.key, Revision::default(), || ColorImage::from_rgba_unmultiplied(image.size.map(|n| n as usize), &image.rgba)); let whole = Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)); ui.draw().texture(cx.rect, texture.id, whole); - let Some(pointer) = cx.response.hover_pos().filter(|at| cx.rect.contains(*at)) else { return }; + let Some(pointer) = craft_ui::runtime::pointer::hover_point_in(ctx, cx.rect) else { return }; let Some((x, y)) = self.pixel(cx.rect, pointer) else { return }; self.loupe(ui, cx, pointer, (x, y)); } diff --git a/crates/color-ui/tests/it/color_parts.rs b/crates/color-ui/tests/it/color_parts.rs index 8bb2598d34..0a44f04ffa 100644 --- a/crates/color-ui/tests/it/color_parts.rs +++ b/crates/color-ui/tests/it/color_parts.rs @@ -210,7 +210,7 @@ fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec> let limits = |_: &usize| craft_ui::contract::SizeLimits::default(); let rules = craft_ui::docking::tree::FrameRules::new(&limits); let area = Rect::from_min_size(ui.max_rect().min + vec2(0.0, 40.0), vec2(400.0, 340.0)); - let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules).show_at(ui, area, |ui, _| { + let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules, 0).show_at(ui, area, |ui, _| { let _ = ColorWheel::new("Color wheel", Bind::given(ModelValues::new("hsb", &[200.0, 50.0, 50.0]))).inner(inner).show(ui); }); let _ = craft_ui::buttons::Button::new("After").show(ui); diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index bb8d7a514d..ffcc37b8c5 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -8,11 +8,11 @@ use craft_behavior::{EditEvent, Mixed, Selection}; use craft_color_ui::palette::{SwatchColor, SwatchGroup}; use craft_color_ui::ui::{ ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel, - PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, - SwatchesWords, swatch_rows, + PaletteCell, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, + SwatchesState, SwatchesWords, swatch_rows, }; use craft_host::target::Os; -use craft_theme::{ColorModel as _, HsbModel, Srgba}; +use craft_theme::{ColorModel as _, HsbModel, ModelValues, Srgba}; use craft_ui::buttons::Button; use craft_ui::choice::SwatchTable; use craft_ui::contract::Role; @@ -197,6 +197,98 @@ fn a_channel_step_keeps_the_other_channels_unrounded() { } } +/// A Color panel whose host supplies authoritative native CMYK components. +fn native_cmyk_panel(picked: PickedColor) -> (Fixture, Rc>, Edits) { + let host = Rc::new(RefCell::new(picked)); + let edits: Edits = Default::default(); + let (color, output) = (host.clone(), edits.clone()); + let mut fixture = Fixture::new(move |ui| { + let picked = *color.borrow(); + let mut state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ..Default::default() }; + let shown = ColorPanel::new(Bind::bound(&mut state), [picked.color; 2]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(picked)) + .shown(ColorPanelShown::Mode(ColorPanelMode::CmykSliders)) + .show(ui); + for (_, event) in &shown.edits { + if let Some(picked) = event.landed() { + *color.borrow_mut() = *picked; + } + } + output.borrow_mut().extend(shown.edits); + }); + fixture.room(COLOR_ROOM).settle(); + (fixture, host, edits) +} + +fn step_cyan(fixture: &mut Fixture) { + let cyan = fixture.by_role(Role::SLIDER).into_iter().next().expect("the Cyan slider"); + fixture.access(AccessActionKind::Focus, &cyan).settle(); + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); +} + +fn last_native_pick(edits: &Edits) -> PickedColor { + edits.borrow().iter().rev().find_map(|(_, event)| event.value().copied()).expect("the channel edit") +} + +/// A host may render its native CMYK through a different working-space transform. Editing one ink still keeps +/// the other explicit components, rather than deriving them from the rendered RGB. +#[trial] +fn a_channel_edit_keeps_native_host_components_with_a_different_transform() { + let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::rgb(0.2, 0.4, 0.6), native); + let (mut fixture, _, edits) = native_cmyk_panel(picked); + step_cyan(&mut fixture); + let after = last_native_pick(&edits).model.expect("native component values"); + assert!(after.values[0] > native.values[0], "Cyan changed"); + assert_eq!(&after.values[1..4], &native.values[1..4], "the other native inks stay exact"); +} + +/// Fresh host components win over remembered components even when both still give the same display pixel. +#[trial] +fn fresh_host_components_replace_the_panels_remembered_components() { + let model = craft_color_ui::CmykModel::new(craft_cms::convert::CmykConverter::coated().clone()); + let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(model.to_srgb(&native.values), native); + let (mut fixture, host, edits) = native_cmyk_panel(picked); + step_cyan(&mut fixture); + let kept = last_native_pick(&edits); + let mut fresh = kept.model.expect("remembered native values"); + fresh.values[1] += 0.001; + assert!(model.to_srgb(&fresh.values).same_rgb8(kept.color), "the host update keeps the display pixel"); + *host.borrow_mut() = PickedColor::in_model(kept.color, fresh); + fixture.settle(); + step_cyan(&mut fixture); + let after = last_native_pick(&edits).model.expect("the next channel edit"); + assert!(after.values[0] > fresh.values[0], "Cyan changed again"); + assert_eq!(&after.values[1..4], &fresh.values[1..4], "fresh host inks replace the older cache"); +} + +/// Cancel restores both the native inks and the host's display colour, even after the host applies live updates. +#[trial] +fn a_canceled_native_channel_drag_restores_the_hosts_original_color() { + let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native); + let (mut fixture, host, edits) = native_cmyk_panel(picked); + let cyan = fixture.by_role(Role::SLIDER).into_iter().next().expect("the Cyan slider"); + fixture.drag_hold_at(cyan.center(), Vec2::new(25.0, 0.0)).settle(); + assert_ne!(*host.borrow(), picked, "the host applies the live channel preview"); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + let canceled = edits + .borrow() + .iter() + .rev() + .find_map(|(_, event)| match event { + EditEvent::Cancel { before: Some(Mixed::Same(before)), .. } => Some(*before), + _ => None, + }) + .expect("the channel drag cancels"); + assert_eq!(canceled, picked, "Cancel carries the host's exact opening colour and model"); + assert_eq!(*host.borrow(), picked, "the host restores the complete opening colour"); + fixture.release_at(cyan.center() + Vec2::new(25.0, 0.0)).settle(); + assert_eq!(*host.borrow(), picked, "release after Cancel cannot reapply the preview"); +} + /// The rect of the FillStroke spectrum in Web Color for a foreground of `color`. fn spectrum_rect(color: Srgba) -> egui::Rect { let mut fixture = Fixture::new(move |ui| { @@ -275,6 +367,88 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow()); } +/// A Recent Colors pick in the FillStroke layout reports the chip's model values with its color, also when the chip +/// shows the edited color's sRGB in another model or without one; a chip whose values the edited color already has +/// sets nothing. +#[trial] +fn a_fill_stroke_recent_pick_keeps_the_chips_model() { + let chip = RECENT[0]; + let cmyk = ModelValues::new("cmyk", &[60.0, 90.0, 0.0, 0.0]); + let pick = |edited: PickedColor| { + let edits: Edits = Default::default(); + let seen = Rc::clone(&edits); + let mut fixture = Fixture::new(move |ui| { + let mut state = ColorPanelState::default(); + let out = ColorPanel::new(Bind::bound(&mut state), [edited.color, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(edited)) + .recent(&RECENT) + .recent_models(&[Some(cmyk)]) + .show(ui); + seen.borrow_mut().extend(out.edits); + }); + fixture.room(COLOR_ROOM).settle(); + let recent = fixture.by_label(&chip.to_hex()).expect("the recent chip is named by its hex"); + fixture.click(&recent).settle(); + edits.take() + }; + let rgb_of = |color: Srgba| ModelValues::new("rgb", &[color.r * 255.0, color.g * 255.0, color.b * 255.0]); + for edited in [PickedColor::in_model(RED, rgb_of(RED)), PickedColor::in_model(chip, rgb_of(chip)), PickedColor::rgb(chip)] { + let edits = pick(edited); + assert!( + matches!(edits.as_slice(), [(PanelTarget::Foreground, EditEvent::Set { after, .. })] + if after.model == Some(cmyk) && after.color.to_rgba() == chip.to_rgba()), + "one Set to the chip in CMYK from {edited:?}: {edits:?}" + ); + } + let edits = pick(PickedColor::in_model(chip, cmyk)); + assert!(edits.is_empty(), "the chip's own values set nothing: {edits:?}"); +} + +/// A Recent Colors pick drops the HSB values the rows kept for a grey: after a host that keeps only sRGB applies a grey +/// chip with HSB values, the Hue row reads the grey afresh instead of the hue of the earlier row edits. +#[trial] +fn a_fill_stroke_recent_pick_drops_the_rows_kept_hue() { + let grey = Srgba::rgb(0.5, 0.5, 0.5); + let chip = [grey]; + let chip_hsb = ModelValues::new("hsb", &[0.0, 0.0, 50.0]); + let host = Rc::new(RefCell::new(grey)); + let color = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| { + let current = *color.borrow(); + let mut state = ColorPanelState { mode: ColorPanelMode::HsbSliders, ..Default::default() }; + let shown = ColorPanel::new(Bind::bound(&mut state), [current, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(PickedColor::rgb(current))) + .shown(ColorPanelShown::Mode(ColorPanelMode::HsbSliders)) + .recent(&chip) + .recent_models(&[Some(chip_hsb)]) + .show(ui); + for (_, event) in &shown.edits { + if let Some(picked) = event.landed() { + *color.borrow_mut() = picked.color; + } + } + }); + fixture.room(COLOR_ROOM).settle(); + let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider"); + fixture.access(AccessActionKind::Focus, &hue).settle(); + for _ in 0..20 { + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); + } + let hue_value = |fixture: &mut Fixture| { + let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider"); + fixture.access(AccessActionKind::Focus, &hue).settle(); + let id = fixture.focused().expect("the hue slider takes the focus"); + fixture.tree().value(id).expect("the hue slider reports its value").to_owned() + }; + let stepped = hue_value(&mut fixture); + assert_ne!(stepped, "0", "the steps moved the kept hue of the grey"); + let recent = fixture.by_label(&grey.to_hex()).expect("the recent chip is named by its hex"); + fixture.click(&recent).settle(); + assert_eq!(hue_value(&mut fixture), "0", "the pick drops the kept hue {stepped}"); +} + /// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked, /// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls. #[trial] @@ -379,6 +553,7 @@ struct PaletteReports { edits: Vec>, requests: Vec, picked: Vec, + cells: Vec, swatches: Vec, } @@ -390,6 +565,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) { reports.edits.extend(shown.edit); reports.requests.extend(shown.pick_color); reports.picked.extend(shown.picked); + reports.cells.extend(shown.cell); reports.swatches.extend(shown.picked_swatch); } @@ -447,11 +623,13 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() { taken.edits[0] ); assert_eq!(bound.get().to_rgba(), RECENT[0].to_rgba(), "the recent pick is written"); + assert_eq!(taken.cells, [PaletteCell::Recent(0)], "the pick names its cell in the recent row"); let violet = fixture.by_label("Violet").expect("violet"); fixture.click(&violet).settle(); - let _ = std::mem::take(&mut *reports.borrow_mut()); + let taken = std::mem::take(&mut *reports.borrow_mut()); assert_eq!(bound.get().to_rgba(), swatch("Violet").to_rgba()); + assert_eq!(taken.cells, [PaletteCell::Swatch(5)], "the pick names its swatch"); // Past the double-click time, so the repeat is a single click of its own. fixture.advance(1.0); let violet = fixture.by_label("Violet").expect("violet"); diff --git a/crates/control-protocol/Cargo.toml b/crates/control-protocol/Cargo.toml index f00bbc1c66..80f7d5af64 100644 --- a/crates/control-protocol/Cargo.toml +++ b/crates/control-protocol/Cargo.toml @@ -13,3 +13,7 @@ workspace = true [dependencies] serde_json = { workspace = true } subtle = "2" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# The session token: 32 random bytes from the operating system (MIT OR Apache-2.0). +getrandom = "0.3" diff --git a/crates/control-protocol/src/lib.rs b/crates/control-protocol/src/lib.rs index 8194dc8e96..4bd0582853 100644 --- a/crates/control-protocol/src/lib.rs +++ b/crates/control-protocol/src/lib.rs @@ -1,7 +1,10 @@ //! 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::cell::Cell; use std::io::{BufRead, BufReader, BufWriter, Read, Write}; +use std::net::TcpStream; +use std::time::{Duration, Instant}; use subtle::ConstantTimeEq; /// Whether a session token has the control protocol's 64 hexadecimal character form. @@ -9,6 +12,15 @@ pub fn valid_token(token: &str) -> bool { token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit()) } +/// A new session token that [`valid_token`] accepts: 32 bytes from the operating system's random +/// source, as lowercase hexadecimal. `None` when the system cannot supply random bytes. +#[cfg(not(target_arch = "wasm32"))] +pub fn new_token() -> Option { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).ok()?; + Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} + /// Encode one client request, including its terminating newline. pub fn request_line(id: u64, token: Option<&str>, method: &str, params: &Value) -> String { format!("{}\n", json!({"id": id, "token": token, "method": method, "params": params})) @@ -103,9 +115,112 @@ pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usiz /// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is /// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and /// returns the reply object (the request's `id` is added here). -pub fn serve_lines(read: R, mut out: W, token: &str, max_line: usize, mut handle: impl FnMut(String, Value) -> Option) { - let mut reader = BufReader::new(read); +pub fn serve_lines(read: R, out: W, token: &str, max_line: usize, handle: impl FnMut(String, Value) -> Option) { + serve(BufReader::new(read), out, token, max_line, |_| Ok(()), |_| false, handle); +} + +/// Serve one TCP connection as [`serve_lines`] does, but give the peer `first_request` from now +/// to send its first authenticated request. Until then every read shares that one deadline, so +/// blank lines or a line sent a byte at a time do not extend it; when it passes, the connection +/// closes without a reply and nothing is dispatched. After the first authenticated request, each +/// read waits at most `idle` (`None` waits without limit). A `first_request` too long for the +/// clock to represent waits without limit. The connection is closed when this returns. +/// +/// Returns an `InvalidInput` error, before reading anything, when `first_request` or `idle` is +/// zero, and any error from setting the socket's read timeout. +pub fn serve_tcp( + stream: TcpStream, + token: &str, + max_line: usize, + first_request: Duration, + idle: Option, + handle: impl FnMut(String, Value) -> Option, +) -> std::io::Result<()> { + if first_request.is_zero() || idle.is_some_and(|d| d.is_zero()) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "control wait times must be longer than zero")); + } + let deadline = Instant::now().checked_add(first_request); + if deadline.is_none() { + // No deadline to apply on each read: clear any read timeout the stream already has. + stream.set_read_timeout(None)?; + } + let timeout_error = Cell::new(None); + let input = FirstRequestDeadline { socket: &stream, deadline, timeout_error: &timeout_error }; + serve( + BufReader::new(input), + &stream, + token, + max_line, + |input: &mut FirstRequestDeadline<'_>| input.admit(idle), + FirstRequestDeadline::expired, + handle, + ); + timeout_error.take().map_or(Ok(()), Err) +} + +/// A TCP connection's input whose reads share one deadline until the peer is admitted. +struct FirstRequestDeadline<'a> { + socket: &'a TcpStream, + deadline: Option, + /// The error from setting the socket's read timeout, which [`serve_tcp`] returns. + timeout_error: &'a Cell>, +} + +impl FirstRequestDeadline<'_> { + fn set_timeout(&self, timeout: Option) -> std::io::Result<()> { + self.socket.set_read_timeout(timeout).map_err(|e| { + let kind = e.kind(); + self.timeout_error.set(Some(e)); + kind.into() + }) + } + + /// The peer sent an authenticated request: from now on each read waits at most `idle`. A + /// request admitted after the first-request deadline returns `TimedOut` instead, and the + /// deadline stays in place. + fn admit(&mut self, idle: Option) -> std::io::Result<()> { + if self.expired() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.deadline = None; + self.set_timeout(idle) + } + + /// Whether the first-request deadline has passed and no request was admitted before it. + fn expired(&self) -> bool { + self.deadline.is_some_and(|deadline| Instant::now() >= deadline) + } +} + +impl Read for FirstRequestDeadline<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if let Some(deadline) = self.deadline { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.set_timeout(Some(left))?; + } + let mut socket = self.socket; + socket.read(buf) + } +} + +/// The request loop of [`serve_lines`] and [`serve_tcp`]: `admit` runs once, on the input, after +/// the first authenticated request and before it is dispatched; an error from it closes the +/// connection. Before the first request is admitted, a rejection closes the connection without a +/// reply when `expired` returns true for the input. +fn serve( + mut reader: BufReader, + mut out: W, + token: &str, + max_line: usize, + mut admit: impl FnMut(&mut R) -> std::io::Result<()>, + expired: impl Fn(&R) -> bool, + mut handle: impl FnMut(String, Value) -> Option, +) { let mut buf = Vec::new(); + let mut admitted = false; loop { let reject = match read_bounded_line(&mut reader, &mut buf, max_line) { Ok(false) => return, @@ -117,6 +232,12 @@ pub fn serve_lines(read: R, mut out: W, token: &str, max_line Line::Blank => continue, Line::Reject(e) => e, Line::Request { id, method, params } => { + if !admitted { + if admit(reader.get_mut()).is_err() { + return; + } + admitted = true; + } let Some(mut r) = handle(method, params) else { return }; if let Some(o) = r.as_object_mut() { o.insert("id".into(), id); @@ -128,6 +249,9 @@ pub fn serve_lines(read: R, mut out: W, token: &str, max_line } }, }; + if !admitted && expired(reader.get_ref()) { + return; + } let _ = write_line(&mut out, &json!({"ok": false, "error": reject})); return; } @@ -249,6 +373,19 @@ mod tests { assert!(!valid_token(&"g".repeat(64))); } #[test] + #[cfg(not(target_arch = "wasm32"))] + fn new_tokens_are_valid_and_distinct() { + let first = new_token().unwrap(); + let second = new_token().unwrap(); + assert!(valid_token(&first)); + assert!(valid_token(&second)); + assert_ne!(first, second); + let input = request_line(1, Some(&first), "status", &json!({})); + let mut output = Vec::new(); + serve_lines(input.as_bytes(), &mut output, &first, 4096, |_, _| Some(json!({"ok": true}))); + assert_eq!(serde_json::from_slice::(&output).unwrap(), json!({"ok": true, "id": 1})); + } + #[test] fn authenticates_each_request_and_closes_after_failure() { let input = b"{\"id\":1,\"method\":\"first\",\"token\":\"secret\"}\n{\"id\":2,\"method\":\"second\"}\n{\"method\":\"third\",\"token\":\"secret\"}\n"; @@ -263,6 +400,115 @@ mod tests { assert_eq!(lines[0], json!({"ok": true, "id": 1})); assert_eq!(lines[1]["error"], "control authentication failed; closing the connection"); } + /// The serving thread: what `serve_tcp` returned and the methods it dispatched. + type Server = std::thread::JoinHandle<(std::io::Result<()>, Vec)>; + /// A loopback connection whose client sent `input` before `serve_tcp` starts serving it on + /// another thread, so the server has read everything the client sends when a wait runs out. + fn tcp_session(input: &[u8], first_request: Duration, idle: Option) -> (TcpStream, Server) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + // Guards the test against a server that never closes; the assertions do not depend on it. + client.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); + client.write_all(input).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let server = std::thread::spawn(move || { + let mut calls = Vec::new(); + let result = serve_tcp(stream, "secret", 1024, first_request, idle, |method, _| { + calls.push(method); + Some(json!({"ok": true})) + }); + (result, calls) + }); + (client, server) + } + #[test] + fn tcp_peer_without_a_request_loses_the_connection() { + let (mut client, server) = tcp_session(b"\n{\"method\":", Duration::from_millis(50), None); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).expect("the server closes the connection"); + assert!(rest.is_empty()); + let (result, calls) = server.join().unwrap(); + assert!(result.is_ok()); + assert!(calls.is_empty()); + } + #[test] + fn tcp_input_waiting_after_the_deadline_is_not_read() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + client.write_all(b"\n\n").unwrap(); + let (stream, _) = listener.accept().unwrap(); + let timeout_error = Cell::new(None); + let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error }; + assert_eq!(input.read(&mut [0; 8]).unwrap_err().kind(), std::io::ErrorKind::TimedOut); + assert!(timeout_error.take().is_none()); + } + #[test] + fn tcp_request_read_after_the_deadline_is_not_admitted() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let timeout_error = Cell::new(None); + let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error }; + assert_eq!(input.admit(None).unwrap_err().kind(), std::io::ErrorKind::TimedOut); + assert!(input.deadline.is_some()); + assert!(timeout_error.take().is_none()); + } + #[test] + fn rejection_read_after_the_deadline_gets_no_reply() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let timeout_error = Cell::new(None); + let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error }; + assert!(input.expired()); + input.deadline = None; + assert!(!input.expired()); + let long = format!("{}\n", "x".repeat(100)); + for line in [&b"{broken}\n"[..], &b"{\"method\":\"x\",\"token\":\"wrong\"}\n"[..], long.as_bytes()] { + let mut out = Vec::new(); + serve(BufReader::new(line), &mut out, "secret", 64, |_| Ok(()), |_| true, |_, _| panic!("must not dispatch")); + assert!(out.is_empty()); + } + } + #[test] + fn tcp_peer_waits_idle_time_after_its_first_request() { + let input = b"{\"id\":1,\"method\":\"first\",\"token\":\"secret\"}\n"; + let (mut client, server) = tcp_session(input, Duration::from_secs(600), Some(Duration::from_millis(50))); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).expect("the server closes the idle connection"); + assert_eq!(serde_json::from_slice::(&rest).unwrap(), json!({"ok": true, "id": 1})); + let (result, calls) = server.join().unwrap(); + assert!(result.is_ok()); + assert_eq!(calls, ["first"]); + } + #[test] + fn tcp_peer_sending_blank_lines_still_loses_the_connection_at_the_deadline() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let server = + std::thread::spawn(move || serve_tcp(stream, "secret", 1024, Duration::from_millis(200), None, |_, _| panic!("must not dispatch"))); + // Every read finds a new line, so a deadline that restarted on each read would never expire. + // The loop ends when the server closes the connection; the guard only stops a hung test. + client.set_write_timeout(Some(Duration::from_secs(30))).unwrap(); + let guard = Instant::now() + Duration::from_secs(30); + while client.write_all(b"\n").is_ok() { + assert!(Instant::now() < guard, "the server kept reading past the first-request deadline"); + std::thread::yield_now(); + } + assert!(Instant::now() < guard, "the server stopped reading but kept the connection open"); + assert!(server.join().unwrap().is_ok()); + } + #[test] + fn tcp_rejects_zero_wait_times() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + for (first, idle) in [(Duration::ZERO, None), (Duration::from_secs(1), Some(Duration::ZERO))] { + let err = serve_tcp(stream.try_clone().unwrap(), "secret", 1024, first, idle, |_, _| panic!("must not dispatch")).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + } + } #[test] fn bounds_requests_and_preserves_last_unterminated_line() { let mut buf = Vec::new(); diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index e71a0e364b..4b128a370b 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -22,9 +22,8 @@ serde_json = { workspace = true } # The loopback server is for desktop apps; the web app is driven through the page instead. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -# The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0). -getrandom = "0.3" -# The request-line reader and the reply's result, shared with servers built on it (MIT OR Apache-2.0, ours). +# The request-line reader, the reply's result and the per-launch token generator, 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 } diff --git a/crates/control/src/agents/live.rs b/crates/control/src/agents/live.rs index fd975fd283..2818e7fad6 100644 --- a/crates/control/src/agents/live.rs +++ b/crates/control/src/agents/live.rs @@ -147,6 +147,16 @@ pub struct LiveConfig { pub launch_timeout: Duration, /// How often a starting app is looked for ([`LAUNCH_POLL`]; kept between 1 ms and 1 s). pub poll: Duration, + /// The clock the launch timeout is measured on ([`Instant::now`]). + #[doc(hidden)] + pub now: Box Instant + Send + Sync>, + /// Waits one poll while a started app is looked for ([`std::thread::sleep`]). + #[doc(hidden)] + pub sleep: Box, + /// Called by each [`Live::resolve`] once it has noted how many starts have finished, before it + /// waits for the lookup. + #[doc(hidden)] + pub on_queued: Option>, consent: ConsentFn, connect: ConnectFn, headless: HeadlessFn, @@ -173,6 +183,9 @@ impl LiveConfig { launch: None, launch_timeout: LAUNCH_TIMEOUT, poll: LAUNCH_POLL, + now: Box::new(Instant::now), + sleep: Box::new(std::thread::sleep), + on_queued: None, consent: Box::new(consent), connect: Box::new(connect), headless: Box::new(headless), @@ -246,6 +259,9 @@ impl Live { /// result. pub fn resolve(&self) -> Result, String> { let queued_at = self.finished.load(Ordering::Acquire); + if let Some(queued) = &self.cfg.on_queued { + queued(); + } let mut last_failure = self.lookup.lock().unwrap_or_else(PoisonError::into_inner); let consent = (self.cfg.consent)(&self.cfg.config_dir); // Allow Agent Control off refuses agents, as the app does: it doesn't listen then. @@ -310,15 +326,15 @@ impl Live { }; launch().map_err(|e| format!("couldn't start {app}: {e}"))?; let timeout = self.cfg.launch_timeout.min(MAX_LAUNCH_TIMEOUT); - let started = Instant::now(); + let started = (self.cfg.now)(); let deadline = started.checked_add(timeout).unwrap_or(started); let poll = self.cfg.poll.clamp(POLL_RANGE.0, POLL_RANGE.1); loop { - std::thread::sleep(poll); + (self.cfg.sleep)(poll); if let Some(window) = self.find_app()? { return self.use_window(window); } - if Instant::now() >= deadline { + if (self.cfg.now)() >= deadline { return Err(format!( "{app} didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check that AI agents are on in ArtCraft Launcher › Settings › AI agents.", timeout.as_secs() diff --git a/crates/control/src/agents/switch.rs b/crates/control/src/agents/switch.rs index 9165879dc3..b5cabcc7fb 100644 --- a/crates/control/src/agents/switch.rs +++ b/crates/control/src/agents/switch.rs @@ -44,7 +44,11 @@ impl AgentSwitch { if !flag { return Self::fixed(false, false); } - Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake) + let tick = || { + std::thread::sleep(POLL); + true + }; + Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), tick, wake) } /// A switch that never changes: tests, the web, an app without agents. @@ -52,14 +56,20 @@ impl AgentSwitch { Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) } } - /// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`. + /// [`Self::watch`] with the flag given and `probe` asked once now. The watch thread then calls + /// `tick`, which returns when the next poll is due ([`Self::watch`] sleeps [`POLL`]), and asks + /// `probe` again; the watch ends when `tick` returns `false`. #[doc(hidden)] - pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: impl Fn() + Send + 'static) -> Self { + pub fn watch_with( + mcp_flag: bool, + probe: impl Fn() -> bool + Send + 'static, + mut tick: impl FnMut() -> bool + Send + 'static, + wake: impl Fn() + Send + 'static, + ) -> Self { let on = Arc::new(AtomicBool::new(probe())); let seen: Weak = Arc::downgrade(&on); let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || { - loop { - std::thread::sleep(poll); + while tick() { let now = probe(); let Some(seen) = seen.upgrade() else { return }; if seen.swap(now, Ordering::Relaxed) != now { diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs index e20bada163..32f757ac8e 100644 --- a/crates/control/src/client_tests.rs +++ b/crates/control/src/client_tests.rs @@ -4,11 +4,12 @@ use super::*; use crate::ControlRequest; use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits}; use socket2::{Domain, Socket, Type}; +use std::cell::RefCell; use std::ffi::OsString; use std::net::TcpListener; use std::path::PathBuf; use std::sync::Arc; -use std::sync::mpsc::channel; +use std::sync::mpsc::{Receiver, Sender, channel}; const TOKEN: &str = "0123456789abcdef0123456789abcdef"; @@ -51,22 +52,17 @@ impl Protocol for Probe { } } -/// The app on `port` (0: an ephemeral one) behind [`TOKEN`]: its window answers each request after -/// `delay` with the request's method and parameters, and the server says a request is still -/// running after `wait`. -fn serve(port: u16, delay: Duration, wait: Duration) -> Stop { - // A port just closed may take a moment to be free again on a loaded machine. - let started = Instant::now(); - let mut bound = TcpListener::bind(("127.0.0.1", port)); - while bound.is_err() && started.elapsed() < Duration::from_secs(2) { - std::thread::sleep(Duration::from_millis(10)); - bound = TcpListener::bind(("127.0.0.1", port)); - } - let listener = bound.unwrap(); +/// The app on `listener` behind [`TOKEN`]: its window answers each request with the request's +/// method and parameters. With a `gate`, it answers each request only once the gate is opened (a +/// message, or the sender dropped), and the server says at once that the request is still running. +fn serve(listener: TcpListener, gate: Option>) -> Stop { + let wait = if gate.is_some() { Duration::ZERO } else { Duration::from_secs(10) }; let (tx, rx) = channel::(); std::thread::spawn(move || { for req in rx { - std::thread::sleep(delay); + if let Some(gate) = &gate { + let _ = gate.recv(); + } let _ = req.reply.send(json!({"ok": true, "result": {"method": req.method, "params": req.params}})); } }); @@ -75,6 +71,60 @@ fn serve(port: u16, delay: Duration, wait: Duration) -> Stop { hub.listen_stoppable(listener, TOKEN.into(), tx, false).unwrap() } +/// A listener on an ephemeral loopback port. +fn any_port() -> TcpListener { + TcpListener::bind("127.0.0.1:0").unwrap() +} + +/// `port` bound as [`TcpListener::bind`] binds it, but not listening yet: the port stays held, and +/// a connection to it is refused until [`listen`]. A listener just stopped may still hold the port +/// on a loaded machine ([`Stop::stop`] waits at most a couple of seconds), so the bind is retried +/// for up to two seconds. +fn hold(port: u16) -> Socket { + let started = Instant::now(); + hold_after(port, || { + if started.elapsed() >= Duration::from_secs(2) { + return false; + } + std::thread::sleep(Duration::from_millis(10)); + true + }) +} + +/// [`hold`], calling `busy` each time the port is still taken; the bind is tried again while +/// `busy` returns true. +fn hold_after(port: u16, mut busy: impl FnMut() -> bool) -> Socket { + let address = std::net::SocketAddr::from(([127, 0, 0, 1], port)).into(); + loop { + let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(socket2::Protocol::TCP)).unwrap(); + #[cfg(not(windows))] + socket.set_reuse_address(true).unwrap(); + match socket.bind(&address) { + Ok(()) => return socket, + Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && busy() => {} + Err(e) => panic!("binding 127.0.0.1:{port}: {e}"), + } + } +} + +fn listen(socket: Socket) -> TcpListener { + socket.listen(128).unwrap(); + socket.into() +} + +thread_local! { + /// Opened by [`open_gate`] when the client first reports a wait. + static GATE: RefCell>> = const { RefCell::new(None) }; +} + +/// A client's progress report: the app said its request is still running, so its window may +/// answer now. +fn open_gate(_: &str) { + if let Some(gate) = GATE.with(|g| g.borrow_mut().take()) { + let _ = gate.send(()); + } +} + fn addr(port: u16) -> String { format!("127.0.0.1:{port}") } @@ -91,7 +141,7 @@ fn reserve_non_listening_port() -> (Socket, u16) { #[test] fn a_call_is_one_round_trip_with_the_token() { - let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let app = serve(any_port(), None); let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)); assert!(!c.is_connected()); let r = c.call(Request::new("document.inspect", json!({"a": 1}))).unwrap(); @@ -109,7 +159,7 @@ fn a_call_is_one_round_trip_with_the_token() { #[test] fn a_wrong_token_or_none_is_refused() { - let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let app = serve(any_port(), None); for token in [Some("fedcba9876543210fedcba9876543210"), None] { let mut c = Connection::new(APP, &addr(app.port()), token); match c.call(Request::new("document.inspect", json!({}))) { @@ -139,20 +189,36 @@ fn the_not_running_fixture_keeps_its_port_from_another_listener() { drop(reserved); } +/// A port a listener still holds is bound once that listener closes, not refused at the first try. +#[test] +fn holding_a_port_waits_for_the_listener_on_it_to_close() { + let mut listener = Some(any_port()); + let port = listener.as_ref().unwrap().local_addr().unwrap().port(); + let mut tries = 0; + let held = hold_after(port, || { + tries += 1; + listener.take().is_some() + }); + assert_eq!(tries, 1, "the port was free while its listener was open"); + assert_eq!(held.local_addr().unwrap().as_socket().unwrap().port(), port); +} + /// An app that goes away during a call is lost, not "not running"; the next call says it is not /// running, and once it runs again the next call reaches it. #[test] fn an_app_gone_during_a_call_is_lost_and_reached_again_once_back() { - let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let app = serve(any_port(), None); let port = app.port(); let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); c.call(Request::new("document.inspect", json!({}))).unwrap(); app.stop(); + // Held, not listening, until the app is back, so no other listener takes the port meanwhile. + let held = hold(port); let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err(); let CallError::Lost(m) = &e else { panic!("{e:?}") }; assert!(m.contains("may have quit") && m.contains("Inspect the design") && m.contains(&format!("`probe --control {port}`")), "{m}"); assert!(matches!(c.call(Request::new("document.inspect", json!({}))), Err(CallError::NotRunning(_)))); - let _back = serve(port, Duration::ZERO, Duration::from_secs(10)); + let _back = serve(listen(held), None); assert_eq!(c.call(Request::new("ui.view", json!({}))).unwrap()["method"], json!("ui.view")); } @@ -178,10 +244,13 @@ fn a_connection_closed_without_a_reply_is_lost() { /// connection, and its own reply is the call's result. #[test] fn a_request_still_running_is_waited_for_through_pending() { - let app = serve(0, Duration::from_millis(400), Duration::from_millis(50)); - let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)); + let (gate, held) = channel(); + let app = serve(any_port(), Some(held)); + GATE.with(|g| *g.borrow_mut() = Some(gate)); + let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)).with_progress(open_gate); c.set_waits(Waits { pending: Duration::from_secs(10), settle: Duration::from_secs(10), poll: Duration::from_millis(5) }); let r = c.call(Request::new("solid.slow", json!({"n": 2}))).unwrap(); + assert!(GATE.with(|g| g.borrow().is_none()), "the app never said the request was still running"); assert_eq!(r, json!({"method": "solid.slow", "params": {"n": 2}})); assert!(!c.has_outstanding()); assert_eq!(c.pending(), json!({"pending": null})); @@ -190,15 +259,17 @@ fn a_request_still_running_is_waited_for_through_pending() { /// Past the wait, the call says the request is still running, and `pending` later has its end. #[test] fn a_request_still_running_past_the_wait_is_reported_and_its_end_kept() { - let app = serve(0, Duration::from_millis(400), Duration::from_millis(20)); + let (gate, held) = channel(); + let app = serve(any_port(), Some(held)); let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)); - c.set_waits(Waits { pending: Duration::from_millis(30), settle: Duration::from_secs(10), poll: Duration::from_millis(5) }); + c.set_waits(Waits { pending: Duration::ZERO, settle: Duration::from_secs(10), poll: Duration::from_millis(5) }); let mut slow = Request::new("solid.slow", json!({})); slow.what = "`solid.slow` (now)".into(); let e = c.call(slow).unwrap_err(); let CallError::StillRunning(m) = &e else { panic!("{e:?}") }; assert!(m.starts_with(STILL_RUNNING) && m.contains("`solid.slow` (now)") && m.contains("will still apply"), "{m}"); assert!(c.has_outstanding()); + gate.send(()).unwrap(); let end = c.pending(); assert_eq!(end["done"], json!(true), "{end}"); assert_eq!(end["reply"]["result"]["method"], json!("solid.slow"), "{end}"); diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs index a276060c81..1346d68d89 100644 --- a/crates/control/src/server.rs +++ b/crates/control/src/server.rs @@ -7,7 +7,7 @@ use std::io::{BufRead, BufReader, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; -use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; use craft_control_protocol::ReadFailure; @@ -60,11 +60,16 @@ pub struct Hub { /// Longest request line accepted. max_line: usize, waits: Waits, + clock: Clock, watch: &'static DocumentWatch, running: Arc, open: AtomicUsize, } +/// The time a connection's token deadline is measured on: [`Instant::now`], or a clock a test +/// moves. +pub type Clock = Arc Instant + Send + Sync>; + impl Hub { /// A server for `protocol`'s requests; `wake` makes the window look at its requests now. pub fn new(protocol: impl Protocol + 'static, wake: impl Fn() + Send + Sync + 'static, max_line: usize) -> Self { @@ -73,6 +78,7 @@ impl Hub { wake: Box::new(wake), max_line, waits: Waits::default(), + clock: Arc::new(Instant::now), watch: &DOCUMENT_WATCH, running: Arc::new(Running::new()), open: AtomicUsize::new(0), @@ -85,6 +91,12 @@ impl Hub { self } + /// Another clock for the token deadline than [`Instant::now`] (tests). + pub fn with_clock(mut self, clock: Clock) -> Self { + self.clock = clock; + self + } + /// Another document watch than the app's [`DOCUMENT_WATCH`] (tests). pub fn with_watch(mut self, watch: &'static DocumentWatch) -> Self { self.watch = watch; @@ -187,12 +199,17 @@ impl Stop { } /// Stop accepting, close the port and end every connection it accepted. Returns once the - /// port is closed (at most a couple of seconds), so the same port can be bound again at once. + /// port is closed, so the same port can be bound again at once. When no connection can be + /// made to wake the listener, it waits at most two seconds for the port to close. pub fn stop(self) { self.shared.stopped.store(true, Ordering::SeqCst); - // The listener waits in `accept`: a connection of our own wakes it to see the flag. - let _ = TcpStream::connect_timeout(&self.addr, Duration::from_secs(1)); - let _ = self.closed.recv_timeout(Duration::from_secs(2)); + // The listener waits in `accept`: a connection of our own wakes it to see the flag. Once + // that connection is made, the listener accepts it and ends however busy the machine is. + if TcpStream::connect_timeout(&self.addr, Duration::from_secs(1)).is_ok() { + let _ = self.closed.recv(); + } else { + let _ = self.closed.recv_timeout(Duration::from_secs(2)); + } self.shared.close_all(); } } @@ -209,12 +226,9 @@ const EVENT_GAP: Duration = Duration::from_millis(100); /// [`MAX_CONNECTIONS`] goes to someone else. const TOKEN_WAIT: Duration = Duration::from_secs(5); -/// A new random token: 32 bytes from the operating system, as hex. -pub fn new_token() -> Option { - let mut bytes = [0u8; 32]; - getrandom::fill(&mut bytes).ok()?; - Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) -} +/// A new random token: 32 bytes from the operating system, as hex. The generator lives in +/// [`craft_control_protocol`], so this crate and servers built on that crate make the same tokens. +pub use craft_control_protocol::new_token; /// 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 @@ -283,7 +297,8 @@ fn refuse(out: &mut TcpStream, reader: &mut BufReader, docs: &str) use std::io::Read; let _ = send(out, &unauthorized(docs)); let _ = out.shutdown(std::net::Shutdown::Write); - reader.get_mut().deadline = Some(Instant::now() + Duration::from_millis(500)); + let input = reader.get_mut(); + input.deadline = Some((input.clock)() + Duration::from_millis(500)); let _ = std::io::copy(&mut reader.by_ref().take(64 * 1024), &mut std::io::sink()); } @@ -293,6 +308,8 @@ fn refuse(out: &mut TcpStream, reader: &mut BufReader, docs: &str) struct ClientInput { socket: TcpStream, deadline: Option, + /// What the deadline is measured on. + clock: Clock, } impl ClientInput { @@ -306,7 +323,7 @@ impl ClientInput { impl std::io::Read for ClientInput { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { if let Some(deadline) = self.deadline { - let left = deadline.saturating_duration_since(Instant::now()); + let left = deadline.saturating_duration_since((self.clock)()); if left.is_zero() { return Err(std::io::ErrorKind::TimedOut.into()); } @@ -402,6 +419,8 @@ fn cancel(pending: &mut Option, late: Option, id: Option<&Value> /// a running request. struct Running { list: Mutex>, + /// Notified each time a request leaves the list. + left: Condvar, connections: AtomicU64, keys: AtomicU64, } @@ -420,7 +439,7 @@ struct InFlight { impl Running { fn new() -> Self { - Running { list: Mutex::new(Vec::new()), connections: AtomicU64::new(0), keys: AtomicU64::new(0) } + Running { list: Mutex::new(Vec::new()), left: Condvar::new(), connections: AtomicU64::new(0), keys: AtomicU64::new(0) } } fn lock(&self) -> MutexGuard<'_, Vec> { @@ -482,6 +501,7 @@ impl Drop for Listing { fn drop(&mut self) { let key = self.key; self.running.lock().retain(|e| e.key != key); + self.running.left.notify_all(); } } @@ -660,7 +680,8 @@ impl Hub { let connection = running.connections.fetch_add(1, Ordering::Relaxed) + 1; let Ok(read) = stream.try_clone() else { return }; let mut out = stream; - let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(Instant::now() + waits.token) }); + let clock = Arc::clone(&self.clock); + let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(clock() + waits.token), clock }); let mut bad = 0usize; let mut authenticated = false; let mut pending: Option = None; @@ -844,6 +865,52 @@ mod tests { Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_watch(watch)) } + /// [`Plain`], except that only `slow` and `queued` take the short wait. + struct Holding; + + impl Protocol for Holding { + fn summary(&self, method: &str, params: &Value) -> Summary { + Summary { long: !matches!(method, "slow" | "queued"), ..Plain.summary(method, params) } + } + fn document(&self) -> &'static str { + Plain.document() + } + fn change_event(&self) -> &'static str { + Plain.change_event() + } + fn revision_method(&self) -> &'static str { + Plain.revision_method() + } + fn docs(&self) -> &'static str { + Plain.docs() + } + fn capabilities(&self) -> Value { + Plain.capabilities() + } + } + + /// A server for [`Holding`] whose test window holds `slow` and `queued` back: they time out at + /// once, as neither has its reply yet, and every other request waits for its reply. The hour + /// only stops a hung test. + fn holding_hub() -> Arc { + let waits = Waits { short: Duration::ZERO, long: Duration::from_secs(3600), token: TOKEN_WAIT }; + Arc::new(Hub::new(Holding, || {}, MAX_LINE).with_waits(waits)) + } + + /// Wait until `hub` lists no request in `control.running`. A request that timed out leaves the + /// list once its connection's `control.pending` has its reply. Each wait ends when the list + /// tells the test that a request left it; one that runs out its ten seconds fails the test, + /// even if the list has emptied since without telling it. + fn wait_until_nothing_runs(hub: &Hub) { + let mut list = hub.running.lock(); + while !list.is_empty() { + let (now, waited) = hub.running.left.wait_timeout(list, Duration::from_secs(10)).unwrap_or_else(PoisonError::into_inner); + list = now; + assert!(!waited.timed_out(), "no request was reported leaving the list"); + } + assert!(list.is_empty(), "a request still runs"); + } + /// The channel never goes on the network: a listener on any address but loopback is refused, /// and nothing is served on it. #[test] @@ -863,55 +930,91 @@ mod tests { fn the_token_has_a_time_limit_and_an_authenticated_client_may_idle() { use std::io::Read; let token = "0123456789abcdef0123456789abcdef"; - let limit = Duration::from_millis(500); - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - let (tx, rx) = channel::(); - std::thread::spawn(move || { - for req in rx { - let _ = req.reply.send(json!({"ok": true, "result": req.method})); - } - }); - let waits = Waits { short: Duration::from_secs(10), long: Duration::from_secs(10), token: limit }; - let hub = hub(waits, &DOCUMENT_WATCH); - std::thread::spawn(move || { - for stream in listener.incoming().flatten() { - let (tx, hub) = (tx.clone(), Arc::clone(&hub)); - std::thread::spawn(move || hub.serve(stream, token, tx, false)); - } - }); - let open = || { - let s = TcpStream::connect(addr).unwrap(); - s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); - s - }; - // Sends `drip` every 50 ms until the server closes; what it read, and when it closed. - let closed_after = |drip: &[u8]| { - let mut s = open(); + let limit = Duration::from_secs(3600); + // A server for one connection, whose clock stands still until the test moves it with the + // returned `at` (the time since the connection's deadline was set). It returns once that + // deadline is set: the clock's first reading. + let serve_one = |limit: Duration| { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); let start = Instant::now(); - s.set_read_timeout(Some(Duration::from_millis(50))).unwrap(); + let now = Arc::new(Mutex::new(start)); + let (read_tx, read) = channel::<()>(); + let clock: Clock = { + let now = Arc::clone(&now); + Arc::new(move || { + let t = *now.lock().unwrap(); + // Told only once the time is read, so the test moves the clock after it. + let _ = read_tx.send(()); + t + }) + }; + let waits = Waits { short: Duration::from_secs(3600), long: Duration::from_secs(3600), token: limit }; + let hub = Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_clock(clock)); + std::thread::spawn(move || { + if let Some(stream) = listener.incoming().flatten().next() { + hub.serve(stream, token, tx, false); + } + }); + let s = TcpStream::connect(addr).unwrap(); + // Only stops a hung test. + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + read.recv_timeout(Duration::from_secs(20)).expect("the connection's deadline is set"); + let at = move |after: Duration| *now.lock().unwrap() = start + after; + (s, at) + }; + // What the server sent until it closed the connection. + let until_closed = |s: &mut TcpStream| { let mut got = Vec::new(); loop { let mut buf = [0u8; 256]; match s.read(&mut buf) { Ok(0) => break, Ok(n) => got.extend_from_slice(buf.get(..n).unwrap()), - Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { - assert!(start.elapsed() < Duration::from_secs(20), "still open"); - let _ = s.write_all(drip); + Err(e) => { + assert!(!matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), "still open"); + break; } - Err(_) => break, } } - (got, start.elapsed()) + got }; - for drip in [&b""[..], b"\n", b"\r\n \n", b" ", b"{"] { - let (got, took) = closed_after(drip); + // A connection that sends nothing is closed when the limit runs out on the socket's own + // read timeout, without a word. + let (mut s, _) = serve_one(Duration::from_millis(100)); + let got = until_closed(&mut s); + assert!(got.is_empty(), "a silent connection was answered: {}", String::from_utf8_lossy(&got)); + for drip in [&b"\n"[..], b"\r\n \n", b" ", b"{"] { + // Once the limit has passed, the next thing sent closes the connection without a + // word, however the time before it was filled. + let (mut s, at) = serve_one(limit); + s.write_all(drip).unwrap(); + at(limit / 2); + s.write_all(drip).unwrap(); + at(limit); + let _ = s.write_all(drip); + let got = until_closed(&mut s); assert!(got.is_empty(), "{drip:?} was answered: {}", String::from_utf8_lossy(&got)); - assert!(took >= limit.saturating_sub(Duration::from_millis(50)), "{drip:?} closed after {took:?}"); + // Before the limit, the connection is still open: a request finished then is answered. + // A `{` is the request's own first byte. + let request = format!("{}\n", json!({"id": 1, "method": "ui.view", "token": token})); + let rest = request.strip_prefix(std::str::from_utf8(drip).unwrap()).unwrap_or(&request); + let (mut s, at) = serve_one(limit); + s.write_all(drip).unwrap(); + at(limit - Duration::from_secs(60)); + s.write_all(rest.as_bytes()).unwrap(); + let mut l = String::new(); + BufReader::new(&s).read_line(&mut l).unwrap(); + assert!(serde_json::from_str::(&l).is_ok_and(|r| r["ok"] == true), "{drip:?} closed before the limit: {l}"); } - let mut s = open(); + let (mut s, at) = serve_one(limit); let mut lines = BufReader::new(s.try_clone().unwrap()); let mut ask = |line: Value| -> Value { writeln!(s, "{line}").unwrap(); @@ -920,11 +1023,11 @@ mod tests { serde_json::from_str(&l).unwrap() }; assert_eq!(ask(json!({"id": 1, "method": "ui.view", "token": token}))["ok"], true); - std::thread::sleep(limit * 3); + at(limit * 3); assert_eq!(ask(json!({"id": 2, "method": "ui.view"}))["ok"], true, "idle for longer than the limit"); // A wrong token is still answered, at once. - let mut wrong = open(); + let (mut wrong, _) = serve_one(limit); writeln!(wrong, "{}", json!({"id": 1, "method": "ui.view", "token": "nope"})).unwrap(); let mut l = String::new(); BufReader::new(wrong).read_line(&mut l).unwrap(); @@ -942,6 +1045,8 @@ mod tests { let addr = listener.local_addr().unwrap(); let (tx, rx) = channel::(); let (gate_tx, gate_rx) = channel::<()>(); + // `()` once the window has taken `slow` to run it. + let (started_tx, started) = channel::<()>(); let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); let seen = ran.clone(); // A stand-in for the window thread: `queued` waits behind the others (never taken until @@ -958,6 +1063,7 @@ mod tests { } seen.lock().unwrap().push(req.method.clone()); if req.method == "slow" { + let _ = started_tx.send(()); let _ = gate_rx.recv(); } let _ = req.reply.send(json!({"ok": true, "result": req.method})); @@ -970,11 +1076,11 @@ mod tests { } } }); - let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; - let hub = hub(waits, &DOCUMENT_WATCH); + let hub = holding_hub(); + let server = Arc::clone(&hub); std::thread::spawn(move || { for stream in listener.incoming().flatten() { - let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + let (tx, hub) = (tx.clone(), Arc::clone(&server)); std::thread::spawn(move || hub.serve(stream, token, tx, false)); } }); @@ -1007,6 +1113,8 @@ mod tests { // Already running in the app: it can't be, and it still answers. let r = ask(&mut a, json!({"id": 4, "method": "slow"})); assert_eq!(r["running"], true, "{r}"); + // The ten seconds only stop a hung test. + started.recv_timeout(Duration::from_secs(10)).expect("the window took `slow`"); let r = ask(&mut b, json!({"id": 2, "method": "control.cancel", "params": {"id": 4}})); assert!(r["ok"] == false && r["error"].as_str().is_some_and(|e| e.contains("its own requests")), "another connection's: {r}"); let r = ask(&mut a, json!({"id": 5, "method": "control.cancel", "params": {"id": 99}})); @@ -1015,14 +1123,8 @@ mod tests { assert!(r["ok"] == false && r["cancellable"] == false, "{r}"); assert!(r["error"].as_str().is_some_and(|e| e.starts_with("cannot be cancelled") && e.contains("control.pending")), "{r}"); gate_tx.send(()).unwrap(); - let deadline = Instant::now() + Duration::from_secs(10); - let r = loop { - let r = ask(&mut a, json!({"id": 7, "method": "control.pending"})); - if r["result"]["done"] == true || Instant::now() > deadline { - break r; - } - std::thread::sleep(Duration::from_millis(10)); - }; + wait_until_nothing_runs(&hub); + let r = ask(&mut a, json!({"id": 7, "method": "control.pending"})); assert_eq!(r["result"]["reply"]["result"], "slow", "{r}"); let r = ask(&mut a, json!({"id": 8, "method": "control.cancel"})); assert!(r["ok"] == true && r["result"]["cancelled"].is_null(), "{r}"); @@ -1052,11 +1154,11 @@ mod tests { let _ = req.reply.send(json!({"ok": true, "result": req.method})); } }); - let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; - let hub = hub(waits, &DOCUMENT_WATCH); + let hub = holding_hub(); + let server = Arc::clone(&hub); std::thread::spawn(move || { if let Some(stream) = listener.incoming().flatten().next() { - hub.serve(stream, token, tx, false); + server.serve(stream, token, tx, false); } }); let s = TcpStream::connect(addr).unwrap(); @@ -1076,14 +1178,8 @@ mod tests { let r = ask(json!({"id": 3, "method": "control.pending"})); assert_eq!((&r["result"]["pending"], &r["result"]["done"]), (&json!(1), &json!(false)), "{r}"); gate_tx.send(()).unwrap(); - let deadline = std::time::Instant::now() + Duration::from_secs(10); - let r = loop { - let r = ask(json!({"id": 4, "method": "control.pending"})); - if r["result"]["done"] == true || std::time::Instant::now() > deadline { - break r; - } - std::thread::sleep(Duration::from_millis(10)); - }; + wait_until_nothing_runs(&hub); + let r = ask(json!({"id": 4, "method": "control.pending"})); assert_eq!( (&r["result"]["pending"], &r["result"]["done"], &r["result"]["reply"]["result"]), (&json!(1), &json!(true), &json!("slow")), @@ -1122,10 +1218,15 @@ mod tests { } }); let hub = hub(Waits::default(), &WATCH); + // `()` each time a connection's own thread is done with it. + let (ended_tx, ended) = channel::<()>(); std::thread::spawn(move || { for stream in listener.incoming().flatten() { - let (tx, hub) = (tx.clone(), Arc::clone(&hub)); - std::thread::spawn(move || hub.serve(stream, token, tx, false)); + let (tx, hub, ended) = (tx.clone(), Arc::clone(&hub), ended_tx.clone()); + std::thread::spawn(move || { + hub.serve(stream, token, tx, false); + let _ = ended.send(()); + }); } }); let open = || { @@ -1176,18 +1277,10 @@ mod tests { assert_eq!(next(&mut lines), json!({"id": 3, "ok": true, "result": "ui.view"})); writeln!(quiet_out, "{}", json!({"id": 2, "method": "ui.view"})).unwrap(); assert_eq!(next(&mut quiet), json!({"id": 2, "ok": true, "result": "ui.view"}), "no events without subscribing"); - // Closed, it is no longer counted. Each publish asks the events thread for one more line, - // and its write to the closed connection is what retires the seat; that keeps the wait off - // the connection's own thread, which anything else this process is doing may hold up past - // the deadline (#7226). + // Closed, it is no longer counted once its own thread is done with it (the quiet one is + // still open). The ten seconds only stop a hung test. drop((out, lines)); - let mut revision = 11; - let deadline = Instant::now() + Duration::from_secs(10); - while WATCH.subscribed() && Instant::now() < deadline { - WATCH.publish("d-1", revision); - revision += 1; - std::thread::sleep(Duration::from_millis(20)); - } + ended.recv_timeout(Duration::from_secs(10)).expect("the closed connection ended"); assert!(!WATCH.subscribed()); } @@ -1215,10 +1308,12 @@ mod tests { } }); let hub = hub(Waits::default(), &WATCH); + // `()` once the connection's own thread is done with it. + let (ended_tx, ended) = channel::<()>(); std::thread::spawn(move || { - for stream in listener.incoming().flatten() { - let (tx, hub) = (tx.clone(), Arc::clone(&hub)); - std::thread::spawn(move || hub.serve(stream, token, tx, false)); + if let Some(stream) = listener.incoming().flatten().next() { + hub.serve(stream, token, tx, false); + let _ = ended_tx.send(()); } }); let s = TcpStream::connect(addr).unwrap(); @@ -1231,18 +1326,47 @@ mod tests { let reply: Value = serde_json::from_str(&l).unwrap(); assert!(reply["ok"] == true, "{reply}"); assert!(WATCH.subscribed(), "the connection is subscribed"); - // Let the events thread settle into its wait: the design stands still, so it has nothing - // to write, and only the end of the connection can retire it. - std::thread::sleep(Duration::from_millis(200)); - // The client goes away without asking anything else. + // The client goes away without asking anything else. The design stands still, so the + // events thread has nothing to write: the seat must be gone when the connection's own + // thread is done, not when the events thread next wakes. The ten seconds only stop a hung + // test. drop((out, lines)); - let deadline = Instant::now() + Duration::from_millis(400); - while WATCH.subscribed() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(10)); - } + ended.recv_timeout(Duration::from_secs(10)).expect("the closed connection ended"); assert!(!WATCH.subscribed(), "a closed connection is not counted on the watch"); } + /// #7226: the events thread leaves the watch at the first write its socket refuses, while the + /// connection's own thread still holds the seat and has not seen the end of the stream. + #[test] + fn the_events_thread_leaves_the_watch_when_a_write_fails() { + static WATCH: DocumentWatch = DocumentWatch::new(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (socket, _) = listener.accept().unwrap(); + // The socket takes no more writes, as one to a client that closed: the next line fails. + socket.shutdown(std::net::Shutdown::Write).unwrap(); + let lines = Arc::new(Lines { socket, turn: Mutex::new(()) }); + let stop = Arc::new(AtomicBool::new(false)); + WATCH.publish("d-1", 3); + let seat = Arc::new(Seat::new(WATCH.join())); + // The connection's own thread, which keeps its share of the seat throughout. + let held = Arc::clone(&seat); + assert!(WATCH.subscribed(), "the connection is subscribed"); + // `()` once the events thread has ended. + let (ended_tx, ended) = channel::<()>(); + let (l, s) = (Arc::clone(&lines), Arc::clone(&stop)); + std::thread::spawn(move || { + send_events(&WATCH, "design.changed", &l, &s, ("d-1".to_string(), 3), seat); + let _ = ended_tx.send(()); + }); + WATCH.publish("d-1", 4); + // The ten seconds only stop a hung test. + ended.recv_timeout(Duration::from_secs(10)).expect("the events thread ended at the failed write"); + assert!(!stop.load(Ordering::Relaxed), "nothing stopped the events thread but the write"); + assert!(!WATCH.subscribed(), "the seat left with the events thread"); + drop((held, client)); + } + /// The token is read from a request object without building the rest of it: other fields, /// however large or nested, are only skipped. Anything but an object with a string token is /// no token. @@ -1449,19 +1573,26 @@ mod tests { #[test] fn a_stopped_listener_closes_its_port_and_its_connections() { use std::io::Read; + let token = "0123456789abcdef0123456789abcdef"; let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); let port = listener.local_addr().unwrap().port(); - let (tx, _rx) = channel(); - let stop = hub(Waits::default(), &DOCUMENT_WATCH).listen_stoppable(listener, "0123456789abcdef0123456789abcdef".into(), tx, false).unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + let stop = hub(Waits::default(), &DOCUMENT_WATCH).listen_stoppable(listener, token.into(), tx, false).unwrap(); assert_eq!(stop.port(), port); let mut client = TcpStream::connect(("127.0.0.1", port)).unwrap(); - client.set_read_timeout(Some(Duration::from_secs(4))).unwrap(); - // Wait until the server holds the connection, so stopping has one to close. - let held = Instant::now(); - while stop.shared.lock().is_empty() && held.elapsed() < Duration::from_secs(4) { - std::thread::sleep(Duration::from_millis(5)); - } - let started = Instant::now(); + // Only stops a hung test. + client.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + // Once its first request is answered, the server holds the connection, so stopping has one + // to close. It has shown the token, so the token wait cannot end it: only stopping can. + writeln!(client, "{}", json!({"id": 1, "method": "ui.view", "token": token})).unwrap(); + let mut l = String::new(); + BufReader::new(&client).read_line(&mut l).unwrap(); + assert!(serde_json::from_str::(&l).is_ok_and(|r| r["ok"] == true), "{l}"); stop.stop(); let mut byte = [0u8; 1]; match client.read(&mut byte) { @@ -1470,15 +1601,8 @@ mod tests { assert!(!matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), "the connection ends, not waits: {e}") } } - assert!(started.elapsed() < Duration::from_secs(3), "before the token wait runs out"); - // The listener thread closes its socket when it notices the stop; on a loaded machine that can - // take a moment after `stop()` returns. Wait for the port to be free, not for one instant. - let freed = Instant::now(); - let mut bound = TcpListener::bind(("127.0.0.1", port)); - while bound.is_err() && freed.elapsed() < Duration::from_secs(2) { - std::thread::sleep(Duration::from_millis(10)); - bound = TcpListener::bind(("127.0.0.1", port)); - } + // `stop` returns once the port is closed. + let bound = TcpListener::bind(("127.0.0.1", port)); assert!(bound.is_ok(), "the port is free again: {:?}", bound.err()); } } diff --git a/crates/control/tests/agents.rs b/crates/control/tests/agents.rs index 5dfaa90c27..5895caf8df 100644 --- a/crates/control/tests/agents.rs +++ b/crates/control/tests/agents.rs @@ -6,7 +6,7 @@ use std::net::TcpListener; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, mpsc}; use std::time::{Duration, Instant}; use craft_control::agents::{ @@ -18,18 +18,6 @@ fn temp_dir(tag: &str) -> tempfile::TempDir { tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") } -/// Waits up to five seconds for `done`. -fn wait_for(mut done: impl FnMut() -> bool) -> bool { - let started = Instant::now(); - while !done() { - if started.elapsed() > Duration::from_secs(5) { - return false; - } - std::thread::sleep(Duration::from_millis(5)); - } - true -} - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; /// Writes `text` as an owner-only token file, as an app's own token writer does. @@ -65,19 +53,53 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() { assert!(!AgentSwitch::fixed(false, true).allows(false)); } -/// The switch follows the launcher's list within a poll, wakes the app once per change rather than -/// once per poll, and its thread ends once the last clone is dropped. +/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns +/// once the thread has finished it and waits for the next. +struct Ticks { + tick: mpsc::SyncSender<()>, + waiting: mpsc::Receiver<()>, +} + +impl Ticks { + /// The clock and the `tick` to give [`AgentSwitch::watch_with`]. + fn new() -> (Self, impl FnMut() -> bool + Send + 'static) { + let (tick, ticks) = mpsc::sync_channel(0); + let (waits, waiting) = mpsc::channel(); + let wait = move || { + let _ = waits.send(()); + ticks.recv().is_ok() + }; + (Self { tick, waiting }, wait) + } + + /// Blocks until the watch thread waits for its next poll; `false` once the thread has ended. + fn waiting(&self) -> bool { + // A hang guard only: the thread answers at once, so the limit is never reached by a run + // that works. + match self.waiting.recv_timeout(Duration::from_secs(60)) { + Ok(()) => true, + Err(mpsc::RecvTimeoutError::Disconnected) => false, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"), + } + } + + /// Runs one poll; `false` when the thread ended in it instead of waiting for the next one. + fn poll(&self) -> bool { + self.tick.send(()).unwrap(); + self.waiting() + } +} + +/// The switch follows the launcher's list at the next poll, wakes the app once per change rather +/// than once per poll, and its thread ends at the first poll after the last clone is dropped. #[test] fn the_switch_wakes_once_per_change() { let launcher = Arc::new(AtomicBool::new(false)); let probes = Arc::new(AtomicUsize::new(0)); let wakes = Arc::new(AtomicUsize::new(0)); - // Held by the watch thread through its probe: gone once the thread has ended. - let alive = Arc::new(()); let probe = { - let (launcher, probes, alive) = (launcher.clone(), probes.clone(), alive.clone()); + let (launcher, probes) = (launcher.clone(), probes.clone()); move || { - let _ = &alive; probes.fetch_add(1, Ordering::Relaxed); launcher.load(Ordering::Relaxed) } @@ -88,26 +110,35 @@ fn the_switch_wakes_once_per_change() { wakes.fetch_add(1, Ordering::Relaxed); } }; - let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let (ticks, tick) = Ticks::new(); + let switch = AgentSwitch::watch_with(true, probe, tick, wake); let clone = switch.clone(); + assert!(ticks.waiting()); assert!(!switch.launcher()); + assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start"); launcher.store(true, Ordering::Relaxed); - assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(ticks.poll()); + assert!(clone.launcher(), "the switch follows the launcher"); assert!(switch.allows(false)); - let polled = probes.load(Ordering::Relaxed); - assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + // Many polls with nothing changed. + for _ in 0..10 { + assert!(ticks.poll()); + } + assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll"); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll"); launcher.store(false, Ordering::Relaxed); - assert!(wait_for(|| !switch.launcher())); - assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert!(ticks.poll()); + assert!(!switch.launcher()); assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); drop(switch); + assert!(ticks.poll(), "a clone keeps the watch"); drop(clone); - assert!(wait_for(|| Arc::strong_count(&alive) == 1), "the watch ended with the last switch"); - let after_end = probes.load(Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(20)); - assert_eq!(probes.load(Ordering::Relaxed), after_end, "nothing probes after the watch ended"); + // The thread probes once more, sees the switch gone and ends, so nothing probes after it. + assert!(!ticks.poll(), "the watch ended with the last switch"); + assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended"); + assert_eq!(wakes.load(Ordering::Relaxed), 2); } // ---- The connection file ------------------------------------------------------------------------ @@ -238,6 +269,21 @@ fn paths(p: &[&str]) -> Vec { p.iter().map(PathBuf::from).collect() } +/// Gives `cfg`'s launch wait a clock that moves only when the wait sleeps: each sleep calls +/// `gate`, then adds its length to the time and returns. Returns the lengths slept. +fn virtual_clock(cfg: &mut LiveConfig, gate: impl Fn() + Send + Sync + 'static) -> Arc>> { + let slept = Arc::new(Mutex::new(Vec::new())); + let start = Instant::now(); + let s = slept.clone(); + cfg.now = Box::new(move || start + s.lock().unwrap().iter().sum::()); + let s = slept.clone(); + cfg.sleep = Box::new(move |d| { + gate(); + s.lock().unwrap().push(d); + }); + slept +} + /// An app accepting agents takes the call; the same port, token and process keep the client, a /// restarted app (another process on the same port and token) gets a new one. #[test] @@ -444,8 +490,10 @@ fn a_launch_that_cannot_happen_or_never_finishes_says_what_to_do() { let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); cfg.launch = Some(Box::new(|| Ok(()))); cfg.launch_timeout = Duration::from_millis(40); + let slept = virtual_clock(&mut cfg, || {}); let err = TestLive::new(cfg).resolve().err().unwrap(); assert!(err.starts_with("Test didn't accept agents within 0 s of starting."), "{err}"); + assert_eq!(*slept.lock().unwrap(), [Duration::from_millis(5); 8], "the app is looked for every poll until the timeout"); } /// "Launch" starts the app once, also for calls that arrive together, and the calls go to its @@ -455,19 +503,24 @@ fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() { let dir = temp_dir("launch"); let made = Arc::new(Made::default()); let launches = Arc::new(AtomicUsize::new(0)); - let app: Arc>> = Arc::new(Mutex::new(None)); let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); - let (d, n, slot) = (dir.path().to_path_buf(), launches.clone(), app.clone()); + let (queued_tx, queued) = mpsc::channel(); + cfg.on_queued = Some(Box::new(move || { + let _ = queued_tx.send(()); + })); + let (launched_tx, launched) = mpsc::channel(); + let n = launches.clone(); cfg.launch = Some(Box::new(move || { n.fetch_add(1, Ordering::Relaxed); - let (d, slot) = (d.clone(), slot.clone()); - // The app takes a moment before it accepts agents. - std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(60)); - *slot.lock().unwrap() = Some(publish(&d).0); - }); + let _ = launched_tx.send(()); Ok(()) })); + // The started app's first poll waits until the test has published the app. + let (open, opened) = mpsc::channel::<()>(); + let opened = Mutex::new(opened); + virtual_clock(&mut cfg, move || { + let _ = opened.lock().unwrap().recv(); + }); let live = Arc::new(TestLive::new(cfg)); let calls: Vec<_> = (0..4) .map(|_| { @@ -475,6 +528,13 @@ fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() { std::thread::spawn(move || window(live.resolve())) }) .collect(); + // Every call is under way before the app is started and accepts agents. + for _ in 0..4 { + queued.recv().unwrap(); + } + launched.recv().unwrap(); + let _app = publish(dir.path()); + drop(open); let ports: Vec = calls.into_iter().map(|c| c.join().unwrap().port).collect(); assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for every call"); assert!(ports.windows(2).all(|p| p[0] == p[1]), "{ports:?}"); @@ -489,26 +549,30 @@ fn calls_queued_behind_a_failed_start_share_its_error() { let made = Arc::new(Made::default()); let launches = Arc::new(AtomicUsize::new(0)); let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); - let entered = Arc::new(AtomicUsize::new(0)); - let (n, e) = (launches.clone(), entered.clone()); - // The app is started but never accepts agents within the timeout. The start waits until every - // call is under way and then a while longer, so a call that hasn't reached its lookup by the - // time the start ends is very unlikely (there is no hook between the two). + let (queued_tx, queued) = mpsc::channel(); + cfg.on_queued = Some(Box::new(move || { + let _ = queued_tx.send(()); + })); + let queued = Mutex::new(queued); + let n = launches.clone(); + // The app is started but never accepts agents within the timeout. The first start returns only + // once every call has queued behind it. cfg.launch = Some(Box::new(move || { - n.fetch_add(1, Ordering::Relaxed); - assert!(wait_for(|| e.load(Ordering::Relaxed) == 4), "every call starts"); - std::thread::sleep(Duration::from_millis(250)); + if n.fetch_add(1, Ordering::Relaxed) == 0 { + let queued = queued.lock().unwrap(); + for _ in 0..4 { + queued.recv().unwrap(); + } + } Ok(()) })); cfg.launch_timeout = Duration::from_millis(150); + virtual_clock(&mut cfg, || {}); let live = Arc::new(TestLive::new(cfg)); let calls: Vec<_> = (0..4) .map(|_| { - let (live, entered) = (live.clone(), entered.clone()); - std::thread::spawn(move || { - entered.fetch_add(1, Ordering::Relaxed); - live.resolve() - }) + let live = live.clone(); + std::thread::spawn(move || live.resolve()) }) .collect(); let answers: Vec<_> = calls.into_iter().map(|c| c.join().unwrap()).collect(); @@ -596,7 +660,19 @@ fn a_huge_launch_timeout_or_poll_neither_panics_nor_hangs() { })); cfg.launch_timeout = Duration::MAX; cfg.poll = Duration::MAX; - let started = Instant::now(); + let slept = virtual_clock(&mut cfg, || {}); window(TestLive::new(cfg).resolve()); - assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); + assert_eq!(*slept.lock().unwrap(), [Duration::from_secs(1)], "the poll is cut to a second"); + + // An app that never accepts agents: the wait ends after the longest launch timeout. + let dir = temp_dir("huge-never"); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + cfg.launch = Some(Box::new(|| Ok(()))); + cfg.launch_timeout = Duration::MAX; + cfg.poll = Duration::MAX; + let slept = virtual_clock(&mut cfg, || {}); + let err = TestLive::new(cfg).resolve().err().unwrap(); + assert!(err.starts_with("Test didn't accept agents within 600 s of starting."), "{err}"); + let slept = slept.lock().unwrap(); + assert_eq!((slept.len(), slept.iter().max()), (600, Some(&Duration::from_secs(1)))); } diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index f62cda215b..e989add35f 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -114,6 +114,7 @@ craft-material-graph = { workspace = true, optional = true } craft-materialx = { workspace = true, optional = true } craft-math = { workspace = true, optional = true } craft-mesh = { workspace = true, optional = true } +craft-mesh-ops = { workspace = true, optional = true } craft-metadata = { workspace = true, optional = true } craft-metafile = { workspace = true, optional = true } craft-midi = { workspace = true, optional = true } @@ -138,6 +139,7 @@ craft-raster-codecs = { workspace = true, optional = true } craft-raw = { workspace = true, optional = true } craft-rtf = { workspace = true, optional = true } craft-scraft-format = { workspace = true, optional = true } +craft-scopes = { workspace = true, optional = true } craft-sf2 = { workspace = true, optional = true } craft-sheet = { workspace = true, optional = true } craft-silhouette-studio = { workspace = true, optional = true } @@ -221,9 +223,11 @@ craft-geom = { workspace = true, optional = true } craft-suite-account = { workspace = true, optional = true } craft-xfa = { workspace = true, optional = true } craft-gpu = { workspace = true, optional = true } +craft-gpu-device = { workspace = true, optional = true } craft-gpu-null = { workspace = true, optional = true } craft-gpu-providers = { workspace = true, optional = true } craft-gpu-wgpu = { workspace = true, optional = true } +craft-gpu-yuv = { workspace = true, optional = true } craft-ipp = { workspace = true, optional = true } craft-ppt-binary = { workspace = true, optional = true } craft-sqlite = { workspace = true, optional = true } @@ -532,6 +536,13 @@ gif-frames = ["gif", "craft-gif/frames"] gpu = ["dep:craft-gpu"] gpu-startup = ["gpu", "craft-gpu/startup"] +gpu-device = ["dep:craft-gpu-device"] +gpu-device-native-dx12 = ["gpu-device", "craft-gpu-device/native-dx12"] +gpu-device-native-gles = ["gpu-device", "craft-gpu-device/native-gles"] +gpu-device-native-metal = ["gpu-device", "craft-gpu-device/native-metal"] +gpu-device-native-vulkan = ["gpu-device", "craft-gpu-device/native-vulkan"] +gpu-device-serde = ["gpu-device", "craft-gpu-device/serde"] + gpu-null = ["dep:craft-gpu-null"] gpu-providers = ["dep:craft-gpu-providers"] @@ -543,6 +554,8 @@ gpu-wgpu-native-gles = ["gpu-wgpu", "craft-gpu-wgpu/native-gles"] gpu-wgpu-native-metal = ["gpu-wgpu", "craft-gpu-wgpu/native-metal"] gpu-wgpu-native-vulkan = ["gpu-wgpu", "craft-gpu-wgpu/native-vulkan"] +gpu-yuv = ["dep:craft-gpu-yuv"] + gridcraft-format = ["dep:craft-gridcraft-format"] gzip = ["dep:craft-gzip"] @@ -663,6 +676,8 @@ mesh-ply = ["mesh", "craft-mesh/ply"] mesh-stl = ["mesh", "craft-mesh/stl"] mesh-threemf = ["mesh", "craft-mesh/threemf"] +mesh-ops = ["dep:craft-mesh-ops"] + metadata = ["dep:craft-metadata"] metafile = ["dep:craft-metafile"] @@ -694,6 +709,8 @@ pages = ["dep:craft-pages", "keymap", "text"] palette = ["dep:craft-palette"] pbr = ["dep:craft-pbr"] +pbr-materialx = ["pbr", "craft-pbr/materialx"] +pbr-mesh = ["pbr", "craft-pbr/mesh"] pbr-parallel = ["pbr", "craft-pbr/parallel"] pcap = ["dep:craft-pcap"] @@ -810,6 +827,8 @@ rtf-outlook = ["rtf", "craft-rtf/outlook"] sbs = ["dep:craft-sbs"] +scopes = ["dep:craft-scopes"] + score = ["dep:craft-score"] scraft-format = ["dep:craft-scraft-format"] @@ -931,7 +950,12 @@ text-ukrainian = ["text", "craft-text/ukrainian"] texture = ["dep:craft-texture"] texture-dds = ["texture", "craft-texture/dds"] +texture-decode = ["texture", "craft-texture/decode"] +texture-exr = ["texture", "craft-texture/exr"] +texture-hdr = ["texture", "craft-texture/hdr"] texture-parallel = ["texture", "craft-texture/parallel"] +texture-png = ["texture", "craft-texture/png"] +texture-tiff = ["texture", "craft-texture/tiff"] tga = ["dep:craft-tga"] diff --git a/crates/craft/README.md b/crates/craft/README.md index 7ccfce5c1a..e302076568 100644 --- a/crates/craft/README.md +++ b/crates/craft/README.md @@ -17,6 +17,7 @@ craft = { workspace = true, features = ["ui", "color-ui", "draw", "imaging", "ke ## Features - One feature per crate, named after the crate without `craft-`: `color-ui` turns on `craft-color-ui` and re-exports it as `craft::color_ui`. +- `gpu-yuv` enables the GPU YUV provider through `craft::gpu_yuv`. - `ui` turns on `craft-ui` (`craft::ui`), re-exports `egui` (`craft::egui`, the egui the library is built with) and forwards `ui` to every enabled crate. - `screen-testing` implies `ui` and forwards to every enabled crate. - Each crate feature is forwarded as `-` (`platform-appearance`, `text-hyphen`, `ui-window-frame`). diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index f02a0ce022..60863cda9a 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -161,12 +161,16 @@ pub use craft_geom as geom; pub use craft_gif as gif; #[cfg(feature = "gpu")] pub use craft_gpu as gpu; +#[cfg(feature = "gpu-device")] +pub use craft_gpu_device as gpu_device; #[cfg(feature = "gpu-null")] pub use craft_gpu_null as gpu_null; #[cfg(feature = "gpu-providers")] pub use craft_gpu_providers as gpu_providers; #[cfg(feature = "gpu-wgpu")] pub use craft_gpu_wgpu as gpu_wgpu; +#[cfg(feature = "gpu-yuv")] +pub use craft_gpu_yuv as gpu_yuv; #[cfg(feature = "gridcraft-format")] pub use craft_gridcraft_format as gridcraft_format; #[cfg(feature = "gzip")] @@ -247,6 +251,8 @@ pub use craft_media_source as media_source; pub use craft_menu as menu; #[cfg(feature = "mesh")] pub use craft_mesh as mesh; +#[cfg(feature = "mesh-ops")] +pub use craft_mesh_ops as mesh_ops; #[cfg(feature = "metadata")] pub use craft_metadata as metadata; #[cfg(feature = "metafile")] @@ -331,6 +337,8 @@ pub use craft_review as review; pub use craft_rtf as rtf; #[cfg(feature = "sbs")] pub use craft_sbs as sbs; +#[cfg(feature = "scopes")] +pub use craft_scopes as scopes; #[cfg(feature = "score")] pub use craft_score as score; #[cfg(feature = "scraft-format")] diff --git a/crates/design-lint/src/contract/pointer.rs b/crates/design-lint/src/contract/pointer.rs index bc764fcec2..270e4e89e7 100644 --- a/crates/design-lint/src/contract/pointer.rs +++ b/crates/design-lint/src/contract/pointer.rs @@ -1,4 +1,4 @@ -//! `contract/pointer`: drag and click queries and press-origin reads outside `runtime::egui`. +//! `contract/pointer`: drag and click queries, press-origin reads and hover-position reads outside `runtime::egui`. use crate::report::Finding; @@ -7,6 +7,13 @@ use super::Cx; pub const ID: &str = "contract/pointer"; pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { + cx.flag_methods( + out, + ID, + ID, + "reads egui's pointer position; `Cx::hover_pos` and `pointer::hover_point_in` read it and mark what follows the pointer", + |name, args| matches!(name, "pointer_hover_pos" | "pointer_latest_pos" | "pointer_interact_pos") || (name == "hover_pos" && args.count == 0), + ); cx.flag_methods(out, ID, ID, "reads egui's pointer state; the pointer frame carries presses and drags", |name, _| { matches!( name, diff --git a/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs index 17699b16f3..a382cbd7b3 100644 --- a/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs +++ b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs @@ -1,4 +1,6 @@ -fn f(r: &Response) { +fn f(r: &Response, ctx: &Context) { if r.drag_started() || r.clicked() {} let _ = r.drag_delta(); + let _ = r.hover_pos(); + let _ = ctx.pointer_latest_pos(); } diff --git a/crates/dialogs/src/ui/chooser/tests.rs b/crates/dialogs/src/ui/chooser/tests.rs index 0e38060c32..ac148378e0 100644 --- a/crates/dialogs/src/ui/chooser/tests.rs +++ b/crates/dialogs/src/ui/chooser/tests.rs @@ -228,7 +228,12 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() { std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("report.docx"), b"x").unwrap(); - let (service, panels) = FileService::scripted(Wake::none(), [Answer::Unavailable("no portal".to_owned())]); + // The service lists the real folder on its own threads and wakes the app when each listing is in. + let (woke, wakes) = std::sync::mpsc::channel(); + let wake = Wake::new(move || { + let _ = woke.send(()); + }); + let (service, panels) = FileService::scripted(wake, [Answer::Unavailable("no portal".to_owned())]); let panels = Rc::new(RefCell::new(panels)); let host = Rc::new(RefCell::new(DialogHost::new())); let (pumped, shown) = (panels.clone(), host.clone()); @@ -236,18 +241,15 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() { pumped.borrow_mut().pump_with(&mut shown.borrow_mut(), NONE); shown.borrow_mut().run(ui); }); - // The service lists the real folder on its own threads: wait until the chooser is listed. - let listed = |fixture: &mut Fixture| { - for _ in 0..400 { - fixture.idle(1); - if fields(&host).get("listed") == Some(&Value::Bool(true)) { - // The chooser lays out its listing in the next passes: a click reads where the controls rest. - fixture.settle(); - return; - } - std::thread::sleep(Duration::from_millis(5)); + // A pass takes in the listings that are in; until the chooser is listed, the next pass waits for the next wake. + let listed = |fixture: &mut Fixture| loop { + fixture.idle(1); + if fields(&host).get("listed") == Some(&Value::Bool(true)) { + // The chooser lays out its listing in the next passes: a click reads where the controls rest. + fixture.settle(); + return; } - panic!("the chooser listed the folder"); + wakes.recv_timeout(Duration::from_secs(10)).expect("a finished listing wakes the app"); }; let click = |fixture: &mut Fixture, label: &str| { let target = fixture.by_label(label).unwrap_or_else(|| panic!("`{label}` is shown")); diff --git a/crates/doc-binary/src/drawing.rs b/crates/doc-binary/src/drawing.rs index 1381455ca3..017ec0be96 100644 --- a/crates/doc-binary/src/drawing.rs +++ b/crates/doc-binary/src/drawing.rs @@ -277,7 +277,7 @@ fn members_into(nodes: &[Node], t: (f32, f32, f32, f32), depth: usize, b: &Build let float = Float { rot: sp.props.rot, flip_h: sp.flip_h(), flip_v: sp.flip_v(), ..Float::default() }; let (w, h) = (fit(ew * sx).max(0.0), fit(eh * sy).max(0.0)); if let Some(obj) = leaf(sp, w, h, float, b, pics) { - out.push(GroupChild { x: fit(x0 + ox * sx), y: fit(y0 + oy * sy), obj }); + out.push(GroupChild { link: None, x: fit(x0 + ox * sx), y: fit(y0 + oy * sy), obj }); } } } diff --git a/crates/doc-binary/src/tests/drawing.rs b/crates/doc-binary/src/tests/drawing.rs index 943c2a5a2f..3e94d0ad3b 100644 --- a/crates/doc-binary/src/tests/drawing.rs +++ b/crates/doc-binary/src/tests/drawing.rs @@ -462,7 +462,7 @@ fn a_floating_copy_is_charged_its_alt_text() { }; let bare = crate::object_cost(&image(String::new())); assert_eq!(crate::object_cost(&image("€".repeat(4096))), bare + 3 * 4096); - let member = |obj| craft_wordmodel::para::GroupChild { x: 0.0, y: 0.0, obj }; + let member = |obj| craft_wordmodel::para::GroupChild { link: None, x: 0.0, y: 0.0, obj }; let group = InlineObject::Group { w: 1.0, h: 1.0, diff --git a/crates/doc/tests/pixels.rs b/crates/doc/tests/pixels.rs index de2687b45e..781b7fd361 100644 --- a/crates/doc/tests/pixels.rs +++ b/crates/doc/tests/pixels.rs @@ -105,6 +105,7 @@ fn eight_bit_tiles_land_on_the_canvas_and_missing_tiles_hold_the_default_pixel() assert_eq!((p.width, p.height, p.rgba.len()), (300, 260, 300 * 260 * 4)); assert_eq!(rgba_at(&p, 0, 0), [0, 0, 7, 255]); assert_eq!(rgba_at(&p, 255, 3), [255, 3, 7, 255]); + assert_eq!(rgba_at(&p, 255, 255), [255, 255, 7, 255]); assert_eq!(rgba_at(&p, 256, 0), [10, 20, 30, 40]); assert_eq!(rgba_at(&p, 0, 256), [10, 20, 30, 40]); assert_eq!(rgba_at(&p, 299, 259), [200, 100, 50, 128]); @@ -112,6 +113,18 @@ fn eight_bit_tiles_land_on_the_canvas_and_missing_tiles_hold_the_default_pixel() assert_eq!(p.mask, None); } +#[test] +fn a_tile_one_decoded_byte_over_its_size_is_refused() { + let mut tile = solid(&[1, 2, 3, 4]); + tile.push(0); + let s = surface("Rgb", "U8", true, &[0; 4], &[(0, 0, &hash(&tile))]); + let file = bundle(256, 256, "Rgb", &[layer(&raster(&s), None)], &[&tile]); + assert!(matches!( + pcraft_layer_rgba(&file, &[0], &Limits::default()), + Err(craft_doc::Error::Malformed(message)) if message.contains("more than 262144 bytes") + )); +} + #[test] fn every_truncation_and_flipped_byte_is_an_error_not_a_panic() { let tile = solid(&[1, 2, 3, 4]); diff --git a/crates/docx/Cargo.toml b/crates/docx/Cargo.toml index 0ffedf2aac..4da7f60729 100644 --- a/crates/docx/Cargo.toml +++ b/crates/docx/Cargo.toml @@ -27,6 +27,7 @@ unicode-bidi = "0.3" zeroize = "1" [dev-dependencies] +craft-flow = { workspace = true } craft-cfb = { workspace = true } craft-testkit = { workspace = true } craft-opc = { workspace = true, features = ["test-support"] } diff --git a/crates/docx/src/flat.rs b/crates/docx/src/flat.rs index b88211805f..5fd20ecb23 100644 --- a/crates/docx/src/flat.rs +++ b/crates/docx/src/flat.rs @@ -116,6 +116,10 @@ fn room(total: u64) -> u64 { /// Unpack a Flat OPC file into its parts, with a `[Content_Types].xml` made from the parts' /// content types (unless the file carries one). pub(crate) fn unpack(bytes: &[u8]) -> Result { + unpack_within(bytes, MAX_PART_ELEMENTS) +} + +fn unpack_within(bytes: &[u8], part_elements: usize) -> Result { let text = utf8_text(bytes); let src: &[u8] = text.as_ref(); let mut r = NsReader::from_reader(src); @@ -150,7 +154,7 @@ pub(crate) fn unpack(bytes: &[u8]) -> Result { } } elements += 1; - if elements > MAX_PART_ELEMENTS { + if elements > part_elements { return Err(DocxError::Limit("too many XML elements".into())); } let local = e.local_name().as_ref().to_vec(); @@ -552,6 +556,27 @@ mod tests { assert_eq!(out.matches("xmlns:p").count(), 256); } + #[test] + fn part_element_budget_counts_parts_that_are_not_read() { + assert_eq!(MAX_PART_ELEMENTS, 8_000_002); + let cap = 100; + let inline = |children| format!("{}", "".repeat(children)); + let part = |name: &str, xml: &str| format!("{xml}"); + let package = |parts: &str| format!("{parts}"); + // The part, xmlData and r wrappers count too: 97 children make exactly 100. + let xml = inline(97); + let first = part("/word/unused.xml", &xml); + let at_cap = unpack_within(package(&first).as_bytes(), cap).unwrap(); + assert_eq!(at_cap.get("word/unused.xml"), Some(xml.as_bytes())); + let over = part("/word/unused.xml", &inline(98)); + assert!(matches!(unpack_within(package(&over).as_bytes(), cap), Err(DocxError::Limit(_)))); + // Each package child has its own allowance, even though neither part is read. + let two = format!("{first}{}", part("/word/also-unused.xml", &xml)); + let reset = unpack_within(package(&two).as_bytes(), cap).unwrap(); + assert_eq!(reset.get("word/unused.xml"), Some(xml.as_bytes())); + assert_eq!(reset.get("word/also-unused.xml"), Some(xml.as_bytes())); + } + #[test] fn nesting_is_capped_where_the_xml_tree_reader_stops() { let inline = |levels: usize| format!("{}{}", "".repeat(levels), "".repeat(levels)); diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 53c04675bf..3588e4d25e 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -76,6 +76,8 @@ pub(crate) struct Reader<'p> { revs: HashMap<(u8, String, String, Option, Option), u32>, /// Move ranges (`w:moveFromRangeStart` …) seen so far. pub moves: MoveCtx, + /// Bytes of drawing hyperlink targets copied into this document. + drawing_link_bytes: usize, media_by_path: HashMap, hf_by_path: HashMap, /// Header/footer parts being read right now (see [`MAX_HF_DEPTH`]). @@ -178,6 +180,7 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, pc: PropCtx::default(), revs: HashMap::new(), moves: MoveCtx::default(), + drawing_link_bytes: 0, media_by_path: HashMap::new(), hf_by_path: HashMap::new(), hf_depth: 0, diff --git a/crates/docx/src/read/story/drawing.rs b/crates/docx/src/read/story/drawing.rs index cbffa58fc8..7c4e3e29e7 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -115,37 +115,62 @@ impl Reader<'_> { /// Part 1 §20.4.2.5, §21.1.2.3.5) naming an external hyperlink relationship. Word stores a /// picture's link there rather than in a `w:hyperlink` around its run (#5267). Its `#name` /// part, when the address has one, stays part of the address. - pub(super) fn drawing_link(d: &El, rels: &Rels) -> Option { + pub(super) fn drawing_link(&mut self, d: &El, rels: &Rels) -> Option { let frame = d.child("wp:inline").or_else(|| d.child("wp:anchor"))?; - let id = frame.child("wp:docPr")?.child("a:hlinkClick")?.attr("r:id")?; + self.drawing_property_link(frame.child("wp:docPr"), rels) + } + + fn drawing_property_link(&mut self, nv: Option<&El>, rels: &Rels) -> Option { + let id = nv?.child("a:hlinkClick")?.attr("r:id")?; let rel = rels.by_id(id).filter(|r| r.external && crate::package::rel_is(&r.kind, rt::HYPERLINK))?; - Some(rel.target.trim().to_string()).filter(|u| !u.is_empty()) + self.keep_drawing_link(&rel.target) + } + + /// A template or relationship can be referenced many times. Charge each retained copy + /// before allocating, using the same target and string ceilings as Flow. + pub(super) fn keep_drawing_link(&mut self, target: &str) -> Option { + let target = target.trim(); + if target.is_empty() || target.len() > 8 << 10 || target.len() > (64 << 20) - self.drawing_link_bytes { + return None; + } + self.drawing_link_bytes += target.len(); + Some(target.to_string()) } /// Native ink or an Office 2016 chart kept with its fallback (`mc:AlternateContent`), and the /// [`Self::drawing_link`] of the choice it was read from, else of its fallback: another /// choice's link is not this object's. pub(super) fn read_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option<(InlineObject, Option)> { - let (object, choice) = match self.read_ink_alternate(sc, ac, rels) { - Some(o) => (o, children_of_choice(ac).filter(|e| e.name == "mc:Choice")), - None => (self.read_chartex_alternate(sc, ac, rels)?, chartex_choice(ac)), - }; + if let Some(linked) = self.read_ink_alternate(sc, ac, rels) { + return Some(linked); + } + let (object, choice) = (self.read_chartex_alternate(sc, ac, rels)?, chartex_choice(ac)); let link = - [choice, ac.child("mc:Fallback")].into_iter().flatten().filter_map(|e| e.child("w:drawing")).find_map(|d| Self::drawing_link(d, rels)); + [choice, ac.child("mc:Fallback")].into_iter().flatten().filter_map(|e| e.child("w:drawing")).find_map(|d| self.drawing_link(d, rels)); Some((object, link)) } /// Keep the selected native-ink branch and its picture fallback as one object. Reading only /// the fallback flattens the ink; reading only the choice loses its preview on the next save. - fn read_ink_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option { + fn read_ink_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option<(InlineObject, Option)> { let choice = children_of_choice(ac).filter(|e| e.name == "mc:Choice")?; let drawing = choice.child("w:drawing")?; if drawing.find("a:graphicData")?.attr("uri") != Some(INK_URI) { return None; } let fallback = ac.child("mc:Fallback"); - let preview = fallback.and_then(|f| f.child("w:pict")).and_then(|p| self.read_vml(sc, p, rels)); - let Some(mut object) = self.read_drawing(sc, drawing, rels) else { return preview }; + let native = self.read_drawing(sc, drawing, rels); + // A lower-priority preview must not spend the native target's budget. + let native_link = native.as_ref().and_then(|_| { + self.drawing_link(drawing, rels).or_else(|| fallback.and_then(|f| f.child("w:drawing")).and_then(|d| self.drawing_link(d, rels))) + }); + let preview = fallback + .and_then(|f| f.child("w:pict")) + .and_then(|p| if native.is_some() { self.read_vml_preview(sc, p, rels) } else { self.read_vml(sc, p, rels) }); + let Some(mut object) = native else { + return preview.map(|(object, target)| (object, target.and_then(|target| self.keep_drawing_link(target)))); + }; + let (preview, preview_link) = preview.map(|(object, link)| (Some(object), link)).unwrap_or_default(); if let InlineObject::Graphic { w, h, graphic, .. } = &mut object { let graphic = Arc::make_mut(graphic); if let Some(InlineObject::Image { media, .. }) = preview { @@ -160,7 +185,8 @@ impl Reader<'_> { // A malformed or over-budget fallback must not discard a valid native part. } } - Some(object) + let link = native_link.or_else(|| preview_link.and_then(|target| self.keep_drawing_link(target))); + Some((object, link)) } /// An Office 2016 chart (`cx:chart`: waterfall, sunburst, box & whisker…) drawn from its @@ -323,7 +349,7 @@ impl Reader<'_> { } /// A `wpg:wgp` group (`w` × `h`): its pictures, shapes and text boxes, nested groups - /// flattened into it. `None` when it has no member we can show. + /// flattened into it unless they carry their own hyperlink. `None` when it has no member we can show. fn read_group(&mut self, sc: &mut StoryCtx, g: &El, rels: &Rels, w: f32, h: f32, mut float: Float) -> Option { let x = group_xfrm(g.child("wpg:grpSpPr")); float.set_spin(xfrm_spin(g.child("wpg:grpSpPr"))); @@ -336,7 +362,8 @@ impl Reader<'_> { let mut children = Vec::new(); let outer = self.group_fill.take(); self.group_fill = own_fill(g.child("wpg:grpSpPr"), &self.doc.settings.theme_colors, None).flatten(); - self.group_members(sc, g, rels, (-cx, -cy, 1.0, 1.0), 0, &mut children); + let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN; + self.group_members(sc, g, rels, (-cx, -cy, 1.0, 1.0), 0, (&mut children, &mut remaining)); self.group_fill = outer; if children.is_empty() { return None; @@ -362,7 +389,8 @@ impl Reader<'_> { stroke_width: ln.and_then(|l| l.attr("w")).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, 100.0), }; let mut children = Vec::new(); - self.group_members(sc, c, rels, (0.0, 0.0, 1.0, 1.0), 0, &mut children); + let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN; + self.group_members(sc, c, rels, (0.0, 0.0, 1.0, 1.0), 0, (&mut children, &mut remaining)); InlineObject::Group { w, h, float, ch_w: w.max(1.0), ch_h: h.max(1.0), children, canvas: Some(style) } } @@ -375,11 +403,12 @@ impl Reader<'_> { rels: &Rels, t: (f32, f32, f32, f32), depth: usize, - out: &mut Vec, + output: (&mut Vec, &mut usize), ) { + let (out, remaining) = output; let (x0, y0, sx, sy) = t; for e in g.els() { - if out.len() >= craft_wordmodel::para::MAX_GROUP_CHILDREN { + if *remaining == 0 { return; } // Native ink (`w14:contentPart`), alone or with a picture fallback: kept whole, in its @@ -412,33 +441,21 @@ impl Reader<'_> { "wpg:grpSp" | "wpg:wgp" => e.child("wpg:grpSpPr"), _ => continue, }; - let x = group_xfrm(sppr); - let ((ox, oy), (ew, eh)) = (x.off, x.ext); if e.name == "wpg:grpSp" || e.name == "wpg:wgp" { - if depth >= 8 { - continue; - } - // Its members' space maps onto its own box. - let (cox, coy) = x.ch_off.unwrap_or((0.0, 0.0)); - let (cw, ch) = x.ch_ext.filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0))); - let (kx, ky) = (ew / cw, eh / ch); - let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky); - // Its own fill, for its members' `a:grpFill` (#1500). - // One without a fill of its own passes its group's on. - let own = own_fill(sppr, &self.doc.settings.theme_colors, self.group_fill.as_ref()).unwrap_or_else(|| self.group_fill.clone()); - let outer = std::mem::replace(&mut self.group_fill, own); - self.group_members(sc, e, rels, nt, depth + 1, out); - self.group_fill = outer; + self.group_member_group(sc, e, rels, t, depth, (&mut *out, &mut *remaining)); continue; } - let max = crate::units::MAX_LEN_PT; - let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); - let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0)); + let x = group_xfrm(sppr); + let ((ox, oy), (ew, eh)) = (x.off, x.ext); let nv = match e.name.as_str() { - "pic:pic" => e.find("pic:cNvPr"), + "pic:pic" => e.child("pic:nvPicPr").and_then(|p| p.child("pic:cNvPr")), "w14:contentPart" => e.child("w14:nvContentPartPr").and_then(|p| p.child("w14:cNvPr")), _ => e.child("wps:cNvPr"), }; + let link = self.drawing_property_link(nv, rels); + let max = crate::units::MAX_LEN_PT; + let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); + let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0)); let (alt, meta) = nv_alt(nv); let float = Float { alt: meta, hidden: nv.is_some_and(|p| on_off_attr(p, "hidden")), ..Float::default() }; let obj = if let Some((source, preview)) = ink { @@ -460,11 +477,65 @@ impl Reader<'_> { o }); if let Some(obj) = obj { - out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj }); + *remaining -= 1; + out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj, link }); } } } + /// Retain a linked nested group without turning the per-root limit into a per-level limit. + fn group_member_group( + &mut self, + sc: &mut StoryCtx, + e: &El, + rels: &Rels, + t: (f32, f32, f32, f32), + depth: usize, + output: (&mut Vec, &mut usize), + ) { + if depth >= 8 { + return; + } + let (out, remaining) = output; + let (x0, y0, sx, sy) = t; + let sppr = e.child("wpg:grpSpPr"); + let x = group_xfrm(sppr); + let ((ox, oy), (ew, eh)) = (x.off, x.ext); + let (cox, coy) = x.ch_off.unwrap_or((0.0, 0.0)); + let (cw, ch) = x.ch_ext.filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0))); + let nv = e.child("wpg:cNvPr"); + let link = self.drawing_property_link(nv, rels); + // A group's own fill supplies its members' grpFill, otherwise its parent's does. + let own = own_fill(sppr, &self.doc.settings.theme_colors, self.group_fill.as_ref()).unwrap_or_else(|| self.group_fill.clone()); + let outer = std::mem::replace(&mut self.group_fill, own); + if link.is_none() { + let (kx, ky) = (ew / cw, eh / ch); + let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky); + self.group_members(sc, e, rels, nt, depth + 1, (out, remaining)); + } else { + *remaining -= 1; + let mut children = Vec::new(); + let max = crate::units::MAX_LEN_PT; + let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); + let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0)); + // Store members in the group's displayed space. Clipping raw child coordinates + // before scaling would move a valid member with a large rebased offset. + let (kx, ky) = (w / cw, h / ch); + self.group_members(sc, e, rels, (-cox * kx, -coy * ky, kx, ky), depth + 1, (&mut children, &mut *remaining)); + if children.is_empty() { + *remaining += 1; + } else { + let (alt, meta) = nv_alt(nv); + let mut float = Float { alt: meta, hidden: nv.is_some_and(|p| on_off_attr(p, "hidden")), ..Float::default() }; + float.set_spin(xfrm_spin(sppr)); + let mut obj = InlineObject::Group { w, h, float, ch_w: w, ch_h: h, children, canvas: None }; + obj.set_alt_text(&alt); + out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj, link }); + } + } + self.group_fill = outer; + } + /// Build a shape from `wps:wsp`, using frame dimensions `w` and `h` in points and the caller's /// placement. Reads geometry, paint, effects and connector ends, and creates a text-box story /// when present within the nesting limit. Explicit outline caps are preserved; missing or diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index f28745bac1..3d8e32cedc 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -272,21 +272,23 @@ impl Reader<'_> { }, "w:drawing" => { if let Some(o) = self.read_drawing(sc, k, rels) { - self.emit_linked_obj(sc, pb, o, props, Self::drawing_link(k, rels)); + let link = self.drawing_link(k, rels); + self.emit_linked_obj(sc, pb, o, props, link); } } "w:pict" => { - if let Some(o) = self.read_signature_line(sc, k, rels) { - self.emit_obj(sc, pb, o, props); + if let Some((o, link)) = self.read_signature_line(sc, k, rels) { + self.emit_linked_obj(sc, pb, o, props, link); } else { - for o in self.read_vml_all(sc, k, rels) { - self.emit_obj(sc, pb, o, props); + for (o, target) in self.read_vml_all(sc, k, rels) { + let link = target.and_then(|target| self.keep_drawing_link(target)); + self.emit_linked_obj(sc, pb, o, props, link); } } } "w:object" => { - if let Some(o) = self.read_object(sc, k, rels) { - self.emit_obj(sc, pb, o, props); + if let Some((o, link)) = self.read_object(sc, k, rels) { + self.emit_linked_obj(sc, pb, o, props, link); } } "w:contentPart" => { diff --git a/crates/docx/src/read/story/vml.rs b/crates/docx/src/read/story/vml.rs index 4fd74b2c92..44f6769bca 100644 --- a/crates/docx/src/read/story/vml.rs +++ b/crates/docx/src/read/story/vml.rs @@ -10,14 +10,80 @@ struct VmlGroupSpace { depth: usize, } +/// Borrowed templates for one picture. Build once so repeated missing IDs do not +/// rescan the picture's groups. Direct definitions keep their existing priority. +struct VmlLinks<'a> { + pict: &'a El, + templates: std::collections::HashMap<&'a str, Option<&'a str>>, + member_links: bool, +} + +impl<'a> VmlLinks<'a> { + fn new(pict: &'a El, member_links: bool) -> Self { + let mut links = Self { pict, templates: Default::default(), member_links }; + links.definitions(pict); + for group in pict.els().filter(|e| e.name == "v:group") { + links.group(group, 0); + } + links + } + + fn definitions(&mut self, parent: &'a El) { + for template in parent.els().filter(|e| e.name == "v:shapetype") { + if let Some(id) = template.attr("id") { + self.templates.entry(id).or_insert_with(|| template.attr("href")); + } + } + } + + fn group(&mut self, group: &'a El, depth: usize) { + self.definitions(group); + if depth < MAX_VML_GROUP_DEPTH { + for nested in group.els().filter(|e| e.name == "v:group") { + self.group(nested, depth + 1); + } + } + } + + fn target(&self, shape: &'a El) -> Option<&'a str> { + shape + .attr("href") + .or_else(|| { + let id = shape.attr("type")?.trim().trim_start_matches('#'); + self.templates.get(id).copied().flatten() + }) + .map(str::trim) + .filter(|target| !target.is_empty()) + } + + fn keep(&self, reader: &mut Reader<'_>, shape: &'a El) -> Option { + if !self.member_links { + return None; + } + self.target(shape).and_then(|target| reader.keep_drawing_link(target)) + } +} + impl Reader<'_> { /// Every legacy VML drawing in one `w:pict`, in document order: a `w:pict` may hold any /// number of shapes (ECMA-376 Part 4, VML), and each one is its own object. A `v:group` /// becomes an [`InlineObject::Group`]. - pub(super) fn read_vml_all(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Vec { + pub(super) fn read_vml_all<'a>(&mut self, sc: &mut StoryCtx, pict: &'a El, rels: &Rels) -> Vec<(InlineObject, Option<&'a str>)> { + self.vml_objects(sc, pict, rels, craft_wordmodel::para::MAX_GROUP_CHILDREN, true) + } + + fn vml_objects<'a>( + &mut self, + sc: &mut StoryCtx, + pict: &'a El, + rels: &Rels, + limit: usize, + member_links: bool, + ) -> Vec<(InlineObject, Option<&'a str>)> { + let links = VmlLinks::new(pict, member_links); let mut out = Vec::new(); for e in pict.els().filter(|e| e.name.starts_with("v:") && e.local() != "shapetype") { - if out.len() >= craft_wordmodel::para::MAX_GROUP_CHILDREN { + if out.len() >= limit { break; } if sc.in_hf @@ -28,23 +94,29 @@ impl Reader<'_> { self.doc.settings.watermark.get_or_insert(wm); continue; } - let o = if e.local() == "group" { self.read_vml_group(sc, pict, e, rels) } else { self.read_vml_shape(sc, pict, e, rels, None) }; - out.extend(o); + let o = if e.local() == "group" { self.read_vml_group(sc, &links, e, rels) } else { self.read_vml_shape(sc, pict, e, rels, None) }; + out.extend(o.map(|o| (o, links.target(e)))); } out } - /// The first VML drawing in `pict`, for the places that show a single one: an OLE object's - /// picture and a `mc:Fallback` preview. - pub(super) fn read_vml(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option { - self.read_vml_all(sc, pict, rels).into_iter().next() + /// The first VML drawing and its own target in `pict`, for an OLE object's + /// picture and a selected `mc:Fallback` preview. + pub(super) fn read_vml<'a>(&mut self, sc: &mut StoryCtx, pict: &'a El, rels: &Rels) -> Option<(InlineObject, Option<&'a str>)> { + self.vml_objects(sc, pict, rels, 1, true).into_iter().next() + } + + /// A native ink preview needs its media and root target, not member targets + /// belonging to a group the ink renderer will not retain. + pub(super) fn read_vml_preview<'a>(&mut self, sc: &mut StoryCtx, pict: &'a El, rels: &Rels) -> Option<(InlineObject, Option<&'a str>)> { + self.vml_objects(sc, pict, rels, 1, false).into_iter().next() } /// A `v:group`: its own box from its `style`, its members in the space `coordsize` and - /// `coordorigin` give it, nested groups flattened into it as [`Self::group_members`] does for - /// DrawingML. `None` when it has no member we can show. `pict` is the picture the group sits + /// `coordorigin` give it. Unlinked nested groups are flattened; a linked group keeps its + /// own node and target, as in DrawingML. `None` when it has no member we can show. `pict` is the picture the group sits /// in, where a member's `v:shapetype` is written. - fn read_vml_group(&mut self, sc: &mut StoryCtx, pict: &El, grp: &El, rels: &Rels) -> Option { + fn read_vml_group<'a>(&mut self, sc: &mut StoryCtx, links: &VmlLinks<'a>, grp: &'a El, rels: &Rels) -> Option { let style = grp.attr("style").unwrap_or(""); let len = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT); let (w, h) = (len("width"), len("height")); @@ -53,7 +125,15 @@ impl Reader<'_> { let (ch_w, ch_h) = vml_coordpair(grp, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((w.max(1.0), h.max(1.0))); let (cx, cy) = vml_coordpair(grp, "coordorigin").unwrap_or((0.0, 0.0)); let mut children = Vec::new(); - self.vml_group_members(sc, pict, grp, rels, VmlGroupSpace { origin: (-cx, -cy), scale: (1.0, 1.0), depth: 0 }, &mut children); + let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN; + self.vml_group_members( + sc, + links, + grp, + rels, + VmlGroupSpace { origin: (-cx, -cy), scale: (1.0, 1.0), depth: 0 }, + (&mut children, &mut remaining), + ); if children.is_empty() { return None; } @@ -63,42 +143,36 @@ impl Reader<'_> { /// The members of VML group `g` into `out`, mapped into the outermost group's space by `t` /// (x0, y0, sx, sy: outer = x0 + inner × sx). A member is placed by `left`/`top` in that /// space, except a `v:line`, which carries its own offset in `from`. - fn vml_group_members( + fn vml_group_members<'a>( &mut self, sc: &mut StoryCtx, - pict: &El, - g: &El, + links: &VmlLinks<'a>, + g: &'a El, rels: &Rels, space: VmlGroupSpace, - out: &mut Vec, + output: (&mut Vec, &mut usize), ) { + let (out, remaining) = output; let (x0, y0) = space.origin; let (sx, sy) = space.scale; let max = crate::units::MAX_LEN_PT; let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); for e in g.els() { - if out.len() >= craft_wordmodel::para::MAX_GROUP_CHILDREN { + if *remaining == 0 { return; } if !e.name.starts_with("v:") || e.local() == "shapetype" { continue; } - let style = e.attr("style").unwrap_or(""); - let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, craft_wordmodel::geom::finite); - let ((ox, oy), (ew, eh)) = ((num("left"), num("top")), (num("width"), num("height"))); if e.local() == "group" { - if space.depth >= MAX_VML_GROUP_DEPTH { - continue; - } - // Its members' space maps onto its own box. - let (cw, ch) = vml_coordpair(e, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0))); - let (cox, coy) = vml_coordpair(e, "coordorigin").unwrap_or((0.0, 0.0)); - let (kx, ky) = (ew / cw, eh / ch); - let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky); - self.vml_group_members(sc, pict, e, rels, VmlGroupSpace { origin: (nt.0, nt.1), scale: (nt.2, nt.3), depth: space.depth + 1 }, out); + self.vml_group_member(sc, links, e, rels, space, (&mut *out, &mut *remaining)); continue; } - let Some(mut obj) = self.read_vml_shape(sc, pict, e, rels, Some((sx, sy))) else { continue }; + let style = e.attr("style").unwrap_or(""); + let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, craft_wordmodel::geom::finite); + let (ox, oy) = (num("left"), num("top")); + let link = links.keep(self, e); + let Some(mut obj) = self.read_vml_shape(sc, links.pict, e, rels, Some((sx, sy))) else { continue }; // A member is placed by `x`/`y`, so a line's own offset comes off the member itself. let (dx, dy) = match obj.float_mut() { Some(f) => { @@ -108,10 +182,71 @@ impl Reader<'_> { } None => (0.0, 0.0), }; - out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + (ox + dx) * sx, -max), y: fit(y0 + (oy + dy) * sy, -max), obj }); + *remaining -= 1; + out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + (ox + dx) * sx, -max), y: fit(y0 + (oy + dy) * sy, -max), obj, link }); } } + /// An inner group shares its root's retained-member budget. Only a group with its + /// own target needs a node; unlinked groups keep the established flattening path. + fn vml_group_member<'a>( + &mut self, + sc: &mut StoryCtx, + links: &VmlLinks<'a>, + e: &'a El, + rels: &Rels, + space: VmlGroupSpace, + output: (&mut Vec, &mut usize), + ) { + if space.depth >= MAX_VML_GROUP_DEPTH { + return; + } + let (out, remaining) = output; + let (x0, y0) = space.origin; + let (sx, sy) = space.scale; + let style = e.attr("style").unwrap_or(""); + let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, craft_wordmodel::geom::finite); + let ((ox, oy), (ew, eh)) = ((num("left"), num("top")), (num("width"), num("height"))); + let (cw, ch) = vml_coordpair(e, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0))); + let (cox, coy) = vml_coordpair(e, "coordorigin").unwrap_or((0.0, 0.0)); + let link = links.keep(self, e); + if link.is_none() { + let (kx, ky) = (ew / cw, eh / ch); + let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky); + self.vml_group_members( + sc, + links, + e, + rels, + VmlGroupSpace { origin: (nt.0, nt.1), scale: (nt.2, nt.3), depth: space.depth + 1 }, + (out, remaining), + ); + return; + } + *remaining -= 1; + let mut children = Vec::new(); + let max = crate::units::MAX_LEN_PT; + let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); + let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0)); + let (kx, ky) = (w / cw, h / ch); + self.vml_group_members( + sc, + links, + e, + rels, + VmlGroupSpace { origin: (-cox * kx, -coy * ky), scale: (kx, ky), depth: space.depth + 1 }, + (&mut children, &mut *remaining), + ); + if children.is_empty() { + *remaining += 1; + return; + } + let mut float = vml_float(e, style, sc.in_hf); + (float.x, float.y) = (0.0, 0.0); + let obj = InlineObject::Group { w, h, float, ch_w: w, ch_h: h, children, canvas: None }; + out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj, link }); + } + /// One legacy VML picture, text box, line, rectangle, oval or preset shape (best effort). /// `pict` is the picture it sits in, where its `v:shapetype` is written -- for a group's /// member too, since Word writes each shapetype once, beside the group rather than inside @@ -395,25 +530,25 @@ impl Reader<'_> { /// An OLE object (`w:object`, ECMA-376 §17.3.3.19): shown as its picture (VML, or a DrawingML /// picture in `w:drawing`), and kept whole so saving writes the object back. - pub(super) fn read_object(&mut self, sc: &mut StoryCtx, obj: &El, rels: &Rels) -> Option { - let mut o = match self.read_vml(sc, obj, rels) { - Some(o) => o, + pub(super) fn read_object(&mut self, sc: &mut StoryCtx, obj: &El, rels: &Rels) -> Option<(InlineObject, Option)> { + let (mut o, link) = match self.read_vml(sc, obj, rels) { + Some((object, target)) => (object, target.and_then(|target| self.keep_drawing_link(target))), None => { let d = obj.child("w:drawing")?; - self.read_drawing(sc, d, rels)? + (self.read_drawing(sc, d, rels)?, self.drawing_link(d, rels)) } }; if let InlineObject::Image { ole, .. } = &mut o { *ole = self.keep_embedded(obj, rels, &[]); } - Some(o) + Some((o, link)) } /// A Word signature line (Insert › Signature Line): a `w:pict` whose one VML picture carries /// an `o:signatureline` (the suggested signer, title, e-mail and instructions). Shown as its /// picture, and kept whole like an OLE object so saving writes the signature line back, /// still signable in Word, not a plain picture. `None` for any other `w:pict`. - pub(super) fn read_signature_line(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option { + pub(super) fn read_signature_line(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option<(InlineObject, Option)> { let mut drawings = pict.els().filter(|e| e.name.starts_with("v:") && e.local() != "shapetype"); let shape = drawings.next().filter(|s| s.name == "v:shape")?; if drawings.next().is_some() || shape.child("o:signatureline").is_none() { @@ -423,7 +558,7 @@ impl Reader<'_> { if let InlineObject::Image { ole, .. } = &mut o { *ole = self.keep_embedded(pict, rels, &[]); } - Some(o) + Some((o, VmlLinks::new(pict, true).target(shape).and_then(|target| self.keep_drawing_link(target)))) } } diff --git a/crates/docx/src/write/story/drawing.rs b/crates/docx/src/write/story/drawing.rs index 507e02b7c1..8216e774f0 100644 --- a/crates/docx/src/write/story/drawing.rs +++ b/crates/docx/src/write/story/drawing.rs @@ -14,6 +14,14 @@ pub(super) struct DrawingInfo<'a> { pub link: Option<&'a str>, } +/// The non-visual identity, placement and hyperlink relationship of one group member. +/// Top-level objects keep their link on `wp:docPr` instead. +pub(super) struct MemberInfo<'a> { + pub id: Option<&'a str>, + pub off: (f32, f32), + pub link: Option<&'a str>, +} + impl Writer<'_> { /// The relationship of the hyperlink a drawing in a run with `props` carries on itself, as /// Word writes a picture's link (`wp:docPr/a:hlinkClick`, #5267): a web or file address. A @@ -24,13 +32,13 @@ impl Writer<'_> { } /// A picture's `pic:pic` (the image in `media/{file}`), at `off` in its group (or 0, 0). - pub(super) fn pic(&mut self, w: &mut W, o: &InlineObject, file: &str, off: (f32, f32), rels: &mut PartRels) { + pub(super) fn pic(&mut self, w: &mut W, o: &InlineObject, file: &str, member: MemberInfo<'_>, rels: &mut PartRels) { let InlineObject::Image { media, w: iw, h: ih, alt, crop, float, fx, .. } = o else { return }; let rid = rels.add(rt::IMAGE, &format!("media/{file}"), false); self.used_media.insert(media.clone()); w.open("pic:pic", &[]); w.open("pic:nvPicPr", &[]); - nv_props(w, "pic:cNvPr", ("0", file), alt, &float.alt, float.hidden, None); + nv_props(w, "pic:cNvPr", (member.id.unwrap_or("0"), file), alt, &float.alt, float.hidden, member.link); w.open("pic:cNvPicPr", &[]); w.empty("a:picLocks", &[("noChangeAspect", "1"), ("noChangeArrowheads", "1")]); w.close("pic:cNvPicPr"); @@ -60,7 +68,7 @@ impl Writer<'_> { w.close("a:stretch"); w.close("pic:blipFill"); w.open("pic:spPr", &[("bwMode", "auto")]); - xfrm(w, off, *iw, *ih, float.spin()); + xfrm(w, member.off, *iw, *ih, float.spin()); w.open("a:prstGeom", &[("prst", "rect")]); w.empty("a:avLst", &[]); w.close("a:prstGeom"); @@ -80,17 +88,16 @@ impl Writer<'_> { &mut self, w: &mut W, o: &InlineObject, - id: Option<&str>, - off: (f32, f32), + member: MemberInfo<'_>, rels: &mut PartRels, depth: usize, ) -> Option> { let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, effects, float, freeform, extra } = o else { return None }; let geom = freeform.as_deref().filter(|_| *kind == ShapeKind::Freeform); w.open("wps:wsp", &[]); - if let Some(id) = id { + if let Some(id) = member.id { let name = shape_name(*kind, freeform.as_deref(), id); - nv_props(w, "wps:cNvPr", (id, &name), &float.alt.text, &float.alt, float.hidden, None); + nv_props(w, "wps:cNvPr", (id, &name), &float.alt.text, &float.alt, float.hidden, member.link); } if kind.is_connector() { // A connector's glued ends (ECMA-376 §20.1.2.2.8 `cNvCxnSpPr`). @@ -112,7 +119,7 @@ impl Writer<'_> { w.empty("wps:cNvSpPr", &[]); } w.open("wps:spPr", &[]); - xfrm(w, off, *sw, *sh, float.spin()); + xfrm(w, member.off, *sw, *sh, float.spin()); let prst = match kind { ShapeKind::Rectangle | ShapeKind::TextBox | ShapeKind::Freeform => "rect", ShapeKind::RoundedRectangle => "roundRect", diff --git a/crates/docx/src/write/story/object.rs b/crates/docx/src/write/story/object.rs index 3a42a8b044..17bde48e2f 100644 --- a/crates/docx/src/write/story/object.rs +++ b/crates/docx/src/write/story/object.rs @@ -1,7 +1,7 @@ -use super::drawing::{DrawingInfo, shape_name, spin_attrs, write_fill, xfrm_spin_only}; +use super::drawing::{DrawingInfo, MemberInfo, nv_props, shape_name, spin_attrs, write_fill, xfrm_spin_only}; use super::field::{FieldData, field_run}; use super::section::comment_reference_style; -use super::{Anchor, CharProps, Fill, Float, InlineObject, NoteKind, PartRels, ShapeKind, TextColor, W, Wrap, Writer, emu, n, rpr}; +use super::{Anchor, CharProps, Fill, Float, InlineObject, MAX_DEPTH, NoteKind, PartRels, ShapeKind, TextColor, W, Wrap, Writer, emu, n, rpr, rt}; impl Writer<'_> { /// Write an inline object (`Bookmark`, `Comment`, `Equation`, `Field`, `Shape`, etc.). @@ -284,7 +284,7 @@ impl Writer<'_> { w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.openxmlformats.org/drawingml/2006/picture")]); - self.pic(w, o, &file, (0.0, 0.0), rels); + self.pic(w, o, &file, MemberInfo { id: None, off: (0.0, 0.0), link: None }, rels); w.close("a:graphicData"); w.close("a:graphic"); w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); @@ -404,7 +404,7 @@ impl Writer<'_> { w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]); - let content = self.wsp(w, o, None, (0.0, 0.0), rels, depth); + let content = self.wsp(w, o, MemberInfo { id: None, off: (0.0, 0.0), link: None }, rels, depth); w.close("a:graphicData"); w.close("a:graphic"); w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); @@ -605,30 +605,8 @@ impl Writer<'_> { "wpg:wgp" } }; - for c in children.iter().take(craft_wordmodel::para::MAX_GROUP_CHILDREN) { - let at = (c.x, c.y); - match &c.obj { - InlineObject::Image { media, .. } => { - if let Some(file) = self.media_files.get(media).cloned() { - self.pic(w, &c.obj, &file, at, rels); - } - } - InlineObject::Shape { extra, .. } => { - let id = self.shape_docpr(extra.id); - self.wsp(w, &c.obj, Some(&id), at, rels, depth); - } - // Native ink kept from the file, with its fallback, at the member's place. - InlineObject::Graphic { w: iw, h: ih, float, graphic, .. } if graphic.kind == craft_wordmodel::graphic::GraphicKind::Ink => { - if let Some(src) = graphic.source.as_deref() - && let Some(mut root) = self.embedded_tree(src, rels, None) - { - Self::place_member(&mut root, [c.x, c.y, *iw, *ih], float, 0); - w.raw(&root.to_xml()); - } - } - _ => {} - } - } + let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN; + self.write_group_members(w, children, rels, depth, &mut remaining); if canvas.is_some() && float.spin() != craft_wordmodel::geom::Spin::default() { // The canvas schema has no transform of its own: keep its turn in our // extension (Word draws it unturned, as it can't turn a canvas). @@ -646,6 +624,84 @@ impl Writer<'_> { w.close("w:r"); self.rev_close(w, props); } + /// Members share one finite budget across the whole recursive group, not one per level. + fn write_group_members( + &mut self, + w: &mut W, + children: &[craft_wordmodel::para::GroupChild], + rels: &mut PartRels, + depth: usize, + remaining: &mut usize, + ) { + if depth > MAX_DEPTH { + return; + } + for c in children { + if *remaining == 0 { + break; + } + *remaining -= 1; + let at = (c.x, c.y); + match &c.obj { + InlineObject::Image { media, .. } => { + if let Some(file) = self.media_files.get(media).cloned() { + let id = self.next_docpr(); + let link = member_link(c.link.as_deref(), rels); + self.pic(w, &c.obj, &file, MemberInfo { id: Some(&id), off: at, link: link.as_deref() }, rels); + } + } + InlineObject::Shape { extra, .. } => { + let id = self.shape_docpr(extra.id); + let link = member_link(c.link.as_deref(), rels); + self.wsp(w, &c.obj, MemberInfo { id: Some(&id), off: at, link: link.as_deref() }, rels, depth); + } + InlineObject::Group { .. } if depth < MAX_DEPTH => { + let id = self.next_docpr(); + let link = member_link(c.link.as_deref(), rels); + self.write_inner_group(w, &c.obj, MemberInfo { id: Some(&id), off: at, link: link.as_deref() }, rels, depth + 1, remaining); + } + // Native ink kept from the file, with its fallback, at the member's place. + InlineObject::Graphic { w: iw, h: ih, float, graphic, .. } if graphic.kind == craft_wordmodel::graphic::GraphicKind::Ink => { + if let Some(src) = graphic.source.as_deref() + && let Some(mut root) = self.embedded_tree(src, rels, None) + { + Self::place_member(&mut root, [c.x, c.y, *iw, *ih], float, 0); + w.raw(&root.to_xml()); + } + } + _ => {} + } + } + } + + /// A nested group is an inner `wpg:grpSp`, never another run or drawing anchor. + fn write_inner_group(&mut self, w: &mut W, o: &InlineObject, member: MemberInfo<'_>, rels: &mut PartRels, depth: usize, remaining: &mut usize) { + if depth > MAX_DEPTH { + return; + } + let InlineObject::Group { w: gw, h: gh, float, ch_w, ch_h, children, .. } = o else { return }; + let id = member.id.unwrap_or("0"); + let name = format!("Group {id}"); + w.open("wpg:grpSp", &[]); + nv_props(w, "wpg:cNvPr", (id, &name), o.alt_text(), &float.alt, float.hidden, member.link); + w.empty("wpg:cNvGrpSpPr", &[]); + w.open("wpg:grpSpPr", &[]); + w.open("a:xfrm", &spin_attrs(float.spin()).iter().map(|(k, v)| (*k, v.as_str())).collect::>()); + w.empty("a:off", &[("x", &emu(member.off.0)), ("y", &emu(member.off.1))]); + w.empty("a:ext", &[("cx", &emu(gw.max(0.0))), ("cy", &emu(gh.max(0.0)))]); + w.empty("a:chOff", &[("x", "0"), ("y", "0")]); + w.empty("a:chExt", &[("cx", &emu(ch_w.max(0.0))), ("cy", &emu(ch_h.max(0.0)))]); + w.close("a:xfrm"); + w.close("wpg:grpSpPr"); + self.write_group_members(w, children, rels, depth, remaining); + w.close("wpg:grpSp"); + } +} + +/// Group members have no enclosing run, so even a literal `#name` needs its own +/// external hyperlink relationship. Top-level drawings retain `drawing_link`'s policy. +fn member_link(target: Option<&str>, rels: &mut PartRels) -> Option { + target.filter(|url| !url.is_empty()).map(|url| rels.add(rt::HYPERLINK, url, true)) } /// The VML element that draws a shape kind, for the kinds VML has one for. diff --git a/crates/docx/tests/it/drawing_payload.rs b/crates/docx/tests/it/drawing_payload.rs index 04a317147d..4b5847efda 100644 --- a/crates/docx/tests/it/drawing_payload.rs +++ b/crates/docx/tests/it/drawing_payload.rs @@ -108,7 +108,7 @@ fn picture_group_canvas_keep_kind() { float: Default::default(), ch_w: 100.0, ch_h: 50.0, - children: vec![GroupChild { x: 3.0, y: 4.0, obj: picture() }], + children: vec![GroupChild { link: None, x: 3.0, y: 4.0, obj: picture() }], canvas, }; for original in [picture(), group(None), group(Some(CanvasStyle::default()))] { diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 6f9f191a22..11307c334c 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -3668,7 +3668,7 @@ const INK_NS: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessi const INK_XML: &str = r##"0 0, 1 1, 2 0"##; const INK_TYPES: &str = r#""#; -fn ink_docx(fallback: bool, alias: bool) -> Vec { +pub(super) fn ink_docx(fallback: bool, alias: bool) -> Vec { let content = r#""#; let drawing = format!( r#"{content}"# diff --git a/crates/docx/tests/it/malformed.rs b/crates/docx/tests/it/malformed.rs index fc65b8e2d6..030ab8433a 100644 --- a/crates/docx/tests/it/malformed.rs +++ b/crates/docx/tests/it/malformed.rs @@ -179,9 +179,14 @@ fn many_fields_and_huge_attribute_values() { /// limit error, or the extras are dropped and the text survives (#3702, WC-06). #[test] fn millions_of_attributes_on_one_paragraph_are_capped() { + use std::fmt::Write as _; + // The gate reads a fraction of the attributes; nightly all of them. - let attrs: String = (0..2_000_000 / craft_testkit::hostile::divisor()).map(|i| format!(" a{i}=\"\"")).collect(); - let x = format!("kept"); + let mut x = format!("kept"); // Only the read is timed: deflating the test input in a debug build is not what is bounded. let z = doc_zip(x.as_bytes()); let start = std::time::Instant::now(); diff --git a/crates/docx/tests/it/picture_links.rs b/crates/docx/tests/it/picture_links.rs index 34cf625e1b..ee16352fc6 100644 --- a/crates/docx/tests/it/picture_links.rs +++ b/crates/docx/tests/it/picture_links.rs @@ -213,3 +213,694 @@ fn a_vml_picture_keeps_its_crop_when_saved() { } assert!(lost.is_empty(), "VML picture crops were lost: {lost:?}"); } + +// Original Transitional DOCX/VML: ISO 29500 VML shape/group href attributes, with +// independent literal targets at each level. No reference-app file or click oracle. +#[test] +fn vml_objects_keep_their_own_hyperlinks() { + fn check_images(doc: &Document, object: &InlineObject, original_png: &[u8], out: &mut Vec<(String, f32, f32)>) { + match object { + InlineObject::Image { media, w, h, alt, crop, .. } => { + assert_eq!(doc.media.get(media).expect("the original embedded picture").as_slice(), original_png); + assert_eq!(*crop, [0.0; 4], "a hyperlink must not invent a crop"); + out.push((alt.clone(), *w, *h)); + } + InlineObject::Group { children, .. } => { + for child in children { + check_images(doc, &child.obj, original_png, out); + } + } + InlineObject::Shape { kind, w, h, .. } => { + assert_eq!(*kind, craft_wordmodel::para::ShapeKind::Rectangle); + assert!((*w - 5.0).abs() < 0.001 && (*h - 7.0).abs() < 0.001); + } + other => panic!("the original picture fixture produced another object: {other:?}"), + } + } + fn top_links(doc: &Document) -> Vec> { + let paragraph = doc.body[1].as_para().expect("the VML paragraph"); + paragraph.object_offsets().into_iter().map(|off| paragraph.props_of_char(off).link.clone()).collect() + } + + fn model_links(doc: &Document) -> Vec<(Vec, Option)> { + fn member_links(object: &InlineObject, path: &[usize], out: &mut Vec<(Vec, Option)>) { + if let InlineObject::Group { children, .. } = object { + for (i, child) in children.iter().enumerate() { + let mut path = path.to_vec(); + path.push(i); + out.push((path.clone(), child.link.clone())); + member_links(&child.obj, &path, out); + } + } + } + let paragraph = doc.body[1].as_para().unwrap(); + let mut out = Vec::new(); + for (i, off) in paragraph.object_offsets().into_iter().enumerate() { + out.push((vec![i], paragraph.props_of_char(off).link.clone())); + member_links(paragraph.object_at(off).unwrap(), &[i], &mut out); + } + out + } + fn xml_link(nv: Option<&craft_xml::El>, rels: &craft_xml::El) -> Option { + let id = nv?.child("a:hlinkClick")?.attr("r:id")?; + let rel = rels.children("Relationship").find(|r| r.attr("Id") == Some(id)).expect("every click must name a saved relationship"); + assert_eq!(rel.attr("Type"), Some("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink")); + assert_eq!(rel.attr("TargetMode"), Some("External")); + Some(rel.attr("Target").expect("the click target").to_string()) + } + fn saved_member_links(group: &craft_xml::El, path: &[usize], rels: &craft_xml::El, out: &mut Vec<(Vec, Option)>) { + for (i, child) in group.elements().filter(|e| matches!(e.name.as_str(), "pic:pic" | "wps:wsp" | "wpg:grpSp")).enumerate() { + let mut path = path.to_vec(); + path.push(i); + let nv = match child.name.as_str() { + "pic:pic" => child.child("pic:nvPicPr").and_then(|p| p.child("pic:cNvPr")), + "wps:wsp" => child.child("wps:cNvPr"), + _ => child.child("wpg:cNvPr"), + }; + out.push((path.clone(), xml_link(nv, rels))); + if child.name == "wpg:grpSp" { + saved_member_links(child, &path, rels, out); + } + } + } + + fn check_group_geometry(current: &Document) { + let InlineObject::Group { children, .. } = ¤t.body[1].as_para().unwrap().objects[3] else { panic!() }; + assert_eq!(children.len(), 3); + assert!((children[0].x - 3.0).abs() < 0.001 && (children[0].y - 4.0).abs() < 0.001); + assert!((children[2].x - 20.0).abs() < 0.001 && (children[2].y - 5.0).abs() < 0.001); + let InlineObject::Group { children, float, ch_w, ch_h, .. } = &children[2].obj else { panic!("the linked nested group must remain a group") }; + assert_eq!((*ch_w, *ch_h), (10.0, 10.0)); + assert_eq!(float.spin(), craft_wordmodel::geom::Spin::new(30.0, true, false)); + assert_eq!(children.len(), 1); + assert!((children[0].x - 1.0).abs() < 0.001 && (children[0].y - 2.0).abs() < 0.001); + } + + let vml = r##" + + + + + + + + +"##; + // A known DrawingML link is a positive control in the same package, with the + // same generated media and relationship table as the independently linked VML. + let body = format!("{}{vml}", picture_run(10, r#""#)); + let original_png = png(); + let doc = craft_docx::read(&package(&body)).expect("the original Transitional package must read"); + let saved = craft_docx::write(&doc).expect("the supported picture/group content must save"); + let reopened = craft_docx::read(&saved).expect("the normalized DOCX must reopen"); + let expected_images = [("first", 24.0, 12.0), ("unlinked", 16.0, 8.0), ("last", 12.0, 6.0), ("child", 6.0, 4.0), ("fragment", 2.0, 3.0)]; + + // All payload, ordering, geometry and positive/unlinked controls run before + // the missing-target assertion; neither a dropped object nor bad media is red proof. + for current in [&doc, &reopened] { + assert_eq!(current.body.len(), 2); + assert_eq!(picture_links(current), [Some("https://example.com/picture".to_string())]); + let paragraph = current.body[1].as_para().expect("the VML paragraph remains a paragraph"); + assert_eq!(paragraph.objects.len(), 4, "three top-level pictures and their following group"); + let InlineObject::Group { w, h, .. } = ¶graph.objects[3] else { + panic!("the last VML object must remain a group"); + }; + assert!((*w - 40.0).abs() < 0.001 && (*h - 20.0).abs() < 0.001); + let mut images = Vec::new(); + for object in ¶graph.objects { + check_images(current, object, &original_png, &mut images); + } + assert_eq!(images.len(), expected_images.len(), "every original picture must remain"); + for ((alt, w, h), (expected_alt, expected_w, expected_h)) in images.iter().zip(expected_images) { + assert_eq!(alt, expected_alt, "picture order/identity changed"); + assert!((w - expected_w).abs() < 0.001 && (h - expected_h).abs() < 0.001, "{alt}: {w} x {h}"); + } + assert_eq!(top_links(current)[1], None, "the unlinked neighbor must stay unlinked"); + } + let rels = part(&saved, "word/_rels/document.xml.rels"); + assert!(rels.contains(r#"Target="https://example.com/picture""#), "the DrawingML control's relationship must survive"); + + let expected_top = [Some("https://example.com/TopFirst"), None, Some("https://example.com/TopLast"), Some("https://example.com/Outer")]; + let mut lost = Vec::new(); + for (phase, current) in [("read", &doc), ("reopened", &reopened)] { + for (index, (actual, expected)) in top_links(current).iter().zip(expected_top).enumerate() { + if actual.as_deref() != expected { + lost.push(format!("{phase} top-level object {index}: {actual:?} instead of {expected:?}")); + } + } + } + // These are necessary persistence checks using today's APIs, not a claim that + // relationship presence proves nested path-to-target association or activation. + for (label, target) in [ + ("first", "https://example.com/TopFirst"), + ("last", "https://example.com/TopLast"), + ("outer group", "https://example.com/Outer"), + ("group child", "https://example.com/Child"), + ("group shape", "https://example.com/Shape"), + ("nested group", "https://example.com/Nested"), + ("fragment data", "#Spot"), + ] { + if !rels.contains(&format!(r#"Target="{target}""#)) { + lost.push(format!("saved {label} target: {target}")); + } + } + let expected: Vec<_> = [ + (vec![0], Some("https://example.com/TopFirst")), + (vec![1], None), + (vec![2], Some("https://example.com/TopLast")), + (vec![3], Some("https://example.com/Outer")), + (vec![3, 0], Some("https://example.com/Child")), + (vec![3, 1], Some("https://example.com/Shape")), + (vec![3, 2], Some("https://example.com/Nested")), + (vec![3, 2, 0], Some("#Spot")), + ] + .into_iter() + .map(|(path, link)| (path, link.map(str::to_string))) + .collect(); + for current in [&doc, &reopened] { + assert_eq!(model_links(current), expected, "each target must remain on its own object path"); + check_group_geometry(current); + } + let xml = craft_xml::parse(part(&saved, "word/document.xml").as_bytes()).unwrap(); + let relationships = craft_xml::parse(rels.as_bytes()).unwrap(); + let paragraph = xml.child("w:body").unwrap().children("w:p").nth(1).unwrap(); + let mut xml_links = Vec::new(); + for (i, drawing) in paragraph.find_all("w:drawing").enumerate() { + let frame = drawing.child("wp:inline").or_else(|| drawing.child("wp:anchor")).unwrap(); + xml_links.push((vec![i], xml_link(frame.child("wp:docPr"), &relationships))); + if let Some(group) = frame.child("a:graphic").and_then(|g| g.child("a:graphicData")).and_then(|d| d.child("wpg:wgp")) { + saved_member_links(group, &[i], &relationships, &mut xml_links); + } + } + assert_eq!(xml_links, expected, "saved cNvPr/docPr clicks must name the target at the same path"); + assert!(lost.is_empty(), "VML object hyperlinks were lost: {lost:?}"); +} + +#[test] +fn vml_hyperlink_templates_and_outer_runs_keep_their_scope() { + let cases = [ + (r##"type="#Linked""##, "", Some("https://example.com/Template")), + (r##"type="#Linked" href="https://example.com/Direct""##, "", Some("https://example.com/Direct")), + (r##"type="#Linked" href=" ""##, "", None), + (r#"href=" https://example.com/Trimmed ""#, "", Some("https://example.com/Trimmed")), + ("", r#"o:href="https://example.com/ImageSource" r:href="rIdWeb""#, None), + ]; + let mut shapes = String::new(); + for (attributes, image_attributes, _) in cases { + shapes + .push_str(&format!(r#""#,)); + } + let body = format!( + r#"{shapes}"#, + ); + let doc = craft_docx::read(&package(&body)).unwrap(); + let saved = craft_docx::write(&doc).unwrap(); + let reopened = craft_docx::read(&saved).unwrap(); + let expected: Vec<_> = cases.into_iter().map(|(_, _, link)| link.map(str::to_string)).collect(); + for current in [&doc, &reopened] { + assert_eq!(picture_links(current), expected, "presence-aware template/direct href precedence"); + let paragraph = current.body[1].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), 1); + assert_eq!(paragraph.props_of_char(paragraph.object_offsets()[0]).link.as_deref(), Some("https://example.com/run")); + let InlineObject::Group { children, .. } = ¶graph.objects[0] else { panic!() }; + assert_eq!(children.len(), 1); + assert_eq!(children[0].link.as_deref(), Some("https://example.com/Child"), "the run overrides the group, not its child"); + } + + // A shape type may be declared inside the group rather than beside it. These + // original inputs use unique IDs and keep image-source URLs out of click lookup. + let local_cases = [(r##"type="#GroupLocal""##, Some("https://example.com/GroupTemplate")), (r##"type="#NotSelected""##, None)]; + let mut local_shapes = String::new(); + for (attributes, _) in local_cases { + local_shapes.push_str(&format!( + r#""#, + )); + } + let local_body = format!( + r##"{local_shapes}"##, + ); + let local_doc = craft_docx::read(&package(&local_body)).unwrap(); + let local_saved = craft_docx::write(&local_doc).unwrap(); + let local_reopened = craft_docx::read(&local_saved).unwrap(); + let original_png = png(); + for current in [&local_doc, &local_reopened] { + assert_eq!(current.body.len(), 1); + let paragraph = current.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), 1); + assert_eq!(paragraph.props_of_char(0).link, None, "a template must not become its containing group's link"); + let InlineObject::Group { children, .. } = ¶graph.objects[0] else { panic!() }; + assert_eq!(children.len(), local_cases.len() + 1); + for (child, (_, expected)) in children.iter().zip(local_cases) { + let InlineObject::Image { media, w, h, .. } = &child.obj else { panic!() }; + assert_eq!(current.media.get(media).unwrap().as_slice(), original_png.as_slice()); + assert!((*w - 6.0).abs() < 0.001 && (*h - 5.0).abs() < 0.001); + assert_eq!(child.link.as_deref(), expected, "group-local template href"); + } + let nested = &children[local_cases.len()]; + assert_eq!(nested.link.as_deref(), Some("https://example.com/NestedTemplateGroup")); + let InlineObject::Group { children: nested_children, .. } = &nested.obj else { panic!() }; + assert_eq!(nested_children.len(), 1); + assert_eq!(nested_children[0].link.as_deref(), Some("https://example.com/DeepTemplate"), "nested group-local template href"); + } +} + +fn replacing_picture_part(bytes: &[u8], name: &str, replacement: &str) -> Vec { + let mut input = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut output = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..input.len() { + let mut file = input.by_index(i).unwrap(); + let entry = file.name().unwrap().to_string(); + let mut data = Vec::new(); + file.read_to_end(&mut data).unwrap(); + if entry == name { + data = replacement.as_bytes().to_vec(); + } + output.start_file(entry, zip::write::SimpleFileOptions::default()).unwrap(); + output.write_all(&data).unwrap(); + } + output.finish().unwrap().into_inner() +} + +#[test] +fn group_picture_links_require_their_own_external_hyperlink_relationship() { + let body = r#""#; + let doc = craft_docx::read(&package(body)).unwrap(); + let saved = craft_docx::write(&doc).unwrap(); + let xml = part(&saved, "word/document.xml"); + let rels = part(&saved, "word/_rels/document.xml.rels"); + let tree = craft_xml::parse(xml.as_bytes()).unwrap(); + let nv = tree.find("pic:pic").unwrap().child("pic:nvPicPr").unwrap().child("pic:cNvPr").unwrap(); + let click = nv.child("a:hlinkClick").expect("the valid child's click must be on its cNvPr"); + let id = click.attr("r:id").unwrap(); + let original_png = png(); + let check = |bytes: &[u8], expected: Option<&str>| { + let doc = craft_docx::read(bytes).unwrap(); + let paragraph = doc.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), 1); + assert_eq!(paragraph.props_of_char(0).link, None, "an unlinked group must not borrow its child's link"); + let InlineObject::Group { children, .. } = ¶graph.objects[0] else { panic!() }; + assert_eq!(children.len(), 1); + let InlineObject::Image { media, w, h, .. } = &children[0].obj else { panic!() }; + assert_eq!(doc.media.get(media).unwrap().as_slice(), original_png.as_slice()); + assert!((*w - 24.0).abs() < 0.001 && (*h - 12.0).abs() < 0.001); + assert_eq!(children[0].link.as_deref(), expected); + }; + check(&saved, Some("https://example.com/Child")); + let type_name = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; + for modified in [ + rels.replace(type_name, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"), + rels.replace(" TargetMode=\"External\"", ""), + rels.replace("Target=\"https://example.com/Child\"", "Target=\" \""), + rels.replace("https://example.com/Child", &format!("https://example.com/{}", "x".repeat(8 << 10))), + ] { + assert_ne!(modified, rels); + check(&replacing_picture_part(&saved, "word/_rels/document.xml.rels", &modified), None); + } + let missing = xml.replace(&format!(r#"r:id="{id}""#), r#"r:id="rIdAbsent""#); + assert_ne!(missing, xml); + check(&replacing_picture_part(&saved, "word/document.xml", &missing), None); + // A click in an unrelated extension is not the picture's nonvisual properties. + let mut unrelated = tree.clone(); + let picture = unrelated + .child_mut("w:body") + .unwrap() + .child_mut("w:p") + .unwrap() + .child_mut("w:r") + .unwrap() + .child_mut("w:drawing") + .unwrap() + .child_mut("wp:inline") + .unwrap() + .child_mut("a:graphic") + .unwrap() + .child_mut("a:graphicData") + .unwrap() + .child_mut("wpg:wgp") + .unwrap() + .child_mut("pic:pic") + .unwrap(); + picture.child_mut("pic:nvPicPr").unwrap().child_mut("pic:cNvPr").unwrap().children.clear(); + let extension = craft_xml::parse(format!(r#""#).as_bytes()).unwrap(); + picture.child_mut("pic:spPr").unwrap().push(extension); + check(&replacing_picture_part(&saved, "word/document.xml", &unrelated.to_xml()), None); +} + +#[test] +fn linked_groups_share_one_retained_member_budget() { + fn count(object: &InlineObject) -> usize { + match object { + InlineObject::Group { children, .. } => children.iter().map(|c| 1 + count(&c.obj)).sum(), + _ => 0, + } + } + fn input(per_group: usize) -> Vec { + let leaf = r#""#.repeat(per_group); + package(&format!( + r#"{leaf}{leaf}"#, + )) + } + let small = craft_docx::read(&input(1)).unwrap(); + assert_eq!(count(&small.body[0].as_para().unwrap().objects[0]), 4, "two linked groups and two picture leaves"); + let saved_small = craft_docx::write(&small).unwrap(); + let reopened_small = craft_docx::read(&saved_small).unwrap(); + assert_eq!(count(&reopened_small.body[0].as_para().unwrap().objects[0]), 4); + let max = craft_wordmodel::para::MAX_GROUP_CHILDREN; + assert_eq!(max, 1000, "this original fixture is bounded to the existing limit plus two nodes"); + let large = craft_docx::read(&input(500)).unwrap(); + assert_eq!(count(&large.body[0].as_para().unwrap().objects[0]), max, "VML must count linked nodes and leaves together"); + // Independently construct the same 1002-node DrawingML input from our small + // original save, so the VML reader's own bound cannot hide a DML budget regression. + let mut xml = craft_xml::parse(part(&saved_small, "word/document.xml").as_bytes()).unwrap(); + let group = xml + .child_mut("w:body") + .unwrap() + .child_mut("w:p") + .unwrap() + .child_mut("w:r") + .unwrap() + .child_mut("w:drawing") + .unwrap() + .child_mut("wp:inline") + .unwrap() + .child_mut("a:graphic") + .unwrap() + .child_mut("a:graphicData") + .unwrap() + .child_mut("wpg:wgp") + .unwrap(); + for child in group.elements_mut().filter(|e| e.name == "wpg:grpSp") { + let picture = child.child("pic:pic").unwrap().clone(); + child.children.retain(|n| !matches!(n, craft_xml::Node::El(e) if e.name == "pic:pic")); + for _ in 0..500 { + child.push(picture.clone()); + } + } + let dml = replacing_picture_part(&saved_small, "word/document.xml", &xml.to_xml()); + let doc = craft_docx::read(&dml).unwrap(); + assert_eq!(count(&doc.body[0].as_para().unwrap().objects[0]), max, "DrawingML must share the same root-wide bound"); +} + +/// An omitted linked group returns its reserved slot before the following drawable is read. +#[test] +fn empty_linked_groups_release_the_last_member_slot() { + let max = craft_wordmodel::para::MAX_GROUP_CHILDREN; + let before = r#""#; + let after = r#""#; + let empty = r#""#; + let input = |members: &str| { + package(&format!( + r#"{members}"#, + )) + }; + let check = |doc: &Document| { + let InlineObject::Group { children, .. } = &doc.body[0].as_para().unwrap().objects[0] else { + panic!("the original root group must remain"); + }; + assert_eq!(children.len(), max, "the empty linked group must return the last member slot"); + assert!(children.iter().all(|child| matches!(&child.obj, InlineObject::Image { .. }) && child.link.is_none())); + assert!( + matches!(&children.last().unwrap().obj, InlineObject::Image { alt, .. } if alt == "after-empty"), + "the drawable after the omitted group must survive" + ); + }; + let vml = input(&format!("{}{empty}{after}", before.repeat(max - 1))); + check(&craft_docx::read(&vml).unwrap()); + + // Save a small, nonempty linked group to obtain normalized DrawingML with its relationship. + // Then remove its drawable and fill the root independently of the VML boundary input. + let seed = + input(&format!(r#"{before}{after}"#,)); + let saved = craft_docx::write(&craft_docx::read(&seed).unwrap()).unwrap(); + let mut xml = craft_xml::parse(part(&saved, "word/document.xml").as_bytes()).unwrap(); + let group = xml + .child_mut("w:body") + .unwrap() + .child_mut("w:p") + .unwrap() + .child_mut("w:r") + .unwrap() + .child_mut("w:drawing") + .unwrap() + .child_mut("wp:inline") + .unwrap() + .child_mut("a:graphic") + .unwrap() + .child_mut("a:graphicData") + .unwrap() + .child_mut("wpg:wgp") + .unwrap(); + let mut empty = group.child("wpg:grpSp").unwrap().clone(); + let filler = empty.child("pic:pic").unwrap().clone(); + let last = group.child("pic:pic").unwrap().clone(); + assert!(empty.child("wpg:cNvPr").unwrap().child("a:hlinkClick").is_some(), "exercise the linked-group reservation path"); + empty.children.retain(|n| !matches!(n, craft_xml::Node::El(e) if e.name == "pic:pic")); + group.children.retain(|n| !matches!(n, craft_xml::Node::El(e) if matches!(e.name.as_str(), "wpg:grpSp" | "pic:pic"))); + for _ in 0..max - 1 { + group.push(filler.clone()); + } + group.push(empty); + group.push(last); + let dml = replacing_picture_part(&saved, "word/document.xml", &xml.to_xml()); + check(&craft_docx::read(&dml).unwrap()); +} + +#[test] +fn linked_group_coordinates_keep_their_scale() { + fn image_rect(object: &InlineObject, x: f32, scale: f32) -> (f32, f32) { + match object { + InlineObject::Image { w, .. } => (x, w * scale), + InlineObject::Group { w, ch_w, children, .. } => { + assert_eq!(children.len(), 1); + let inner = scale * w / ch_w; + image_rect(&children[0].obj, x + children[0].x * inner, inner) + } + _ => panic!("expected a picture or its group"), + } + } + let picture = picture_run(1, ""); + let picture = &picture[picture.find("").unwrap()..picture.find("").unwrap() + "".len()]; + let picture = picture + .replace(r#""#, r#""#); + for linked in [false, true] { + let vml_link = if linked { r#"href="https://example.com/subgroup""# } else { "" }; + let dml_link = if linked { r#""# } else { "" }; + let vml = format!( + r#""#, + ); + let dml = format!( + r#"{dml_link}{picture}"#, + ); + for body in [vml, dml] { + let doc = craft_docx::read(&package(&body)).unwrap(); + let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + for current in [&doc, &reopened] { + let (x, w) = image_rect(¤t.body[0].as_para().unwrap().objects[0], 0.0, 1.0); + assert!((x - 160.0).abs() < 0.01, "the rebased offset must be scaled before clipping: {x}"); + assert!((w - 10.0).abs() < 0.01, "the picture keeps its size in the same coordinate system: {w}"); + } + } + } +} + +#[test] +fn inherited_drawing_targets_share_a_document_byte_budget() { + let target = format!("https://example.com/{}", "x".repeat((8 << 10) - "https://example.com/".len())); + let leaf = r##""##.repeat(1000); + let paragraph = format!( + r#"{leaf}"#, + ); + let doc = craft_docx::read(&package(¶graph.repeat(9))).unwrap(); + let mut bytes = 0; + let mut retained = 0; + let mut dropped = 0; + for block in &doc.body { + let InlineObject::Group { children, .. } = &block.as_para().unwrap().objects[0] else { panic!() }; + assert_eq!(children.len(), 1000, "a target budget must not discard the drawing"); + for child in children { + assert!(matches!(child.obj, InlineObject::Image { .. })); + if let Some(link) = &child.link { + assert_eq!(link, &target); + bytes += link.len(); + retained += 1; + } else { + dropped += 1; + } + } + } + assert!(retained > 0 && dropped > 0, "the same budget must span every group in the document"); + assert!(bytes <= 64 << 20); +} + +#[test] +fn native_ink_keeps_its_vml_preview_target_without_overriding_its_own() { + for own_target in [false, true] { + let input = super::fixtures::ink_docx(true, false); + let mut xml = part(&input, "word/document.xml"); + xml = xml.replace(r#""##.repeat(1000); + let later = format!(r#"{leaf}"#).repeat(9); + xml = xml.replace("", &format!(r#"{later}"#)); + let mut input = replacing_picture_part(&input, "word/document.xml", &xml); + if own_target { + let xml = xml.replace( + r#""#, + r#""#, + ); + let rels = part(&input, "word/_rels/document.xml.rels").replace( + "", + r#""#, + ); + input = replacing_picture_part(&input, "word/document.xml", &xml); + input = replacing_picture_part(&input, "word/_rels/document.xml.rels", &rels); + } + let mut doc = craft_docx::read(&input).unwrap(); + for _ in 0..2 { + let paragraph = doc.body[1].as_para().unwrap(); + let InlineObject::Graphic { graphic, .. } = ¶graph.objects[0] else { panic!() }; + assert_eq!(graphic.kind.noun(), "ink"); + assert!(graphic.source.is_some() && !graphic.items.is_empty()); + let expected = if own_target { "https://example.com/native" } else { "https://example.com/preview" }; + assert_eq!(paragraph.props_of_char(0).link.as_deref(), Some(expected)); + doc = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + } + } +} + +#[test] +fn deepest_linked_vml_tree_survives_flow_and_docx() { + fn check(doc: &Document) { + let paragraph = doc.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), 1); + assert_eq!(paragraph.props_of_char(0).link.as_deref(), Some("https://example.com/root")); + let mut object = ¶graph.objects[0]; + for level in 0..=8 { + let InlineObject::Group { children, .. } = object else { panic!("group at level {level}") }; + assert_eq!(children.len(), 1); + let expected = if level == 8 { "#last-picture".to_string() } else { format!("https://example.com/level{}", level + 1) }; + assert_eq!(children[0].link.as_deref(), Some(expected.as_str())); + object = &children[0].obj; + } + let InlineObject::Image { media, w, h, .. } = object else { panic!("deepest picture") }; + assert_eq!(doc.media.get(media).unwrap().as_slice(), png().as_slice()); + assert!((*w - 6.0).abs() < 0.001 && (*h - 5.0).abs() < 0.001); + } + let mut members = r##""##.to_string(); + for level in (1..=8).rev() { + members = format!(r#"{members}"#,); + } + let body = format!( + r#"{members}"#, + ); + let imported = craft_docx::read(&package(&body)).unwrap(); + check(&imported); + let flow = craft_flow::from_doc_with(&imported, craft_flow::FlowOpts { boxes: true, paras: true, ..Default::default() }); + let rebuilt = craft_flow::to_doc(&flow); + check(&rebuilt); + let reopened = craft_docx::read(&craft_docx::write(&rebuilt).unwrap()).unwrap(); + check(&reopened); +} + +/// Original Flow callers used the mark for a textless paragraph's single drawing. +#[test] +fn a_single_flow_picture_keeps_its_paragraph_mark_link() { + const MARK: &str = "https://example.com/paragraph"; + const OWN: &str = "https://example.com/object"; + let bytes = Arc::new(png()); + for (links, text, expected) in [ + (vec![None], false, vec![Some(MARK)]), + (vec![Some(OWN)], false, vec![Some(OWN)]), + (vec![Some("")], false, vec![None]), + (vec![None, None], false, vec![None, None]), + (vec![Some(OWN), None], false, vec![Some(OWN), None]), + (vec![None, Some(OWN)], false, vec![None, Some(OWN)]), + (vec![None], true, vec![None]), + ] { + let inlines = links + .into_iter() + .map(|link| { + let mut picture = craft_flow::make_img(bytes.clone(), Some(12.0), Some(6.0), "original picture").unwrap(); + picture.link = link.map(str::to_string); + craft_flow::Inline::Image(picture) + }) + .collect(); + let mut paragraph = + craft_flow::Para { inlines, mark: Some(Box::new(CharProps { link: Some(MARK.into()), ..Default::default() })), ..Default::default() }; + if text { + paragraph.push_text("beside the picture", &Default::default()); + } + let flow = craft_flow::Flow { blocks: vec![craft_flow::FBlock::Para(paragraph)], ..Default::default() }; + let model = craft_flow::to_doc(&flow); + let reopened = craft_docx::read(&craft_docx::write(&model).unwrap()).unwrap(); + let expected: Vec<_> = expected.into_iter().map(|target| target.map(str::to_string)).collect(); + for current in [&model, &reopened] { + assert_eq!( + picture_links(current), + expected, + "only the legacy single drawing inherits the mark; explicit targets and neighbors keep their own scope" + ); + let paragraph = current.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), expected.len()); + for object in ¶graph.objects { + let InlineObject::Image { media, w, h, .. } = object else { panic!("the picture remains a picture") }; + assert_eq!(current.media.get(media).unwrap().as_slice(), bytes.as_slice()); + assert!((*w - 12.0).abs() < 0.001 && (*h - 6.0).abs() < 0.001, "the original picture size is retained"); + } + } + } +} + +/// The legacy paragraph target has the same byte limit as an object's own target. +#[test] +fn a_single_flow_picture_bounds_its_inherited_mark_target() { + const OWN: &str = "https://example.com/object"; + let prefix = "https://example.com/"; + let remaining = craft_flow::MAX_LINK - prefix.len(); + let ascii = format!("{prefix}{}", "a".repeat(remaining)); + let utf8 = format!("{prefix}{}{}", "é".repeat(remaining / 2), "a".repeat(remaining % 2)); + let ascii_over = format!("{ascii}a"); + let utf8_over = format!("{utf8}a"); + let bytes = Arc::new(png()); + for (mark, links, expected) in [ + (ascii.as_str(), vec![None], vec![Some(ascii.as_str())]), + (ascii_over.as_str(), vec![None], vec![None]), + (utf8.as_str(), vec![None], vec![Some(utf8.as_str())]), + (utf8_over.as_str(), vec![None], vec![None]), + (ascii_over.as_str(), vec![Some(OWN)], vec![Some(OWN)]), + (ascii_over.as_str(), vec![Some("")], vec![None]), + (ascii_over.as_str(), vec![Some(" \t ")], vec![None]), + (ascii_over.as_str(), vec![Some(ascii_over.as_str())], vec![None]), + (OWN, vec![Some(utf8_over.as_str())], vec![None]), + (ascii_over.as_str(), vec![None, None], vec![None, None]), + (ascii_over.as_str(), vec![Some(OWN), None], vec![Some(OWN), None]), + (ascii_over.as_str(), vec![None, Some(OWN)], vec![None, Some(OWN)]), + ] { + let inlines = links + .into_iter() + .map(|link| { + let mut picture = craft_flow::make_img(bytes.clone(), Some(12.0), Some(6.0), "original picture").unwrap(); + picture.link = link.map(str::to_string); + craft_flow::Inline::Image(picture) + }) + .collect(); + let paragraph = + craft_flow::Para { inlines, mark: Some(Box::new(CharProps { link: Some(mark.into()), ..Default::default() })), ..Default::default() }; + let flow = craft_flow::Flow { blocks: vec![craft_flow::FBlock::Para(paragraph)], ..Default::default() }; + let expected: Vec<_> = expected.into_iter().map(|target| target.map(str::to_string)).collect(); + let check = |current: &Document| { + assert_eq!(picture_links(current), expected, "each drawing keeps only its own or eligible inherited target"); + let paragraph = current.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), expected.len()); + for object in ¶graph.objects { + let InlineObject::Image { media, w, h, .. } = object else { panic!("the picture remains a picture") }; + assert_eq!(current.media.get(media).unwrap().as_slice(), bytes.as_slice()); + assert!((*w - 12.0).abs() < 0.001 && (*h - 6.0).abs() < 0.001, "the original picture size is retained"); + } + }; + let model = craft_flow::to_doc(&flow); + check(&model); + let reopened = craft_docx::read(&craft_docx::write(&model).unwrap()).unwrap(); + check(&reopened); + } +} diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 07a7b79888..945bb2fbbe 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -1412,9 +1412,9 @@ fn groups_round_trip() { ch_w: 200.0, ch_h: 100.0, children: vec![ - GroupChild { x: 0.0, y: 0.0, obj: pic }, - GroupChild { x: 150.0, y: 10.0, obj: oval.clone() }, - GroupChild { x: 50.0, y: 60.0, obj: tb }, + GroupChild { link: None, x: 0.0, y: 0.0, obj: pic }, + GroupChild { link: None, x: 150.0, y: 10.0, obj: oval.clone() }, + GroupChild { link: None, x: 50.0, y: 60.0, obj: tb }, ], canvas: None, }; @@ -1486,7 +1486,7 @@ fn drawing_canvas_round_trips() { float: Float::default(), ch_w: 432.0, ch_h: 216.0, - children: vec![GroupChild { x: 12.0, y: 18.0, obj: pic }, GroupChild { x: 300.0, y: 100.0, obj: star.clone() }], + children: vec![GroupChild { link: None, x: 12.0, y: 18.0, obj: pic }, GroupChild { link: None, x: 300.0, y: 100.0, obj: star.clone() }], canvas: Some(style.clone()), }; let mut p = Paragraph::with_text("drawn ", CharProps::default()); @@ -1533,7 +1533,7 @@ fn rotated_drawing_canvas_round_trips() { float, ch_w: 200.0, ch_h: 100.0, - children: vec![GroupChild { x: 10.0, y: 20.0, obj: member.clone() }], + children: vec![GroupChild { link: None, x: 10.0, y: 20.0, obj: member.clone() }], canvas: Some(CanvasStyle { fill: Some(Fill::solid(Rgb(0xF0, 0xF4, 0xFF))), stroke: None, stroke_width: 0.0 }), }; let square = Float { wrap: Wrap::Square, ..Default::default() }; @@ -2484,6 +2484,7 @@ fn rotation_and_flips_round_trip() { ch_w: 120.0, ch_h: 60.0, children: vec![craft_wordmodel::para::GroupChild { + link: None, x: 0.0, y: 0.0, obj: shape(ShapeKind::Ellipse, Float { rot: 10.0, ..Default::default() }), @@ -2542,8 +2543,8 @@ fn rotated_group_and_shadow_rotation_round_trip() { ch_w: 120.0, ch_h: 40.0, children: vec![ - craft_wordmodel::para::GroupChild { x: 0.0, y: 0.0, obj: member(true) }, - craft_wordmodel::para::GroupChild { x: 60.0, y: 0.0, obj: member(false) }, + craft_wordmodel::para::GroupChild { link: None, x: 0.0, y: 0.0, obj: member(true) }, + craft_wordmodel::para::GroupChild { link: None, x: 60.0, y: 0.0, obj: member(false) }, ], canvas: None, }; @@ -2996,6 +2997,7 @@ fn alt_text_title_and_decorative_round_trip_for_every_object() { ch_w: 120.0, ch_h: 60.0, children: vec![craft_wordmodel::para::GroupChild { + link: None, x: 0.0, y: 0.0, obj: shape(AltText { text: "Left circle".into(), ..Default::default() }), diff --git a/crates/draw/src/geometry/shape.rs b/crates/draw/src/geometry/shape.rs index 3a8ce7a585..f1e3cdbd9b 100644 --- a/crates/draw/src/geometry/shape.rs +++ b/crates/draw/src/geometry/shape.rs @@ -41,10 +41,13 @@ pub enum ShapeGeometry { rect: Rect, }, /// A triangle filling `rect`: the apex at the top centre, the base on the bottom edge (PhotoCraft's Triangle - /// tool and Create Triangle). + /// tool and Create Triangle), each corner rounded by `corner_radius`. Triangle { /// The triangle's bounds. rect: Rect, + /// One radius for every corner, in document units; 0 for sharp corners. A radius larger than the + /// triangle allows is capped by the shape ([`ShapeGeometry::to_path`]). + corner_radius: f64, }, /// A regular polygon or star inscribed in the ellipse of `rect` (the Box frame: PhotoCraft's Polygon). /// `sides` in [`SIDES`]; `star_ratio` in [`STAR_RATIO`], 1 for a plain polygon. @@ -98,7 +101,9 @@ impl ShapeGeometry { /// to half the shorter side, as kurbo's `RoundedRect` does); all radii 0 is the plain /// rectangle. /// - `Ellipse`: kurbo's `Ellipse::from_rect`. - /// - `Triangle`: the top centre, the bottom right and the bottom left of `rect`. + /// - `Triangle`: the top centre, the bottom right and the bottom left of `rect`. A `corner_radius` over 0 + /// rounds each corner with a circular arc tangent to both its edges; the arc's ends lie no farther from + /// the corner than half its shorter edge, which caps a radius the triangle cannot hold. /// - `Polygon`: the outline of [`RadialPolygon`](Self::RadialPolygon) with the first point /// straight up, its outer points on the ellipse inscribed in `rect` (PhotoCraft's engine: /// a 3-sided polygon's base lies a quarter of the height below the centre, not on the bottom @@ -125,10 +130,10 @@ impl ShapeGeometry { } } Self::Ellipse { rect } => Ellipse::from_rect(rect.abs()).to_path(tolerance), - Self::Triangle { rect } => { - // pc: #13350 (the triangle fills its box, apex on top). + Self::Triangle { rect, corner_radius } => { + // pc: #13350 (the triangle fills its box, apex on top); #13355 (the Triangle tool's radius). let rect = rect.abs(); - closed(&[Point::new(rect.center().x, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]) + rounded_closed(&[Point::new(rect.center().x, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)], corner_radius) } Self::Polygon { rect, sides, star_ratio } => { let rect = rect.abs(); @@ -156,9 +161,11 @@ impl ShapeGeometry { pub fn bounds(&self) -> Rect { // pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:85-96 `shape_bounds` (a line's ends' box). match *self { - Self::Rect { rect, .. } | Self::Ellipse { rect } | Self::Triangle { rect } | Self::Polygon { rect, .. } | Self::Custom { rect, .. } => { - rect.abs() - } + Self::Rect { rect, .. } + | Self::Ellipse { rect } + | Self::Triangle { rect, .. } + | Self::Polygon { rect, .. } + | Self::Custom { rect, .. } => rect.abs(), Self::RadialPolygon { center, radius, .. } => Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius), Self::Line { from, to, .. } => Rect::from_points(from, to), } @@ -312,6 +319,50 @@ fn polygon_points(center: Point, radius: f64, rotation: f64, sides: u32, star_ra points } +/// The closed outline through `points` with every corner rounded by `radius`: a circular arc (a cubic) tangent to +/// both edges, whose ends lie no farther from the corner than half the shorter of its two edges. A radius that is +/// 0, negative or not finite, and a corner too flat or too sharp to round, keep the sharp corner. +fn rounded_closed(points: &[Point], radius: f64) -> BezPath { + let n = points.len(); + if !(radius.is_finite() && radius > 0.0) || n < 3 { + return closed(points); + } + // Per corner: where the arc meets the incoming edge, the cubic's two control points and where it leaves. + let corners: Vec<(Point, Point, Point, Point)> = (0..n) + .map(|i| { + let (prev, at, next) = (points[(i + n - 1) % n], points[i], points[(i + 1) % n]); + let (to_prev, to_next) = (prev - at, next - at); + let (len_prev, len_next) = (to_prev.hypot(), to_next.hypot()); + let angle = if len_prev > 0.0 && len_next > 0.0 { (to_prev.dot(to_next) / (len_prev * len_next)).clamp(-1.0, 1.0).acos() } else { 0.0 }; + if !(angle > f64::EPSILON && angle < PI - f64::EPSILON) { + return (at, at, at, at); + } + let half = angle / 2.0; + // The tangent points' distance from the corner, capped at half the shorter edge. + let reach = (radius / half.tan()).min(len_prev.min(len_next) / 2.0); + let (u_prev, u_next) = (to_prev / len_prev, to_next / len_next); + let (enter, leave) = (at + u_prev * reach, at + u_next * reach); + // The arc turns by π − angle; a cubic's handles for a circular arc of turn φ are 4/3·tan(φ/4)·r long. + let arc_radius = reach * half.tan(); + let handle = 4.0 / 3.0 * ((PI - angle) / 4.0).tan() * arc_radius; + (enter, enter - u_prev * handle, leave - u_next * handle, leave) + }) + .collect(); + let mut path = BezPath::new(); + for (i, (enter, c1, c2, leave)) in corners.iter().enumerate() { + if i == 0 { + path.move_to(*enter); + } else { + path.line_to(*enter); + } + if enter != leave { + path.curve_to(*c1, *c2, *leave); + } + } + path.close_path(); + path +} + fn closed(points: &[Point]) -> BezPath { let mut path = BezPath::new(); for (i, p) in points.iter().enumerate() { diff --git a/crates/draw/src/ui/crop/options.rs b/crates/draw/src/ui/crop/options.rs index 003ba54801..8e5cc3388c 100644 --- a/crates/draw/src/ui/crop/options.rs +++ b/crates/draw/src/ui/crop/options.rs @@ -24,7 +24,7 @@ pub const FIELD_MAX: f64 = 1e9; pub const LENGTH_MIN: f64 = 0.01; /// What the frame's proportions follow. -#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropRatio { @@ -55,7 +55,7 @@ impl CropRatio { } /// The resolution field's unit. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ResolutionUnit { @@ -68,7 +68,7 @@ pub enum ResolutionUnit { /// A length with the unit it was entered in: the W and H of W × H × Resolution mode keep what the user typed ("2 in" /// stays in inches when the document resizes). -#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct CropLength { @@ -97,7 +97,7 @@ impl CropLength { /// The W, H and Resolution fields of W × H × Resolution mode. Unset W and H are `None`; the resolution is typed text /// ("300"), empty when unset. Perspective Crop's options bar uses the same fields. -#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct CropSizeFields { @@ -112,7 +112,7 @@ pub struct CropSizeFields { } /// What the area a turned or extending crop uncovers is filled with. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropFill { @@ -229,7 +229,7 @@ pub const CROP_SIZES: [CropSizePreset; 8] = [ /// options bar edits it in place, the tool reads it each pass and reports key changes (O, ⇧O, H, /// P, I, X) as [`CropEvent::Settings`](super::CropEvent::Settings). Every field defaults on its /// own, so older settings load. -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct CropSettings { diff --git a/crates/draw/src/ui/paint_bar.rs b/crates/draw/src/ui/paint_bar.rs index 870b80016d..cd1cfee7f3 100644 --- a/crates/draw/src/ui/paint_bar.rs +++ b/crates/draw/src/ui/paint_bar.rs @@ -1,6 +1,7 @@ //! [`PaintBar`]: the options bar members of the Brush, Pencil, Eraser and Mixer Brush tools after the preset picker. use std::cell::RefCell; +use std::ops::RangeInclusive; use std::sync::Arc; use craft_behavior::{EditEvent, EditEvents, IconId, Mixed, Value}; @@ -201,6 +202,25 @@ pub const MIXER_COMBINATIONS: [Option<(f64, f64, f64)>; 13] = [ /// The index of the first combination of each group (Dry, Moist, Wet, Very Wet); a separator goes above each. pub const MIXER_GROUP_STARTS: [usize; 4] = [1, 4, 7, 10]; +/// The percents a field of the bar holds, and whether it takes input. +struct Percents { + range: RangeInclusive, + enabled: bool, +} + +impl Percents { + /// 0 to 100 %. + fn any(enabled: bool) -> Self { + Percents { range: 0.0..=100.0, enabled } + } + + /// 1 to 100 %, for Opacity and Flow: a stroke at 0 % paints nothing, so a typed 0 is out of range like 150, and + /// the range alert names 1 %. + fn from_one(enabled: bool) -> Self { + Percents { range: 1.0..=100.0, enabled } + } +} + /// Whether the smoothing options popover is open. #[derive(Clone, Default)] struct SmoothingOpen(bool); @@ -208,7 +228,8 @@ struct SmoothingOpen(bool); /// The bar's members for one painting tool, after the preset picker that carries the size and the hardness: a rule, /// Mode, Opacity and the pressure-for-opacity toggle, Flow and the build-up toggle (not the Pencil), Smoothing and its /// options (the Pencil's Auto Erase in their place), Erase to History for the Eraser, a rule and the -/// pressure-for-size toggle. The Mixer Brush shows its load, combinations and mix values instead. +/// pressure-for-size toggle. Opacity and Flow hold 1 to 100 %, Smoothing 0 to 100 %. The Mixer Brush shows its load, +/// combinations and mix values instead. #[must_use = "show the bar with `show`"] #[derive(craft_ui::contract::Pattern)] #[pattern(probe(PaintBar<'static, u32>))] @@ -269,10 +290,10 @@ impl<'a, M: Value> PaintBar<'a, M> { pass.check(ui, &words.load_after_stroke, true, None, pass.values.mixer.load_after_stroke, |v, x| v.mixer.load_after_stroke = x); pass.check(ui, &words.clean_after_stroke, true, None, pass.values.mixer.clean_after_stroke, |v, x| v.mixer.clean_after_stroke = x); pass.combination(ui, &words); - pass.percent(ui, "mixer-wet", &words.wet, true, pass.values.mixer.wet, |v, x| v.mixer.wet = x); - pass.percent(ui, "mixer-load", &words.load, true, pass.values.mixer.load, |v, x| v.mixer.load = x); - pass.percent(ui, "mixer-mix", &words.mix, true, pass.values.mixer.mix, |v, x| v.mixer.mix = x); - pass.percent(ui, "mixer-flow", &words.flow, true, pass.values.mixer.flow, |v, x| v.mixer.flow = x); + pass.percent(ui, "mixer-wet", &words.wet, Percents::any(true), pass.values.mixer.wet, |v, x| v.mixer.wet = x); + pass.percent(ui, "mixer-load", &words.load, Percents::any(true), pass.values.mixer.load, |v, x| v.mixer.load = x); + pass.percent(ui, "mixer-mix", &words.mix, Percents::any(true), pass.values.mixer.mix, |v, x| v.mixer.mix = x); + pass.percent(ui, "mixer-flow", &words.flow, Percents::any(true), pass.values.mixer.flow, |v, x| v.mixer.flow = x); pass.check(ui, &words.sample_all_layers, true, None, pass.values.mixer.sample_all_layers, |v, x| v.mixer.sample_all_layers = x); return; } @@ -283,13 +304,13 @@ impl<'a, M: Value> PaintBar<'a, M> { } else { pass.mode(ui, &words.mode, modes); } - pass.percent(ui, "opacity", &words.opacity, sized, pass.values.opacity, |v, x| v.opacity = x); + pass.percent(ui, "opacity", &words.opacity, Percents::from_one(sized), pass.values.opacity, |v, x| v.opacity = x); pass.toggle(ui, PRESSURE, &words.pressure_opacity, sized, pass.values.pressure_opacity, |v, x| v.pressure_opacity = x); if tool != PaintTool::Pencil { - pass.percent(ui, "flow", &words.flow, sized && soft, pass.values.flow, |v, x| v.flow = x); + pass.percent(ui, "flow", &words.flow, Percents::from_one(sized && soft), pass.values.flow, |v, x| v.flow = x); pass.toggle(ui, "sparkles", &words.build_up, sized && soft, pass.values.build_up, |v, x| v.build_up = x); } - pass.percent(ui, "smoothing", &words.smoothing, true, pass.values.smoothing.amount, |v, x| v.smoothing.amount = x); + pass.percent(ui, "smoothing", &words.smoothing, Percents::any(true), pass.values.smoothing.amount, |v, x| v.smoothing.amount = x); if tool == PaintTool::Pencil { Divider::vertical().show(ui); pass.check(ui, &words.auto_erase, true, Some(&words.auto_erase_tip), pass.values.auto_erase, |v, x| v.auto_erase = x); @@ -361,15 +382,16 @@ impl Pass<'_, M> { } } - /// A percent field over a fraction 0..1. - fn percent(&mut self, ui: &mut Ui, salt: &'static str, caption: &Label, enabled: bool, current: f64, set: fn(&mut PaintValues, f64)) { + /// A percent field over a fraction 0..1, holding `percents`. + fn percent(&mut self, ui: &mut Ui, salt: &'static str, caption: &Label, percents: Percents, current: f64, set: fn(&mut PaintValues, f64)) { + let Percents { range, enabled } = percents; // The body may run more than once in a pass and only the run that reads the input reports its events, so every // run's events and alert are collected. let collected: RefCell<(EditEvents>, Option)> = RefCell::new((EditEvents::new(), None)); let _ = Field::new(caption.clone()).side(SideLabel::new().scrub(true)).id_salt(salt).enabled(enabled).show(ui, |ui, _| { let field = NumberField::new(caption.clone(), Bind::given(Some(current * 100.0))) .unit_kind(UnitKind::Percent) - .range(0.0..=100.0) + .range(range.clone()) .commit_decimals(0) .scrub_by_label() .show(ui); diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index 5c08d39e94..84decd8143 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -77,7 +77,8 @@ pub enum BezierTool { /// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t` /// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does /// ([`PathEdit::PullAnchor`]: ⇧ turns them to the nearest 45°, ⌥ during the drag breaks the pair); the new anchor is - /// selected. A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to + /// selected. Holding Space during that drag moves the anchor and both handles; releasing it resumes pulling. + /// A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to /// the selection, ⌥ on a handle moves it alone), and a click on empty canvas deselects the anchors and keeps the /// path. With ⌥ held at the press a click on a segment selects its whole subpath and a drag moves a copy of it /// ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on an anchor does @@ -250,16 +251,20 @@ enum Target { t: f64, from: Point, }, - /// Add Anchor's drag from a segment: an insert into `segment` at `t`, whose anchor stays at `from`, the point of - /// the curve at `t`, and whose handles follow the pointer. `out` is the out handle of the last pass, and - /// `in_ctrl` the in handle ⌥ left once it broke the pair. + /// Add Anchor's drag from a segment: `from` stays the original curve point, while Space moves the anchor by + /// `by` with both handles. `last` tracks pointer travel; `out` is the last out handle, and `in_ctrl` the in + /// handle ⌥ left once it broke the pair. Pull { path: u64, segment: KnotRef, t: f64, from: Point, + by: Vec2, out: Point, in_ctrl: Option, + last: Pos2, + /// A translated handle stays put until the pointer or its constraints change. + translated_mods: Option, }, /// Direct Selection's ⌥ drag on a segment: a copy of `subpath` dragged from `from`, the grabbed point. Duplicate { @@ -305,6 +310,7 @@ struct Pointing<'a> { start: PressStart, pos: Pos2, mods: Mods, + space: bool, } /// The kind of a part of the overlay. @@ -623,7 +629,7 @@ impl<'a> BezierOverlay<'a> { // Anchor's with ⌥, moves it. BezierHit::Segment { path, segment, t } if self.tool == BezierTool::AddAnchor && self.tool.adds(mods) => { let from = Self::segment_point(paths, path, segment, t); - Target::Pull { path, segment, t, from, out: from, in_ctrl: None } + Target::Pull { path, segment, t, from, by: Vec2::ZERO, out: from, in_ctrl: None, last: start.origin, translated_mods: None } } BezierHit::Segment { path, segment, t } if self.tool.adds(mods) => { Target::Insert { path, segment, t, from: Self::segment_point(paths, path, segment, t) } @@ -752,34 +758,46 @@ impl<'a> BezierOverlay<'a> { PathEdit::InsertCurvature { path, segment, t, by: snapped(from + locked(delta)) - from } } &Target::Insert { path, segment, t, from } => PathEdit::InsertAnchor { path, segment, t, by: snapped(from + locked(delta)) - from }, - &Target::Pull { path, segment, t, from, in_ctrl, .. } => { + &Target::Pull { path, segment, t, from, by, in_ctrl, .. } => { let to = from + delta; - let out = if mods.shift { handle_45(from, to) } else { snapped(to) }; - PathEdit::PullAnchor { path, segment, t, out, in_ctrl } + let out = if mods.shift { handle_45(from + by, to) } else { snapped(to) }; + PathEdit::PullAnchor { path, segment, t, by, out, in_ctrl } } &Target::Duplicate { path, subpath, from } => PathEdit::DuplicateSubpath { path, subpath, by: snapped(from + locked(delta)) - from }, Target::Nothing | Target::Toggle { .. } | Target::Pick { .. } | Target::Marquee => return None, }) } - /// [`edit`](Self::edit), keeping what a [`Target::Pull`] carries from pass to pass: ⌥ pressed during the drag - /// leaves the in handle where the last pass had it, and the out handle is remembered for the next pass. - fn edit_pulled( - view: &CanvasView, - snap: Option<&Snap>, - tool: BezierTool, - target: &mut Target, - origin: Pos2, - pointer: Pos2, - mods: Mods, - ) -> Option { - if let Target::Pull { from, out, in_ctrl, .. } = target - && mods.alt - && in_ctrl.is_none() - { - *in_ctrl = Some(*from - (*out - *from)); + /// Keeps Add Anchor's anchor and handles together while Space is held; otherwise pulls the handles. + /// ⌥ leaves the previous in handle in place until Space moves the whole knot again. + fn edit_pulled(tool: BezierTool, target: &mut Target, at: Pointing<'_>) -> Option { + let Pointing { view, snap, start, pos, mods, space } = at; + if let Target::Pull { path, segment, t, from, by, out, in_ctrl, last, translated_mods } = target { + if space { + let delta = view.to_doc(pos) - view.to_doc(*last); + *by += delta; + *out += delta; + if let Some(incoming) = in_ctrl { + *incoming += delta; + } + *last = pos; + *translated_mods = Some(mods); + return Some(PathEdit::PullAnchor { path: *path, segment: *segment, t: *t, by: *by, out: *out, in_ctrl: *in_ctrl }); + } + // Space keeps translation priority; on release, Alt can break the pair without moving its geometry. + if mods.alt && in_ctrl.is_none() { + let anchor = *from + *by; + *in_ctrl = Some(anchor - (*out - anchor)); + } + // Space moves by raw travel, including off the snap targets. Releasing it is not a pointer move: + // keep that geometry on every stationary pass, but still read modifier-only constraint changes. + if *last == pos && *translated_mods == Some(mods) { + return Some(PathEdit::PullAnchor { path: *path, segment: *segment, t: *t, by: *by, out: *out, in_ctrl: *in_ctrl }); + } + *translated_mods = None; + *last = pos; } - let edit = Self::edit(view, snap, tool, target, origin, pointer, mods); + let edit = Self::edit(view, snap, tool, target, start.origin, pos, mods); if let (Target::Pull { out, .. }, Some(PathEdit::PullAnchor { out: pulled, .. })) = (target, &edit) { *out = *pulled; } @@ -846,6 +864,7 @@ impl<'a> BezierOverlay<'a> { fn run_pointer(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, scene: &Scene, paths: &[EditPath]) { let snap = canvas_snap(&cx.env); let view = &space.view; + let space_held = space.space_held(); let mut hovered: Option<(u8, BezierHit, Mods)> = None; let mut pressed = false; for item in &scene.items { @@ -853,7 +872,7 @@ impl<'a> BezierOverlay<'a> { continue; } let Some(result) = cx.part_if_declared(item.part()) else { continue }; - let (press, hover) = (result.press, result.hover_pos); + let (press, hover) = (result.press, cx.hover_pos(item.part())); pressed |= press.phase.is_press(); if let Some(at) = hover { let rank = match item.kind { @@ -882,10 +901,10 @@ impl<'a> BezierOverlay<'a> { } PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => { let first = matches!(press.phase, PressPhase::DragStart { .. }); - self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, Some(item), paths, first); + self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, Some(item), paths, first); } PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => { - self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths); + self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, click, paths); } PressPhase::Cancel { .. } => *cx.press_slot::() = None, _ => {} @@ -904,10 +923,10 @@ impl<'a> BezierOverlay<'a> { } PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => { let first = matches!(press.phase, PressPhase::DragStart { .. }); - self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, None, paths, first); + self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, None, paths, first); } PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => { - self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths); + self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, click, paths); } PressPhase::Cancel { .. } => *cx.press_slot::() = None, _ => {} @@ -916,7 +935,7 @@ impl<'a> BezierOverlay<'a> { if matches!(self.tool, BezierTool::AddAnchor | BezierTool::DeleteAnchor) && let Some(result) = cx.part_if_declared(EMPTY) { - let (press, hover) = (result.press, result.hover_pos); + let (press, hover) = (result.press, cx.hover_pos(EMPTY)); // The part covers the canvas background, so it owns the cursor the host tool shows off the paths too. if hover.is_some() { let tool = if self.tool == BezierTool::AddAnchor { PathTool::AddAnchor } else { PathTool::DeleteAnchor }; @@ -945,7 +964,7 @@ impl<'a> BezierOverlay<'a> { /// One pass of a press dragged to `pos`; `first` on the pass the drag begins. fn drag(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, item: Option<&Item>, paths: &[EditPath], first: bool) { - let Pointing { view, snap, start, pos, mods } = at; + let Pointing { view, start, pos, mods, .. } = at; let kept = cx.press_slot::().take().filter(|held| held.origin == start.origin); let mut held = match (kept, item) { (Some(held), _) => held, @@ -974,7 +993,7 @@ impl<'a> BezierOverlay<'a> { } } _ => { - if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut held.target, start.origin, pos, mods) { + if let Some(edit) = Self::edit_pulled(self.tool, &mut held.target, at) { self.propose(cx, &held.start, edit); } } @@ -985,7 +1004,7 @@ impl<'a> BezierOverlay<'a> { /// The release of a press at `pos`: a drag commits, a click does what its tool's click does. fn release(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, click: bool, paths: &[EditPath]) { - let Pointing { view, snap, start, pos, mods } = at; + let Pointing { view, start, pos, mods, .. } = at; // A press reports its Down, and its drag start, before its release, and the overlay holds the press from // either: a release with nothing held is of a press the overlay let go (a cancelled one), and does nothing. let Some(held) = cx.press_slot::().take().filter(|held| held.origin == start.origin) else { return }; @@ -1003,7 +1022,7 @@ impl<'a> BezierOverlay<'a> { } if held.began { let mut target = held.target.clone(); - if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut target, start.origin, pos, mods) { + if let Some(edit) = Self::edit_pulled(self.tool, &mut target, at) { self.propose(cx, &held.start, edit); } // The copy is what was dragged: it ends up selected, not the source. diff --git a/crates/draw/src/ui/pen/bezier/model.rs b/crates/draw/src/ui/pen/bezier/model.rs index d95f1d0532..b3ece745a8 100644 --- a/crates/draw/src/ui/pen/bezier/model.rs +++ b/crates/draw/src/ui/pen/bezier/model.rs @@ -452,7 +452,8 @@ pub enum PathEdit { }, /// Add Anchor's drag from a segment: add an anchor to the segment leaving `segment` at `t` and pull out its /// handles, as the Pen does: the out handle at `out` and the in handle opposite it through the anchor, a smooth - /// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot. + /// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot. `by` moves the new anchor from + /// the original segment point; both handles are absolute document positions, including that move. #[non_exhaustive] PullAnchor { /// The path's host key. @@ -461,7 +462,9 @@ pub enum PathEdit { segment: KnotRef, /// Position along the segment, 0..=1. t: f64, - /// The new anchor's out handle. + /// The move of the new anchor from the original segment point, in document units. + by: Vec2, + /// The new anchor's out handle, in document coordinates. out: Point, /// The new anchor's in handle once Alt broke the pair; `None` mirrors `out`. in_ctrl: Option, @@ -546,7 +549,14 @@ impl PathEdit { /// Add Anchor's insert into the segment leaving `segment` at `t` with the new anchor's handles pulled out to `out` /// and mirrored, or with the in handle at `in_ctrl`. pub fn pull_anchor(path: u64, segment: KnotRef, t: f64, out: Point, in_ctrl: Option) -> Self { - PathEdit::PullAnchor { path, segment, t, out, in_ctrl } + Self::pull_anchor_moved(path, segment, t, Vec2::ZERO, out, in_ctrl) + } + + /// Add Anchor's insert with its anchor moved by `by` from the original segment point. + /// `out` and `in_ctrl` are absolute document positions; `None` mirrors `out` through the moved anchor. + /// Hosts applying edits themselves must apply `by` to the inserted anchor before setting the handles. + pub fn pull_anchor_moved(path: u64, segment: KnotRef, t: f64, by: Vec2, out: Point, in_ctrl: Option) -> Self { + PathEdit::PullAnchor { path, segment, t, by, out, in_ctrl } } /// The Curvature tool's toggle of `knot` between smooth and corner. diff --git a/crates/draw/src/ui/pen/bezier/ops.rs b/crates/draw/src/ui/pen/bezier/ops.rs index 889e4f5767..1befd5fbf2 100644 --- a/crates/draw/src/ui/pen/bezier/ops.rs +++ b/crates/draw/src/ui/pen/bezier/ops.rs @@ -137,9 +137,9 @@ impl PathEdit { /// `by`, then the subpath reflowed. /// - `InsertAnchor`: [`EditSubpath::insert_at`], the new knot with its handles moved by `by`; no /// reflow and no smoothing, so a straight segment gets a corner knot. - /// - `PullAnchor`: [`EditSubpath::insert_at`], then the new knot's out handle at `out` and its in - /// handle at `in_ctrl` (a corner), or mirrored through the anchor (smooth). Nothing changes when - /// a handle is not finite. + /// - `PullAnchor`: [`EditSubpath::insert_at`], then the new anchor moved by `by`, its out handle at + /// `out` and its in handle at `in_ctrl` (a corner), or mirrored through the moved anchor (smooth). + /// Nothing changes when the offset, moved anchor or a resulting handle is not finite. /// - `ToggleCurvature`: a smooth knot becomes a corner with retracted handles, a corner /// becomes smooth, then the subpath reflows. /// - `DuplicateSubpath`: a copy of the subpath goes last and moves, with its handles, by `by`; @@ -206,16 +206,23 @@ impl PathEdit { k.in_ctrl += *by; k.out_ctrl += *by; } - PathEdit::PullAnchor { segment, t, out, in_ctrl, .. } => { + PathEdit::PullAnchor { segment, t, by, out, in_ctrl, .. } => { let finite = |p: &Point| p.x.is_finite() && p.y.is_finite(); - if !finite(out) || !in_ctrl.as_ref().is_none_or(finite) { + if !by.x.is_finite() || !by.y.is_finite() || !finite(out) || !in_ctrl.as_ref().is_none_or(finite) { return false; } let Some(sp) = path.subpaths.get_mut(segment.subpath) else { return false }; let Some(at) = sp.insert_at(segment.knot, *t) else { return false }; let k = &mut sp.knots[at]; + let anchor = k.anchor + *by; + let incoming = in_ctrl.unwrap_or(anchor - (*out - anchor)); + if !finite(&anchor) || !finite(&incoming) { + *path = before; + return false; + } + k.anchor = anchor; k.out_ctrl = *out; - k.in_ctrl = in_ctrl.unwrap_or(k.anchor - (*out - k.anchor)); + k.in_ctrl = incoming; k.smooth = in_ctrl.is_none(); } PathEdit::Convert { knot, out, .. } => { diff --git a/crates/draw/src/ui/pen/options.rs b/crates/draw/src/ui/pen/options.rs index a616018e1a..ff745df7bf 100644 --- a/crates/draw/src/ui/pen/options.rs +++ b/crates/draw/src/ui/pen/options.rs @@ -38,7 +38,7 @@ pub const PATH_OPTIONS_COLOR_KEY: &str = "pathOptions.color"; /// The pen's Path Options, persisted by the app with its preferences (Photoshop's Pen gear popover). Serialised in /// camelCase; unknown fields are ignored and missing ones take their defaults. -#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct PathOptionsSettings { @@ -58,7 +58,7 @@ pub struct PathOptionsSettings { } /// How the direction handles' ends are drawn. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum HandleStyle { diff --git a/crates/draw/src/ui/shape/bar.rs b/crates/draw/src/ui/shape/bar.rs index cbe183040a..1f08eafe2f 100644 --- a/crates/draw/src/ui/shape/bar.rs +++ b/crates/draw/src/ui/shape/bar.rs @@ -35,8 +35,9 @@ pub struct ShapeBarOutput { /// The cells a Shape tool adds to the options bar, in PhotoCraft's order: the "Fill" check box and chip, the /// "Stroke" chip, the stroke width (0 to 288 px), the Stroke style button; then the kind's cell: Rectangle and -/// Rounded Rectangle "Radius" (0 to 150,000), Polygon and Star "Sides" (3 to 100), Line "Weight" (1 to 10,000). A -/// pattern shown as children of a `Bar`. +/// Rounded Rectangle "Radius" (0 to 150,000), Triangle "Radius" (0 to 150,000, its own +/// [`triangle_corner_radius`](ShapeToolSettings::triangle_corner_radius)), Polygon and Star "Sides" (3 to 100), Line +/// "Weight" (1 to 10,000). A pattern shown as children of a `Bar`. /// /// - The values are the selected shape layer's when one is selected, else the tool settings' (the app passes the /// right [`ShapeAppearance`]). @@ -143,6 +144,10 @@ impl<'a> ShapeBar<'a> { NumberCell::pixels(&units, pixels_per_inch, "radius", &words.radius, settings.corner_radius, RADIUS_RANGE), ShapeChange::CornerRadius as fn(f64) -> ShapeChange, )), + ShapeKind::Triangle => Some(( + NumberCell::pixels(&units, pixels_per_inch, "radius", &words.radius, settings.triangle_corner_radius, RADIUS_RANGE), + ShapeChange::CornerRadius as fn(f64) -> ShapeChange, + )), ShapeKind::Polygon | ShapeKind::Star => Some(( NumberCell::count(&units, "sides", &words.sides, f64::from(settings.sides), SIDES_RANGE), sides_change as fn(f64) -> ShapeChange, diff --git a/crates/draw/src/ui/shape/mod.rs b/crates/draw/src/ui/shape/mod.rs index 02995f04d8..8be6c93dfc 100644 --- a/crates/draw/src/ui/shape/mod.rs +++ b/crates/draw/src/ui/shape/mod.rs @@ -29,7 +29,7 @@ pub use stroke_cells::{StrokeCells, StrokeCellsOutput}; pub use words::ShapeWords; /// The drawing mode of the vector tools. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum VectorMode { @@ -252,7 +252,8 @@ pub enum ShapeChange { }, /// A rectangle's four radii (the "Corner radius" field sets all four). Radii([f64; 4]), - /// A polygon's corner radius, or the options bar's Radius. + /// A polygon's or triangle's corner radius, or the options bar's Radius (the Rectangle's, or the Triangle + /// tool's own). CornerRadius(f64), /// A polygon's number of sides. Sides(u32), @@ -270,8 +271,8 @@ impl ShapeChange { pub const ENABLED_STROKE_WIDTH: f64 = 3.0; } -/// The Shape tools' persisted options-bar values (Fill on, radius, sides, star ratio, weight, -/// stroke width, the Rectangle's gear); the paints are the app's foreground and background. +/// The Shape tools' persisted options-bar values (Fill on, the Rectangle's and the Triangle's radius, sides, star +/// ratio, weight, stroke width, the Rectangle's gear); the paints are the app's foreground and background. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] @@ -280,6 +281,9 @@ pub struct ShapeToolSettings { pub fill_on: bool, /// The Rectangle's corner radius. pub corner_radius: f64, + /// The Triangle's corner radius, one for its three corners: the Triangle tool keeps its own, apart from the + /// Rectangle's (storytold/photocraft#13355). + pub triangle_corner_radius: f64, /// A polygon's sides or a star's points. pub sides: u32, /// A star's inner over outer radius. @@ -295,12 +299,13 @@ pub struct ShapeToolSettings { } impl Default for ShapeToolSettings { - /// Fill on, square corners, 5 sides, a star ratio of 0.5 (production's Star), weight 3, no stroke, no + /// Fill on, square corners (Rectangle and Triangle), 5 sides, a star ratio of 0.5 (production's Star), weight 3, no stroke, no /// arrowheads, an unconstrained Rectangle. fn default() -> Self { ShapeToolSettings { fill_on: true, corner_radius: 0.0, + triangle_corner_radius: 0.0, sides: 5, star_ratio: 0.5, line_weight: 3.0, @@ -312,10 +317,11 @@ impl Default for ShapeToolSettings { } impl ShapeToolSettings { - /// The drag options of `kind` with these values; the gear's constraints apply to the Rectangle only. + /// The drag options of `kind` with these values; the gear's constraints apply to the Rectangle only, and a + /// Triangle takes its own corner radius. pub fn drag_options(&self, kind: ShapeKind) -> ShapeDragOptions { - let options = - ShapeDragOptions::new(kind).corner_radius(self.corner_radius).sides(self.sides).star_ratio(self.star_ratio).line_weight(self.line_weight); + let radius = if kind == ShapeKind::Triangle { self.triangle_corner_radius } else { self.corner_radius }; + let options = ShapeDragOptions::new(kind).corner_radius(radius).sides(self.sides).star_ratio(self.star_ratio).line_weight(self.line_weight); match kind { ShapeKind::Rectangle => options.constraints(self.rect_box), _ => options, diff --git a/crates/draw/src/ui/shape_drag/dialog.rs b/crates/draw/src/ui/shape_drag/dialog.rs index ad6b6e35ab..02f6ef61dd 100644 --- a/crates/draw/src/ui/shape_drag/dialog.rs +++ b/crates/draw/src/ui/shape_drag/dialog.rs @@ -26,6 +26,7 @@ use serde_json::{Value, json}; use super::ShapeKind; use super::words::CreateShapeWords; use crate::geometry::shape::{SIDES, ShapeGeometry}; +use crate::ui::shape::RADIUS_RANGE; /// The farthest the click may lie from the origin on either axis, in pixels: the same bound as /// a side (PhotoCraft's `MAX_PX`, `shape_dialog.rs:19`, checked at `:111`). @@ -52,7 +53,7 @@ pub struct CreateShapeOptions { /// Width and height in document pixels (100 × 100 by default). pub size: (f64, f64), /// A rectangle's radii, top-left, top-right, bottom-right, bottom-left (from the tool's corner - /// radius). + /// radius). A triangle's one corner radius is all four. pub radii: [f64; 4], /// "Link radii": one radius for all four corners; on by default. pub link_radii: bool, @@ -102,7 +103,7 @@ impl CreateShapeOptions { self } - /// The tool's corner radius (all four corners), sides and star ratio. + /// The tool's corner radius (all four corners; a triangle's three), sides and star ratio. #[must_use] pub fn tool(mut self, corner_radius: f64, sides: u32, star_ratio: f64) -> Self { self.radii = [corner_radius; 4]; @@ -149,8 +150,9 @@ struct Memory { /// picked for a field is not remembered, storytold/photocraft#7786). Rectangle and Rounded /// Rectangle: four radii Top Left, Top Right, Bottom Left, Bottom Right in two columns under one /// "Radius" label, with the "Link radii" toggle between the columns (`LinkMode::Equal`, on by -/// default). Polygon and Star: Sides (3–100) and Star Ratio (1–100 %, default 100); the Polygon drag -/// keeps ratio 1. Then "From Center". +/// default). Triangle: one "Radius" for its three corners (0 to 150,000 px, from the Triangle tool's own radius; +/// storytold/photocraft#13355). Polygon and Star: Sides (3–100) and Star Ratio (1–100 %, default 100); the Polygon +/// drag keeps ratio 1. Then "From Center". /// - A width or height typed past [`CreateShapeOptions::SIZE`] keeps the nearest end and raises the range alert, /// which the app opens from [`take_range_alert`](Self::take_range_alert) (#13358). A size set out of range /// through automation shows [`CreateShapeWords::bad_size`] under the fields and disables OK; so does a click @@ -214,7 +216,11 @@ fn answer(o: &CreateShapeOptions, words: &CreateShapeWords, units: &Units) -> Re ShapeGeometry::Rect { rect, radii } } ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect }, - ShapeKind::Triangle => ShapeGeometry::Triangle { rect }, + ShapeKind::Triangle => { + let radius = o.radii[0]; + let corner_radius = if radius.is_finite() { radius.clamp(*RADIUS_RANGE.start(), *RADIUS_RANGE.end()) } else { 0.0 }; + ShapeGeometry::Triangle { rect, corner_radius } + } ShapeKind::Polygon | ShapeKind::Star => { let ratio = if o.star_ratio.is_finite() { o.star_ratio.clamp(0.01, 1.0) } else { 1.0 }; ShapeGeometry::Polygon { rect, sides, star_ratio: ratio } @@ -441,6 +447,20 @@ fn body( } }); } + if kind == ShapeKind::Triangle { + Field::new(Label::from(words.radius.as_str().to_owned())).show(ui, |ui, _| { + let radius = values.radii[0]; + let field = NumberField::new(words.radius.as_str().to_owned(), Bind::given(Some(radius))) + .range(RADIUS_RANGE) + .unit(numbers.symbol(UnitKind::Pixels)) + .commit_decimals(2); + if let Some(value) = field.show(ui).value().copied().flatten() + && value != radius + { + values.radii = [value.clamp(*RADIUS_RANGE.start(), *RADIUS_RANGE.end()); 4]; + } + }); + } if matches!(kind, ShapeKind::Polygon | ShapeKind::Star) { Field::new(Label::from(words.sides.as_str().to_owned())).show(ui, |ui, _| { let field = NumberField::new(words.sides.as_str().to_owned(), Bind::given(Some(f64::from(values.sides)))) @@ -487,7 +507,7 @@ impl StackDialog for CreateShapeDialog { type Result = CreatedShape; /// `width` and `height` in the unit their field shows, `widthUnit` and `heightUnit`, `radii` (top-left, - /// top-right, bottom-right, bottom-left, in pixels), `linkRadii`, `sides`, `starRatio` (in percent, as its + /// top-right, bottom-right, bottom-left, in pixels), `linkRadii`, a triangle's `cornerRadius` (pixels), `sides`, `starRatio` (in percent, as its /// field shows it) and `fromCenter`. fn json_fields(&self) -> Option { let o = &self.options; @@ -499,15 +519,16 @@ impl StackDialog for CreateShapeDialog { "heightUnit": self.units[1], "radii": o.radii, "linkRadii": o.link_radii, + "cornerRadius": o.radii[0], "sides": o.sides, "starRatio": (o.star_ratio * 100.0).clamp(1.0, 100.0), "fromCenter": o.from_center, })) } - /// Sets a field as its row does, from the remembered values on. The radius rows answer only for a rectangle, and - /// Sides and Star Ratio only for a polygon or star; elsewhere they refuse as inactive. Linked radii take four - /// equal values. + /// Sets a field as its row does, from the remembered values on. The radius rows answer only for a rectangle, + /// `cornerRadius` only for a triangle, and Sides and Star Ratio only for a polygon or star; elsewhere they refuse + /// as inactive. Linked radii take four equal values. fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> { self.recall(ctx); let rejects = || FieldRefusal::Rejects(&value).message(field); @@ -516,6 +537,7 @@ impl StackDialog for CreateShapeDialog { let polygon = matches!(kind, ShapeKind::Polygon | ShapeKind::Star); let shown = match field { "radii" | "linkRadii" => rect, + "cornerRadius" => kind == ShapeKind::Triangle, "sides" | "starRatio" => polygon, _ => true, }; @@ -545,6 +567,10 @@ impl StackDialog for CreateShapeDialog { o.radii = radii.map(|radius| radius.clamp(0.0, MAX_RADIUS)); } "linkRadii" => o.link_radii = value.as_bool().ok_or_else(rejects)?, + "cornerRadius" => { + let radius = value.as_f64().filter(|radius| radius.is_finite()).ok_or_else(rejects)?; + o.radii = [radius.clamp(*RADIUS_RANGE.start(), *RADIUS_RANGE.end()); 4]; + } "sides" => { let sides = value.as_f64().ok_or_else(rejects)?; o.sides = sides.round().clamp(f64::from(*SIDES.start()), f64::from(*SIDES.end())) as u32; diff --git a/crates/draw/src/ui/shape_drag/mod.rs b/crates/draw/src/ui/shape_drag/mod.rs index 9d24fe9690..c065ede2a5 100644 --- a/crates/draw/src/ui/shape_drag/mod.rs +++ b/crates/draw/src/ui/shape_drag/mod.rs @@ -115,7 +115,8 @@ impl Default for BoxConstraints { pub struct ShapeDragOptions { /// Which shape the drag draws. pub kind: ShapeKind, - /// The Rectangle's corner radius; over 0 draws four equal radii. + /// The Rectangle's corner radius, over 0 drawing four equal radii; for a Triangle, the radius of its three + /// corners. pub corner_radius: f64, /// The polygon's sides or the star's points, in [`SIDES`](crate::geometry::shape::SIDES). pub sides: u32, @@ -136,7 +137,7 @@ impl ShapeDragOptions { ShapeDragOptions { kind, ..ShapeDragOptions::default() } } - /// The Rectangle's corner radius. + /// The Rectangle's or the Triangle's corner radius. #[must_use] pub fn corner_radius(mut self, radius: f64) -> Self { self.corner_radius = radius; diff --git a/crates/draw/src/ui/shape_drag/tool.rs b/crates/draw/src/ui/shape_drag/tool.rs index d21a7a8182..0660c2bc5c 100644 --- a/crates/draw/src/ui/shape_drag/tool.rs +++ b/crates/draw/src/ui/shape_drag/tool.rs @@ -150,7 +150,7 @@ impl ShapeDragTool { /// when a side is under 1 px: [`box_drag`] for the box kinds under the options' constraints, ⇧ /// toggling Square and ⌥ From Center (Rectangle with four equal radii when /// `corner_radius` > 0, Rounded Rectangle always with them, Triangle filling the box (⇧: the equilateral - /// triangle in the square's circle), Polygon and + /// triangle in the square's circle) with its corners rounded by `corner_radius`, Polygon and /// Star with the options' sides and ratio, Custom a `Custom` box keeping proportions with ⇧), /// [`line_drag`] for a Line (weight at least 1, ⇧ snapping the end by [`line_shift`]), and /// [`RadialFrame::drag`] in the radial frame. @@ -194,7 +194,7 @@ impl ShapeDragTool { ShapeKind::Rectangle => ShapeGeometry::Rect { rect, radii: [0.0; 4] }, ShapeKind::RoundedRectangle => ShapeGeometry::Rect { rect, radii }, ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect }, - ShapeKind::Triangle => ShapeGeometry::Triangle { rect: if rule.square { equilateral_in(rect) } else { rect } }, + ShapeKind::Triangle => ShapeGeometry::Triangle { rect: if rule.square { equilateral_in(rect) } else { rect }, corner_radius: radii[0] }, ShapeKind::Polygon => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: 1.0 }, ShapeKind::Star => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: o.star_ratio }, ShapeKind::Custom | ShapeKind::Line => ShapeGeometry::Custom { rect, keep_proportions: mods.shift }, diff --git a/crates/draw/src/ui/transform/session/settings.rs b/crates/draw/src/ui/transform/session/settings.rs index 72601b2bc3..3a779f3ba8 100644 --- a/crates/draw/src/ui/transform/session/settings.rs +++ b/crates/draw/src/ui/transform/session/settings.rs @@ -49,7 +49,7 @@ impl TransformPreset { /// How the transform resamples the moving pixels: PhotoCraft's three choices (LC11). The app maps /// them to its engine; [`id`](Self::id) gives PhotoCraft's ids. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum Interpolation { @@ -100,7 +100,7 @@ pub enum TransformChoice { /// Free Transform's persisted section: the app keeps it with its preferences. Unknown fields are /// ignored, missing ones take their defaults. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct TransformSettings { diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index a7c7230f99..2169a87453 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -493,7 +493,8 @@ pub struct TransformBox<'a> { #[prop] round_handles: bool, /// The side of the corner and side handles in points, for a host with a handle size preference; `None` uses the - /// theme's (`size.handle.md`). A handle's reach grows with a larger side and stays at least the theme's. + /// theme's (`size.handle.md`), as does a side that is zero, negative or not finite. A handle's reach grows with a + /// larger side and stays at least the theme's. #[prop(quantity = "points, from the host's handle size preference")] handle_side: Option, /// Draws the box as a live line's controls (the Line tool's live line as the whole selection). Only the two ends @@ -585,14 +586,19 @@ impl<'a> TransformBox<'a> { self.color.map_or(StrokeColor::from(theme), StrokeColor::from) } + /// The host's handle side when it is a finite side above zero; `None` for none or any other value. + fn host_handle_side(&self) -> Option { + self.handle_side.filter(|side| side.is_finite() && *side > 0.0) + } + /// The side of a corner or side handle: the host's, else the theme's. fn side_of_handles(&self, style: &TransformBoxStyle) -> f32 { - self.handle_side.unwrap_or(style.handle.side) + self.host_handle_side().unwrap_or(style.handle.side) } /// The hit radius of a corner or side handle: the theme's, or more for a host's larger handle. fn reach_of_handles(&self, style: &TransformBoxStyle) -> f32 { - self.handle_side.map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES)) + self.host_handle_side().map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES)) } /// Whether the middle of the box is a move part: the reference point is hidden, so it does not take that place. @@ -842,7 +848,7 @@ impl<'a> TransformBox<'a> { let suspend = suspend_key(snap.as_ref()); for (reference, part) in self.pointer_parts() { let Some(result) = cx.part_if_declared(reference) else { continue }; - let (press, hover) = (result.press, result.hover_pos.filter(|_| result.hovered)); + let (press, hover) = (result.press, cx.hover_pos(reference)); let mods = self.mods.unwrap_or(press.mods); let acting = drag_mods(mods, suspend); if let Some(pos) = hover diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 7db3cbe69a..82a6612dc5 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -1,12 +1,13 @@ //! `BezierOverlay`: the pure path operations, and the overlay's pointer, keyboard and tools through the public API. +use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets}; use craft_behavior::kurbo::{ParamCurve as _, Point, Size, Vec2}; use craft_behavior::{CanvasView, EditEvent}; use craft_draw::ui::{ AnchorDelete, AnchorTool, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef, PathEdit, PathSelection, PathTool, SegmentMark, }; -use craft_ui::canvas::{Canvas, Guide, ToolHost, tool_pass}; +use craft_ui::canvas::{Canvas, Guide, Momentary, NavigationOptions, Snap, ToolHost, tool_pass}; use craft_ui::canvas_controls::Guides; use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft_ui::primitives::cancel_press_of; @@ -176,6 +177,7 @@ struct State { paths: Vec, selection: PathSelection, guides: Vec, + snap: Option, tool: BezierTool, handles: HandlesShown, anchors: AnchorsShown, @@ -199,6 +201,8 @@ struct State { tool_clicks: usize, /// The anchor tool the canvas runs under the overlay, if any. canvas_tool: Option, + /// The app-owned momentary navigation set, enabled by tests that exercise Space-to-Hand routing. + momentary: Option, /// Passes in which that tool ran a gesture. tool_gestures: usize, } @@ -246,6 +250,7 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { paths, selection: PathSelection::default(), guides: Vec::new(), + snap: None, tool: BezierTool::Direct, handles: HandlesShown::Selected, anchors: AnchorsShown::All, @@ -264,6 +269,7 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { lone_selects: 0, tool_clicks: 0, canvas_tool: None, + momentary: None, tool_gestures: 0, })); let shown = Rc::clone(&state); @@ -285,6 +291,10 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { let canvas_id = ui.scope_id().with("document canvas"); let canvas = Canvas::new("Document").id(canvas_id).view(view).precise_cursors(st.precise); let canvas = if st.pans { canvas.document(Size::new(4000.0, 4000.0)) } else { canvas }; + let canvas = match &st.snap { + Some(snap) => canvas.snap(snap.clone()), + None => canvas, + }; let mut reply = None; let canvas = canvas.show(ui, |ui, body| { // The guides lie under the paths: a stack position hides the levels of the ones below it. @@ -298,18 +308,25 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { .segment_mark(st.segment_mark) .show_at(ui, body.rect); if let (Some(tool), Some(pass)) = (st.canvas_tool, tool_pass(&body.env)) { - reply = Some(ToolHost::new().run(ui, &pass, &mut AnchorTool::new(tool))); + let mut host = ToolHost::new(); + if let Some(momentary) = st.momentary.as_mut() { + host = host.momentary(momentary); + } + reply = Some(host.run(ui, &pass, &mut AnchorTool::new(tool))); } output }); if canvas.output.click_at().is_some() { st.tool_clicks += 1; } - if let Some(reply) = reply { + let tool_view = if let Some(reply) = reply { st.tool_gestures += usize::from(reply.gesture.is_some()); - } + reply.view + } else { + None + }; if st.pans { - st.view = canvas.output.view.or(st.view); + st.view = tool_view.or(canvas.output.view).or(st.view); } let Some(output) = canvas.inner else { return }; st.id = output.edit.response.id; @@ -1416,3 +1433,282 @@ fn a_cancelled_press_reports_nothing_on_release() { assert_eq!(st.changes.len(), changes, "{:?}", st.changes); assert_eq!(st.paths, before); } + +// Add Anchor owns one drag while Space temporarily translates the new anchor and its handles. Letting Space go +// resumes pulling the handles from that translated anchor; the canvas never takes this owned drag to pan. +#[trial] +fn space_moves_the_pulled_anchor_then_release_resumes_its_handles() { + let space_key = |pressed| egui::Event::Key { + key: egui::Key::Space, + physical_key: Some(egui::Key::Space), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + let close = |a: Vec2, b: Vec2| (a - b).hypot() < 1e-6; + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + }); + let at = h.screen(p(110.0, 60.0)); + let pulled_at = at + vec2(0.0, 60.0); + h.press_at(at); + h.move_to(at + vec2(0.0, 30.0)); + h.move_to(pulled_at); + let (pulled, view) = { + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + let knot = st.paths[0].subpaths[0].knots[1]; + assert!(knot.anchor.distance(p(110.0, 60.0)) < 1e-3); + assert!(close(knot.out_ctrl - knot.anchor, Vec2::new(0.0, 60.0)) && knot.smooth); + (knot, st.view.expect("the canvas showed")) + }; + + h.fixture.frame(vec![space_key(true)]); + { + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots[1], pulled, "Space down alone must not jump the anchor or handles"); + } + let moved_at = pulled_at + vec2(30.0, 20.0); + h.move_to(pulled_at + vec2(15.0, 10.0)); + h.move_to(moved_at); + let moved = { + let st = h.state.borrow(); + let knot = st.paths[0].subpaths[0].knots[1]; + let by = Vec2::new(30.0, 20.0); + assert!(close(knot.anchor - pulled.anchor, by), "the held key moves the new anchor with the pointer: {knot:?}"); + assert!( + close(knot.out_ctrl - pulled.out_ctrl, by) && close(knot.in_ctrl - pulled.in_ctrl, by), + "both handles travel with the anchor: {knot:?}" + ); + assert!(knot.smooth); + assert_eq!(st.view.expect("the canvas showed").center, view.center, "an overlay-owned drag must not turn into a pan"); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5, "Space adds no second knot"); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert!(!st.seen.contains(&Seen::Commit) && !st.seen.contains(&Seen::Cancel)); + knot + }; + + h.fixture.frame(vec![space_key(false)]); + assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "Space up alone preserves the current geometry"); + let end = moved_at + vec2(20.0, 10.0); + h.move_to(moved_at + vec2(10.0, 5.0)); + h.move_to(end); + { + let st = h.state.borrow(); + let knot = st.paths[0].subpaths[0].knots[1]; + assert!(knot.anchor.distance(moved.anchor) < 1e-6, "released Space leaves the translated anchor in place"); + assert!(knot.out_ctrl.distance(view.to_doc(end)) < 1e-6, "the handle follows the pointer again"); + assert!(close(knot.in_ctrl - knot.anchor, -(knot.out_ctrl - knot.anchor)) && knot.smooth); + assert!(!close(knot.out_ctrl - knot.anchor, moved.out_ctrl - moved.anchor), "pulling resumes rather than freezing the handles"); + assert_eq!(st.view.expect("the canvas showed").center, view.center); + } + h.release_at(end); + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1); + assert_eq!((st.seen.first(), st.seen.last()), (Some(&Seen::Begin), Some(&Seen::Commit))); + assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set)); + assert!(st.inserts.is_empty(), "this drag is not an Insert-key report"); + drop(st); + + space_before_the_first_movement_translates_from_the_press(space_key); + space_release_preserves_raw_geometry_until_constraints_change(space_key); + space_release_applies_only_an_alt_modifier_still_held(space_key); +} + +fn space_before_the_first_movement_translates_from_the_press(space_key: fn(bool) -> egui::Event) { + // Space after the press but before the first movement translates from the press, not from a first pulled handle. + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + }); + let at = h.screen(p(110.0, 60.0)); + let to = at + vec2(30.0, 20.0); + h.press_at(at); + h.fixture.frame(vec![space_key(true)]); + h.move_to(to); + let translated = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(translated.anchor.distance(p(140.0, 80.0)) < 1e-3, "the first Space move includes all travel from the press: {translated:?}"); + assert!(near(translated.in_ctrl, translated.anchor) && near(translated.out_ctrl, translated.anchor)); + h.fixture.frame(vec![space_key(false)]).frame(Vec::new()); + assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], translated); + let end = to + vec2(20.0, 10.0); + h.move_to(end); + let resumed = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(near(resumed.anchor, translated.anchor) && resumed.out_ctrl.distance(h.state.borrow().view.unwrap().to_doc(end)) < 1e-6); + h.release_at(end); + assert_eq!(h.state.borrow().seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert_eq!(h.state.borrow().seen.iter().filter(|s| **s == Seen::Commit).count(), 1); +} + +fn space_release_preserves_raw_geometry_until_constraints_change(space_key: fn(bool) -> egui::Event) { + // A real canvas Snap would pull x=160 to the guide at x=165. Space keeps raw translation; release alone must + // not apply that snap, including later stationary passes. Moving or changing Shift/Alt still reads constraints. + let mut targets = SnapTargets::new(); + targets.add(SnapTarget::new(craft_behavior::Axis::Y, 165.0, SnapKind::Guide)); + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + st.snap = Some(Snap::new(std::sync::Arc::new(targets), SnapOptions::default())); + }); + let at = h.screen(p(110.0, 60.0)); + let pulled_at = at + vec2(20.0, 60.0); + h.press_at(at); + h.move_to(at + vec2(10.0, 30.0)); + h.move_to(pulled_at); + let pulled = h.state.borrow().paths[0].subpaths[0].knots[1]; + h.fixture.frame(vec![space_key(true)]); + let moved_at = pulled_at + vec2(30.0, 20.0); + h.move_to(moved_at); + let moved = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(near(moved.anchor, pulled.anchor + Vec2::new(30.0, 20.0))); + assert!(moved.out_ctrl.distance(p(160.0, 140.0)) < 1e-3 && near(moved.in_ctrl, pulled.in_ctrl + Vec2::new(30.0, 20.0))); + h.fixture.frame(vec![space_key(false)]).frame(Vec::new()).frame(Vec::new()); + h.move_to(moved_at); + assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "no delayed stationary snap after Space release"); + // Modifier-only frames travel through the real input/press route: no synthetic PathEdit calls. + h.fixture.hold(egui::Modifiers::SHIFT).frame(Vec::new()); + let locked = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!( + near(locked.anchor, moved.anchor) && locked.out_ctrl.distance(p(140.0, 140.0)) < 1e-3, + "stationary Shift still locks the handle: {locked:?}" + ); + h.fixture.hold(egui::Modifiers::NONE).frame(Vec::new()); + let snapped = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(snapped.out_ctrl.distance(p(165.0, 140.0)) < 1e-3, "releasing Shift reevaluates the actual enabled guide snap: {snapped:?}"); + h.fixture.hold(egui::Modifiers::ALT).frame(Vec::new()); + let alone = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(near(alone.in_ctrl, snapped.in_ctrl) && !alone.smooth, "stationary Alt still breaks the handle pair: {alone:?}"); + let end = moved_at + vec2(20.0, 10.0); + h.move_to(end); + let resumed = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(near(resumed.anchor, moved.anchor) && resumed.out_ctrl.distance(p(180.0, 150.0)) < 1e-3 && near(resumed.in_ctrl, alone.in_ctrl)); + h.fixture.hold(egui::Modifiers::NONE); + h.release_at(end); + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1); + assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set)); +} + +fn space_release_applies_only_an_alt_modifier_still_held(space_key: fn(bool) -> egui::Event) { + // Alt held at Space-up breaks the pair, but an Alt tap released entirely during Space must not latch. + for keep_alt in [true, false] { + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + }); + let at = h.screen(p(110.0, 60.0)); + let pulled_at = at + vec2(0.0, 60.0); + h.press_at(at); + h.move_to(at + vec2(0.0, 30.0)); + h.move_to(pulled_at); + h.fixture.frame(vec![space_key(true)]); + let moved_at = pulled_at + vec2(30.0, 20.0); + h.move_to(moved_at); + let moved = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(moved.smooth, "the translated pair starts smooth"); + h.fixture.hold(egui::Modifiers::ALT).frame(Vec::new()); + assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "Space keeps translation priority over Alt"); + if !keep_alt { + h.fixture.hold(egui::Modifiers::NONE).frame(Vec::new()); + } + let modifiers = if keep_alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE }; + let space_up = egui::Event::Key { key: egui::Key::Space, physical_key: Some(egui::Key::Space), pressed: false, repeat: false, modifiers }; + h.fixture.frame(vec![space_up]).frame(Vec::new()); + let released = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert_eq!((released.anchor, released.in_ctrl, released.out_ctrl), (moved.anchor, moved.in_ctrl, moved.out_ctrl)); + assert_eq!(released.smooth, !keep_alt, "only Alt still held at Space-up breaks the pair"); + h.release_at(moved_at); + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots[1], released, "mouse-up without travel commits the same geometry and smooth state"); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1); + assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set)); + } +} + +// Without an overlay-owned press, the same held key still gives the canvas its ordinary hand drag. +#[trial] +fn space_still_pans_when_add_anchor_has_no_drag() { + let space_key = |pressed| egui::Event::Key { + key: egui::Key::Space, + physical_key: Some(egui::Key::Space), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + }); + let (before, paths, selection) = { + let st = h.state.borrow(); + (st.view.expect("the canvas showed"), st.paths.clone(), st.selection.clone()) + }; + // This empty corner is clear of both paths. Drag toward the document interior, away from the origin clamp. + let at = before.rect.right_bottom() - vec2(24.0, 24.0); + h.move_to(at); + h.fixture.frame(vec![space_key(true)]); + h.drag(at, vec2(-60.0, -40.0)); + h.fixture.frame(vec![space_key(false)]).settle(); + let st = h.state.borrow(); + let after = st.view.expect("the canvas showed"); + assert!( + after.center.x > before.center.x && after.center.y > before.center.y && (after.center - before.center).hypot() > 1.0, + "ordinary Space still pans: {:?} -> {:?}", + before.center, + after.center + ); + assert_eq!(st.paths, paths, "panning does not edit the paths"); + assert_eq!(st.selection, selection); + assert!(st.changes.is_empty() && st.inserts.is_empty() && st.deletes.is_empty()); + assert!(!st.seen.contains(&Seen::Begin) && !st.seen.contains(&Seen::Commit)); +} + +// The translated public edit mirrors around the translated anchor and refuses nonfinite resulting geometry +// without partially inserting a knot. The original zero-translation constructor remains covered above. +#[trial] +fn a_translated_pull_mirrors_around_its_anchor_and_refuses_nonfinite_geometry() { + let straight = || ops_path(EditSubpath::new(vec![Knot::corner(p(0.0, 0.0)), Knot::corner(p(100.0, 0.0))], false)); + let mut path = straight(); + let by = Vec2::new(12.0, 7.0); + let out = p(80.0, 40.0); + assert!(PathEdit::pull_anchor_moved(7, kr(0), 0.5, by, out, None).apply(&mut path)); + let knot = path.subpaths[0].knots[1]; + assert!(near(knot.anchor, p(50.0, 0.0) + by) && near(knot.out_ctrl, out) && knot.smooth); + assert!((knot.in_ctrl - knot.anchor + (knot.out_ctrl - knot.anchor)).hypot() < 1e-6, "the mirror is about the moved anchor: {knot:?}"); + + let huge = f64::MAX * 0.75; + let far_x = f64::MAX * 0.25; + let far = ops_path(EditSubpath::new(vec![Knot::corner(p(far_x, 0.0)), Knot::corner(p(far_x, 100.0))], false)); + let at = far.subpaths[0].segment(0).unwrap().eval(0.5); + assert!(at.x.is_finite() && at.y.is_finite(), "the input curve is finite before translation"); + for (why, mut path, by, out) in [ + ("NaN offset", straight(), Vec2::new(f64::NAN, 0.0), p(50.0, 30.0)), + ("infinite offset", straight(), Vec2::new(0.0, f64::INFINITY), p(50.0, 30.0)), + ("overflowing anchor", far, Vec2::new(f64::MAX, 0.0), p(0.0, 0.0)), + ("overflowing mirrored handle", straight(), Vec2::new(huge, 0.0), p(-huge, 0.0)), + ] { + let before = path.clone(); + assert!(!PathEdit::pull_anchor_moved(7, kr(0), 0.5, by, out, None).apply(&mut path), "{why}"); + assert_eq!(path, before, "{why}: a refused edit changes nothing"); + } +} diff --git a/crates/draw/tests/it/paint_bar.rs b/crates/draw/tests/it/paint_bar.rs index 1ec55b56c5..39cb008986 100644 --- a/crates/draw/tests/it/paint_bar.rs +++ b/crates/draw/tests/it/paint_bar.rs @@ -1,5 +1,5 @@ //! `PaintBar`: which members each tool disables, the smoothing options, the gestures, the combinations list, what the -//! load swatch shows and a click on its menu. +//! load swatch shows, a click on its menu and the percents each field holds. use std::cell::RefCell; use std::rc::Rc; @@ -13,6 +13,7 @@ use craft_ui::contract::{Entry, ShowContainer as _}; use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Fixture, Room, trial}; +use craft_ui::text::RangeAlert; use egui::{Color32, ColorImage, Key, Modifiers, Pos2, Shape, TextureId}; struct Host { @@ -21,16 +22,18 @@ struct Host { edits: Vec>>, /// How many passes reported Clean Brush. cleans: u32, + /// The range alerts the passes reported. + alerts: Vec, } fn harness(tool: PaintTool, eraser: EraserMode, prepare: impl FnOnce(&mut PaintValues)) -> (Fixture, Rc>) { let mut values = PaintValues::new(0u32); prepare(&mut values); - let host = Rc::new(RefCell::new(Host { values, eraser, edits: Vec::new(), cleans: 0 })); + let host = Rc::new(RefCell::new(Host { values, eraser, edits: Vec::new(), cleans: 0, alerts: Vec::new() })); let shown = Rc::clone(&host); let mut fixture = Fixture::new(move |ui| { let mut host = shown.borrow_mut(); - let Host { values, eraser, edits, cleans } = &mut *host; + let Host { values, eraser, edits, cleans, alerts } = &mut *host; let modes = [Entry::new(0u32, "Normal"), Entry::new(1u32, "Multiply")]; Bar::new("Options", BarKind::Options).show(ui, |ui, _| { let mut bar = PaintBar::new(tool, &mut *values).modes(&modes); @@ -40,6 +43,7 @@ fn harness(tool: PaintTool, eraser: EraserMode, prepare: impl FnOnce(&mut PaintV let out = bar.show(ui); edits.extend(out.edits); *cleans += u32::from(out.mixer_clean); + alerts.extend(out.out_of_range); }); }); // The options bar spans an application window; its members still run past it, and the bar scrolls. @@ -188,3 +192,46 @@ fn the_load_swatch_shows_each_mixer_load() { assert_eq!(load_swatch(&mut fixture), (value, pictures), "{load:?}"); } } + +fn type_into(fixture: &mut Fixture, label: &str, text: &str) { + let field = fixture.by_label(label).unwrap_or_else(|| panic!("the bar shows {label}")); + fixture.click(&field); + fixture.key(Key::A, Modifiers::COMMAND); + fixture.type_text(text); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); +} + +/// Opacity and Flow hold 1 to 100 % on every tool that shows them (photocraft#16809): a typed 0 or -5 keeps 1 % and +/// 150 keeps 100 %, each reported once with a range that starts at 1 %. Smoothing still takes 0 with no alert. +#[trial] +fn opacity_and_flow_hold_one_to_a_hundred_percent_and_smoothing_still_takes_zero() { + let fields = [ + (PaintTool::Brush, "Opacity"), + (PaintTool::Brush, "Flow"), + (PaintTool::Eraser, "Opacity"), + (PaintTool::Eraser, "Flow"), + (PaintTool::Pencil, "Opacity"), + ]; + for (tool, label) in fields { + for (typed, kept) in [("0", 0.01), ("-5", 0.01), ("150", 1.0)] { + let (mut fixture, host) = harness(tool, EraserMode::Brush, |v| { + v.opacity = 0.5; + v.flow = 0.5; + }); + type_into(&mut fixture, label, typed); + let host = host.borrow(); + let value = if label == "Opacity" { host.values.opacity } else { host.values.flow }; + assert_eq!(value, kept, "{tool:?} {label}: {typed} keeps {kept}"); + assert_eq!(host.alerts.len(), 1, "{tool:?} {label}: {typed} is reported once: {:?}", host.alerts); + assert_eq!(host.alerts[0].range, 1.0..=100.0, "{tool:?} {label}: the alert names 1 to 100 %"); + } + } + + let (mut fixture, host) = harness(PaintTool::Brush, EraserMode::Brush, |v| v.smoothing.amount = 0.5); + page_to_end(&mut fixture); + type_into(&mut fixture, "Smoothing", "0"); + let host = host.borrow(); + assert_eq!(host.values.smoothing.amount, 0.0, "Smoothing takes 0"); + assert!(host.alerts.is_empty(), "and reports nothing: {:?}", host.alerts); +} diff --git a/crates/draw/tests/it/shape_cells.rs b/crates/draw/tests/it/shape_cells.rs index 5f58967853..e29ad711a4 100644 --- a/crates/draw/tests/it/shape_cells.rs +++ b/crates/draw/tests/it/shape_cells.rs @@ -285,3 +285,63 @@ fn a_fixed_size_typed_past_its_range_keeps_the_end_and_reports_it_once_and_an_em assert_eq!(host.borrow().value.fixed, (None, Some(50.0)), "an emptied field is empty"); assert_eq!(host.borrow().alerts.len(), 1, "an emptied field reports nothing"); } + +struct BarHost { + settings: ShapeToolSettings, + look: ShapeAppearance, + alerts: Vec, +} + +/// The Triangle tool's bar shows a Radius of its own (storytold/photocraft#13355): it starts from +/// `triangle_corner_radius`, not the Rectangle's radius, reports a typed value as `CornerRadius`, and keeps a value +/// past 0–150,000 px at the end with one range alert. The Ellipse's bar has no Radius. +#[trial] +#[allow(clippy::field_reassign_with_default, reason = "ShapeToolSettings is non_exhaustive: no struct literal outside its crate")] +fn the_triangle_bar_shows_its_own_radius() { + let kind = Rc::new(RefCell::new(ShapeKind::Triangle)); + let mut settings = ShapeToolSettings::default(); + settings.corner_radius = 7.0; + settings.triangle_corner_radius = 15.0; + let host = Rc::new(RefCell::new(BarHost { settings, look: ShapeAppearance::new(Paint::None, Paint::None, 0.0), alerts: Vec::new() })); + let (shown, shown_kind) = (Rc::clone(&host), Rc::clone(&kind)); + let mut fixture = Fixture::new(move |ui| { + let mut held = shown.borrow_mut(); + let BarHost { settings, look, alerts } = &mut *held; + let kind = *shown_kind.borrow(); + let out = Bar::new("Shape options", BarKind::Options).show(ui, |ui, _| ShapeBar::new(kind, settings, look, 72.0).show(ui)).inner; + let Some(out) = out else { return }; + if let Some(ShapeChange::CornerRadius(radius)) = out.events.iter().rev().find_map(|event| event.value()) { + settings.triangle_corner_radius = *radius; + } + alerts.extend(out.out_of_range); + }); + fixture.settle(); + let field = fixture.by_label("Radius").expect("the Triangle's Radius"); + let value = fixture.tree().value_of(field.node).map(str::to_owned); + assert!(value.as_deref().is_some_and(|v| v.starts_with("15")), "the Triangle's own radius, not the Rectangle's 7: {value:?}"); + type_into(&mut fixture, "Radius", "12"); + assert_eq!(host.borrow().settings.triangle_corner_radius, 12.0); + assert_eq!(host.borrow().settings.corner_radius, 7.0, "the Rectangle's radius is not touched"); + assert!(host.borrow().alerts.is_empty(), "12 is in range"); + type_into(&mut fixture, "Radius", "200000"); + assert_eq!(host.borrow().settings.triangle_corner_radius, 150_000.0, "a radius past the range keeps its end"); + assert_eq!(host.borrow().alerts.len(), 1, "the clamp is reported once"); + + *kind.borrow_mut() = ShapeKind::Ellipse; + fixture.settle(); + assert!(fixture.by_label("Radius").is_none(), "an Ellipse has no Radius"); +} + +/// The tool settings keep the Triangle's radius apart and read it from settings saved before it existed as 0. +#[trial] +fn the_triangle_radius_is_saved_with_the_tool_settings() { + let mut settings = ShapeToolSettings::default(); + assert_eq!(settings.triangle_corner_radius, 0.0, "sharp corners by default"); + settings.triangle_corner_radius = 25.0; + let saved = serde_json::to_value(settings).expect("settings serialize"); + assert_eq!(saved["triangleCornerRadius"], serde_json::json!(25.0)); + let back: ShapeToolSettings = serde_json::from_value(saved).expect("settings read back"); + assert_eq!(back.triangle_corner_radius, 25.0); + let old: ShapeToolSettings = serde_json::from_value(serde_json::json!({"cornerRadius": 4.0})).expect("older settings read"); + assert_eq!((old.corner_radius, old.triangle_corner_radius), (4.0, 0.0)); +} diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index 3eb3fd5027..53a366425e 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -1,6 +1,6 @@ //! The Shape tools and the Create Shape dialog. The view maps one document unit to one screen point. -use craft_behavior::kurbo::{Point, Rect, Vec2}; +use craft_behavior::kurbo::{ParamCurve as _, Point, Rect, Vec2}; use craft_behavior::{CanvasView, EditEvent}; use craft_draw::geometry::shape::ShapeGeometry; use craft_draw::ui::shape::VectorMode; @@ -373,3 +373,123 @@ fn create_shape_alerts_once_for_a_size_typed_past_its_range() { assert!(take(&host).is_none(), "{kind:?}: a width in range raises no alert"); } } + +/// The ends of each piece of `shape`'s outline, in order: for a rounded triangle, where each arc meets an edge. +fn anchors(shape: &ShapeGeometry) -> Vec { + shape.to_path(0.1).elements().iter().filter_map(|el| el.end_point()).collect() +} + +fn near(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-3 +} + +/// A triangle's corner radius rounds each corner with an arc tangent to both edges (storytold/photocraft#13355): radius +/// 20 in the box 400,300 to 600,400 meets the edges at the six points PhotoCraft's engine draws, and the arc at the +/// right-angled apex has its middle 20 px from its centre. +#[trial] +fn a_triangle_corner_radius_rounds_each_corner_tangent_to_its_edges() { + let shape = ShapeGeometry::Triangle { rect: Rect::new(400.0, 300.0, 600.0, 400.0), corner_radius: 20.0 }; + let want = [(485.858, 314.142), (514.142, 314.142), (565.858, 365.858), (551.716, 400.0), (448.284, 400.0), (434.142, 365.858)]; + let got = anchors(&shape); + assert_eq!(got.len(), want.len(), "two points per rounded corner: {got:?}"); + for (g, w) in got.iter().zip(want) { + assert!(near(*g, Point::new(w.0, w.1)), "{got:?}"); + } + let apex = shape.to_path(0.1).segments().next().expect("the apex arc"); + let middle = apex.eval(0.5); + // The apex's edges meet at 90°: the arc's centre lies 20·√2 below the apex, its middle 20 px above that. + let centre = Point::new(500.0, 300.0 + 20.0 * 2f64.sqrt()); + assert!(((middle - centre).hypot() - 20.0).abs() < 0.01, "the arc is circular: its middle is {middle:?}"); + assert_eq!(shape.bounds(), Rect::new(400.0, 300.0, 600.0, 400.0), "the bounds stay the box"); +} + +/// A radius larger than the triangle allows is capped by the shape: each arc ends at most halfway along an edge, the +/// outline stays inside the box, and no number is lost. Radius 0 keeps the sharp corners. +#[trial] +fn a_triangle_radius_past_what_the_shape_holds_is_capped_and_zero_is_sharp() { + let rect = Rect::new(0.0, 0.0, 200.0, 100.0); + for radius in [1.0e6, f64::INFINITY, f64::NAN, -5.0, 0.0] { + let got = anchors(&ShapeGeometry::Triangle { rect, corner_radius: radius }); + assert!(got.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{radius}: {got:?}"); + assert!(got.iter().all(|p| rect.inflate(1e-9, 1e-9).contains(*p)), "{radius}: the outline stays in the box: {got:?}"); + if radius.is_finite() && radius > 0.0 { + assert_eq!(got.len(), 6, "{radius}: still two points per corner"); + // The slanted edges (about 141 px) are shorter than the 200 px base: the arcs at their two ends meet + // halfway along each of them. + for middle in [Point::new(50.0, 50.0), Point::new(150.0, 50.0)] { + assert_eq!(got.iter().filter(|p| near(**p, middle)).count(), 2, "{radius}: capped at half a slanted edge: {got:?}"); + } + } else { + assert_eq!(got, vec![Point::new(100.0, 0.0), Point::new(200.0, 100.0), Point::new(0.0, 100.0)], "{radius}: sharp corners"); + } + } +} + +/// A Triangle drag takes the Triangle's own corner radius from the tool settings, not the Rectangle's, and a +/// Rectangle drag keeps the Rectangle's. +#[trial] +#[allow(clippy::field_reassign_with_default, reason = "ShapeToolSettings is non_exhaustive: no struct literal outside its crate")] +fn a_triangle_drag_takes_the_triangle_radius_from_the_settings() { + let mut settings = craft_draw::ui::shape::ShapeToolSettings::default(); + settings.corner_radius = 7.0; + settings.triangle_corner_radius = 20.0; + let mut shapes = Shapes::new(settings.drag_options(ShapeKind::Triangle)); + shapes.drag(PRESS, PRESS + Vec2::new(60.0, 40.0), Modifiers::NONE); + match shapes.committed() { + Some(ShapeGeometry::Triangle { corner_radius, .. }) => assert_eq!(corner_radius, 20.0), + other => panic!("a triangle: {other:?}"), + } + let mut shapes = Shapes::new(settings.drag_options(ShapeKind::Rectangle)); + shapes.drag(PRESS, PRESS + Vec2::new(60.0, 40.0), Modifiers::NONE); + match shapes.committed() { + Some(ShapeGeometry::Rect { radii, .. }) => assert_eq!(radii, [7.0; 4], "the Rectangle keeps its own radius"), + other => panic!("a rectangle: {other:?}"), + } +} + +/// Create Triangle starts from the tool's radius, shows it in one Radius field and answers it on OK; automation sets +/// it as `cornerRadius`, kept to 0–150,000 px, and the field is inactive for another kind. +#[trial] +fn create_triangle_takes_one_corner_radius() { + let ctx = egui::Context::default(); + let mut host = DialogHost::new(); + let options = CreateShapeOptions::initial(ShapeKind::Triangle, Point::new(10.0, 20.0)).tool(15.0, 5, 1.0).recalled(); + let id = host.open(CreateShapeDialog::new(options)); + assert_eq!(fields(&host, id)["cornerRadius"], json!(15.0), "the dialog starts from the tool's radius"); + let shape = confirm(&mut host, &ctx).expect("OK answers the triangle"); + assert_eq!(shape.geometry, ShapeGeometry::Triangle { rect: Rect::new(10.0, 20.0, 110.0, 120.0), corner_radius: 15.0 }); + + let id = open_create(&mut host, ShapeKind::Triangle); + assert_eq!(host.set_json_field(&ctx, id, "cornerRadius", json!(200000)), Ok(())); + assert_eq!(fields(&host, id)["cornerRadius"], json!(150000.0), "a radius past the range keeps its end"); + assert!(host.set_json_field(&ctx, id, "cornerRadius", json!("abc")).is_err(), "text that is not a number is refused"); + assert_eq!(host.set_json_field(&ctx, id, "cornerRadius", json!(8)), Ok(())); + match confirm(&mut host, &ctx).map(|shape| shape.geometry) { + Some(ShapeGeometry::Triangle { corner_radius, .. }) => assert_eq!(corner_radius, 8.0), + other => panic!("a triangle: {other:?}"), + } + + let id = open_create(&mut host, ShapeKind::Rectangle); + assert!(host.set_json_field(&ctx, id, "cornerRadius", json!(8)).is_err(), "a rectangle has no single corner radius"); + assert!(host.cancel::(&ctx)); + + // The field itself: one Radius field for the triangle, typed values taken. + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(egui::Vec2::new(1200.0, 900.0)); + let options = CreateShapeOptions::initial(ShapeKind::Triangle, Point::new(10.0, 20.0)).tool(15.0, 5, 1.0).recalled(); + host.borrow_mut().open(CreateShapeDialog::new(options)); + fixture.settle(); + let names: Vec = + fixture.by_role(Role::SPIN_BUTTON).into_iter().filter_map(|field| fixture.tree().name_of(field.node).map(str::to_owned)).collect(); + assert_eq!(names.iter().filter(|name| name.as_str() == "Radius").count(), 1, "one Radius field: {names:?}"); + assert!(!names.iter().any(|name| name == "Top Left" || name == "Sides"), "no rectangle radii or sides: {names:?}"); + let radius = + fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|field| fixture.tree().name_of(field.node) == Some("Radius")).expect("the Radius field"); + fixture.click(&radius).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text("30"); + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let radii = host.borrow().get::().map(|dialog| dialog.options().radii); + assert_eq!(radii, Some([30.0; 4]), "the typed radius is the triangle's"); +} diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 90c8f0568e..9448dbb9f3 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -1678,6 +1678,43 @@ fn a_host_handle_side_sets_the_drawn_handle_square() { assert!(large > small, "a larger side draws a larger square: {large} against {small}"); } +/// A host handle side that is zero, negative or not finite draws the theme's handle and keeps the theme's reach. +#[trial] +fn an_unusable_host_handle_side_uses_the_themes() { + let corner_side = |side: Option| { + let mut h = harness(BoxState::from_rect(RECT), |config| config.handle_side = side); + let corner = h.screen(Point::new(RECT.x1, RECT.y1)); + h.fixture + .frame_shapes() + .iter() + .filter_map(|shape| match shape { + Shape::Rect(square) if (square.rect.center() - corner).length() < 0.5 => Some(square.rect.width()), + _ => None, + }) + .collect::>() + }; + let theme = corner_side(None); + assert!(!theme.is_empty(), "the theme's corner handle is drawn"); + // 3 points in from the bottom right corner on both axes: inside the theme's handle reach. + let near = Point::new(RECT.x1 - 3.0, RECT.y1 - 3.0); + for side in [0.0, -6.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + assert_eq!(corner_side(Some(side)), theme, "a side of {side} draws the theme's corner handle"); + let mut h = harness(BoxState::from_rect(RECT), |config| { + config.rules = free_rules(); + config.handle_side = Some(side); + }); + hover(&mut h, near); + assert_eq!(h.host.borrow().hovered, Some(BoxPart::Corner(2)), "a side of {side} keeps the theme's reach"); + // Far outside the theme's reach: an infinite side must not widen the reach to the whole canvas. + let mut far = harness(BoxState::from_rect(RECT), |config| { + config.rules = free_rules(); + config.handle_side = Some(side); + }); + hover(&mut far, Point::new(RECT.x1 + 60.0, RECT.y1 + 60.0)); + assert_ne!(far.host.borrow().hovered, Some(BoxPart::Corner(2)), "a side of {side} does not widen the reach"); + } +} + /// A large host handle takes a press anywhere on its square, also past the theme's reach, and the press drags it. #[trial] fn a_press_just_inside_a_large_handles_edge_grabs_it() { diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index 91321e351f..6e3f14e6f7 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -1773,6 +1773,8 @@ mod chartex_tests { assert!(stats[0].iter().all(Option::is_some)); // Enough series to cap the groups so the result stays within MAX_BOX_CELLS. let series = MAX_BOX_CELLS / n * 2; + // Keep 100 values beyond the group cap without cloning the unused tail. + c.series[0].values.truncate(MAX_BOX_CELLS / series + 100); c.series = vec![c.series[0].clone(); series]; let (groups, stats) = c.box_groups(); assert_eq!(groups.len(), MAX_BOX_CELLS / series); diff --git a/crates/exr/src/seek_tests.rs b/crates/exr/src/seek_tests.rs index 2bb2ddb071..f262de09d5 100644 --- a/crates/exr/src/seek_tests.rs +++ b/crates/exr/src/seek_tests.rs @@ -1456,7 +1456,8 @@ fn groups_must_be_slots_of_one_part_each_in_one_group() { #[test] fn the_estimate_covers_what_the_read_does() { // A flat colour in ZIP16 (decodes to far more than it reads), lines of a ramp, and tiles. - let (w, h) = (256usize, 160usize); + // 136 rows retain ZIP16's eight-row final block while reducing the 160-row upstream fixture. + let (w, h) = (256usize, 136usize); let list = vec![AnyChannel::new("R", FlatSamples::F32(vec![0.25; w * h])), AnyChannel::new("G", FlatSamples::F32(vec![0.5; w * h]))]; let encoding = Encoding { compression: Compression::ZIP16, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; let flat = file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)); diff --git a/crates/fig/src/rest/tests.rs b/crates/fig/src/rest/tests.rs index e277814a5b..a8a207803f 100644 --- a/crates/fig/src/rest/tests.rs +++ b/crates/fig/src/rest/tests.rs @@ -748,9 +748,10 @@ fn nested(instances: bool) -> Kv<'static> { let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])]; let levels = 270; if instances { + // Index every main, but map only a long and a short chain plus the top instance. for i in 0..levels { let id = 10 + 2 * i; - nodes.push(node(id, Some((1, "!")), "SYMBOL", "M", vec![("size", xy(1.0, 1.0))])); + nodes.push(node(id, (i == 0 || i + 2 == levels).then_some((1, "!")), "SYMBOL", "M", vec![("size", xy(1.0, 1.0))])); if i + 1 < levels { nodes.push(node( id + 1, diff --git a/crates/flow/README.md b/crates/flow/README.md index bb0a21de17..858ee31503 100644 --- a/crates/flow/README.md +++ b/crates/flow/README.md @@ -29,3 +29,12 @@ report of what an importer leaves out to stay within a limit (`Dropped`, `begin_ WordCraft's `crates/formats/src/model` (at `07f97737`), moved as it is onto craft-wordmodel. Image decoding for re-encoding (`decode_bounded`) stays with the RTF writer that needs it. + +## Grouped drawing hyperlinks + +Pictures, shapes and groups can retain their own target in `Img::link` or the corresponding +`Inline::Shape`/`Inline::Group` field. Each `Member::link` and `craft_wordmodel::para::GroupChild::link` +keeps that member's separate target through the document/flow conversions. Add `link: None` to +older Rust struct/variant literals that do not carry a target. Older JSON group children without +`link` deserialize as unlinked, and unlinked children omit that key when serialized. This does +not promise compatibility for every binary serde format or hyperlink activation in every exporter. diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 4911e2f2b1..4162d89d04 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -1,12 +1,35 @@ use super::types::{ - BoxLook, Cell, FBlock, FComment, FTable, Flow, FlowOpts, Fmt, FmtChange, Img, Inline, Kind, ListInfo, MAX_DEPTH, MAX_GROUP_DEPTH, Member, Meta, - Para, RevMark, Spacing, + BoxLook, Cell, Dropped, FBlock, FComment, FTable, Flow, FlowOpts, Fmt, FmtChange, Img, Inline, Kind, ListInfo, MAX_DEPTH, MAX_GROUP_DEPTH, + MAX_LINK, MAX_RUN_STRINGS, Member, Meta, Para, RevMark, Spacing, dropped, }; use super::{ Arc, Block, Blocks, CharProps, Document, InlineObject, NumFormat, OBJ, PAGE_BREAK, ParaProps, Paragraph, StyleKind, Table, TextColor, Underline, VMerge, VertAlign, }; +/// One conversion's retained drawing targets, across roots, members and nested stories. +#[derive(Default)] +struct DrawingLinks { + bytes: usize, +} + +impl DrawingLinks { + fn keep(&mut self, target: Option<&str>) -> Option { + let target = target?; + if target.len() > MAX_LINK { + let _ = super::kept_link(target); + return None; + } + let Some(bytes) = self.bytes.checked_add(target.len()).filter(|&n| n <= MAX_RUN_STRINGS) else { + dropped(Dropped::RunStrings); + return None; + }; + let target = super::kept_link(target)?; + self.bytes = bytes; + Some(target.to_string()) + } +} + pub(super) fn uses_kind(blocks: &[FBlock], k: Kind, depth: usize) -> bool { depth <= MAX_DEPTH && blocks.iter().any(|b| match b { @@ -281,12 +304,12 @@ fn media_ext(key: &str, data: &[u8]) -> String { /// The flow inlines for a note reference, comment mark or field `o` of `doc`, when `opts` asks /// for them; `None` for other objects. `f` is the formatting of the run `o` is in. -fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Option> { +fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts, links: &mut DrawingLinks) -> Option> { Some(match o { InlineObject::NoteRef { kind, id, custom } if opts.notes => { // The note's content without its own mark (a note holds no notes). let story = doc.parts.get(id).map(|part| &part.blocks); - let mut blocks = story.map(|b| flow_blocks(doc, b, 0, FlowOpts { notes: false, ..opts })).unwrap_or_default(); + let mut blocks = story.map(|b| flow_blocks(doc, b, 0, FlowOpts { notes: false, ..opts }, links)).unwrap_or_default(); // The space after the mark is the mark's (see `to_doc`'s `note`); a tab or more // spaces there are the note's own. if let Some(FBlock::Para(first)) = blocks.first_mut() { @@ -305,7 +328,7 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op // comment that starts the thread), which have no place of their own. InlineObject::CommentStart { id } if opts.comments => { let Some(c) = doc.comments.get(id) else { return Some(Vec::new()) }; - let mut out = vec![Inline::Comment { id: *id, comment: Box::new(flow_comment(doc, c, None, opts)) }]; + let mut out = vec![Inline::Comment { id: *id, comment: Box::new(flow_comment(doc, c, None, opts, links)) }]; let mut thread = std::collections::BTreeSet::from([*id]); let mut k = 0; while let Some(Inline::Comment { id: at, .. }) = out.get(k) { @@ -313,7 +336,7 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op k += 1; for (rid, r) in doc.comments.iter().filter(|(_, r)| r.parent == Some(at)) { if thread.insert(*rid) { - out.push(Inline::Comment { id: *rid, comment: Box::new(flow_comment(doc, r, Some(*id), opts)) }); + out.push(Inline::Comment { id: *rid, comment: Box::new(flow_comment(doc, r, Some(*id), opts, links)) }); } } } @@ -328,7 +351,13 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op } // A text box's content, without notes, comments or boxes of its own. // A drawing shape, text box or group (pictures have their own place below). - InlineObject::Shape { .. } | InlineObject::Group { .. } if opts.boxes => vec![drawing_inline(doc, o, opts, 0, (1.0, 1.0))?], + InlineObject::Shape { .. } | InlineObject::Group { .. } if opts.boxes => { + let mut inline = drawing_inline(doc, o, opts, 0, (1.0, 1.0), links)?; + if let Inline::Shape { link, .. } | Inline::Group { link, .. } = &mut inline { + *link = links.keep(f.link.as_deref()); + } + vec![inline] + } InlineObject::FieldStart { instr, .. } if opts.fields => vec![Inline::FieldStart(instr.clone())], InlineObject::FieldEnd if opts.fields => vec![Inline::FieldEnd], // Where a bookmark ends, so it covers its text (Word's `_GoBack` is the last edit's spot). @@ -360,7 +389,7 @@ fn frame_freeform(corner: Option, w: f32, h: f32) -> craft_wordmodel::freef /// its size scaled by `scale` (a group's members are in its own coordinates). A shape or text /// box keeps its text, but not notes, comments or boxes of its own. `None` for what a flow has /// no drawing for: a freeform's paths, a picture whose data is missing. -fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize, scale: (f32, f32)) -> Option { +fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize, scale: (f32, f32), links: &mut DrawingLinks) -> Option { use craft_wordmodel::para::ShapeKind; let (sx, sy) = scale; match o { @@ -380,7 +409,7 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize }; let inner = FlowOpts { notes: false, comments: false, boxes: false, ..opts }; let part = story.and_then(|id| doc.parts.get(&id)); - let blocks = part.map(|p| flow_blocks(doc, &p.blocks, 0, inner)).unwrap_or_default(); + let blocks = part.map(|p| flow_blocks(doc, &p.blocks, 0, inner, links)).unwrap_or_default(); let look = BoxLook { fill: fill.clone().filter(|_| kind != ShapeKind::Line), line: stroke.filter(|_| stroke_width.is_finite() && *stroke_width > 0.0).map(|c| (c, stroke_width.min(12.0))), @@ -400,12 +429,13 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize }), }; let path = frame.or_else(|| freeform.clone()).filter(|_| kind == ShapeKind::Freeform); - Some(Inline::Shape { kind, w: w * sx, h: h * sy, float: kept_float(float), blocks, look, path }) + Some(Inline::Shape { kind, w: w * sx, h: h * sy, float: kept_float(float), blocks, look, path, link: None }) } InlineObject::Image { media, w, h, alt, float, ole, crop, .. } => { let data = doc.media.get(media)?; let alt = if o.is_decorative() { "" } else { alt.as_str() }; Some(Inline::Image(Img { + link: None, data: data.clone(), ext: media_ext(media, data), w: w * sx, @@ -416,7 +446,7 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize crop: if opts.paras { *crop } else { [0.0; 4] }, })) } - InlineObject::Group { w, h, float, ch_w, ch_h, children, .. } if depth < MAX_GROUP_DEPTH => { + InlineObject::Group { w, h, float, ch_w, ch_h, children, .. } if depth <= MAX_GROUP_DEPTH => { let ratio = |outer: f32, inner: f32| { let r = outer / inner; if r.is_finite() && r > 0.0 { r } else { 1.0 } @@ -425,10 +455,15 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize let members: Vec = children .iter() .filter_map(|c| { - drawing_inline(doc, &c.obj, opts, depth + 1, inner).map(|inline| Member { x: c.x * inner.0, y: c.y * inner.1, inline }) + drawing_inline(doc, &c.obj, opts, depth + 1, inner, links).map(|inline| Member { + link: links.keep(c.link.as_deref()), + x: c.x * inner.0, + y: c.y * inner.1, + inline, + }) }) .collect(); - (!members.is_empty()).then(|| Inline::Group { w: w * sx, h: h * sy, float: kept_float(float), members }) + (!members.is_empty()).then(|| Inline::Group { w: w * sx, h: h * sy, float: kept_float(float), members, link: None }) } _ => None, } @@ -441,9 +476,9 @@ fn kept_float(f: &craft_wordmodel::para::Float) -> Option, opts: FlowOpts) -> FComment { +fn flow_comment(doc: &Document, c: &craft_wordmodel::Comment, parent: Option, opts: FlowOpts, links: &mut DrawingLinks) -> FComment { let story = doc.parts.get(&c.part).map(|p| &p.blocks); - let blocks = story.map(|b| flow_blocks(doc, b, 0, FlowOpts { notes: false, comments: false, ..opts })).unwrap_or_default(); + let blocks = story.map(|b| flow_blocks(doc, b, 0, FlowOpts { notes: false, comments: false, ..opts }, links)).unwrap_or_default(); FComment { author: c.author.clone(), initials: c.initials.clone(), date: c.date.clone(), resolved: c.resolved, parent, blocks } } @@ -495,12 +530,12 @@ fn shown_text(o: &InlineObject) -> &str { } pub fn flow_paras(doc: &Document, p: &Paragraph) -> Vec { - flow_paras_in(doc, p, FlowOpts::default()) + flow_paras_in(doc, p, FlowOpts::default(), &mut DrawingLinks::default()) } /// [`flow_paras`]; `tracked` keeps tracked changes: deleted text stays, and text carries its /// insertion and deletion marks. -fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { +fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts, links: &mut DrawingLinks) -> Vec { let tracked = opts.tracked; let (kind, list) = para_kind(doc, p); let list = flow_list(doc, kind, list, p, opts); @@ -606,7 +641,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { continue; } let from = out.inlines.len(); - if let Some(items) = obj.and_then(|o| rich_inlines(doc, o, &f, opts)) { + if let Some(items) = obj.and_then(|o| rich_inlines(doc, o, &f, opts, links)) { if !buf.is_empty() { out.push_text(&std::mem::take(&mut buf), &f); } @@ -624,6 +659,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { let alt = if o.is_decorative() { "" } else { alt.as_str() }; match doc.media.get(media) { Some(data) => out.inlines.push(Inline::Image(Img { + link: links.keep(f.link.as_deref()), data: data.clone(), ext: media_ext(media, data), w: *w, @@ -794,8 +830,9 @@ fn graphic_group( line: stroke.filter(|_| stroke_width.is_finite() && *stroke_width > 0.0).map(|c| (c, stroke_width.min(12.0))), ..plain.clone() }; - let inline = Inline::Shape { kind: *kind, w: rect[2] * sx, h: rect[3] * sy, float: None, blocks: Vec::new(), look, path: None }; - Some(Member { x: rect[0] * sx, y: rect[1] * sy, inline }) + let inline = + Inline::Shape { kind: *kind, w: rect[2] * sx, h: rect[3] * sy, float: None, blocks: Vec::new(), look, path: None, link: None }; + Some(Member { link: None, x: rect[0] * sx, y: rect[1] * sy, inline }) } GraphicItem::Text { rect, text, size, color, bold, align, font, .. } if finite(rect) && !text.trim().is_empty() => { let size = if size.is_finite() { size.clamp(1.0, 400.0) } else { 11.0 }; @@ -815,6 +852,7 @@ fn graphic_group( ..Para::default() }; let inline = Inline::Shape { + link: None, kind: ShapeKind::Rectangle, w: bw, h: bh, @@ -823,11 +861,12 @@ fn graphic_group( look: plain.clone(), path: None, }; - Some(Member { x: rect[0] * sx, y, inline }) + Some(Member { link: None, x: rect[0] * sx, y, inline }) } GraphicItem::Image { rect, media } if finite(rect) => { let data = doc.media.get(media)?; let img = Img { + link: None, data: data.clone(), ext: media_ext(media, data), w: rect[2] * sx, @@ -837,7 +876,7 @@ fn graphic_group( object: None, crop: [0.0; 4], }; - Some(Member { x: rect[0] * sx, y: rect[1] * sy, inline: Inline::Image(img) }) + Some(Member { link: None, x: rect[0] * sx, y: rect[1] * sy, inline: Inline::Image(img) }) } _ => None, }) @@ -847,9 +886,9 @@ fn graphic_group( } // A group is as big as its members together (ODF 1.3 §10.3.15): an invisible rectangle the // size of the graphic keeps the room around its drawing. - let frame = Inline::Shape { kind: ShapeKind::Rectangle, w, h, float: None, blocks: Vec::new(), look: plain, path: None }; - let all = std::iter::once(Member { x: 0.0, y: 0.0, inline: frame }).chain(members).collect(); - Some(Inline::Group { w, h, float: kept_float(float), members: all }) + let frame = Inline::Shape { kind: ShapeKind::Rectangle, w, h, float: None, blocks: Vec::new(), look: plain, path: None, link: None }; + let all = std::iter::once(Member { link: None, x: 0.0, y: 0.0, inline: frame }).chain(members).collect(); + Some(Inline::Group { w, h, float: kept_float(float), members: all, link: None }) } /// The mark formatting of `out`, the last piece of `p`, when it holds no text (its height, its @@ -962,11 +1001,11 @@ type ItemText = [Option; 9]; /// 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 { +fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemText, links: &mut DrawingLinks) -> 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); + let mut paras = flow_paras_in(doc, p, opts, links); 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); @@ -995,7 +1034,7 @@ fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemTex paras } -fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> Vec { +fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts, links: &mut DrawingLinks) -> Vec { let mut out = Vec::new(); let mut skip = 0usize; let mut at: ItemText = [None; 9]; @@ -1013,7 +1052,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_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para)); + out.extend(flow_paras_at(doc, p, tracked, &mut at, links).into_iter().map(FBlock::Para)); } } let n = out.len() - from; @@ -1024,12 +1063,12 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> continue; } match &**b { - 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::Para(p) => out.extend(flow_paras_at(doc, p, tracked, &mut at, links).into_iter().map(FBlock::Para)), + Block::Table(t) if depth < MAX_DEPTH => out.push(FBlock::Table(flow_table(doc, t, depth, tracked, links))), Block::Table(t) => { for r in &t.rows { for c in &r.cells { - out.extend(flow_blocks(doc, &c.blocks, depth, tracked)); + out.extend(flow_blocks(doc, &c.blocks, depth, tracked, links)); } } } @@ -1160,7 +1199,7 @@ fn with_cell_text(doc: &Document, blocks: &Blocks, chr: &CharProps, align: Optio .collect() } -fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTable { +fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts, links: &mut DrawingLinks) -> FTable { let mut rows = Vec::new(); // Formats that keep cell formatting get the table style's and the table's borders cell by cell. let style = t.props.style.as_deref().and_then(|id| doc.styles.table_style(id)); @@ -1190,8 +1229,8 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa } } let blocks = match &styled { - Some(st) => flow_blocks(doc, &with_cell_text(doc, &c.blocks, &st.chr, st.align, &st.para), depth + 1, tracked), - None => flow_blocks(doc, &c.blocks, depth + 1, tracked), + Some(st) => flow_blocks(doc, &with_cell_text(doc, &c.blocks, &st.chr, st.align, &st.para), depth + 1, tracked, links), + None => flow_blocks(doc, &c.blocks, depth + 1, tracked, links), }; cells.push(Cell { blocks, @@ -1209,6 +1248,7 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa picture: c.props.picture.as_deref().filter(|_| tracked.paras).and_then(|p| { let data = doc.media.get(&p.media)?; let img = Img { + link: None, data: data.clone(), ext: media_ext(&p.media, data), w: p.size[0], @@ -1281,13 +1321,13 @@ pub fn from_doc_with(doc: &Document, opts: FlowOpts) -> Flow { /// `blocks` of `doc` (a header, footer or note) as flow blocks, keeping what `opts` asks for. pub fn part_flow(doc: &Document, blocks: &Blocks, opts: FlowOpts) -> Vec { - flow_blocks(doc, blocks, 0, opts) + flow_blocks(doc, blocks, 0, opts, &mut DrawingLinks::default()) } fn flow_of(doc: &Document, tracked: FlowOpts) -> Flow { let c = &doc.core; Flow { - blocks: flow_blocks(doc, &doc.body, 0, tracked), + blocks: flow_blocks(doc, &doc.body, 0, tracked, &mut DrawingLinks::default()), meta: Meta { title: c.title.clone(), author: c.creator.clone(), @@ -1362,3 +1402,57 @@ mod stacking_tests { assert!(super::kept_float(&Float::default()).is_none()); } } + +#[cfg(test)] +mod drawing_link_tests { + use super::*; + + #[test] + fn vml_hyperlinks_share_one_conversion_budget() { + let group = || Inline::Group { + w: 12.0, + h: 8.0, + float: None, + link: Some("root".into()), + members: vec![Member { + x: 0.0, + y: 0.0, + link: Some("member".into()), + inline: Inline::Shape { + kind: craft_wordmodel::para::ShapeKind::Rectangle, + w: 12.0, + h: 8.0, + float: None, + blocks: Vec::new(), + look: BoxLook::default(), + path: None, + link: None, + }, + }], + }; + let flow = Flow { + blocks: vec![ + FBlock::Para(Para { kind: Kind::Normal, inlines: vec![group()], ..Default::default() }), + FBlock::Para(Para { kind: Kind::Normal, inlines: vec![group()], ..Default::default() }), + ], + ..Default::default() + }; + let doc = crate::to_doc(&flow); + // Use the real conversion consumer near its existing limit, without a + // 64 MiB fixture. Both groups and both paragraphs share this same counter. + let mut links = DrawingLinks { bytes: MAX_RUN_STRINGS - 14 }; + let blocks = flow_blocks(&doc, &doc.body, 0, FlowOpts { boxes: true, paras: true, ..Default::default() }, &mut links); + assert_eq!(blocks.len(), 2); + let FBlock::Para(first) = &blocks[0] else { panic!() }; + let FBlock::Para(second) = &blocks[1] else { panic!() }; + let [Inline::Group { link: first_root, members: first_members, .. }] = first.inlines.as_slice() else { panic!("first group") }; + let [Inline::Group { link: second_root, members: second_members, .. }] = second.inlines.as_slice() else { panic!("second group") }; + assert_eq!(first_root.as_deref(), Some("root")); + assert_eq!(first_members.len(), 1); + assert_eq!(first_members[0].link.as_deref(), Some("member")); + assert_eq!(second_members.len(), 1); + assert!(second_members[0].link.is_none(), "later member exceeds the conversion's remaining bytes"); + assert_eq!(second_root.as_deref(), Some("root"), "a fitting root target remains independent of its member"); + assert_eq!(links.bytes, MAX_RUN_STRINGS); + } +} diff --git a/crates/flow/src/media.rs b/crates/flow/src/media.rs index 44e2a24acb..e44d372108 100644 --- a/crates/flow/src/media.rs +++ b/crates/flow/src/media.rs @@ -46,6 +46,7 @@ pub fn sized_img(data: Arc>, ext: &str, natural: Option<(f32, f32)>, w: w = 468.0; } Img { + link: None, data, ext: ext.to_string(), w: w.clamp(1.0, 1584.0), diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index 303dc022cc..dafb9944a5 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -217,6 +217,14 @@ fn para_props(p: &Para, list_num: Option) -> ParaProps { out } +fn drawing_link(inline: &Inline) -> Option<&str> { + match inline { + Inline::Image(img) => img.link.as_deref(), + Inline::Shape { link, .. } | Inline::Group { link, .. } => link.as_deref(), + _ => None, + } +} + struct Builder<'a> { doc: &'a mut Document, /// Revisions already in `doc` by (kind, author, date), so each change is added once. @@ -433,7 +441,7 @@ impl<'a> Builder<'a> { graphic: Arc::new(graphic), }) } - Inline::Shape { kind, w, h, float, blocks, look, path } => { + Inline::Shape { kind, w, h, float, blocks, look, path, .. } => { // A text box always has its story; a shape only when it holds text. let story = if *kind == craft_wordmodel::para::ShapeKind::TextBox || !blocks.is_empty() { let story = self.blocks(blocks, 1); @@ -494,14 +502,20 @@ impl<'a> Builder<'a> { }; Some(obj) } - Inline::Group { w, h, float, members } if depth < MAX_GROUP_DEPTH => { + Inline::Group { w, h, float, members, .. } if depth <= MAX_GROUP_DEPTH => { let fit = |v: f32| if v.is_finite() { v.clamp(1.0, 1584.0) } else { 72.0 }; let (w, h) = (fit(*w), fit(*h)); let off = |v: f32| if v.is_finite() { v.clamp(-1584.0, 1584.0) } else { 0.0 }; let children: Vec = members .iter() .take(MAX_GROUP_CHILDREN) - .filter_map(|m| self.drawing(&m.inline, depth + 1).map(|obj| GroupChild { x: off(m.x), y: off(m.y), obj })) + .filter_map(|m| { + let obj = self.drawing(&m.inline, depth + 1)?; + let target = m.link.as_deref().or_else(|| drawing_link(&m.inline)); + let link = target.map(str::trim).filter(|s| !s.is_empty()).and_then(super::kept_link).map(|s| s.to_string()); + let link = self.budget(CharProps { link, ..Default::default() }).link; + Some(GroupChild { x: off(m.x), y: off(m.y), obj, link }) + }) .collect(); (!children.is_empty()).then(|| InlineObject::Group { w, @@ -562,6 +576,14 @@ impl<'a> Builder<'a> { out.props.keep_next = Some(true); } out.section.clone_from(&p.section); + // A legacy paragraph-mark target belongs to its sole drawing, not to an unlinked neighbor. + let single_drawing = p.textless() + && p.inlines + .iter() + .filter(|i| matches!(i, Inline::Image(_) | Inline::Chart(_) | Inline::Shape { .. } | Inline::Group { .. } | Inline::Figure(_))) + .take(2) + .count() + == 1; // Inlines are appended in order, so build the runs directly: inserting each one through // `Paragraph::insert_text` rescans every earlier run and is quadratic in their number. for i in &p.inlines { @@ -595,8 +617,17 @@ impl<'a> Builder<'a> { .mark .as_deref() .filter(|_| p.textless()) - .map(|m| self.budget(CharProps { ins: None, del: None, fmt_change: None, ..m.clone() })) + .map(|m| CharProps { ins: None, del: None, fmt_change: None, ..m.clone() }) .unwrap_or_default(); + if !matches!(i, Inline::Chart(_)) { + let link = drawing_link(i); + if link.is_some() || !single_drawing { + cp.link = link.map(str::trim).filter(|s| !s.is_empty()).and_then(super::kept_link).map(|s| s.to_string()); + } else { + cp.link = cp.link.take().filter(|link| super::kept_link(link).is_some()); + } + } + cp = self.budget(cp); if let Some(f) = obj.float_mut() && f.wrap == craft_wordmodel::para::Wrap::Inline && f.y != 0.0 diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index 357c9c6ff4..a8cacf35eb 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -14,7 +14,7 @@ pub const MAX_DEPTH: usize = 8; /// header made 2 million cells and took 3 to 5 GB to convert; past this, rows are left out. pub const MAX_TABLE_CELLS: usize = 1 << 18; -/// Deepest groups in groups kept (hostile files). +/// Deepest subgroup level kept, with the outer group at depth 0 (hostile files). pub const MAX_GROUP_DEPTH: usize = 8; /// Longest font name the importers keep, in bytes (as the .docx reader); a longer one (no real @@ -179,6 +179,8 @@ pub struct Img { /// How much is cut off its left, top, right and bottom, fractions of its size (0..1), for /// formats that keep it (ODT). pub crop: [f32; 4], + /// This picture's own hyperlink target, when it is a paragraph drawing. + pub link: Option, } /// An embedded object WordCraft shows but doesn't edit, kept whole for saving back (ODF 1.3 @@ -290,6 +292,8 @@ pub enum Inline { look: BoxLook, /// A freeform's paths ([`craft_wordmodel::para::ShapeKind::Freeform`]). path: Option>, + /// This shape's own hyperlink target, when it is a paragraph drawing. + link: Option, }, /// The start of a field whose result is the content after it, up to the matching /// [`Inline::FieldEnd`] (a table of contents around its entries); its field code. Only flows @@ -305,6 +309,8 @@ pub enum Inline { h: f32, float: Option>, members: Vec, + /// The group's own target; members retain their separate targets. + link: Option, }, } @@ -316,6 +322,8 @@ pub struct Member { pub x: f32, pub y: f32, pub inline: Inline, + /// This member's own hyperlink target, independent of the containing group. + pub link: Option, } /// How a text box or shape looks: its fill, its outline (colour and width, dash and diff --git a/crates/flow/tests/round_trip.rs b/crates/flow/tests/round_trip.rs index 9be4213d5a..0bfa461246 100644 --- a/crates/flow/tests/round_trip.rs +++ b/crates/flow/tests/round_trip.rs @@ -121,3 +121,173 @@ fn drop_cap_not_repeated_after_page_break() { assert_eq!(paras[1].extra.as_ref().and_then(|x| x.drop_cap_distance), None); assert_eq!(paras[1].extra.as_ref().and_then(|x| x.shading), Some(craft_wordmodel::Rgb(255, 0, 0))); } + +#[test] +fn vml_hyperlinks_survive_flow_for_roots_and_nested_members() { + use craft_flow::{BoxLook, FlowOpts, Member, from_doc_with}; + use craft_wordmodel::{Block, CharProps, para::ShapeKind}; + + let image = |target: Option<&str>| { + let mut img = make_img(PNG.to_vec(), Some(12.0), Some(8.0), "original tiny picture").unwrap(); + img.link = target.map(str::to_string); + img.crop = [0.125, 0.25, 0.0, 0.0]; + Inline::Image(img) + }; + let nested = Inline::Group { + w: 10.0, + h: 10.0, + float: None, + link: None, + members: vec![Member { x: 2.0, y: 1.0, inline: image(None), link: Some("#nested-place".into()) }], + }; + let group = Inline::Group { + w: 40.0, + h: 30.0, + float: None, + link: Some("https://example.com/group".into()), + members: vec![ + Member { x: 1.0, y: 2.0, inline: image(None), link: Some("https://example.com/child".into()) }, + Member { x: 8.0, y: 3.0, inline: nested, link: Some("https://example.com/nested-group".into()) }, + Member { x: 4.0, y: 5.0, inline: image(None), link: None }, + ], + }; + let shape = Inline::Shape { + kind: ShapeKind::Rectangle, + w: 9.0, + h: 6.0, + float: None, + blocks: Vec::new(), + look: BoxLook::default(), + path: None, + link: Some("https://example.com/shape".into()), + }; + let mut paragraph = para(Kind::Normal, vec![group, image(Some("https://example.com/picture")), shape, image(None)]); + paragraph.mark = Some(Box::new(CharProps { link: Some("https://example.com/not-the-object".into()), ..Default::default() })); + let flow = Flow { blocks: vec![FBlock::Para(paragraph)], ..Default::default() }; + let doc = to_doc(&flow); + let Block::Para(p) = &*doc.body[0] else { panic!("drawing paragraph") }; + assert_eq!( + p.runs.iter().map(|r| r.props.link.as_deref()).collect::>(), + [Some("https://example.com/group"), Some("https://example.com/picture"), Some("https://example.com/shape"), None], + "each root's target comes from that object, not the paragraph mark" + ); + let craft_wordmodel::para::InlineObject::Group { children, .. } = &p.objects[0] else { panic!("group") }; + assert_eq!(children[0].link.as_deref(), Some("https://example.com/child")); + assert_eq!(children[1].link.as_deref(), Some("https://example.com/nested-group")); + assert!(children[2].link.is_none()); + let back = from_doc_with(&doc, FlowOpts { boxes: true, paras: true, ..Default::default() }); + let got = paras(&back.blocks); + let [Inline::Group { link, members, .. }, Inline::Image(picture), Inline::Shape { link: shape_link, .. }, Inline::Image(unlinked)] = + got[0].inlines.as_slice() + else { + panic!("all four drawings survive") + }; + assert_eq!(link.as_deref(), Some("https://example.com/group")); + assert_eq!(picture.link.as_deref(), Some("https://example.com/picture")); + assert_eq!(shape_link.as_deref(), Some("https://example.com/shape")); + assert!(unlinked.link.is_none()); + assert_eq!(picture.data.as_slice(), PNG); + assert_eq!((picture.w, picture.h, picture.crop), (12.0, 8.0, [0.125, 0.25, 0.0, 0.0])); + assert_eq!((members[0].x, members[0].y), (1.0, 2.0)); + assert_eq!(members[0].link.as_deref(), Some("https://example.com/child")); + assert_eq!(members[1].link.as_deref(), Some("https://example.com/nested-group")); + assert!(members[2].link.is_none()); + let Inline::Group { link: own, members: inner, .. } = &members[1].inline else { panic!("nested group") }; + assert!(own.is_none(), "the nested group's target is carried by its Member, not duplicated on descendants"); + assert_eq!(inner[0].link.as_deref(), Some("#nested-place")); + + fn check_depth_boundary(image: impl Fn(Option<&str>) -> Inline) { + // DOCX retains an outer group at depth 0 and eight nested subgroups. Flow must + // keep that complete tree rather than lose its last drawable member. + fn linked_chain(leaf: Inline, deepest: usize) -> Inline { + let mut inline = leaf; + for level in (0..=deepest).rev() { + let target = if level == deepest { "#last-picture".to_string() } else { format!("https://example.com/level{}", level + 1) }; + inline = Inline::Group { + w: 12.0, + h: 8.0, + float: None, + link: (level == 0).then(|| "https://example.com/deep-root".into()), + members: vec![Member { x: 0.0, y: 0.0, inline, link: Some(target) }], + }; + } + inline + } + let boundary = Flow { blocks: vec![FBlock::Para(para(Kind::Normal, vec![linked_chain(image(None), 8)]))], ..Default::default() }; + let boundary_doc = to_doc(&boundary); + let boundary_para = boundary_doc.body[0].as_para().unwrap(); + assert_eq!(boundary_para.objects.len(), 1, "root plus eight subgroups remains drawable"); + assert_eq!(boundary_para.props_of_char(0).link.as_deref(), Some("https://example.com/deep-root")); + let mut object = &boundary_para.objects[0]; + for level in 0..=8 { + let craft_wordmodel::para::InlineObject::Group { children, .. } = object else { panic!("group at level {level}") }; + assert_eq!(children.len(), 1); + let target = if level == 8 { "#last-picture".to_string() } else { format!("https://example.com/level{}", level + 1) }; + assert_eq!(children[0].link.as_deref(), Some(target.as_str()), "document target at level {level}"); + object = &children[0].obj; + } + let craft_wordmodel::para::InlineObject::Image { media, .. } = object else { panic!("last picture") }; + assert_eq!(boundary_doc.media.get(media).unwrap().as_slice(), PNG); + let boundary_back = from_doc_with(&boundary_doc, FlowOpts { boxes: true, paras: true, ..Default::default() }); + let boundary_paras = paras(&boundary_back.blocks); + assert_eq!(boundary_paras[0].inlines.len(), 1); + let mut inline = &boundary_paras[0].inlines[0]; + for level in 0..=8 { + let Inline::Group { members, link, .. } = inline else { panic!("flow group at level {level}") }; + assert_eq!(link.as_deref(), (level == 0).then_some("https://example.com/deep-root")); + assert_eq!(members.len(), 1); + let target = if level == 8 { "#last-picture".to_string() } else { format!("https://example.com/level{}", level + 1) }; + assert_eq!(members[0].link.as_deref(), Some(target.as_str()), "flow target at level {level}"); + inline = &members[0].inline; + } + let Inline::Image(last) = inline else { panic!("last flow picture") }; + assert_eq!(last.data.as_slice(), PNG); + + // One further subgroup still exceeds the existing limit. Its root's separate + // drawable sibling survives, so dropping the over-deep branch cannot pass vacuously. + let mut beyond = linked_chain(image(None), 9); + let Inline::Group { members, .. } = &mut beyond else { panic!() }; + members.push(Member { x: 0.0, y: 0.0, inline: image(None), link: Some("https://example.com/sibling".into()) }); + let beyond_flow = Flow { blocks: vec![FBlock::Para(para(Kind::Normal, vec![beyond]))], ..Default::default() }; + let beyond_doc = to_doc(&beyond_flow); + let beyond_para = beyond_doc.body[0].as_para().unwrap(); + assert_eq!(beyond_para.objects.len(), 1); + let craft_wordmodel::para::InlineObject::Group { children, .. } = &beyond_para.objects[0] else { panic!() }; + assert_eq!(children.len(), 1, "the ninth subgroup is still excluded"); + assert_eq!(children[0].link.as_deref(), Some("https://example.com/sibling")); + assert!(matches!(&children[0].obj, craft_wordmodel::para::InlineObject::Image { .. })); + } + check_depth_boundary(image); + + fn check_oversized_drawing_links(image: impl Fn(Option<&str>) -> Inline) { + // Construct valid drawable inputs first; to_doc's own budget must not hide + // the from_doc boundary being checked by this regression. + let group = + Inline::Group { w: 12.0, h: 8.0, float: None, link: None, members: vec![Member { x: 0.0, y: 0.0, inline: image(None), link: None }] }; + let input = Flow { + blocks: vec![FBlock::Para(para(Kind::Normal, vec![group, image(None), image(Some("https://example.com/kept"))]))], + ..Default::default() + }; + let mut doc = to_doc(&input); + let mut paragraph = doc.body[0].as_para().unwrap().clone(); + let offsets = paragraph.object_offsets(); + let oversized = "x".repeat(craft_flow::MAX_LINK + 1); + paragraph.format(offsets[0], offsets[0] + craft_wordmodel::para::OBJ.len_utf8(), &|props| props.link = Some(oversized.clone())).unwrap(); + paragraph.format(offsets[1], offsets[1] + craft_wordmodel::para::OBJ.len_utf8(), &|props| props.link = Some(oversized.clone())).unwrap(); + let craft_wordmodel::para::InlineObject::Group { children, .. } = &mut paragraph.objects[0] else { panic!() }; + children[0].link = Some(oversized); + doc.body = vec![Block::Para(paragraph).into()]; + let back = from_doc_with(&doc, FlowOpts { boxes: true, paras: true, ..Default::default() }); + let got = paras(&back.blocks); + let [Inline::Group { link, members, .. }, Inline::Image(unlinked), Inline::Image(kept)] = got[0].inlines.as_slice() else { + panic!("all drawings remain") + }; + assert!(link.is_none(), "oversized group target is dropped"); + assert_eq!(members.len(), 1); + assert!(members[0].link.is_none(), "oversized member target is dropped"); + assert!(unlinked.link.is_none(), "oversized root image target is dropped"); + assert_eq!(kept.link.as_deref(), Some("https://example.com/kept")); + assert_eq!(kept.data.as_slice(), PNG); + } + check_oversized_drawing_links(image); +} diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index d2027c029f..01692fc984 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -588,12 +588,20 @@ impl Catalog { /// it. Does nothing once it has started or run, or when no thread can be started (the first /// lookup then scans). pub fn scan_in_background(self: &Arc) { - if self.ready.get().is_none() && !self.scanning.swap(true, Ordering::AcqRel) { - let me = Arc::clone(self); - if std::thread::Builder::new().name("font-catalog-scan".into()).spawn(move || me.background_scan()).is_err() { - self.scanning.store(false, Ordering::Release); - } + drop(self.start_background_scan()); + } + + /// [`Catalog::scan_in_background`], returning the thread it started, if it started one. + pub(crate) fn start_background_scan(self: &Arc) -> Option> { + if self.ready.get().is_some() || self.scanning.swap(true, Ordering::AcqRel) { + return None; } + let me = Arc::clone(self); + let thread = std::thread::Builder::new().name("font-catalog-scan".into()).spawn(move || me.background_scan()); + if thread.is_err() { + self.scanning.store(false, Ordering::Release); + } + thread.ok() } /// The background thread's scan. A scan that panics leaves the catalog unscanned and not diff --git a/crates/font-catalog/src/tests.rs b/crates/font-catalog/src/tests.rs index 54c044fd0b..e8b438154e 100644 --- a/crates/font-catalog/src/tests.rs +++ b/crates/font-catalog/src/tests.rs @@ -586,11 +586,11 @@ fn a_background_scan_that_panics_lets_the_next_call_scan_again() { }); let cat = Arc::new(Catalog::new(linux_env(&root)).with_font_service(false).with_lister(lister)); // Each call starts a scan only when none is running; the second starts once the failed one has ended. - let deadline = std::time::Instant::now() + Duration::from_secs(10); - while !cat.is_ready() && std::time::Instant::now() < deadline { - cat.scan_in_background(); - std::thread::sleep(Duration::from_millis(1)); - } + let failed = cat.start_background_scan().expect("the first call starts a scan"); + assert!(failed.join().is_err(), "the first scan fails"); + assert!(!cat.is_ready()); + let again = cat.start_background_scan().expect("a failed scan must not leave the catalog waiting on it"); + again.join().unwrap(); assert!(cat.is_ready(), "a failed scan must not leave the catalog waiting on it"); assert_eq!(calls.load(Ordering::Relaxed), 2); } @@ -605,13 +605,10 @@ fn adding_fonts_does_not_wait_for_the_installed_fonts() { let (entered, scan_entered) = mpsc::channel(); let (release, scan_released) = mpsc::channel::<()>(); let scan_released = std::sync::Mutex::new(scan_released); - let waited_out = Arc::new(AtomicUsize::new(0)); - let flag = Arc::clone(&waited_out); let lister: Lister = Arc::new(move || { let _ = entered.send(()); - if let Err(mpsc::RecvTimeoutError::Timeout) = scan_released.lock().unwrap().recv_timeout(Duration::from_secs(10)) { - flag.fetch_add(1, Ordering::Relaxed); - } + // The first scan stays here until the test sends on `release`; once it is dropped, scans go straight through. + let _ = scan_released.lock().unwrap().recv(); Vec::new() }); let cat = Arc::new(Catalog::new(linux_env(&root)).with_font_service(false).with_lister(lister)); @@ -619,12 +616,19 @@ fn adding_fonts_does_not_wait_for_the_installed_fonts() { assert!(!cat.is_ready(), "adding started no scan"); cat.scan_in_background(); scan_entered.recv_timeout(Duration::from_secs(10)).unwrap(); - cat.add_bytes(font(&spec("App Face", "Regular", 400)), Source::Bundled, &Limits::default()).unwrap(); + let adding = Arc::clone(&cat); + let (added, add_returned) = mpsc::channel(); + std::thread::spawn(move || { + let _ = added.send(adding.add_bytes(font(&spec("App Face", "Regular", 400)), Source::Bundled, &Limits::default())); + }); + // The scan cannot end before `release` sends, so an add that returns now did not wait for it. The limit only stops a + // test whose add waits. + let returned = add_returned.recv_timeout(Duration::from_secs(10)); release.send(()).unwrap(); // Later scans (the rescans below) go straight through. drop(release); + returned.expect("the add during the scan returned before the scan did").unwrap(); assert_eq!(cat.styles("App Face").len(), 1); - assert_eq!(waited_out.load(Ordering::Relaxed), 0, "the add during the scan returned before the scan did"); // The added Bold comes first; the installed file's Bold is another version of it, not another face. assert_eq!(cat.resolve("Test Sans", "Bold").map(|(f, _)| f), bold.first().cloned()); assert_eq!(cat.versions(&bold[0]).len(), 2); diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index 124c41610b..d6c5386309 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -734,7 +734,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: } }); over_rows = rows.response.contains_pointer(); - let pointer = ui.ctx().pointer_hover_pos(); + let pointer = craft_ui::runtime::pointer::hover_point_in(ui.ctx(), rows.response.rect); under_pointer = pointer.and_then(|at| rows.shown.iter().find(|row| row.rect.contains(at)).map(|row| row.key.clone())); events = rows.events; }); diff --git a/crates/font-manager/tests/it/panel.rs b/crates/font-manager/tests/it/panel.rs index b321381712..363dab42c6 100644 --- a/crates/font-manager/tests/it/panel.rs +++ b/crates/font-manager/tests/it/panel.rs @@ -4,8 +4,8 @@ use std::cell::RefCell; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::rc::Rc; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::time::Duration; use craft_font_manager::craft_font_catalog::Os; @@ -73,6 +73,36 @@ struct Rig { fx: Fixture, panel: Rc>, store: Arc, + woken: Arc, +} + +/// How long a test waits for another thread before it fails as hung. A result that comes does not depend on it. +const HANG: Duration = Duration::from_secs(10); + +/// Counts the repaints asked for from threads other than the test's, as the preview workers ask for one after each +/// result. +#[derive(Default)] +struct Woken { + count: Mutex, + changed: Condvar, +} + +impl Woken { + fn count(&self) -> u64 { + *self.count.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn wake(&self) { + *self.count.lock().unwrap_or_else(PoisonError::into_inner) += 1; + self.changed.notify_all(); + } + + /// Waits until a repaint is asked for after [`Woken::count`] was `seen`. + fn wait_past(&self, seen: u64) { + let count = self.count.lock().unwrap_or_else(PoisonError::into_inner); + let (count, _) = self.changed.wait_timeout_while(count, HANG, |count| *count == seen).unwrap_or_else(PoisonError::into_inner); + assert!(*count > seen, "previews kept loading"); + } } fn root(name: &str) -> PathBuf { @@ -132,9 +162,16 @@ fn show(panel: FontsPanel, store: Arc, host: Arc) -> Rig { let mut fx = Fixture::new(move |ui| { FontsPanelView::new(&mut shown.borrow_mut()).show(ui); }); + let woken = Arc::new(Woken::default()); + let (counted, test) = (Arc::clone(&woken), std::thread::current().id()); + fx.ctx().set_repaint_observer(move |_| { + if std::thread::current().id() != test { + counted.wake(); + } + }); fx.in_room(Room::Window).host(host); fx.settle(); - Rig { fx, panel, store } + Rig { fx, panel, store, woken } } impl Rig { @@ -367,8 +404,9 @@ fn a_cards_install_menu_chooses_where_the_fonts_go() { struct FakeService { answered: Mutex>, cancelled: Mutex>, - /// Requests that reached the service. - started: AtomicUsize, + /// Requests that reached the service, notified on `arrived` as each one does. + started: Mutex, + arrived: Condvar, held: AtomicBool, /// Answers sample subsets with HTTP 404, as for a sample text the service doesn't have. no_samples: AtomicBool, @@ -378,7 +416,8 @@ struct FakeService { impl Fetch for FakeService { fn get(&self, url: &str, _: u64, cancel: &Cancel) -> Result, FetchError> { - self.started.fetch_add(1, Ordering::SeqCst); + *self.started.lock().unwrap_or_else(PoisonError::into_inner) += 1; + self.arrived.notify_all(); while self.held.load(Ordering::SeqCst) && !cancel.is_cancelled() { std::thread::sleep(Duration::from_millis(2)); } @@ -403,6 +442,18 @@ impl FakeService { std::mem::take(&mut *self.answered.lock().unwrap_or_else(PoisonError::into_inner)) } + /// The requests that reached the service. + fn started(&self) -> usize { + *self.started.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Waits until a request has reached the service. + fn wait_started(&self) { + let started = self.started.lock().unwrap_or_else(PoisonError::into_inner); + let (started, _) = self.arrived.wait_timeout_while(started, HANG, |started| *started == 0).unwrap_or_else(PoisonError::into_inner); + assert!(*started > 0, "the service was asked"); + } + /// The numbers of the families whose `subset` the URLs of `answered` name: `sample`, `ascii`, or `u/` for typed /// characters. fn numbers(answered: &[String], subset: &str) -> Vec { @@ -468,16 +519,22 @@ impl Rig { self.fx.settle(); } - /// Runs passes until the panel has fetched what it asks for and asks for nothing more. + /// Runs passes until the panel has fetched what it asks for and asks for nothing more. While a preview is on its + /// way, the next pass waits for the repaint its worker asks for once the result is ready. fn load(&mut self) { let mut quiet = 0; for _ in 0..500 { + let seen = self.woken.count(); self.fx.frame(Vec::new()); - quiet = if self.panel.borrow().loading_previews() { 0 } else { quiet + 1 }; + if self.panel.borrow().loading_previews() { + quiet = 0; + self.woken.wait_past(seen); + continue; + } + quiet += 1; if quiet == 3 { return; } - std::thread::sleep(Duration::from_millis(1)); } panic!("previews kept loading"); } @@ -563,13 +620,7 @@ fn a_resize_and_a_search_cancel_no_preview() { service.held.store(true, Ordering::SeqCst); let mut rig = service_rig("previews-kept", &service, latin_index()); rig.set_previews(true); - for _ in 0..500 { - if service.started.load(Ordering::SeqCst) > 0 { - break; - } - std::thread::sleep(Duration::from_millis(1)); - } - assert!(service.started.load(Ordering::SeqCst) > 0, "the service was asked"); + service.wait_started(); let shown = rig.numbers(); rig.fx.room(Room::Window.size() + Vec2::new(40.0, 120.0)).settle(); rig.type_into("Search", "Family"); @@ -602,7 +653,7 @@ fn a_family_of_an_added_source_is_not_asked_of_the_service() { rig.open("Added"); rig.load(); rig.named(Role::BUTTON, "Preview"); - assert_eq!(service.started.load(Ordering::SeqCst), 0, "{:?}", service.urls()); + assert_eq!(service.started(), 0, "{:?}", service.urls()); } /// A sample the service has not (another text) is asked for as the sample's characters, once. diff --git a/crates/font-manager/tests/remote.rs b/crates/font-manager/tests/remote.rs index e8c1062ea0..59413800bd 100644 --- a/crates/font-manager/tests/remote.rs +++ b/crates/font-manager/tests/remote.rs @@ -9,8 +9,9 @@ use std::collections::HashMap; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::path::PathBuf; +use std::sync::mpsc::{Receiver, channel}; use std::sync::{Arc, Condvar, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; use craft_font_manager::craft_font_catalog::Os; use craft_font_manager::store::{FakeStore, Installer, SuiteStore}; @@ -118,7 +119,8 @@ enum Reply { struct Service { base: String, routes: Arc>>, - log: Arc>>, + /// The paths asked for, notified as each one arrives. + log: Arc<(Mutex>, Condvar)>, gate: Arc<(Mutex, Condvar)>, } @@ -143,7 +145,14 @@ impl Service { } fn requests(&self) -> Vec { - self.log.lock().unwrap().clone() + self.log.0.lock().unwrap().clone() + } + + /// Waits until `n` requests have reached the service. + fn wait_for_requests(&self, n: usize) { + let log = self.log.0.lock().unwrap(); + let (log, _) = self.log.1.wait_timeout_while(log, HANG, |log| log.len() < n).unwrap(); + assert!(log.len() >= n, "{} of {n} requests reached the service", log.len()); } fn release(&self) { @@ -152,7 +161,7 @@ impl Service { } } -fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex>, gate: &(Mutex, Condvar)) { +fn answer(mut s: TcpStream, routes: &Mutex>, log: &(Mutex>, Condvar), gate: &(Mutex, Condvar)) { let mut head = Vec::new(); let mut b = [0u8; 1]; while !head.ends_with(b"\r\n\r\n") { @@ -162,7 +171,8 @@ fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex< } } let path = String::from_utf8_lossy(&head).split_whitespace().nth(1).unwrap_or("/").to_string(); - log.lock().unwrap().push(path.clone()); + log.0.lock().unwrap().push(path.clone()); + log.1.notify_all(); let reply = routes.lock().unwrap().get(&path).cloned(); let body = match reply { Some(Reply::Ok(body)) => body, @@ -182,22 +192,28 @@ fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex< let _ = s.write_all(&body); } -/// The results until `n` have come, or two seconds. -fn wait_for(previews: &Previews, n: usize) -> Vec { - let deadline = Instant::now() + Duration::from_secs(2); - let mut out = Vec::new(); - while out.len() < n && Instant::now() < deadline { - out.extend(previews.poll()); - std::thread::sleep(Duration::from_millis(5)); - } - out +/// How long a test waits for a result or a request before it fails as hung. A result that comes does not depend on it. +const HANG: Duration = Duration::from_secs(10); + +/// `previews` and a channel that gets `()` after each result it delivers ([`Previews::on_ready`]). +fn watched(previews: Previews) -> (Previews, Receiver<()>) { + let (ready, results) = channel(); + let previews = previews.on_ready(move || { + let _ = ready.send(()); + }); + (previews, results) } -fn wait_until(mut done: impl FnMut() -> bool) { - let deadline = Instant::now() + Duration::from_secs(2); - while !done() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(5)); +/// The results until `n` have come. +fn wait_for(previews: &Previews, ready: &Receiver<()>, n: usize) -> Vec { + let mut out = previews.poll(); + while out.len() < n { + if ready.recv_timeout(HANG).is_err() { + panic!("{} of {n} previews came", out.len()); + } + out.extend(previews.poll()); } + out } #[test] @@ -209,12 +225,12 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { let broken = PreviewKey::new(&sha(2), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); service.serve(&sample, Reply::Ok(WOFF2.to_vec())); service.serve(&broken, Reply::Ok(b"wOF2 but not really".to_vec())); - let previews = Previews::new(store.clone()); + let (previews, ready) = watched(Previews::new(store.clone())); // No service: nothing happens. assert!(!previews.available()); previews.request(sample.clone(), 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NoService)); // A service, but previews off: no request. @@ -222,7 +238,7 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { store.set_previews_enabled(false).unwrap(); assert!(!previews.available()); previews.request(sample.clone(), 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::PreviewsOff)); assert!(service.requests().is_empty()); @@ -231,7 +247,7 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { assert!(previews.available() && !store.downloads_allowed()); previews.request(sample.clone(), 1); previews.request(broken.clone(), 1); - let got = wait_for(&previews, 2); + let got = wait_for(&previews, &ready, 2); let font = |key: &PreviewKey| got.iter().find(|p| &p.key == key).map(|p| p.font.clone()); assert!(font(&sample).unwrap().is_ok_and(|f| is_font(&f))); assert_eq!(font(&broken), Some(Err(PreviewError::NotAFont))); @@ -241,9 +257,9 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { // A new session reads the disk cache, even with previews off. store.set_previews_enabled(false).unwrap(); - let later = Previews::new(store.clone()); + let (later, later_ready) = watched(Previews::new(store.clone())); later.request(sample.clone(), 1); - assert!(wait_for(&later, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f)))); + assert!(wait_for(&later, &later_ready, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f)))); assert_eq!(service.requests().len(), 2); let _ = std::fs::remove_dir_all(dir); } @@ -276,9 +292,9 @@ fn a_service_marked_down_gets_no_requests() { // The client is shared with, say, the store's installs, which found the service unreachable. let client = Client::default(); client.mark_service_down(&service.base); - let previews = Previews::new(store.clone()).with_fetcher(Arc::new(client)); + let (previews, ready) = watched(Previews::new(store.clone()).with_fetcher(Arc::new(client))); previews.request(key, 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert!(matches!(got.first().map(|p| p.font.clone()), Some(Err(PreviewError::Failed(_))))); assert!(service.requests().is_empty()); let _ = std::fs::remove_dir_all(dir); @@ -297,10 +313,10 @@ fn highest_priority_first_and_cancelled_requests_deliver_nothing() { for key in [low, high, dropped] { service.serve(key, Reply::Ok(WOFF2.to_vec())); } - let previews = Previews::new(store.clone()).with_cache(None).with_workers(1); + let (previews, ready) = watched(Previews::new(store.clone()).with_cache(None).with_workers(1)); previews.request(held.clone(), 9); - wait_until(|| !service.requests().is_empty()); + service.wait_for_requests(1); previews.request(low.clone(), 1); previews.request(dropped.clone(), 1); previews.request(high.clone(), 5); @@ -310,11 +326,12 @@ fn highest_priority_first_and_cancelled_requests_deliver_nothing() { // The running request stops while the service still sends nothing. previews.cancel(held); - let got = wait_for(&previews, 2); + let got = wait_for(&previews, &ready, 2); assert_eq!(got.iter().map(|p| &p.key).collect::>(), [high, low]); let path = |k: &PreviewKey| format!("/{}", k.path()); assert_eq!(service.requests(), [path(held), path(high), path(low)]); - std::thread::sleep(Duration::from_millis(100)); + // The one worker delivers in the order it takes requests, and it had ended the held one before it asked for `high`, + // so nothing more can come. assert!(previews.poll().is_empty()); assert_eq!(previews.pending(), 0); service.release(); @@ -343,9 +360,9 @@ fn a_404_comes_back_as_not_found() { let store = Arc::new(FakeStore::new(&dir, HashMap::new())); store.set_preview_service(Some(&service.base)).unwrap(); let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); - let previews = Previews::new(store.clone()); + let (previews, ready) = watched(Previews::new(store.clone())); previews.request(key, 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NotFound)); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/gpu-device/Cargo.toml b/crates/gpu-device/Cargo.toml new file mode 100644 index 0000000000..19f6cfa356 --- /dev/null +++ b/crates/gpu-device/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "craft-gpu-device" +description = "Choosing and opening a wgpu device: an adapter choice the user can set (Auto, high performance, low power, a named adapter, software), fixes for drivers that crash, a software fallback, a capability report, and device health with recovery after a device loss" +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 `Preference` and `AdapterKey` with serde. +serde = ["dep:serde"] +# Native wgpu backends, as in craft-gpu-wgpu. None is on by default; the app turns on the ones it +# ships, through this crate or through craft-gpu-wgpu. +native-vulkan = ["wgpu/vulkan"] +native-dx12 = ["wgpu/dx12"] +native-metal = ["wgpu/metal"] +native-gles = ["wgpu/gles"] + +[dependencies] +craft-gpu = { workspace = true } +log = { workspace = true } +serde = { workspace = true, optional = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true } +wgpu = { workspace = true } + +[dev-dependencies] +# The noop backend opens devices without a GPU in the tests. +wgpu = { workspace = true, features = ["noop"] } +serde_json = { workspace = true } diff --git a/crates/gpu-device/NOTICE b/crates/gpu-device/NOTICE new file mode 100644 index 0000000000..e7ca2f2c92 --- /dev/null +++ b/crates/gpu-device/NOTICE @@ -0,0 +1,10 @@ +craft-gpu-device +Licensed under the MIT license or the Apache License, Version 2.0, at your option. + +The adapter rule and its driver corrections (src/adapter.rs) come from FilmCraft's +`crates/gpu/src/adapter.rs` (https://github.com/storytold/filmcraft, commit +93a88a839aae370740b09434fdec410abb8c24ca), MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and +the FilmCraft contributors. +Device health (src/health.rs) comes from PhotoCraft's `crates/gpu/src/health.rs` +(https://github.com/storytold/photocraft, commit 01a5b5a389acc93f081e5ce6a8d0580d6438774a), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md new file mode 100644 index 0000000000..bb083932ad --- /dev/null +++ b/crates/gpu-device/README.md @@ -0,0 +1,128 @@ +# craft-gpu-device + +Choosing and opening a wgpu device for a Craft app: an adapter choice the user can set, fixes for +drivers that crash, a software fallback, a capability report, and device health with recovery +after a device loss. The crate depends on `craft-gpu`, `wgpu` 30, `pollster` and `log`, with +`serde` as an optional feature (on by default). It depends on no app crate. + +It uses the workspace's `wgpu`, which turns on no native backend, and the WebGPU backend on +`wasm32`. The `native-vulkan`, `native-dx12`, `native-metal` and `native-gles` features turn on +wgpu's backends, as the features of the same names in `craft-gpu-wgpu` do. Cargo merges the +features, so an app can turn them on through either crate. + +The `gpu-device` feature of `craft` exports this crate as `craft::gpu_device`. + +`native_instance` shares one instance across calls on native targets. It reads wgpu's environment +settings for flags and backend options when that instance is first created. `native_descriptor` +reads those settings on every call. + +Licensed under MIT OR Apache-2.0. + +## Contents + +| Item | What | +|---|---| +| `Candidate` | one listed adapter as plain data: name, backend, device type, PCI vendor, device and bus, driver, feature count, and whether it can draw to the window's surface | +| `list(instance, surface)` | every adapter the instance lists, as `wgpu::Adapter`s and as `Candidate`s | +| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL except on Windows; wgpu's `WGPU_*` flag variables apply | +| `choose(candidates, power)` | wgpu's own adapter rule with two corrections: the newest version of a driver that lists one GPU twice, and DirectX 12 instead of Vulkan on Intel Gen 9 to Gen 11 integrated GPUs (`intel_gen9_to_gen11`) | +| `Preference` | `Auto` (high performance), `LowPower`, `Adapter(AdapterKey)` or `Software`; serde form `{"kind":"auto"}`, `{"kind":"adapter","name":…,"backend":…,"vendor":…,"device":…,"pciBusId":…,"driver":…}` | +| `AdapterKey` | what identifies an adapter across runs: backend, PCI vendor, device and bus, the Vulkan driver's name, and the name when the backend reports no PCI ids | +| `select(candidates, preference)` | the adapter to draw with, as a `Selection` with its `Notice`s | +| `ranked(candidates, preference)` | the order in which to try opening a device: the selection, then the other usable adapters by type with software after hardware, never an older version of a driver listed twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver | +| `open(instance, surface, preference, request)` | native only, like `list`: opens a device through `ranked`, then wgpu's fallback adapter; returns `Opened` (adapter, device, queue, `Capabilities`, `DeviceHealth`, notices) or `OpenError` | +| `list_async`, `open_async` | `list` and `open` as futures, for a `wasm32` web worker as well as native; in a browser `list_async` gives the high-performance adapter, the one `open_async` opens for `Auto` and a named adapter | +| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector`; the error is an `OpenError` (convert it with `map_err(\|e\| e.to_string())` for that selector) | +| `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one, read from the `craft_gpu::DeviceCaps` it holds (its fields are readable through `Deref`; `From` converts both ways) | +| `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device | +| `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) | +| `device_caps(device)`, `Opened::device_caps` | the `craft_gpu::DeviceCaps` of a device: its own limits, enabled feature names, vendor id and software flag, in the form `craft-gpu-wgpu` reports | +| `DeviceHealth::device_status` | a recorded loss as `craft_gpu::GpuFault::DeviceLost`, in the form of `GpuContext::device_status`; `Fault` converts to `GpuFault` (a loss to `DeviceLost`, an error to `Operation`) | +| `Notice` | the adapter asked for is missing, no software adapter is listed, only a software adapter can draw, an adapter failed to open, or drawing moved to software after losses; the `Display` text is English, for the log | + +## Failure cases + +- With no usable adapter, `select` returns `None`, and `open` and `pick` return + `OpenError::NoAdapter`, or `OpenError::UnsafeDriver` when only a driver that can end the + process can draw. +- In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be + chosen. `open_async` asks for the adapter with `Preference::power()` as the power preference, + and gives the automatic choice with `Notice::AdapterMissing` for a named adapter. wgpu 30 + does not pass the fallback-adapter option to the browser, so `Preference::Software` opens the + browser's adapter, with `Notice::NoSoftwareAdapter` unless that adapter is a software one, and + `Recovery` cannot move drawing to software there. `Capabilities` and + `Recovery` otherwise work there as they do on native, and so does `DeviceHealth` apart from `wait`, + `wait_timeout` and `wait_timeout_cancelable`, which are native only. On the browser backend, + wgpu 30 panics on an uncaptured `GPUInternalError` before the handler `DeviceHealth::watch` + installs runs, so such an error is not recorded. Validation and out-of-memory errors are. +- An adapter that lacks `Request::required_features`, whose limits are lower than + `Request::limits`, or whose `request_device` fails, adds a `Notice::DeviceFailed`, and `open` + tries the next one. When every adapter fails, the error lists each failure. +- A named adapter that is no longer listed, or can no longer draw to the surface, gives the + automatic choice and `Notice::AdapterMissing`. +- A driver that ends the process cannot be caught. `choose` and `ranked` never use an older + version of a driver that lists one GPU twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 + GPU on Intel's Windows driver. When those are the only adapters that can draw and wgpu's + fallback adapter does not open either, `open` returns `OpenError::UnsafeDriver` with their + names. When a + driver reports no bus id, a second GPU of the same model on the same driver looks like an + older version, and is used through its other backend (DirectX 12 on Windows, OpenGL + elsewhere). +- Only an error whose cause is wgpu's "Parent device is lost" counts as a loss. The same words in + a resource's label do not count. An error about a destroyed buffer or texture is recorded as an + error. +- `wait`, `wait_timeout` and `wait_timeout_cancelable` wait for one submission index. To wait for + everything submitted so far, pass `queue.submit([])`; work submitted later does not extend the + wait. +- `wait` has no deadline. It polls in slices of at most 100 ms, and a loss or an error other than + out of memory that another clone of the `DeviceHealth` records ends it after the current slice. +- `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that + `Device::poll` raises on a lost device and record the loss. +- wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback` + replaces the one `DeviceHealth::watch` set. A `craft-gpu` context on a watched device reads + `DeviceHealth::device_status` instead of setting its own callback. +- After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed. + The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and + passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again, + unless it was lost, another error was recorded, or a new out-of-memory error came in after the + count was read. + +## After a device loss + +`DeviceHealth::device_status` returns `GpuFault::DeviceLost` once a loss is recorded, and the +caller starts recovery then. `DeviceHealth::device_lost` turns true only when wgpu itself reported +the loss; it stays false for a loss the health layer recorded on its own, such as a bounded wait +that reached its deadline. Nothing made with the lost device can be used again, and wgpu keeps +none of its contents. The caller then: + +1. Drops the old `Opened` and everything made with its device: buffers, textures and their + views, samplers, bind group layouts and bind groups, shader modules, pipeline layouts and + pipelines, query sets, unsubmitted command encoders, and any renderer that holds them (an + egui-wgpu `Renderer`, for example). Work submitted before the loss does not complete, and + waits on it return `false`. +2. Calls `Recovery::lost` with the time and opens a new device with `open` or `open_async`, + using the returned preference and the same `Request`. When the step has a notice + (`Notice::SoftwareAfterLosses`), the app shows it only if the new `Opened::caps.software()` is + true. Otherwise no software adapter opened (in a browser, or with none listed), and the new + `Opened::notices` say what was opened instead. +3. Reads the new `Opened::caps` before choosing pipelines again. The new device can be another + adapter, or a software one, with other features and limits: for example, without NV12 the + planes are drawn into `R8Unorm` and `Rg8Unorm` textures instead. +4. Configures each window surface again with the new device (`Surface::configure`). The surface + itself is kept when it was passed to `open`, which then opens only an adapter that can draw + to it. The new adapter may not support the old configuration (an HDR format, for example), so + the caller reads `Surface::get_capabilities` with the new adapter and picks a format, present + mode and alpha mode from it. +5. Builds the pipelines for the surface format picked in step 4, and the bind groups and + renderers, again, and uploads the textures and buffers again from the app's own copies of + their data. +6. Makes any `craft-gpu` context again on the new device, with the new `Opened::device_caps`, and + submits again the jobs and frames that did not complete. +7. Uses the new `Opened::health`. The old `DeviceHealth` keeps reporting the loss. + +## Tests + +The selection tests run on `Candidate` lists from real machines. The `open` tests use wgpu's noop +backend (the `noop` feature, enabled for tests only), so they do not need a GPU. One test compares +`choose` with wgpu's own `request_adapter` on the machine that runs it, and passes when no adapter +is listed. diff --git a/crates/gpu-device/src/adapter.rs b/crates/gpu-device/src/adapter.rs new file mode 100644 index 0000000000..b837d47b1b --- /dev/null +++ b/crates/gpu-device/src/adapter.rs @@ -0,0 +1,647 @@ +//! Which adapter wgpu's own rule would draw with, and two corrections to it for drivers that crash. +//! +//! On Windows the Vulkan loader takes one driver from each display adapter's driver package. A PC +//! whose GPUs were installed from different packages of one vendor (a laptop with an integrated +//! and a discrete AMD GPU, the first on the manufacturer's old package and the second on a current +//! one) loads two versions of that driver, and the newer GPU is listed once through each. wgpu +//! takes the first entry of the device type it prefers, which is whichever version the loader +//! listed first; a window drawn through the stale one ends the process inside the driver +//! (`amdvlk64.dll`, 0xc0000005), where no Rust error handling runs. +//! +//! [`choose`] is wgpu's own rule (`Instance::request_adapter`: the adapters that can draw to the +//! surface, by device type for the power preference, then as enumerated) with one addition: when +//! the adapter that rule picks is listed again by the same driver, the entry exposing the most +//! features is used, which is the newer version. Without such a duplicate the choice is wgpu's own. +//! Entries of one GPU from different drivers (RADV and AMDVLK, a vendor's driver and Dozen) are +//! left alone, and wgpu's order between them stays. +//! +//! An Intel Gen 9 to Gen 11 integrated GPU draws through its DirectX 12 entry rather than Vulkan +//! ([`intel_gen9_to_gen11`]). Intel's Vulkan driver for them (`igvk64.dll`) ends the process with +//! 0xc0000005 when the device is created, after the adapters are listed. + +use std::cmp::Reverse; +use std::fmt; + +use wgpu::{Adapter, Backend, DeviceType, PowerPreference, Surface}; + +/// One enumerated adapter as plain data, so that [`choose`] and [`crate::select`] are pure +/// functions that tests run without a GPU. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Candidate { + pub name: String, + pub backend: Backend, + pub device_type: DeviceType, + /// PCI vendor and device ids; both zero when the backend reports none (OpenGL). + pub vendor: u32, + pub device: u32, + /// PCI bus id such as `0000:03:00.0`; empty when the driver reports none. + pub pci_bus_id: String, + /// The driver's name (Vulkan) or version (DirectX 12). + pub driver: String, + /// More about the driver, for the log. + pub driver_info: String, + /// How many wgpu features the driver exposes; a newer version of one driver exposes more. + pub features: u32, + /// Whether the surface can be drawn through this adapter (true without a surface). + pub usable: bool, +} + +impl Candidate { + pub fn of(adapter: &Adapter, surface: Option<&Surface<'_>>) -> Self { + let info = adapter.get_info(); + Candidate { + name: info.name, + backend: info.backend, + device_type: info.device_type, + vendor: info.vendor, + device: info.device, + pci_bus_id: info.device_pci_bus_id, + driver: info.driver, + driver_info: info.driver_info, + features: adapter.features().bits().0.iter().map(|word| word.count_ones()).sum(), + usable: surface.is_none_or(|s| adapter.is_surface_supported(s)), + } + } + + /// Whether the adapter draws on the CPU (WARP, llvmpipe, lavapipe, SwiftShader). + pub fn is_software(&self) -> bool { + self.device_type == DeviceType::Cpu + } +} + +impl fmt::Display for Candidate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.device_type { + DeviceType::DiscreteGpu => "discrete GPU", + DeviceType::IntegratedGpu => "integrated GPU", + DeviceType::VirtualGpu => "virtual GPU", + DeviceType::Cpu => "software", + DeviceType::Other => "unknown type", + }; + let driver = format!("{} {}", self.driver, self.driver_info); + write!(f, "\"{}\" ({:?}, {kind}, driver {}, {} features", self.name, self.backend, driver.trim(), self.features)?; + if !self.pci_bus_id.is_empty() { + write!(f, ", bus {}", self.pci_bus_id)?; + } + if !self.usable { + write!(f, ", cannot draw to the window")?; + } + write!(f, ")") + } +} + +/// Whether `a` and `b` are one GPU listed twice by one driver, through two installed versions of +/// it: the same backend, device type, PCI vendor and device and driver name, and the same bus id +/// when both report one. Adapters without PCI ids (OpenGL reports zeros) are never the same: two +/// of them cannot be told apart. +pub(crate) fn same_gpu_and_driver(a: &Candidate, b: &Candidate) -> bool { + let identified = a.vendor != 0 || a.device != 0; + let same_bus = a.pci_bus_id.is_empty() || b.pci_bus_id.is_empty() || a.pci_bus_id == b.pci_bus_id; + identified + && a.backend == b.backend + && a.device_type == b.device_type + && a.vendor == b.vendor + && a.device == b.device + && a.driver == b.driver + && same_bus +} + +/// wgpu's device type order for `power` (wgpu-core's `Instance::request_adapter`): lower first. +/// Without a preference the adapters stay as enumerated. +pub(crate) fn type_order(device_type: DeviceType, power: PowerPreference) -> u8 { + let prefer_integrated = match power { + PowerPreference::LowPower => true, + PowerPreference::HighPerformance => false, + PowerPreference::None => return 0, + }; + match device_type { + DeviceType::DiscreteGpu if prefer_integrated => 2, + DeviceType::IntegratedGpu if prefer_integrated => 1, + DeviceType::DiscreteGpu => 1, + DeviceType::IntegratedGpu => 2, + DeviceType::Other => 3, + DeviceType::VirtualGpu => 4, + DeviceType::Cpu => 5, + } +} + +/// The index of the adapter wgpu's `request_adapter` picks: the first usable one of the best +/// device type for `power`. `None` without a usable adapter. +pub(crate) fn wgpu_choice(candidates: &[Candidate], power: PowerPreference) -> Option { + let usable = candidates.iter().enumerate().filter(|(_, c)| c.usable); + usable.min_by_key(|(index, c)| (type_order(c.device_type, power), *index)).map(|(index, _)| index) +} + +/// A wgpu instance over the native backends (Vulkan, Metal, DirectX 12), and OpenGL except on +/// Windows. On Windows, OpenGL starts a WGL context thread inside the vendor driver (NVIDIA's +/// `nvoglv64` is both its OpenGL driver and its Vulkan driver), and instances created and devices +/// dropped at the same time can then deadlock in that driver. +/// +/// On native targets, the first call creates one shared instance and reads wgpu's environment +/// settings for flags and backend options. Later calls return clones of that instance. +pub fn native_instance() -> wgpu::Instance { + #[cfg(not(target_arch = "wasm32"))] + { + static SHARED: std::sync::OnceLock = std::sync::OnceLock::new(); + SHARED.get_or_init(|| wgpu::Instance::new(native_descriptor())).clone() + } + #[cfg(target_arch = "wasm32")] + { + wgpu::Instance::new(native_descriptor()) + } +} + +/// [`native_instance`]'s descriptor. wgpu's environment variables apply to its flags and backend +/// options: `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER=1` lists a Vulkan driver that reports no +/// conformance version, such as Mesa's Dozen (the only one on WSL2), and `WGPU_VALIDATION`, +/// `WGPU_DX12_COMPILER` and the others work too. The backends stay as above whatever +/// `WGPU_BACKEND` says. +/// +/// The descriptor has no display handle, which a headless instance does not need. OpenGL on +/// Wayland needs one to draw to a window: add it with `InstanceDescriptor::with_display_handle`, +/// or pass the descriptor to egui-wgpu as `WgpuSetupCreateNew::instance_descriptor`, where eframe +/// fills in the window's display handle. +pub fn native_descriptor() -> wgpu::InstanceDescriptor { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + desc.flags = desc.flags.with_env(); + desc.backend_options = desc.backend_options.with_env(); + desc +} + +/// The index of the adapter to draw with for `power`: `wgpu_choice`, or the entry exposing the +/// most features among those that are the same GPU listed by the same driver (the first of them +/// when several expose as many), repeated until the entry is its own newest version. For an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows Vulkan driver it is the same GPU's DirectX 12 entry, or +/// without one the best other usable adapter. `None` without a usable adapter, and when that +/// Intel Vulkan entry is the only one. The result is never an entry `avoided` excludes. +pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option { + let first = wgpu_choice(candidates, power)?; + let index = settled(candidates, first); + if candidates.get(index).is_some_and(intel_vulkan_crashes) { + // No usable DirectX 12 entry for that GPU: the best other adapter wgpu would take. + let safe = candidates.iter().enumerate().filter(|(_, c)| c.usable && !intel_vulkan_crashes(c)); + let (other, _) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?; + return Some(settled(candidates, other)); + } + Some(index) +} + +/// [`corrected`] applied until it returns the entry it was given. An entry without a bus id can +/// be the same GPU as two entries on different buses, so one correction can land on an entry that +/// has a newer version of its own. Each step moves to an entry exposing more features (or the +/// same number at a lower index), or to a DirectX 12 entry, so the loop ends. +pub(crate) fn settled(candidates: &[Candidate], mut index: usize) -> usize { + for _ in 0..=candidates.len() { + let Some(c) = candidates.get(index) else { + return index; + }; + let next = corrected(candidates, index, c); + if next == index { + return index; + } + index = next; + } + index +} + +/// `index` (the entry `preferred`), or the entry to draw with instead of it. +pub(crate) fn corrected(candidates: &[Candidate], index: usize, preferred: &Candidate) -> usize { + if let Some(dx12) = dx12_instead(candidates, preferred) { + return dx12; + } + let versions = candidates.iter().enumerate().filter(|(_, c)| c.usable && same_gpu_and_driver(preferred, c)); + versions.max_by_key(|(index, c)| (c.features, Reverse(*index))).map_or(index, |(index, _)| index) +} + +/// Whether the entry at `index` is one [`choose`] never draws with: the Vulkan entry of an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows driver, or an older version of a driver that lists one +/// GPU twice. Creating a device or drawing through either can end the process, so it is never +/// tried as a fallback either. A second GPU of the same model on the same driver, when the +/// driver reports no bus id for either, looks like an older version; it is still listed through +/// the other backends (DirectX 12 on Windows, OpenGL elsewhere). +pub(crate) fn avoided(candidates: &[Candidate], index: usize) -> bool { + let Some(c) = candidates.get(index) else { + return true; + }; + intel_vulkan_crashes(c) || corrected(candidates, index, c) != index +} + +/// PCI vendor id of Intel. +pub(crate) const INTEL: u32 = 0x8086; + +/// Whether `device` is an Intel Gen 9 to Gen 11 integrated GPU: 6th to 10th generation Core, and +/// the Atom, Pentium and Celeron graphics of those years (Skylake, Broxton, Gemini Lake, Kaby +/// Lake, Coffee Lake, Whiskey Lake, Comet Lake, Cannon Lake, Ice Lake, Elkhart Lake, Jasper Lake), +/// by the PCI device ids of Linux's `include/drm/intel/pciids.h`: these prefixes hold those +/// families and no others, except `0x0a84` (Broxton), whose prefix Haswell shares. +/// +/// Their Windows Vulkan driver ends the process with 0xc0000005 in `igvk64.dll` when a device is +/// created, on every version reported, from 25.20.100.6576 (2019) to 31.0.101.2145, the legacy +/// branch that is the last driver Intel ships for them. DirectX 12 works on the same GPUs. +pub fn intel_gen9_to_gen11(device: u32) -> bool { + matches!(device >> 8, 0x19 | 0x1a | 0x31 | 0x3e | 0x45 | 0x4e | 0x59 | 0x5a | 0x87 | 0x8a | 0x9b) || device == 0x0a84 +} + +/// Whether `c` is an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan +/// driver ([`intel_gen9_to_gen11`]). Mesa's Vulkan driver for the same GPUs on Linux reports a +/// driver name with "Mesa" in it and is not included. +pub(crate) fn intel_vulkan_crashes(c: &Candidate) -> bool { + c.backend == Backend::Vulkan + && c.device_type == DeviceType::IntegratedGpu + && c.vendor == INTEL + && intel_gen9_to_gen11(c.device) + && !c.driver.to_ascii_lowercase().contains("mesa") +} + +/// For an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan driver, the +/// index of the same GPU's usable DirectX 12 entry, if there is one. +fn dx12_instead(candidates: &[Candidate], preferred: &Candidate) -> Option { + if !intel_vulkan_crashes(preferred) { + return None; + } + candidates.iter().position(|c| c.usable && c.backend == Backend::Dx12 && c.vendor == INTEL && c.device == preferred.device) +} + +/// Write the adapters and the choice to the log, with a warning when a correction applied. +pub(crate) fn log_choice(candidates: &[Candidate], index: usize, power: PowerPreference) { + for candidate in candidates { + log::info!("graphics adapter available: {candidate}"); + } + let Some(chosen) = candidates.get(index) else { + return; + }; + let others = candidates.iter().enumerate().filter(|(i, c)| *i != index && c.usable && same_gpu_and_driver(chosen, c)).count(); + if others > 0 { + log::warn!( + "{:?} lists \"{}\" {} times: several versions of its driver are installed, and a window drawn through a stale one can crash. Using the one with the most features; installing one driver package for every GPU removes the others.", + chosen.backend, + chosen.name, + others.saturating_add(1) + ); + } + if let Some(wgpu_own) = wgpu_choice(candidates, power).and_then(|i| candidates.get(i)) + && wgpu_own.backend == Backend::Vulkan + && chosen.backend == Backend::Dx12 + && wgpu_own.vendor == INTEL + && wgpu_own.device == chosen.device + { + log::warn!("Intel's Vulkan driver for \"{}\" crashes when the device is created: drawing through DirectX 12", wgpu_own.name); + } + log::info!("graphics adapter chosen: {chosen}"); +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use wgpu::Backend::{Dx12, Gl, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, Other}; + use wgpu::PowerPreference::{HighPerformance, LowPower}; + + pub(crate) const AMD: u32 = 0x1002; + pub(crate) const RX_6800M: u32 = 0x73df; + pub(crate) const RADEON_IGPU: u32 = 0x1638; + const POWERS: [PowerPreference; 3] = [PowerPreference::None, LowPower, HighPerformance]; + + #[expect(clippy::too_many_arguments, reason = "one line per adapter in the listings below")] + pub(crate) fn gpu( + name: &str, + backend: Backend, + device_type: DeviceType, + vendor: u32, + device: u32, + bus: &str, + driver: &str, + driver_info: &str, + features: u32, + ) -> Candidate { + Candidate { + name: name.into(), + backend, + device_type, + vendor, + device, + pci_bus_id: bus.into(), + driver: driver.into(), + driver_info: driver_info.into(), + features, + usable: true, + } + } + + /// A laptop with an integrated Radeon on a 2021 driver package and an RX 6800M on a 2026 one, + /// as wgpu 30 lists it: the Vulkan loader has both versions of AMD's driver, and the 2021 one + /// lists the RX 6800M first. A window drawn through that entry ended inside `amdvlk64.dll` + /// (0xc0000005) on every launch. + pub(crate) fn two_amd_drivers() -> Vec { + let amd = "AMD proprietary driver"; + vec![ + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2", 60), + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2 (AMD proprietary shader compiler)", 68), + gpu("AMD Radeon(TM) Graphics", Vulkan, IntegratedGpu, AMD, RADEON_IGPU, "", amd, "21.30.02.13", 56), + gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, AMD, RX_6800M, "0000:03:00.0", "32.0.21045.11001", "", 36), + gpu("AMD Radeon(TM) Graphics", Dx12, IntegratedGpu, AMD, RADEON_IGPU, "0000:08:00.0", "30.0.13002.13003", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9549", "", 36), + ] + } + + #[test] + fn a_gpu_listed_through_two_versions_of_its_driver_draws_with_the_newer_one() { + let adapters = two_amd_drivers(); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(wgpu_choice(&adapters, power), Some(0), "wgpu takes the stale entry, which crashed"); + assert_eq!(choose(&adapters, power), Some(1)); + } + // whichever version the loader lists first + let mut newer_first = adapters.clone(); + newer_first.swap(0, 1); + assert_eq!(choose(&newer_first, HighPerformance), Some(0)); + // two entries exposing as much: wgpu's, the first + let mut equal = adapters.clone(); + if let Some(c) = equal.get_mut(1) { + c.features = 60; + } + assert_eq!(choose(&equal, HighPerformance), Some(0)); + // three versions: the one exposing the most + let mut three = adapters.clone(); + three.insert(1, gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", "AMD proprietary driver", "24.1.1", 64)); + assert_eq!(choose(&three, HighPerformance), Some(2)); + // the stale entries are avoided, the newest is not + assert!(avoided(&three, 0) && avoided(&three, 1) && !avoided(&three, 2)); + } + + #[test] + fn an_entry_without_a_bus_between_two_cards_is_never_drawn_with_when_avoided() { + // two cards of one model on their own buses, and an entry of the same driver without a bus + // id, which can be either card's other version + let radeon = |bus, features| gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, bus, "AMD proprietary driver", "", features); + let adapters = vec![radeon("0000:03:00.0", 60), radeon("", 70), radeon("0000:04:00.0", 80)]; + for power in POWERS { + let chosen = choose(&adapters, power); + assert_eq!(chosen, Some(2), "{power:?}"); + assert!(chosen.is_some_and(|i| !avoided(&adapters, i)), "{power:?}"); + } + assert!(avoided(&adapters, 0) && avoided(&adapters, 1) && !avoided(&adapters, 2)); + } + + #[test] + fn a_newer_version_never_overtakes_another_gpu_or_backend() { + assert_eq!(choose(&two_amd_drivers(), LowPower), Some(2)); + let mut dx12_first = two_amd_drivers(); + dx12_first.rotate_left(3); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(choose(&dx12_first, power), Some(0)); + } + assert_eq!(choose(&dx12_first, LowPower), wgpu_choice(&dx12_first, LowPower)); + } + + #[test] + fn without_two_versions_of_one_driver_the_choice_is_wgpus() { + let nvidia = |backend, bus, driver, features| gpu("NVIDIA GeForce RTX 4070", backend, DiscreteGpu, 0x10de, 0x2786, bus, driver, "", features); + let intel = + |backend, bus, driver, features| gpu("Intel(R) UHD Graphics 770", backend, IntegratedGpu, 0x8086, 0x4680, bus, driver, "", features); + let radeon = |bus, driver, features| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, AMD, 0x744c, bus, driver, "", features); + let gl = |name: &str, features| gpu(name, Gl, Other, 0, 0, "", "", "", features); + let without = |skip: usize| two_amd_drivers().into_iter().enumerate().filter(|(i, _)| *i != skip).map(|(_, c)| c).collect::>(); + let listings: Vec> = vec![ + vec![], + vec![nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // a laptop with two GPUs, through Vulkan and DirectX 12 + vec![ + intel(Vulkan, "0000:00:02.0", "Intel Corporation", 60), + nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70), + nvidia(Dx12, "0000:01:00.0", "32.0.15.6094", 36), + intel(Dx12, "0000:00:02.0", "31.0.101.5186", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.1", "", 36), + ], + // one GPU through two different drivers: Linux with AMDVLK and RADV + vec![radeon("0000:03:00.0", "AMD open-source driver", 58), radeon("0000:03:00.0", "radv", 71)], + // a vendor's driver and Dozen (Vulkan on DirectX 12) + vec![nvidia(Vulkan, "", "Dozen", 75), nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // two cards of one model, on their own buses + vec![radeon("0000:03:00.0", "AMD proprietary driver", 60), radeon("0000:04:00.0", "AMD proprietary driver", 68)], + // OpenGL reports no ids: two adapters cannot be told apart + vec![gl("ANGLE", 20), gl("ANGLE", 30)], + vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)], + without(0), + without(1), + ]; + for adapters in &listings { + for power in POWERS { + assert_eq!(choose(adapters, power), wgpu_choice(adapters, power), "{power:?} over {adapters:#?}"); + } + } + assert_eq!(choose(&[], HighPerformance), None); + } + + /// An Intel UHD Graphics 630 (Coffee Lake) on driver 25.20.100.6576 as wgpu 30 lists it. A + /// Vulkan device on it ended inside `igvk64.dll` (0xc0000005) as it was created. + pub(crate) fn uhd_630() -> Vec { + vec![ + gpu("Intel(R) UHD Graphics 630", Vulkan, IntegratedGpu, INTEL, 0x3e91, "", "Intel Corporation", "Intel driver", 44), + gpu("Intel(R) UHD Graphics 630", Dx12, IntegratedGpu, INTEL, 0x3e91, "0000:00:02.0", "25.20.100.6576", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9711", "", 36), + ] + } + + fn uhd_630_as(name: &str, device: u32) -> Vec { + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { name: name.into(), device, ..c } } else { c }).collect() + } + + #[test] + fn an_intel_gen9_to_gen11_gpu_draws_through_directx_12() { + for power in POWERS { + assert_eq!(wgpu_choice(&uhd_630(), power), Some(0), "wgpu takes Vulkan, which crashed"); + assert_eq!(choose(&uhd_630(), power), Some(1), "{power:?}"); + } + for (name, device) in [("Intel(R) HD Graphics 520", 0x1916), ("Intel(R) Iris(R) Plus Graphics", 0x8a5a)] { + assert_eq!(choose(&uhd_630_as(name, device), HighPerformance), Some(1), "{name}"); + } + let mut dx12_first = uhd_630(); + dx12_first.swap(0, 1); + assert_eq!(choose(&dx12_first, HighPerformance), Some(0)); + // without a usable DirectX 12 entry, the Vulkan entry is still never drawn with + let vulkan_only: Vec = uhd_630().into_iter().take(1).collect(); + assert_eq!(choose(&vulkan_only, HighPerformance), None); + assert!(avoided(&vulkan_only, 0)); + let mut dx12_unusable = uhd_630(); + if let Some(c) = dx12_unusable.get_mut(1) { + c.usable = false; + } + assert_eq!(choose(&dx12_unusable, HighPerformance), Some(2), "the software adapter"); + // Mesa's Vulkan driver for the same GPU on Linux is drawn with + let mesa = vec![gpu( + "Intel(R) UHD Graphics 630 (CFL GT2)", + Vulkan, + IntegratedGpu, + INTEL, + 0x3e91, + "0000:00:02.0", + "Intel open-source Mesa driver", + "Mesa 25.2.4", + 44, + )]; + assert_eq!(choose(&mesa, HighPerformance), Some(0)); + assert!(!avoided(&mesa, 0)); + // beside a discrete GPU: high performance keeps it; low power takes the Intel GPU's DirectX 12 entry + let mut laptop = uhd_630(); + laptop.insert(1, gpu("NVIDIA GeForce MX250", Vulkan, DiscreteGpu, 0x10de, 0x1d13, "0000:01:00.0", "NVIDIA", "", 70)); + assert_eq!(choose(&laptop, HighPerformance), Some(1)); + assert_eq!(choose(&laptop, LowPower), Some(2)); + assert!(avoided(&laptop, 0)); + } + + #[test] + fn later_intel_gpus_keep_wgpus_choice() { + for (name, device) in [("Intel(R) Iris(R) Xe Graphics", 0x9a49), ("Intel(R) UHD Graphics 770", 0x4680), ("Intel(R) Arc(TM) Graphics", 0x7d55)] + { + let adapters = uhd_630_as(name, device); + for power in POWERS { + assert_eq!(choose(&adapters, power), Some(0), "{name} {power:?}"); + } + } + let discrete: Vec = + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { device_type: DiscreteGpu, ..c } } else { c }).collect(); + assert_eq!(choose(&discrete, HighPerformance), Some(0)); + } + + #[test] + fn gen9_to_gen11_ids() { + for id in [0x1916, 0x0a84, 0x5a85, 0x3184, 0x5917, 0x87c0, 0x3e91, 0x3ea0, 0x9b41, 0x5a52, 0x8a5a, 0x4571, 0x4e61] { + assert!(intel_gen9_to_gen11(id), "{id:#06x}"); + } + for id in [0x0a16, 0x0a1e, 0x1616, 0x9a49, 0x4c8a, 0x4680, 0x46a6, 0xa780, 0x4905, 0x56a0, 0x7d55, 0x64a0, 0xe20b, 0xb080] { + assert!(!intel_gen9_to_gen11(id), "{id:#06x}"); + } + } + + #[test] + fn two_entries_are_one_gpu_only_with_the_same_ids_type_driver_and_bus() { + let stale = two_amd_drivers().swap_remove(0); + let newer = two_amd_drivers().swap_remove(1); + assert!(same_gpu_and_driver(&stale, &newer) && same_gpu_and_driver(&stale, &stale)); + let on_bus = |bus: &str| Candidate { pci_bus_id: bus.into(), ..newer.clone() }; + assert!(same_gpu_and_driver(&stale, &on_bus("0000:03:00.0"))); + assert!(same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:03:00.0"))); + assert!(!same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:04:00.0"))); + for other in [ + Candidate { backend: Dx12, ..newer.clone() }, + Candidate { device_type: IntegratedGpu, ..newer.clone() }, + Candidate { vendor: 0x10de, ..newer.clone() }, + Candidate { device: RADEON_IGPU, ..newer.clone() }, + Candidate { driver: "radv".into(), ..newer.clone() }, + ] { + assert!(!same_gpu_and_driver(&stale, &other), "{other}"); + } + let unidentified = Candidate { vendor: 0, device: 0, ..newer }; + assert!(!same_gpu_and_driver(&unidentified, &unidentified)); + } + + #[test] + fn adapters_that_cannot_draw_to_the_window_are_left_out() { + let unusable = |which: &dyn Fn(usize, &Candidate) -> bool| { + let mut adapters = two_amd_drivers(); + for (i, c) in adapters.iter_mut().enumerate() { + c.usable = !which(i, c); + } + adapters + }; + assert_eq!(choose(&unusable(&|i, _| i == 1), HighPerformance), Some(0)); + assert_eq!(choose(&unusable(&|i, _| i == 0), HighPerformance), Some(1)); + assert_eq!(choose(&unusable(&|_, c| c.backend == Vulkan), HighPerformance), Some(3)); + assert_eq!(choose(&unusable(&|_, _| true), HighPerformance), None); + } + + #[test] + fn candidates_describe_themselves_for_the_log() { + let adapters = two_amd_drivers(); + let text = adapters.get(1).map(ToString::to_string).unwrap_or_default(); + assert_eq!( + text, + "\"AMD Radeon RX 6800M\" (Vulkan, discrete GPU, driver AMD proprietary driver 26.9.2 (AMD proprietary shader compiler), 68 features)" + ); + let offscreen = adapters.get(4).map(|c| Candidate { usable: false, ..c.clone() }.to_string()).unwrap_or_default(); + assert_eq!( + offscreen, + "\"AMD Radeon(TM) Graphics\" (Dx12, integrated GPU, driver 30.0.13002.13003, 36 features, bus 0000:08:00.0, cannot draw to the window)" + ); + assert!(adapters.get(5).is_some_and(Candidate::is_software)); + assert!(!adapters.first().is_some_and(Candidate::is_software)); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn native_instance_is_shared_across_callers() { + let gate = std::sync::Barrier::new(3); + std::thread::scope(|scope| { + let first = scope.spawn(|| { + gate.wait(); + native_instance() + }); + let second = scope.spawn(|| { + gate.wait(); + native_instance() + }); + gate.wait(); + let first = first.join().unwrap(); + assert_eq!(first, second.join().unwrap()); + assert_eq!(first, native_instance()); + }); + } + + /// The instance reads wgpu's flag variables and keeps its own backends whatever `WGPU_BACKEND` + /// says. Runs in a child process, which has them set. + #[test] + fn native_descriptor_reads_wgpu_flags_but_keeps_its_backends() { + const CHILD: &str = "CRAFT_GPU_DEVICE_TEST_NATIVE_DESCRIPTOR_CHILD"; + if std::env::var_os(CHILD).is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "adapter::tests::native_descriptor_reads_wgpu_flags_but_keeps_its_backends", "--nocapture"]) + .env(CHILD, "1") + .env("WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER", "1") + .env("WGPU_BACKEND", "gl") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "{stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + return; + } + let desc = native_descriptor(); + assert!(desc.flags.contains(wgpu::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER), "{:?}", desc.flags); + let backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + assert_eq!(desc.backends, backends); + } + + /// Against the adapters of the machine running the tests: [`wgpu_choice`] is what wgpu's + /// `request_adapter` returns, and [`choose`] returns that adapter too, or, when wgpu's choice + /// is one [`avoided`] excludes, an adapter it does not exclude: a version exposing more + /// features, an Intel Gen 9 to Gen 11 GPU's DirectX 12 entry, or the best other adapter. + /// `None` only when every usable adapter is that Intel Vulkan entry. Passes without adapters. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn on_this_host_the_choice_is_wgpus_unless_a_correction_applies() { + let backends = wgpu::Backends::PRIMARY; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle() }); + let adapters = pollster::block_on(instance.enumerate_adapters(backends)); + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, None)).collect(); + for power in POWERS { + let options = wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() }; + let wgpu_own = pollster::block_on(instance.request_adapter(&options)).ok().map(|a| Candidate::of(&a, None)); + assert_eq!(wgpu_choice(&candidates, power).and_then(|i| candidates.get(i)), wgpu_own.as_ref(), "{power:?} over {candidates:#?}"); + let own_index = wgpu_choice(&candidates, power); + let chosen = choose(&candidates, power); + let picked = chosen.and_then(|i| candidates.get(i)); + match (own_index, chosen) { + (Some(own), Some(index)) if own != index => { + assert!(avoided(&candidates, own), "{power:?}: {picked:?} instead of {wgpu_own:?}, which is not avoided"); + assert!(!avoided(&candidates, index), "{power:?}: {picked:?} is avoided"); + } + (Some(own), None) => { + let only_intel_vulkan = candidates.iter().filter(|c| c.usable).all(intel_vulkan_crashes); + assert!(only_intel_vulkan, "{power:?}: nothing instead of {:?}", candidates.get(own)); + } + _ => assert_eq!(picked, wgpu_own.as_ref(), "{power:?}"), + } + } + } +} diff --git a/crates/gpu-device/src/caps.rs b/crates/gpu-device/src/caps.rs new file mode 100644 index 0000000000..ea72379bbe --- /dev/null +++ b/crates/gpu-device/src/caps.rs @@ -0,0 +1,311 @@ +//! What an adapter can do, for choosing a pipeline and for the settings and the log. + +use std::fmt; +use std::ops::Deref; + +use craft_gpu::DeviceCaps; +use wgpu::{AdapterInfo, DeviceType, Features, Limits}; + +/// The maker of a GPU, from its PCI vendor id (or the Khronos vendor id some Vulkan drivers +/// report instead). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Vendor { + Nvidia, + Amd, + Intel, + Apple, + Qualcomm, + Arm, + ImgTec, + /// Microsoft's software adapter (WARP) and its virtual GPUs. + Microsoft, + /// Mesa's software drivers (llvmpipe, lavapipe). + Mesa, + /// Another id, or none (0). + Other(u32), +} + +impl Vendor { + pub fn from_id(id: u32) -> Vendor { + match id { + 0x10de => Vendor::Nvidia, + 0x1002 | 0x1022 => Vendor::Amd, + 0x8086 => Vendor::Intel, + 0x106b => Vendor::Apple, + 0x5143 => Vendor::Qualcomm, + 0x13b5 => Vendor::Arm, + 0x1010 => Vendor::ImgTec, + 0x1414 => Vendor::Microsoft, + 0x10005 => Vendor::Mesa, + other => Vendor::Other(other), + } + } +} + +impl fmt::Display for Vendor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + Vendor::Nvidia => "NVIDIA", + Vendor::Amd => "AMD", + Vendor::Intel => "Intel", + Vendor::Apple => "Apple", + Vendor::Qualcomm => "Qualcomm", + Vendor::Arm => "Arm", + Vendor::ImgTec => "Imagination", + Vendor::Microsoft => "Microsoft", + Vendor::Mesa => "Mesa", + Vendor::Other(0) => return f.write_str("unknown vendor"), + Vendor::Other(id) => return write!(f, "vendor {id:#06x}"), + }; + f.write_str(name) + } +} + +/// What a device (or an adapter) can do, read from the [`DeviceCaps`] a `craft-gpu` context +/// reports. It holds only that `DeviceCaps`: the video formats, `f16` and timestamps come from its +/// feature names, the vendor from its vendor id, and its fields (the name, the backend and the +/// limits) can be read through `Deref`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Capabilities(DeviceCaps); + +impl Capabilities { + /// From an adapter's (or a device's) info, features and limits. + pub fn from_parts(info: &AdapterInfo, features: Features, limits: &Limits) -> Self { + Capabilities(device_caps_of(info, features, limits)) + } + + /// What `adapter` offers, for a settings page before a device is opened. A `craft-gpu` + /// context reports [`of_device`](Self::of_device) instead: a device can be granted less. + pub fn of_adapter(adapter: &wgpu::Adapter) -> Self { + Self::from_parts(&adapter.get_info(), adapter.features(), &adapter.limits()) + } + + /// What `device` can do: the features and limits it was opened with. + pub fn of_device(device: &wgpu::Device) -> Self { + Self::from_parts(&device.adapter_info(), device.features(), &device.limits()) + } + + /// The `DeviceCaps` these capabilities read. + pub fn device_caps(&self) -> &DeviceCaps { + &self.0 + } + + pub fn into_device_caps(self) -> DeviceCaps { + self.0 + } + + /// Whether every feature in `features` is named in the caps. + fn has(&self, features: Features) -> bool { + features.iter_names().all(|(name, _)| self.0.has_feature(name)) + } + + /// NV12 textures (8-bit 4:2:0, a luma plane and an interleaved chroma plane) can be created + /// and sampled through plane views. wgpu 30 does not render to them: draw the planes into + /// `R8Unorm` and `Rg8Unorm` textures instead. + pub fn nv12(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_NV12) + } + + /// P010 textures (10 bits in 16-bit words, 4:2:0) can be created and sampled through plane + /// views. wgpu 30 does not render to them: draw the planes into `R16Unorm` and `Rg16Unorm` + /// textures ([`norm16`](Self::norm16)) instead. + pub fn p010(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_P010) + } + + /// `R16Unorm`, `Rg16Unorm` and `Rgba16Unorm` textures, for 10-bit and higher planes without + /// P010. + pub fn norm16(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_16BIT_NORM) + } + + /// `f16` in shaders. + pub fn shader_f16(&self) -> bool { + self.has(Features::SHADER_F16) + } + + /// Timestamp queries, for measuring GPU time per pass. + pub fn timestamps(&self) -> bool { + self.has(Features::TIMESTAMP_QUERY) + } + + pub fn vendor(&self) -> Vendor { + Vendor::from_id(self.0.vendor_id) + } + + /// The adapter draws on the CPU. + pub fn software(&self) -> bool { + self.0.software + } + + /// Whether a `width` × `height` texture fits. + pub fn fits(&self, width: u32, height: u32) -> bool { + let max = self.0.max_texture_dimension_2d; + width > 0 && height > 0 && width <= max && height <= max + } + + /// Whether 10-bit planes can be drawn: 16-bit normalized textures. P010 textures can only be + /// sampled. + pub fn ten_bit(&self) -> bool { + self.norm16() + } + + /// The features from `wanted` this adapter has, to ask for when opening a device. + pub fn available(adapter_features: Features, wanted: Features) -> Features { + adapter_features & wanted + } +} + +impl Deref for Capabilities { + type Target = DeviceCaps; + + fn deref(&self) -> &DeviceCaps { + &self.0 + } +} + +impl From for Capabilities { + fn from(caps: DeviceCaps) -> Self { + Capabilities(caps) + } +} + +impl From for DeviceCaps { + fn from(caps: Capabilities) -> Self { + caps.0 + } +} + +impl fmt::Display for Capabilities { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({}, {}", self.0.device_name, self.vendor(), self.0.backend_name)?; + if self.software() { + f.write_str(", software")?; + } + let flags = [ + (self.nv12(), "NV12"), + (self.p010(), "P010"), + (self.norm16(), "16-bit norm"), + (self.shader_f16(), "f16"), + (self.timestamps(), "timestamps"), + ]; + for (on, name) in flags { + if on { + write!(f, ", {name}")?; + } + } + write!(f, ", textures up to {} px)", self.0.max_texture_dimension_2d) + } +} + +/// The [`DeviceCaps`] a `craft-gpu` context reports for `device`: the limits and features the +/// device was opened with, not the adapter's, in the same form `craft-gpu-wgpu` reports for a +/// device it opens itself. +pub fn device_caps(device: &wgpu::Device) -> DeviceCaps { + Capabilities::of_device(device).into_device_caps() +} + +fn device_caps_of(info: &AdapterInfo, features: Features, limits: &Limits) -> DeviceCaps { + DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name.clone(), + max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, + max_buffer_size: limits.max_buffer_size, + max_texture_dimension_2d: limits.max_texture_dimension_2d, + features: features.iter_names().map(|(name, _)| name.to_string()).collect(), + vendor_id: info.vendor, + software: info.device_type == DeviceType::Cpu, + } +} + +#[cfg(test)] +mod tests { + use wgpu::Backend; + + use super::*; + + fn info(name: &str, vendor: u32, device_type: DeviceType) -> AdapterInfo { + AdapterInfo { name: name.into(), vendor, ..AdapterInfo::new(device_type, Backend::Vulkan) } + } + + #[test] + fn vendors_from_pci_and_khronos_ids() { + assert_eq!(Vendor::from_id(0x10de), Vendor::Nvidia); + assert_eq!(Vendor::from_id(0x1002), Vendor::Amd); + assert_eq!(Vendor::from_id(0x8086), Vendor::Intel); + assert_eq!(Vendor::from_id(0x10005), Vendor::Mesa); + assert_eq!(Vendor::from_id(0x1414), Vendor::Microsoft); + assert_eq!(Vendor::from_id(0), Vendor::Other(0)); + assert_eq!(Vendor::Other(0).to_string(), "unknown vendor"); + assert_eq!(Vendor::from_id(0x1234).to_string(), "vendor 0x1234"); + } + + #[test] + fn features_and_limits_become_capabilities() { + let features = Features::TEXTURE_FORMAT_NV12 | Features::TEXTURE_FORMAT_16BIT_NORM | Features::TIMESTAMP_QUERY; + let limits = Limits { max_texture_dimension_2d: 16384, ..Limits::default() }; + let c = Capabilities::from_parts(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); + assert!(c.nv12() && !c.p010() && c.norm16() && c.timestamps() && !c.shader_f16() && !c.software()); + assert!(c.ten_bit()); + assert_eq!(c.vendor(), Vendor::Nvidia); + assert!(c.fits(7680, 4320) && c.fits(16384, 16384)); + assert!(!c.fits(16385, 1) && !c.fits(0, 1080) && !c.fits(1920, 0)); + assert_eq!(c.to_string(), "\"NVIDIA GeForce RTX 4070\" (NVIDIA, Vulkan, NV12, 16-bit norm, timestamps, textures up to 16384 px)"); + } + + #[test] + fn a_software_adapter_without_extras() { + let limits = Limits::downlevel_defaults(); + let c = Capabilities::from_parts(&info("llvmpipe (LLVM 19.1.0, 256 bits)", 0x10005, DeviceType::Cpu), Features::empty(), &limits); + assert!(c.software() && !c.ten_bit() && !c.nv12()); + // P010 alone is sampled, not drawn to + let p010 = Capabilities::from_parts(&info("x", 0x8086, DeviceType::IntegratedGpu), Features::TEXTURE_FORMAT_P010, &limits); + assert!(p010.p010() && !p010.ten_bit()); + assert_eq!(c.max_texture_dimension_2d, 2048); + assert!(!c.fits(3840, 2160)); + assert!(c.to_string().contains("software")); + let wanted = Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16; + assert_eq!(Capabilities::available(Features::SHADER_F16 | Features::TIMESTAMP_QUERY, wanted), Features::SHADER_F16); + } + + #[test] + fn device_caps_carry_the_device_limits_and_feature_names() { + let limits = + Limits { max_texture_dimension_2d: 16384, max_buffer_size: 1 << 30, max_storage_buffer_binding_size: 1 << 28, ..Limits::default() }; + let features = Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY; + let caps = device_caps_of(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); + assert_eq!(caps.backend_name, "Vulkan"); + assert_eq!(caps.device_name, "NVIDIA GeForce RTX 4070"); + assert_eq!((caps.max_texture_dimension_2d, caps.max_buffer_size, caps.max_storage_buffer_binding_size), (16384, 1 << 30, 1 << 28)); + assert_eq!((caps.vendor_id, caps.software), (0x10de, false)); + let mut names = caps.features.clone(); + names.sort(); + assert_eq!(names, ["TEXTURE_FORMAT_NV12", "TIMESTAMP_QUERY"]); + // a device opened without features reports none + let bare = device_caps_of(&info("llvmpipe", 0x10005, DeviceType::Cpu), Features::empty(), &Limits::downlevel_defaults()); + assert!(bare.features.is_empty()); + assert_eq!(bare.max_texture_dimension_2d, 2048); + assert_eq!((bare.vendor_id, bare.software), (0x10005, true)); + } + + #[test] + fn caps_from_a_craft_gpu_context_read_as_capabilities() { + let caps = DeviceCaps { + backend_name: "Dx12".into(), + device_name: "Intel(R) Arc(TM) A770".into(), + features: vec!["TEXTURE_FORMAT_P010".into(), "SHADER_F16".into(), "TEXTURE_FORMAT_16BIT_NORM".into()], + vendor_id: 0x8086, + ..DeviceCaps::default() + }; + let c = Capabilities::from(caps.clone()); + assert!(c.p010() && c.shader_f16() && c.ten_bit() && !c.nv12() && !c.timestamps() && !c.software()); + assert_eq!(c.vendor(), Vendor::Intel); + assert_eq!(c.to_string(), "\"Intel(R) Arc(TM) A770\" (Intel, Dx12, P010, 16-bit norm, f16, textures up to 8192 px)"); + assert_eq!(DeviceCaps::from(c), caps); + // the caps of a backend with no device claim nothing + let none = Capabilities::from(DeviceCaps::default()); + assert!(!none.nv12() && !none.p010() && !none.norm16() && !none.shader_f16() && !none.timestamps() && !none.software()); + assert_eq!(none.vendor(), Vendor::Other(0)); + } +} diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs new file mode 100644 index 0000000000..9374175a6b --- /dev/null +++ b/crates/gpu-device/src/health.rs @@ -0,0 +1,764 @@ +//! Device health: notices a lost wgpu device or an uncaptured wgpu error, so callers stop issuing +//! GPU work and reopen a device or fall back, instead of panicking. +//! +//! wgpu's default uncaptured-error handler panics, and `Device::poll` panics on a lost device +//! whatever the handler. [`DeviceHealth::watch`] replaces the handler with one that records the +//! fault and registers the device-lost callback, and the polls here run only while the device is +//! healthy, catching the poll's panic as a last resort. Every GPU entry point checks +//! [`DeviceHealth::fault`] first. +//! +//! Builds for the web too: the callbacks only touch atomics and a mutex. + +use std::fmt; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; + +#[cfg(not(target_arch = "wasm32"))] +use std::time::{Duration, Instant}; + +/// Outcome of a bounded wait for submitted GPU work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WaitOutcome { + /// The submitted work finished before the deadline, or just after it, when wgpu read the + /// fence again at the end of the last poll. + Finished, + /// The deadline passed (or the device faulted) before the work finished. + TimedOut, + /// The caller canceled the wait before the work finished. + Canceled, +} + +/// Why the GPU cannot be used any more. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fault { + /// The device was lost (driver reset, the OS ended a submission, `Device::destroy`). + Lost(String), + /// An uncaptured wgpu error (out of memory, validation, internal): the GPU output cannot be + /// trusted, and on most drivers the device is about to be lost anyway. + Error(String), +} + +impl Fault { + /// Whether the device itself was lost (rather than an error reported). + pub fn is_lost(&self) -> bool { + matches!(self, Fault::Lost(_)) + } + + /// An out-of-memory error on a device that still works: freeing memory, calling + /// [`DeviceHealth::clear_out_of_memory`] with the count read from + /// [`DeviceHealth::out_of_memory_count`] and trying again can succeed, unlike after a loss or + /// a validation error. Polls and waits keep running meanwhile. Only wgpu's own out-of-memory + /// error is recorded with exactly [`OUT_OF_MEMORY`]; a validation error that mentions memory + /// is not one. + pub fn is_out_of_memory(&self) -> bool { + matches!(self, Fault::Error(s) if s == OUT_OF_MEMORY) + } + + /// The driver's or wgpu's message. + pub fn detail(&self) -> &str { + match self { + Fault::Lost(s) | Fault::Error(s) => s, + } + } +} + +impl fmt::Display for Fault { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Fault::Lost(s) if s.is_empty() => f.write_str("GPU device lost"), + Fault::Lost(s) => write!(f, "GPU device lost: {s}"), + Fault::Error(s) => write!(f, "GPU error: {s}"), + } + } +} + +/// A loss becomes [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost), and any other +/// fault becomes [`GpuFault::Operation`](craft_gpu::GpuFault::Operation), each with the fault's +/// text. +impl From for craft_gpu::GpuFault { + fn from(fault: Fault) -> Self { + match fault { + Fault::Lost(s) => craft_gpu::GpuFault::DeviceLost(s), + Fault::Error(s) => craft_gpu::GpuFault::Operation(s), + } + } +} + +/// The message an out-of-memory [`Fault::Error`] carries (wgpu's `Error::OutOfMemory`). +pub const OUT_OF_MEMORY: &str = "Out of Memory"; + +/// The state wgpu's callbacks write and callers read, without a lock: flags in atomics and each +/// fault's text in a [`OnceLock`], whose `get` does not wait. A `set` that races another `set` +/// of the same slot waits only for that one store. +#[derive(Default)] +struct Inner { + /// The first device loss. + lost: OnceLock, + /// Out-of-memory errors seen. + out_of_memory_seen: AtomicU64, + /// Out-of-memory errors the caller cleared ([`DeviceHealth::clear_out_of_memory`]). + out_of_memory_cleared: AtomicU64, + /// The first other error. + error: OnceLock, + errors: AtomicU64, + /// wgpu itself reported the device lost (see [`DeviceHealth::device_lost`]). + device_lost: AtomicBool, +} + +/// Shared health flag of one wgpu device. Cheap to clone; every clone sees the same state. +#[derive(Clone, Default)] +pub struct DeviceHealth(Arc); + +impl fmt::Debug for DeviceHealth { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DeviceHealth").field("fault", &self.fault()).field("errors", &self.errors()).finish() + } +} + +impl DeviceHealth { + /// A healthy flag not attached to a device (tests, CPU-only callers). + pub fn new() -> Self { + Self::default() + } + + /// Watch `device`: its device-lost callback and uncaptured errors mark the returned flag + /// instead of panicking. Replaces any handler set before (wgpu keeps one of each). On the + /// browser backend, wgpu 30 panics on an uncaptured `GPUInternalError` before this handler + /// runs, so such an error is not recorded; validation and out-of-memory errors are. + pub fn watch(device: &wgpu::Device) -> Self { + let health = Self::new(); + let lost = health.clone(); + // Called by wgpu with its own locks held: only record, never call back into wgpu. + device.set_device_lost_callback(move |reason, message| { + let detail = match (reason, message.is_empty()) { + (wgpu::DeviceLostReason::Destroyed, true) => "device destroyed".to_string(), + (_, true) => "lost by the driver".to_string(), + (_, false) => message, + }; + log::error!("wgpu device lost ({reason:?}): {detail}"); + // The loss first: a caller that sees `device_lost` then also sees the fault. + lost.mark(Fault::Lost(detail)); + lost.0.device_lost.store(true, Ordering::Release); + }); + let errors = health.clone(); + device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e))); + health + } + + /// Record an uncaptured wgpu error. + fn uncaptured(&self, e: &wgpu::Error) { + self.0.errors.fetch_add(1, Ordering::Relaxed); + log::error!("uncaptured wgpu error: {e}"); + self.mark(fault_of(e)); + } + + /// Record an error an error scope caught. + /// + /// The uncaptured-error handler never sees a scoped error, so without this a watched device + /// would keep being handed work after it failed. Polls first: a lost device is a + /// [`Fault::Lost`], and its callback may not have run yet (it runs on a poll). The poll does + /// not block. + pub fn caught(&self, device: &wgpu::Device, error: &wgpu::Error) { + if self.lost() { + return; + } + #[cfg(not(target_arch = "wasm32"))] + self.poll(device); + #[cfg(target_arch = "wasm32")] + let _ = device; + if self.lost() { + return; + } + self.mark(fault_of(error)); + } + + fn lost(&self) -> bool { + self.fault().is_some_and(|f| f.is_lost()) + } + + /// Mark the device unusable. The first fault is kept; a later device loss replaces an error, + /// and a later out-of-memory error is reported over another error, so a caller still sees + /// that freeing memory may help after a validation error in the same frame. + pub fn mark(&self, fault: Fault) { + if fault.is_out_of_memory() { + self.0.out_of_memory_seen.fetch_add(1, Ordering::AcqRel); + return; + } + // A slot already set keeps its first text. + let _ = match fault { + Fault::Lost(text) => self.0.lost.set(text), + Fault::Error(text) => self.0.error.set(text), + }; + } + + /// Out-of-memory errors recorded so far. Read it when handling an out-of-memory fault, and + /// pass it to [`clear_out_of_memory`](Self::clear_out_of_memory) once memory was freed. + pub fn out_of_memory_count(&self) -> u64 { + self.0.out_of_memory_seen.load(Ordering::Acquire) + } + + /// Clear the out-of-memory errors up to `count` (from + /// [`out_of_memory_count`](Self::out_of_memory_count)) after the caller freed memory. One + /// recorded after `count` was read stays. The device counts as healthy again unless it was + /// lost or another error was recorded, which [`fault`](Self::fault) then reports. + pub fn clear_out_of_memory(&self, count: u64) { + let count = count.min(self.0.out_of_memory_seen.load(Ordering::Acquire)); + self.0.out_of_memory_cleared.fetch_max(count, Ordering::AcqRel); + } + + /// Whether an out-of-memory error is recorded and not cleared. + fn out_of_memory(&self) -> bool { + let cleared = self.0.out_of_memory_cleared.load(Ordering::Acquire); + self.0.out_of_memory_seen.load(Ordering::Acquire) > cleared + } + + /// Whether the device may still be used: no fault was recorded, or only out-of-memory errors + /// that [`clear_out_of_memory`](Self::clear_out_of_memory) cleared. + pub fn is_ok(&self) -> bool { + self.0.lost.get().is_none() && self.0.error.get().is_none() && !self.out_of_memory() + } + + /// Whether polls and waits still run: the device was not lost and reported no error other + /// than out of memory. A poll reclaims the staging memory that recovering from an + /// out-of-memory error needs. + fn pollable(&self) -> bool { + self.0.lost.get().is_none() && self.0.error.get().is_none() + } + + /// Why the device cannot be used, if it cannot. + pub fn fault(&self) -> Option { + if let Some(text) = self.0.lost.get() { + return Some(Fault::Lost(text.clone())); + } + if self.out_of_memory() { + return Some(Fault::Error(OUT_OF_MEMORY.into())); + } + self.0.error.get().map(|text| Fault::Error(text.clone())) + } + + /// The device loss in the form of `craft_gpu::GpuContext::device_status`: + /// [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost) once a loss is recorded, + /// otherwise `Ok`. Other errors are reported by [`fault`](Self::fault). wgpu keeps one + /// device-lost callback per device, so a `craft-gpu` context on a device that + /// [`watch`](Self::watch) watches reads the loss here instead of setting its own callback. + pub fn device_status(&self) -> Result<(), craft_gpu::GpuFault> { + match self.0.lost.get() { + Some(text) => Err(craft_gpu::GpuFault::DeviceLost(text.clone())), + None => Ok(()), + } + } + + /// Uncaptured wgpu errors seen so far. + pub fn errors(&self) -> u64 { + self.0.errors.load(Ordering::Relaxed) + } + + /// Whether wgpu itself reported the device lost: its device-lost callback ran, or polling it + /// panicked. A fault recorded with [`mark`](Self::mark) is not one. After a real loss nothing + /// drawn with the device reaches the screen, the window's own frames included. + pub fn device_lost(&self) -> bool { + self.0.device_lost.load(Ordering::Acquire) + } + + /// Non-blocking poll that runs even after a fault was recorded, so a device that is lost + /// later (a driver reset while the app sat idle, or the PC slept) is noticed before the next + /// frame is drawn with it. Skipped once [`device_lost`](Self::device_lost). + pub fn probe(&self, device: &wgpu::Device) { + if self.device_lost() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// `Device::poll` panicked: wgpu found the device lost. + fn lost_by_poll(&self) { + self.mark(Fault::Lost("the device stopped responding".into())); + self.0.device_lost.store(true, Ordering::Release); + } + + /// Block until the work up to `index` finished, unless the device was lost or reported an + /// error other than out of memory. To wait for everything submitted so far, pass the index of + /// an empty submission (`queue.submit([])`); work submitted after it does not extend the + /// wait. Returns whether the work finished with the device still usable: `false` when it was + /// lost or reported such an error, before or during the wait, and when the poll itself + /// failed, so the work may still be running. After an out-of-memory error the wait still + /// runs. The wait has no deadline, but it polls in slices of at most 100 ms, so a loss or an + /// error other than out of memory that another clone records while the work has not finished + /// ends it after the current slice. A panic in `Device::poll` is caught and recorded as a + /// loss. Native only: the web has no blocking wait. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex) -> bool { + const SLICE: Duration = Duration::from_millis(100); + self.wait_unbounded(|| { + let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(SLICE) }) + })); + match poll { + Ok(Ok(_)) => SlicePoll::Done, + Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending, + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + SlicePoll::Failed + } + Err(_) => { + self.lost_by_poll(); + SlicePoll::Failed + } + } + }) + } + + /// [`Self::wait`]'s loop: `poll` runs one slice and reports what wgpu returned. The loop ends + /// when a slice finished or failed, and before the next slice once a clone of this flag + /// recorded a loss or an error other than out of memory. + #[cfg(not(target_arch = "wasm32"))] + fn wait_unbounded(&self, mut poll: impl FnMut() -> SlicePoll) -> bool { + loop { + if !self.pollable() { + return false; + } + match poll() { + SlicePoll::Done => return self.pollable(), + SlicePoll::Pending => {} + SlicePoll::Failed => return false, + } + } + } + + /// Non-blocking poll (reclaims staging memory), skipped once the device was lost or reported + /// an error other than out of memory. + pub fn poll(&self, device: &wgpu::Device) { + if !self.pollable() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// Like [`Self::wait`], but bounded: returns whether the work up to `index` finished within + /// `timeout`. To wait for everything submitted so far, pass the index of an empty submission + /// (`queue.submit([])`); work submitted after it does not extend the wait. A timeout marks the + /// device faulted, so later work stops going to a GPU that no longer answers. A submission + /// index the device never issued returns `false` and leaves the device healthy. A zero + /// `timeout`, or one that passes before the first poll, returns `false` and leaves the device + /// healthy. A device that was already lost, or that reported an error other than out of + /// memory, returns `false` unchanged. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex, timeout: Duration) -> bool { + self.wait_timeout_cancelable(device, index, timeout, &|| false) == WaitOutcome::Finished + } + + /// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between + /// them, keeping the same overall deadline. Every slice waits for the same `index`. A slice + /// that times out means the work has not finished yet; only the overall deadline (or a poll + /// that panics) marks the device faulted. A loss or an error other than out of memory that + /// another clone records during the wait ends it after the current slice, with + /// [`WaitOutcome::TimedOut`]. wgpu reads the fence again after a slice's own timeout, so work + /// that finishes in that gap, just after the deadline, is [`WaitOutcome::Finished`]. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout_cancelable( + &self, + device: &wgpu::Device, + index: wgpu::SubmissionIndex, + timeout: Duration, + canceled: &(dyn Fn() -> bool + Sync), + ) -> WaitOutcome { + if !self.pollable() { + return WaitOutcome::TimedOut; + } + let mut wrong_index = false; + let mut polled = false; + let start = Instant::now(); + let elapsed = || start.elapsed(); + let outcome = wait_slices(timeout, canceled, elapsed, |slice| { + polled = true; + let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(slice) }) + })); + match poll { + Ok(Ok(_)) => self.after_slice(true), + Ok(Err(wgpu::PollError::Timeout)) => self.after_slice(false), + // A submission index the device never issued: the caller's mistake, not the GPU's. + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + wrong_index = true; + SlicePoll::Failed + } + Err(_) => { + self.lost_by_poll(); + SlicePoll::Failed + } + } + }); + // A deadline that passed before the first poll says nothing about the device. + if outcome == WaitOutcome::TimedOut && polled && !wrong_index && self.pollable() { + self.mark(Fault::Lost(format!("GPU wait timed out after {:.1} s", timeout.as_secs_f64()))); + } + outcome + } + + /// What a slice that returned reports, `finished` or not: failed once a clone of this flag + /// recorded a loss or an error other than out of memory, so the next slice does not poll a + /// device that is not to be used. + #[cfg(not(target_arch = "wasm32"))] + fn after_slice(&self, finished: bool) -> SlicePoll { + if !self.pollable() { + SlicePoll::Failed + } else if finished { + SlicePoll::Done + } else { + SlicePoll::Pending + } + } +} + +/// What one bounded poll reported. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SlicePoll { + Done, + Pending, + Failed, +} + +/// Wait for `total`, polling in slices no longer than 100 ms and checking `canceled` between +/// them. `elapsed` gives the time since the wait started. A slice that times out is pending, not +/// a failure; only the overall deadline or a failed poll ends the wait early. +#[cfg(not(target_arch = "wasm32"))] +fn wait_slices( + total: Duration, + canceled: &(dyn Fn() -> bool + Sync), + mut elapsed: impl FnMut() -> Duration, + mut poll: impl FnMut(Duration) -> SlicePoll, +) -> WaitOutcome { + const SLICE: Duration = Duration::from_millis(100); + loop { + if canceled() { + return WaitOutcome::Canceled; + } + let remaining = total.saturating_sub(elapsed()); + if remaining.is_zero() { + return WaitOutcome::TimedOut; + } + match poll(remaining.min(SLICE)) { + SlicePoll::Done => return WaitOutcome::Finished, + SlicePoll::Pending => {} + SlicePoll::Failed => return WaitOutcome::TimedOut, + } + } +} + +/// The whole message of wgpu's `DeviceError::Lost`. +const LOST_CAUSE: &str = "Parent device is lost"; + +/// Whether one of the errors that caused `e` (its `source` chain) is wgpu's `DeviceError::Lost`: +/// an error whose whole message is [`LOST_CAUSE`]. A resource label is part of another error's +/// message, so a label never matches. +fn caused_by_loss(e: &wgpu::Error) -> bool { + let source: &(dyn std::error::Error + 'static) = match e { + wgpu::Error::Validation { source, .. } | wgpu::Error::Internal { source, .. } => source.as_ref(), + _ => return false, + }; + std::iter::successors(Some(source), |c| c.source()).any(|c| c.to_string().trim().eq_ignore_ascii_case(LOST_CAUSE)) +} + +/// The fault a wgpu error stands for. An error caused by a lost device ([`caused_by_loss`]) +/// follows a device loss whose callback may not have run yet (it runs on the next poll), so it +/// counts as a loss rather than as an error. An error about a destroyed buffer or texture is an +/// error. Only wgpu's own out-of-memory error is [`OUT_OF_MEMORY`]. The text keeps the causes +/// ([`one_line`]). +fn fault_of(e: &wgpu::Error) -> Fault { + let text = e.to_string(); + if matches!(e, wgpu::Error::OutOfMemory { .. }) { + Fault::Error(OUT_OF_MEMORY.into()) + } else if caused_by_loss(e) { + Fault::Lost(one_line(&text)) + } else { + Fault::Error(one_line(&text)) + } +} + +/// wgpu's multi-line error text on one line: the heading and each cause, joined with ": ", +/// without wgpu's "Caused by:" line, cut to 200 characters. +fn one_line(s: &str) -> String { + const MAX: usize = 200; + let mut out = String::new(); + let mut count = 0; + let lines = s.lines().map(str::trim).filter(|l| !l.is_empty() && !l.eq_ignore_ascii_case("Caused by:")); + for (i, line) in lines.enumerate() { + let separator = if i == 0 { "" } else { ": " }; + for c in separator.chars().chain(line.chars()) { + if count == MAX { + out.push('…'); + return out; + } + out.push(c); + count += 1; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn first_fault_wins_but_loss_replaces_an_error() { + let h = DeviceHealth::new(); + assert!(h.is_ok()); + assert_eq!(h.fault(), None); + h.mark(Fault::Error("out of memory".into())); + assert!(!h.is_ok()); + let c = h.clone(); + c.mark(Fault::Error("second".into())); + assert_eq!(h.fault(), Some(Fault::Error("out of memory".into()))); + c.mark(Fault::Lost("reset".into())); + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + c.mark(Fault::Lost("later".into())); + assert_eq!(h.fault().map(|f| f.to_string()).as_deref(), Some("GPU device lost: reset")); + // a recorded loss is not wgpu reporting the device lost + assert!(!h.device_lost()); + } + + #[test] + fn faults_in_the_craft_gpu_form() { + use craft_gpu::GpuFault; + let h = DeviceHealth::new(); + assert_eq!(h.device_status(), Ok(())); + // an error, out of memory included, is not a loss + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + h.mark(Fault::Error("Validation Error".into())); + assert_eq!(h.device_status(), Ok(())); + h.mark(Fault::Lost("reset".into())); + assert_eq!(h.device_status(), Err(GpuFault::DeviceLost("reset".into()))); + assert_eq!(GpuFault::from(Fault::Lost("reset".into())), GpuFault::DeviceLost("reset".into())); + assert_eq!(GpuFault::from(Fault::Error(OUT_OF_MEMORY.into())), GpuFault::Operation(OUT_OF_MEMORY.into())); + assert_eq!(h.fault().map(GpuFault::from), Some(GpuFault::DeviceLost("reset".into()))); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_cancel_timeout_and_completion() { + let never = || false; + // a clock that does not move: only the polls end these waits + let still = || Duration::ZERO; + assert_eq!(wait_slices(Duration::ZERO, &never, still, |_| SlicePoll::Done), WaitOutcome::TimedOut); + assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Done), WaitOutcome::Finished); + assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Failed), WaitOutcome::TimedOut); + + let mut polls = 0; + let outcome = wait_slices(Duration::from_secs(1), &never, still, |_| { + polls += 1; + if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } + }); + assert_eq!(outcome, WaitOutcome::Finished); + assert_eq!(polls, 3, "a timed-out slice is retried, not treated as a failure"); + + let canceled = || true; + let mut called = false; + assert_eq!( + wait_slices(Duration::from_secs(1), &canceled, still, |_| { + called = true; + SlicePoll::Done + }), + WaitOutcome::Canceled + ); + assert!(!called, "cancellation is checked before polling"); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_end_at_the_deadline_of_a_moving_clock() { + let never = || false; + let now = std::cell::Cell::new(Duration::ZERO); + let mut slices = Vec::new(); + let clock = || now.get(); + let outcome = wait_slices(Duration::from_millis(250), &never, clock, |slice| { + slices.push(slice); + now.set(now.get() + slice); + SlicePoll::Pending + }); + assert_eq!(outcome, WaitOutcome::TimedOut); + assert_eq!(slices, [Duration::from_millis(100), Duration::from_millis(100), Duration::from_millis(50)]); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_observes_cancel_while_pending() { + let flag = AtomicBool::new(false); + let canceled = || flag.load(Ordering::SeqCst); + let mut polls = 0; + let still = || Duration::ZERO; + let outcome = wait_slices(Duration::from_secs(1), &canceled, still, |_| { + polls += 1; + flag.store(true, Ordering::SeqCst); + SlicePoll::Pending + }); + assert_eq!(outcome, WaitOutcome::Canceled); + assert_eq!(polls, 1, "a cancel set during a pending poll ends the wait"); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_fault_recorded_during_a_wait_stops_the_next_slice() { + let h = DeviceHealth::new(); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + assert_eq!(h.after_slice(true), SlicePoll::Done); + // out of memory alone: polls keep reclaiming memory + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + // another clone records a validation error while a slice is pending + h.clone().mark(Fault::Error("Validation Error".into())); + assert_eq!(h.after_slice(false), SlicePoll::Failed, "the next slice must not poll"); + assert_eq!(h.after_slice(true), SlicePoll::Failed); + let lost = DeviceHealth::new(); + lost.clone().mark(Fault::Lost("reset".into())); + assert_eq!(lost.after_slice(false), SlicePoll::Failed); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_fault_recorded_during_an_unbounded_wait_ends_it() { + let h = DeviceHealth::new(); + let other = h.clone(); + let mut polls = 0; + let finished = h.wait_unbounded(|| { + polls += 1; + if polls == 2 { + other.mark(Fault::Error("Validation Error".into())); + } + assert!(polls <= 2, "a slice ran after the fault"); + SlicePoll::Pending + }); + assert!(!finished); + assert_eq!(polls, 2); + // out of memory alone keeps the wait going until the work finishes + let oom = DeviceHealth::new(); + oom.mark(Fault::Error(OUT_OF_MEMORY.into())); + let mut polls = 0; + assert!(oom.wait_unbounded(|| { + polls += 1; + if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } + })); + assert_eq!(polls, 3); + assert!(!DeviceHealth::new().wait_unbounded(|| SlicePoll::Failed)); + } + + #[test] + fn fault_text() { + assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost"); + assert_eq!(Fault::Error("x".into()).to_string(), "GPU error: x"); + assert_eq!(one_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid: more"); + assert_eq!(one_line(&"a".repeat(300)).chars().count(), 201); + assert_eq!(one_line(&"a".repeat(200)), "a".repeat(200)); + assert_eq!(one_line(&format!("{}\nb", "a".repeat(199))), format!("{}:…", "a".repeat(199))); + assert!(Fault::Error("Out of Memory".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error: buffer allocation would run out of memory".into()).is_out_of_memory()); + let h = DeviceHealth::new(); + h.mark(Fault::Error("Validation Error".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_out_of_memory())); + h.mark(Fault::Lost("reset".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_lost())); + assert!(!Fault::Lost("out of memory".into()).is_out_of_memory()); + } + + #[test] + fn out_of_memory_keeps_polls_running_until_cleared() { + let h = DeviceHealth::new(); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.is_ok()); + assert!(h.pollable(), "polls reclaim the memory that recovery needs"); + let seen = h.out_of_memory_count(); + // one recorded while the caller freed memory is not cleared with the earlier ones + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + h.clear_out_of_memory(seen); + assert!(h.fault().is_some_and(|f| f.is_out_of_memory())); + h.clear_out_of_memory(h.out_of_memory_count()); + assert!(h.is_ok()); + assert_eq!(h.fault(), None); + // a count larger than the ones recorded does not hide later errors + h.clear_out_of_memory(u64::MAX); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.is_ok()); + h.clear_out_of_memory(h.out_of_memory_count()); + // an earlier error is still there once the out-of-memory error is cleared + h.mark(Fault::Error("Validation Error".into())); + assert!(!h.pollable()); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.pollable(), "a later out-of-memory error does not undo the earlier error"); + h.clear_out_of_memory(h.out_of_memory_count()); + assert_eq!(h.fault(), Some(Fault::Error("Validation Error".into()))); + assert!(!h.is_ok() && !h.pollable()); + let lost = DeviceHealth::new(); + lost.mark(Fault::Error(OUT_OF_MEMORY.into())); + lost.mark(Fault::Lost("reset".into())); + assert!(!lost.pollable()); + } + + #[test] + fn marks_from_several_threads_keep_the_loss() { + let h = DeviceHealth::new(); + let threads: Vec<_> = (0..8) + .map(|i| { + let h = h.clone(); + std::thread::spawn(move || h.mark(if i == 5 { Fault::Lost("reset".into()) } else { Fault::Error(format!("e{i}")) })) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + } + + /// An error and the errors that caused it, outermost first, as wgpu-core chains them. + #[derive(Debug)] + struct Cause(&'static str, Option>); + + impl fmt::Display for Cause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.0) + } + } + + impl std::error::Error for Cause { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.1.as_deref().map(|c| c as _) + } + } + + /// A validation error with the causes `chain` and wgpu's description of them. + fn validation(chain: &[&'static str]) -> wgpu::Error { + let source = chain.iter().rev().fold(None, |inner, text| Some(Box::new(Cause(text, inner)))); + let mut description = String::from("Validation Error\n\nCaused by:\n"); + for c in chain { + description.push_str(&format!(" {c}\n")); + } + wgpu::Error::Validation { source: source.unwrap_or_else(|| Box::new(Cause("", None))), description } + } + + #[test] + fn only_a_lost_device_counts_as_a_loss() { + let lost = validation(&["In Device::create_buffer", "Parent device is lost"]); + assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost)); + let destroyed = validation(&["In Queue::submit", "Buffer 'pc' has been destroyed"]); + // the stored text names what failed, not only wgpu's heading + assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error: In Queue::submit: Buffer 'pc' has been destroyed".into())); + assert_eq!(fault_of(&lost), Fault::Lost("Validation Error: In Device::create_buffer: Parent device is lost".into())); + let texture = validation(&["Texture with 'frame' label has been destroyed"]); + assert!(!fault_of(&texture).is_lost()); + // a label is the caller's text, not the cause, even on a line of its own + let labeled = validation(&["In Queue::submit", "Buffer 'device is lost' has been destroyed"]); + assert_eq!(fault_of(&labeled), Fault::Error("Validation Error: In Queue::submit: Buffer 'device is lost' has been destroyed".into())); + for label in ["Buffer 'Parent device is lost' has been destroyed", "Buffer 'a\nParent device is lost\nb' has been destroyed"] { + let labeled = validation(&["In Queue::submit", label]); + assert!(!fault_of(&labeled).is_lost(), "{label:?}"); + } + } +} diff --git a/crates/gpu-device/src/lib.rs b/crates/gpu-device/src/lib.rs new file mode 100644 index 0000000000..a2988b90d2 --- /dev/null +++ b/crates/gpu-device/src/lib.rs @@ -0,0 +1,43 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Choosing and opening a wgpu device for a Craft app. +//! +//! - [`list`] gives every adapter as plain [`Candidate`] data for a settings page, and +//! [`AdapterKey`] identifies one across runs. +//! - [`select`] and [`ranked`] choose an adapter for a [`Preference`] (Auto, low power, a named +//! adapter, software) with wgpu's own rule and two corrections for drivers that crash +//! ([`choose`]); [`Notice`] says when the choice was not the one asked for. +//! - [`open`] opens a device, moving to the next adapter and last to a software one when a device +//! fails to open. [`pick`] fits egui-wgpu's adapter selector for a window. `list` and `open` +//! block on wgpu's futures and are native only; [`list_async`] and [`open_async`] are the same +//! as futures, for a `wasm32` web worker as well as native. +//! - In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be +//! chosen, and wgpu 30 cannot ask for the browser's fallback (software) adapter. `open_async` +//! asks for the adapter with [`Preference::power`]. [`Capabilities`] and [`Recovery`] work +//! there as they do on native, and so does [`DeviceHealth`] apart from its blocking waits, +//! which are native only. +//! - [`Capabilities`] reads what the device can do (NV12 and P010 textures, 16-bit norm formats, +//! `f16`, timestamps, the vendor, a software adapter, sizes) from the `craft_gpu::DeviceCaps` +//! it holds, which [`device_caps`] and [`Opened::device_caps`] give for a `craft-gpu` context. +//! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and +//! [`Recovery`] says what to open after a loss. [`DeviceHealth::device_status`] reports a loss +//! as `craft_gpu::GpuFault::DeviceLost`, and a [`Fault`] converts to a `craft_gpu::GpuFault`. +//! +//! The selection functions are pure, so tests run without a GPU. + +mod adapter; +mod caps; +mod health; +mod open; +mod preference; +mod recovery; + +pub use adapter::{Candidate, choose, intel_gen9_to_gen11, native_descriptor, native_instance}; +pub use caps::{Capabilities, Vendor, device_caps}; +pub use health::{DeviceHealth, Fault, OUT_OF_MEMORY, WaitOutcome}; +pub use open::{OpenError, Opened, Request, list_async, open_async, pick}; +#[cfg(not(target_arch = "wasm32"))] +pub use open::{list, open}; +pub use preference::{AdapterKey, Notice, Preference, Selection, backend_name, ranked, select}; +pub use recovery::{Recovery, RecoveryPolicy, RecoveryStep}; diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs new file mode 100644 index 0000000000..cb55cdfcc3 --- /dev/null +++ b/crates/gpu-device/src/open.rs @@ -0,0 +1,474 @@ +//! Listing adapters and opening a device, trying the next adapter when one fails. + +use std::fmt; + +use wgpu::{Adapter, Features, Instance, Limits, Surface}; + +use crate::adapter::{Candidate, avoided, log_choice}; +use crate::caps::Capabilities; +use crate::health::DeviceHealth; +use crate::preference::{Notice, Preference, Selection, asked_for, ranked, select}; + +/// What the device is opened with. +#[derive(Clone, Debug, Default)] +pub struct Request<'a> { + pub label: Option<&'a str>, + /// Features the device must have. An adapter without them is skipped. + pub required_features: Features, + /// Features asked for when the adapter has them. Experimental features + /// (`Features::all_experimental_mask`) are left out here: the device descriptor does not + /// enable experimental features, and wgpu refuses a device that asks for one without that. + pub optional_features: Features, + /// The limits to ask for; `None` asks for the adapter's own limits. An adapter whose limits + /// are lower is skipped. + pub limits: Option, +} + +/// An opened device. +#[derive(Debug)] +pub struct Opened { + pub adapter: Adapter, + pub device: wgpu::Device, + pub queue: wgpu::Queue, + /// The adapter as plain data. + pub candidate: Candidate, + /// What the device was opened with, as the `craft_gpu::DeviceCaps` it reports. + pub caps: Capabilities, + /// Watches the device for a loss and for uncaptured errors. + pub health: DeviceHealth, + /// What to tell the user about the choice. + pub notices: Vec, +} + +impl Opened { + /// The device's [`DeviceCaps`](craft_gpu::DeviceCaps) for a `craft-gpu` context + /// ([`device_caps`](crate::device_caps)). + pub fn device_caps(&self) -> craft_gpu::DeviceCaps { + self.caps.device_caps().clone() + } +} + +/// Why no device could be opened. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OpenError { + /// No adapter is listed that can draw (to the surface, when there is one). + NoAdapter, + /// Every adapter tried failed to open a device; each failure is a [`Notice::DeviceFailed`]. + NoDevice(Vec), + /// The only adapters that can draw are ones [`choose`](crate::choose) never draws with, + /// because their driver can end the process; these are their names. + UnsafeDriver(Vec), +} + +impl fmt::Display for OpenError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + OpenError::NoAdapter => f.write_str("no graphics adapter is available"), + OpenError::NoDevice(notices) => { + f.write_str("no graphics adapter could be opened")?; + for n in notices { + if let Notice::DeviceFailed { adapter, error } = n { + write!(f, "; \"{adapter}\": {error}")?; + } + } + Ok(()) + } + OpenError::UnsafeDriver(names) => { + let names = names.iter().map(|n| format!("\"{n}\"")).collect::>().join(", "); + write!(f, "the only graphics adapters that can draw ({names}) use a driver that can crash; update the graphics driver") + } + } + } +} + +impl std::error::Error for OpenError {} + +/// Every adapter `instance` lists over its backends, as adapters and as plain data. `surface` +/// marks the adapters that cannot draw to it as unusable. Native only: it blocks on wgpu's +/// future, which on the web would wait on the thread that must resolve it. [`list_async`] works +/// on both. +#[cfg(not(target_arch = "wasm32"))] +pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { + pollster::block_on(list_async(instance, surface)) +} + +/// [`list`] as a future, for a `wasm32` web worker as well as native. In a browser, WebGPU offers +/// one adapter for a power preference, and the list holds the high-performance one, which +/// [`open_async`] opens for `Auto` and for a named adapter. +pub async fn list_async(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { + #[cfg(not(target_arch = "wasm32"))] + let adapters = instance.enumerate_adapters(wgpu::Backends::all()).await; + #[cfg(target_arch = "wasm32")] + let adapters = browser_adapter(instance, surface, wgpu::PowerPreference::HighPerformance).await; + let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + (adapters, candidates) +} + +/// The adapter a browser offers for `power`, if any. +#[cfg(target_arch = "wasm32")] +async fn browser_adapter(instance: &Instance, surface: Option<&Surface<'_>>, power: wgpu::PowerPreference) -> Vec { + let options = wgpu::RequestAdapterOptions { power_preference: power, compatible_surface: surface, ..Default::default() }; + instance.request_adapter(&options).await.into_iter().collect() +} + +/// The adapter to draw with for `preference`, from adapters already listed, with the choice in the +/// log. This fits egui-wgpu's `native_adapter_selector` for a window, which then opens the device +/// itself; that selector takes a `String` error, so convert with `map_err(|e| e.to_string())`. +/// With no usable adapter the error is [`OpenError::UnsafeDriver`] when only adapters that +/// [`choose`](crate::choose) never draws with can draw, and [`OpenError::NoAdapter`] otherwise, +/// with the listed adapters in the log. +pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), OpenError> { + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + let Some(selection) = select(&candidates, preference) else { + return Err(unselected(&candidates)); + }; + log_choice(&candidates, selection.index, preference.power()); + for notice in &selection.notices { + log::warn!("{notice}"); + } + let adapter = adapters.get(selection.index).cloned().ok_or(OpenError::NoAdapter)?; + Ok((adapter, selection)) +} + +/// The error for `candidates` among which `select` found no adapter, with the list in the log +/// when it is not [`OpenError::UnsafeDriver`]. +fn unselected(candidates: &[Candidate]) -> OpenError { + let left_out = left_out(candidates); + if !left_out.is_empty() { + return OpenError::UnsafeDriver(left_out); + } + let listed = candidates.iter().map(ToString::to_string).collect::>().join(", "); + log::warn!("no usable graphics adapter among {}: {listed}", candidates.len()); + OpenError::NoAdapter +} + +/// Open a device for `preference`: the selected adapter first, then the others in [`ranked`] +/// order, and last wgpu's fallback adapter (a software one) when none of those opened. An adapter +/// without `request.required_features`, or whose device fails to open, adds a +/// [`Notice::DeviceFailed`] and the next one is tried. Native only, like [`list`]; [`open_async`] +/// works on both. +#[cfg(not(target_arch = "wasm32"))] +pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference, request: &Request<'_>) -> Result { + pollster::block_on(open_async(instance, surface, preference, request)) +} + +/// [`open`] as a future, for a `wasm32` web worker as well as native. On native it lists every +/// adapter, as `open` does. In a browser, WebGPU offers one adapter for a power preference, so +/// `open_async` asks for the adapter with [`Preference::power`]. A named adapter then gives the +/// automatic choice with [`Notice::AdapterMissing`]. wgpu 30 does not pass the fallback-adapter +/// option to the browser, so [`Preference::Software`] gives the browser's adapter with +/// [`Notice::NoSoftwareAdapter`] unless that adapter is itself a software one. +pub async fn open_async( + instance: &Instance, + surface: Option<&Surface<'_>>, + preference: &Preference, + request: &Request<'_>, +) -> Result { + let (adapters, candidates) = adapters_for(instance, surface, preference).await; + // Whether drawing is in software depends on the adapter that opens, which `finish` knows. + let mut notices: Vec = + select(&candidates, preference).map(|s| s.notices).unwrap_or_default().into_iter().filter(|n| *n != Notice::SoftwareOnly).collect(); + let order = ranked(&candidates, preference); + if let Some(first) = order.first() { + log_choice(&candidates, *first, preference.power()); + } + let mut tried: Vec<&Candidate> = Vec::new(); + for index in order { + let (Some(adapter), Some(candidate)) = (adapters.get(index), candidates.get(index)) else { + continue; + }; + tried.push(candidate); + match open_on(adapter, request).await { + Ok((device, queue)) => return Ok(finish(adapter.clone(), device, queue, candidate.clone(), preference, notices)), + Err(error) => { + log::warn!("graphics adapter {candidate} could not be opened: {error}"); + notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }); + } + } + } + // wgpu's fallback adapter, unless the loop above already tried it. In a browser the request + // below would ask for the same adapter again. + if cfg!(not(target_arch = "wasm32")) { + let options = wgpu::RequestAdapterOptions { force_fallback_adapter: true, compatible_surface: surface, ..Default::default() }; + let fallback = instance.request_adapter(&options).await.ok().map(|a| (Candidate::of(&a, surface), a)); + if let Some((candidate, adapter)) = fallback.filter(|(c, _)| !tried.contains(&c)) { + match open_on(&adapter, request).await { + Ok((device, queue)) => { + log::info!("graphics adapter chosen: {candidate}"); + return Ok(finish(adapter, device, queue, candidate, preference, notices)); + } + Err(error) => notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }), + } + } + } + if notices.iter().any(|n| matches!(n, Notice::DeviceFailed { .. })) { + return Err(OpenError::NoDevice(notices)); + } + let left_out = left_out(&candidates); + if left_out.is_empty() { Err(OpenError::NoAdapter) } else { Err(OpenError::UnsafeDriver(left_out)) } +} + +/// The names of the adapters that can draw but that [`choose`](crate::choose) never draws with. +fn left_out(candidates: &[Candidate]) -> Vec { + candidates.iter().enumerate().filter(|(i, c)| c.usable && avoided(candidates, *i)).map(|(_, c)| c.name.clone()).collect() +} + +/// The adapters `open_async` chooses among: every listed one on native, and in a browser the one +/// it offers for the preference's power. +async fn adapters_for(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference) -> (Vec, Vec) { + #[cfg(not(target_arch = "wasm32"))] + { + let _ = preference; + list_async(instance, surface).await + } + #[cfg(target_arch = "wasm32")] + { + let adapters = browser_adapter(instance, surface, preference.power()).await; + let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + (adapters, candidates) + } +} + +fn finish( + adapter: Adapter, + device: wgpu::Device, + queue: wgpu::Queue, + candidate: Candidate, + preference: &Preference, + mut notices: Vec, +) -> Opened { + let caps = Capabilities::of_device(&device); + // wgpu's fallback adapter can be a software one that the listing did not show. + if candidate.is_software() { + notices.retain(|n| *n != Notice::NoSoftwareAdapter); + } + if candidate.is_software() && !asked_for(preference, &candidate) { + notices.push(Notice::SoftwareOnly); + } + for notice in ¬ices { + log::warn!("{notice}"); + } + log::info!("graphics device opened: {caps}"); + let health = DeviceHealth::watch(&device); + Opened { adapter, device, queue, candidate, caps, health, notices } +} + +/// Open a device on `adapter`, or say why it cannot be. +async fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> { + let has = adapter.features(); + if !has.contains(request.required_features) { + return Err(format!("it lacks the features {:?}", request.required_features - has)); + } + let required_limits = request.limits.clone().unwrap_or_else(|| adapter.limits()); + let desc = wgpu::DeviceDescriptor { + label: request.label, + required_features: request.required_features | (request.optional_features & has & !Features::all_experimental_mask()), + required_limits, + ..Default::default() + }; + adapter.request_device(&desc).await.map_err(|e| e.to_string()) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use crate::preference::AdapterKey; + + /// An instance whose only adapter is wgpu's noop one, which opens devices without a GPU. wgpu + /// 30 lists it as a software adapter whatever `NoopBackendOptions::device_type` says. + fn noop(features: Option) -> Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, features, ..Default::default() }; + Instance::new(desc) + } + + #[test] + fn a_device_opens_with_the_optional_features_the_adapter_has() { + let instance = noop(Some(Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY)); + let request = Request { optional_features: Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12(), "{}", opened.caps); + assert!(!opened.caps.shader_f16() && !opened.caps.timestamps(), "only the features asked for: {}", opened.caps); + assert!(opened.notices.is_empty(), "{:?}", opened.notices); + assert!(opened.health.is_ok()); + // the craft-gpu caps name only the features the device was opened with + let caps = opened.device_caps(); + assert_eq!(caps.features, ["TEXTURE_FORMAT_NV12"]); + assert_eq!(&caps, opened.caps.device_caps()); + assert_eq!(caps, crate::device_caps(&opened.device)); + assert_eq!(caps.max_texture_dimension_2d, opened.device.limits().max_texture_dimension_2d); + assert!(caps.software && caps.vendor_id == opened.candidate.vendor, "{caps:?}"); + assert_eq!(opened.health.device_status(), Ok(())); + } + + #[test] + fn open_async_opens_as_open_does() { + let instance = noop(Some(Features::TEXTURE_FORMAT_P010)); + let request = Request { optional_features: Features::TEXTURE_FORMAT_P010 | Features::SHADER_F16, ..Default::default() }; + let opened = pollster::block_on(open_async(&instance, None, &Preference::Auto, &request)).unwrap(); + let blocking = open(&instance, None, &Preference::Auto, &request).unwrap(); + assert!(opened.caps.p010() && !opened.caps.shader_f16(), "{}", opened.caps); + assert_eq!(opened.caps, blocking.caps); + assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); + assert_eq!(opened.notices, blocking.notices); + let (adapters, candidates) = pollster::block_on(list_async(&instance, None)); + assert_eq!((adapters.len(), candidates), (1, list(&instance, None).1)); + // the same errors + let missing = Request { required_features: Features::SHADER_F16, ..Default::default() }; + let err = pollster::block_on(open_async(&instance, None, &Preference::Auto, &missing)).unwrap_err(); + assert!(matches!(&err, OpenError::NoDevice(n) if n.len() == 1), "{err}"); + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + let none = Instance::new(desc); + assert_eq!(pollster::block_on(open_async(&none, None, &Preference::Auto, &Request::default())).unwrap_err(), OpenError::NoAdapter); + } + + #[test] + fn a_software_device_drops_the_no_software_notice() { + let instance = noop(None); + let opened = open(&instance, None, &Preference::Software, &Request::default()).unwrap(); + assert!(opened.candidate.is_software()); + // as when the listing showed no software adapter and wgpu's fallback adapter opened + let notices = vec![Notice::NoSoftwareAdapter]; + let again = finish(opened.adapter, opened.device, opened.queue, opened.candidate, &Preference::Software, notices); + assert!(again.notices.is_empty(), "{:?}", again.notices); + } + + #[test] + fn an_optional_experimental_feature_does_not_stop_the_device_opening() { + let instance = noop(Some(Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12)); + let request = Request { optional_features: Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12(), "{}", opened.caps); + assert!(!opened.device.features().contains(Features::EXPERIMENTAL_RAY_QUERY)); + // a required one still fails as before + let required = Request { required_features: Features::EXPERIMENTAL_RAY_QUERY, ..Default::default() }; + assert!(matches!(open(&instance, None, &Preference::Software, &required), Err(OpenError::NoDevice(_)))); + } + + #[test] + fn an_adapter_without_a_required_feature_is_reported() { + let instance = noop(Some(Features::empty())); + let request = Request { required_features: Features::SHADER_F16, ..Default::default() }; + let err = open(&instance, None, &Preference::Auto, &request).unwrap_err(); + let OpenError::NoDevice(notices) = &err else { panic!("{err}") }; + assert!(notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } if error.contains("SHADER_F16"))), "{notices:?}"); + assert!(err.to_string().starts_with("no graphics adapter could be opened"), "{err}"); + } + + #[test] + fn an_adapter_below_the_requested_limits_is_reported() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, limits: Some(Limits::default()), ..Default::default() }; + let instance = Instance::new(desc); + let over = Limits::default().max_texture_dimension_2d + 1; + let request = Request { limits: Some(Limits { max_texture_dimension_2d: over, ..Limits::default() }), ..Default::default() }; + let err = open(&instance, None, &Preference::Software, &request).unwrap_err(); + let OpenError::NoDevice(notices) = &err else { panic!("{err}") }; + assert!( + notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } + if error.contains("max_texture_dimension_2d"))), + "{notices:?}" + ); + // limits within the adapter's still open + let within = Request { limits: Some(Limits::downlevel_defaults()), ..Default::default() }; + assert!(open(&instance, None, &Preference::Software, &within).is_ok()); + } + + #[test] + fn a_software_adapter_is_reported_unless_it_was_asked_for() { + let cpu = noop(None); + let opened = open(&cpu, None, &Preference::Auto, &Request::default()).unwrap(); + assert!(opened.caps.software()); + assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); + let asked = open(&cpu, None, &Preference::Software, &Request::default()).unwrap(); + assert!(asked.notices.is_empty(), "{:?}", asked.notices); + // the software adapter picked by name is what was asked for + let named = open(&cpu, None, &Preference::Adapter(AdapterKey::of(&asked.candidate)), &Request::default()).unwrap(); + assert!(named.notices.is_empty(), "{:?}", named.notices); + // a named adapter that is gone: the automatic choice, with both notices + let gone = + AdapterKey { name: "gone".into(), backend: "vulkan".into(), vendor: 0x10de, device: 1, pci_bus_id: String::new(), driver: String::new() }; + let opened = open(&cpu, None, &Preference::Adapter(gone.clone()), &Request::default()).unwrap(); + assert_eq!(opened.notices, vec![Notice::AdapterMissing(gone), Notice::SoftwareOnly]); + } + + #[test] + fn no_adapter_is_an_error() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + let instance = Instance::new(desc); + assert_eq!(open(&instance, None, &Preference::Auto, &Request::default()).unwrap_err(), OpenError::NoAdapter); + assert_eq!(OpenError::NoAdapter.to_string(), "no graphics adapter is available"); + assert_eq!( + OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()]).to_string(), + "the only graphics adapters that can draw (\"Intel(R) UHD Graphics 630\") use a driver that can crash; update the graphics driver" + ); + assert_eq!(pick(&[], None, &Preference::Auto).unwrap_err(), OpenError::NoAdapter); + } + + #[test] + fn pick_says_when_only_a_driver_that_can_crash_can_draw() { + let vulkan_only: Vec = crate::adapter::tests::uhd_630().into_iter().take(1).collect(); + assert_eq!(select(&vulkan_only, &Preference::Auto), None); + assert_eq!(unselected(&vulkan_only), OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()])); + assert_eq!(unselected(&[]), OpenError::NoAdapter); + } + + #[test] + fn a_zero_timeout_leaves_a_healthy_device_healthy() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let everything = opened.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, everything.clone(), std::time::Duration::ZERO)); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + assert!(opened.health.wait_timeout(&opened.device, everything, std::time::Duration::from_secs(5))); + // an index from another device's queue is one this device never issued + let other = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + other.queue.submit([]); + let index = other.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, index, std::time::Duration::from_secs(5))); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + } + + #[test] + fn waits_run_after_an_out_of_memory_error() { + use crate::health::{Fault, OUT_OF_MEMORY}; + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let health = opened.health.clone(); + health.mark(Fault::Error(OUT_OF_MEMORY.into())); + let index = opened.queue.submit([]); + assert!(health.wait(&opened.device, index.clone()), "{health:?}"); + assert!(health.wait_timeout(&opened.device, index.clone(), std::time::Duration::from_secs(5)), "{health:?}"); + health.clear_out_of_memory(health.out_of_memory_count()); + assert!(health.is_ok(), "{health:?}"); + // any other error still stops them + health.mark(Fault::Error("Validation Error".into())); + assert!(!health.wait(&opened.device, index)); + } + + #[test] + fn a_lost_device_is_seen_by_its_health() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let health = opened.health.clone(); + let index = opened.queue.submit([]); + opened.device.destroy(); + health.probe(&opened.device); + assert!(health.fault().is_some_and(|f| f.is_lost()), "{health:?}"); + assert!(!health.is_ok()); + assert!(matches!(health.device_status(), Err(craft_gpu::GpuFault::DeviceLost(_))), "{health:?}"); + // a later wait does not touch the lost device + assert!(!health.wait(&opened.device, index)); + } + + #[test] + fn pick_returns_the_selected_adapter() { + let instance = noop(None); + let (adapters, candidates) = list(&instance, None); + assert_eq!(candidates.len(), 1); + let (adapter, selection) = pick(&adapters, None, &Preference::Auto).unwrap(); + assert_eq!(selection.index, 0); + assert_eq!(Candidate::of(&adapter, None), candidates[0]); + } +} diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs new file mode 100644 index 0000000000..542bf66305 --- /dev/null +++ b/crates/gpu-device/src/preference.rs @@ -0,0 +1,422 @@ +//! The adapter the user asked for, and what was drawn with instead when it is not there. + +use std::fmt; + +use wgpu::{Backend, PowerPreference}; + +use crate::adapter::{Candidate, avoided, choose, intel_vulkan_crashes, settled, type_order}; + +/// Which adapter to draw with. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", tag = "kind"))] +pub enum Preference { + /// The fastest adapter: a discrete GPU before an integrated one, hardware before software. + #[default] + Auto, + /// An integrated GPU before a discrete one, for battery life. + LowPower, + /// One adapter the user picked from [`crate::list`]. + Adapter(AdapterKey), + /// A software adapter that draws on the CPU. + Software, +} + +impl Preference { + /// The power preference that orders the adapters for this preference: low power for + /// [`Preference::LowPower`], high performance otherwise. + pub fn power(&self) -> PowerPreference { + match self { + Preference::LowPower => PowerPreference::LowPower, + _ => PowerPreference::HighPerformance, + } + } +} + +/// What identifies an adapter across runs: the backend, the PCI ids and bus, the driver name, and +/// the name. The order in which the system lists adapters can change between runs, so an index +/// cannot be kept. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", default))] +pub struct AdapterKey { + pub name: String, + /// wgpu's lowercase backend name (`vulkan`, `dx12`, `metal`, `gl`). + pub backend: String, + pub vendor: u32, + pub device: u32, + /// Empty when the driver reports none. + pub pci_bus_id: String, + /// The Vulkan driver's name, which tells apart two Vulkan drivers for one GPU (such as two on + /// Linux) and stays the same across versions of a driver. Empty on the other backends, and + /// when the driver reports none. + pub driver: String, +} + +impl AdapterKey { + pub fn of(candidate: &Candidate) -> Self { + AdapterKey { + name: candidate.name.clone(), + backend: backend_name(candidate.backend).to_string(), + vendor: candidate.vendor, + device: candidate.device, + pci_bus_id: candidate.pci_bus_id.clone(), + // DirectX 12 reports the driver's version here, which changes with every update. + driver: if candidate.backend == Backend::Vulkan { candidate.driver.clone() } else { String::new() }, + } + } + + /// Whether `candidate` is this adapter: the same backend and PCI ids, the same bus and the + /// same driver when both report one, and the same name when the backend reports no PCI ids. + pub fn matches(&self, candidate: &Candidate) -> bool { + let identified = self.vendor != 0 || self.device != 0; + let same = |a: &str, b: &str| a.is_empty() || b.is_empty() || a == b; + self.backend == backend_name(candidate.backend) + && self.vendor == candidate.vendor + && self.device == candidate.device + && same(&self.pci_bus_id, &candidate.pci_bus_id) + && same(&self.driver, &candidate.driver) + && (identified || self.name == candidate.name) + } +} + +impl fmt::Display for AdapterKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({})", self.name, self.backend) + } +} + +/// wgpu's lowercase name of `backend`. +pub fn backend_name(backend: Backend) -> &'static str { + backend.to_str() +} + +/// Something the app tells the user about the adapter it draws with. The [`fmt::Display`] text is +/// English, for the log; an app shows its own translated text for each variant. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Notice { + /// The adapter the user picked is not listed (unplugged, disabled, or its driver removed). + /// The automatic choice draws instead. + AdapterMissing(AdapterKey), + /// Software was asked for and no software adapter is listed. The automatic choice draws + /// instead. + NoSoftwareAdapter, + /// The only adapter that can draw is a software one: drawing is slower and uses the CPU. + SoftwareOnly, + /// An adapter could not open a device, and the next one was tried. + DeviceFailed { adapter: String, error: String }, + /// The device was lost this many times in a short time, so drawing moved to software. + SoftwareAfterLosses(u32), +} + +impl fmt::Display for Notice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Notice::AdapterMissing(key) => write!(f, "the graphics adapter {key} is not available; using the automatic choice"), + Notice::NoSoftwareAdapter => f.write_str("no software graphics adapter is available; using the automatic choice"), + Notice::SoftwareOnly => f.write_str("no graphics hardware can be used; drawing in software, which is slower"), + Notice::DeviceFailed { adapter, error } => { + write!(f, "the graphics adapter \"{adapter}\" could not be opened ({error}); trying the next one") + } + Notice::SoftwareAfterLosses(n) => write!(f, "the graphics device stopped working {n} times; drawing in software"), + } + } +} + +/// The adapter chosen for a preference, and what the user should be told about it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Selection { + /// Index into the candidates. + pub index: usize, + pub notices: Vec, +} + +/// The adapter to draw with for `preference`, or `None` when no adapter is usable. +/// +/// - [`Preference::Auto`] and [`Preference::LowPower`] use [`choose`]. +/// - [`Preference::Adapter`] uses the usable entry that matches the key (the one exposing the most +/// features when a driver lists it twice), with [`choose`]'s corrections; without one, or when +/// it is an Intel Vulkan entry [`choose`] never draws with, the automatic choice and +/// [`Notice::AdapterMissing`]. +/// - [`Preference::Software`] uses the first usable software adapter, with [`choose`]'s +/// corrections; without one, the automatic choice and [`Notice::NoSoftwareAdapter`]. +/// +/// A software adapter that the automatic choice took adds [`Notice::SoftwareOnly`]. +pub fn select(candidates: &[Candidate], preference: &Preference) -> Option { + let mut notices = Vec::new(); + let wanted = match preference { + Preference::Auto | Preference::LowPower => None, + Preference::Adapter(key) => { + // An entry that reports no bus id matches any saved bus. When it is the same model on + // the same driver it cannot be told apart from an older version of that driver, and + // the correction draws with the entry exposing the most features. + let found = + candidates.iter().enumerate().filter(|(_, c)| c.usable && key.matches(c)).max_by_key(|(i, c)| (c.features, std::cmp::Reverse(*i))); + let found = found.and_then(|(index, _)| drawn_with(candidates, index)); + if found.is_none() { + notices.push(Notice::AdapterMissing(key.clone())); + } + found + } + Preference::Software => { + let found = candidates.iter().position(|c| c.usable && c.is_software()).and_then(|index| drawn_with(candidates, index)); + if found.is_none() { + notices.push(Notice::NoSoftwareAdapter); + } + found + } + }; + let index = match wanted { + Some(index) => index, + None => { + let index = choose(candidates, preference.power())?; + if candidates.get(index).is_some_and(Candidate::is_software) { + notices.push(Notice::SoftwareOnly); + } + index + } + }; + Some(Selection { index, notices }) +} + +/// The entry to draw with when the entry at `index` is asked for, with [`choose`]'s corrections: +/// the newest version of a driver that lists the GPU twice, or the DirectX 12 entry of an Intel +/// GPU whose Vulkan entry [`choose`] never draws with. `None` when that Intel Vulkan entry has no +/// usable DirectX 12 entry. +fn drawn_with(candidates: &[Candidate], index: usize) -> Option { + candidates.get(index)?; + let index = settled(candidates, index); + (!candidates.get(index).is_some_and(intel_vulkan_crashes)).then_some(index) +} + +/// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key +/// of this adapter. +pub(crate) fn asked_for(preference: &Preference, candidate: &Candidate) -> bool { + match preference { + Preference::Software => candidate.is_software(), + Preference::Adapter(key) => key.matches(candidate), + Preference::Auto | Preference::LowPower => false, + } +} + +/// The order in which to try opening a device for `preference`: [`select`]'s choice first, then +/// every other usable adapter by device type for the preference's power (software after +/// hardware), leaving out the entries [`choose`] never draws with: an older version of a driver +/// listed twice, and the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver. +/// Empty when no adapter is usable. +pub fn ranked(candidates: &[Candidate], preference: &Preference) -> Vec { + let Some(first) = select(candidates, preference).map(|s| s.index) else { + return Vec::new(); + }; + let power = preference.power(); + let mut rest: Vec = + (0..candidates.len()).filter(|&i| i != first && candidates.get(i).is_some_and(|c| c.usable) && !avoided(candidates, i)).collect(); + rest.sort_by_key(|&i| (candidates.get(i).map_or(u8::MAX, |c| type_order(c.device_type, power)), i)); + let mut order = vec![first]; + order.extend(rest); + order +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::adapter::tests::{gpu, two_amd_drivers, uhd_630}; + use wgpu::Backend::{Dx12, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu}; + + fn key_of(candidates: &[Candidate], index: usize) -> AdapterKey { + candidates.get(index).map(AdapterKey::of).unwrap_or_default() + } + + #[test] + fn auto_and_low_power_are_the_corrected_wgpu_choice() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Auto), Some(Selection { index: 1, notices: vec![] })); + assert_eq!(select(&adapters, &Preference::LowPower).map(|s| s.index), Some(2)); + assert_eq!(select(&[], &Preference::Auto), None); + assert_eq!(Preference::default(), Preference::Auto); + } + + #[test] + fn a_named_adapter_is_found_wherever_it_is_listed() { + let adapters = two_amd_drivers(); + // the integrated Radeon through DirectX 12, picked by the user + let key = key_of(&adapters, 4); + assert_eq!(select(&adapters, &Preference::Adapter(key.clone())).map(|s| s.index), Some(4)); + // listed in another order on the next run + let mut reordered = adapters.clone(); + reordered.reverse(); + assert_eq!(select(&reordered, &Preference::Adapter(key)).map(|s| s.index), Some(1)); + // the stale Vulkan entry of the RX 6800M stored as the choice: the newer version draws + let stale = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(stale)).map(|s| s.index), Some(1)); + } + + #[test] + fn a_named_intel_gen9_vulkan_entry_draws_through_directx_12() { + let adapters = uhd_630(); + let vulkan = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(vulkan.clone())).map(|s| s.index), Some(1)); + // without the DirectX 12 entry, the named Vulkan entry is not available + let mut dx12_unusable = adapters.clone(); + dx12_unusable[1].usable = false; + let s = select(&dx12_unusable, &Preference::Adapter(vulkan.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((2, vec![Notice::AdapterMissing(vulkan), Notice::SoftwareOnly]))); + } + + #[test] + fn a_missing_named_adapter_falls_back_to_auto_with_a_notice() { + let adapters = two_amd_drivers(); + let gone = AdapterKey { + name: "NVIDIA GeForce RTX 4090".into(), + backend: "vulkan".into(), + vendor: 0x10de, + device: 0x2684, + pci_bus_id: String::new(), + driver: "NVIDIA".into(), + }; + let s = select(&adapters, &Preference::Adapter(gone.clone())); + assert_eq!(s, Some(Selection { index: 1, notices: vec![Notice::AdapterMissing(gone.clone())] })); + // listed but unable to draw to the window counts as missing + let mut unusable = adapters.clone(); + for c in &mut unusable { + c.usable = c.backend != Vulkan; + } + let vulkan_key = key_of(&adapters, 1); + let s = select(&unusable, &Preference::Adapter(vulkan_key.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((3, vec![Notice::AdapterMissing(vulkan_key)]))); + // nothing usable at all + assert_eq!(select(&[], &Preference::Adapter(gone)), None); + } + + #[test] + fn keys_tell_apart_backends_buses_and_unidentified_names() { + let adapters = two_amd_drivers(); + let dx12 = key_of(&adapters, 3); + assert!(dx12.matches(&adapters[3])); + assert!(!dx12.matches(&adapters[1]), "same GPU, other backend"); + let other_bus = Candidate { pci_bus_id: "0000:04:00.0".into(), ..adapters[3].clone() }; + assert!(!dx12.matches(&other_bus)); + // a key stored without a bus id still matches an entry that reports one + let no_bus = AdapterKey { pci_bus_id: String::new(), ..dx12.clone() }; + assert!(no_bus.matches(&adapters[3])); + // two Vulkan drivers for one GPU are told apart by the driver name; a key saved without + // one matches either + let radv = gpu("AMD Radeon RX 6800M (RADV NAVI22)", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "radv", "Mesa 25.2.4", 70); + let amdvlk = gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "AMD open-source driver", "2025.Q2.1", 72); + let two = vec![radv.clone(), amdvlk.clone()]; + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&radv))).map(|s| s.index), Some(0)); + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&amdvlk))).map(|s| s.index), Some(1)); + let old = AdapterKey { driver: String::new(), ..AdapterKey::of(&radv) }; + assert!(old.matches(&radv) && old.matches(&amdvlk)); + // a DirectX 12 key keeps matching after a driver update changes the reported version + assert!(dx12.driver.is_empty()); + let updated = Candidate { driver: "32.0.21045.12000".into(), ..adapters[3].clone() }; + assert!(dx12.matches(&updated)); + // OpenGL reports no ids: the name decides + let angle = gpu("ANGLE (D3D11)", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let swiftshader = gpu("SwiftShader", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let key = AdapterKey::of(&angle); + assert!(key.matches(&angle) && !key.matches(&swiftshader)); + assert_eq!(dx12.to_string(), "\"AMD Radeon RX 6800M\" (dx12)"); + } + + #[test] + fn software_is_used_when_asked_and_reported_when_it_is_all_there_is() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 5, notices: vec![] })); + let hardware_only: Vec = adapters.iter().filter(|c| !c.is_software()).cloned().collect(); + assert_eq!(select(&hardware_only, &Preference::Software), Some(Selection { index: 1, notices: vec![Notice::NoSoftwareAdapter] })); + let llvmpipe = vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)]; + assert_eq!(select(&llvmpipe, &Preference::Auto), Some(Selection { index: 0, notices: vec![Notice::SoftwareOnly] })); + assert_eq!(select(&llvmpipe, &Preference::Software), Some(Selection { index: 0, notices: vec![] })); + // picked by name, it is what was asked for + let named = Preference::Adapter(AdapterKey::of(&llvmpipe[0])); + assert_eq!(select(&llvmpipe, &named), Some(Selection { index: 0, notices: vec![] })); + #[cfg(not(target_arch = "wasm32"))] + { + assert!(asked_for(&named, &llvmpipe[0]) && asked_for(&Preference::Software, &llvmpipe[0])); + assert!(!asked_for(&Preference::Auto, &llvmpipe[0]) && !asked_for(&Preference::Software, &adapters[1])); + } + } + + #[test] + fn software_draws_with_the_newer_version_of_a_driver_listed_twice() { + let stale = gpu("llvmpipe (LLVM 15.0.7, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 23.0.4", 40); + let newer = gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 25.2.4", 50); + let hardware = gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "32.0.21045.11001", "", 36); + let adapters = vec![stale, newer, hardware]; + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 1, notices: vec![] })); + // the stale entry is never tried, and the newer one is not left out + assert_eq!(ranked(&adapters, &Preference::Software), vec![1, 2]); + } + + #[test] + fn the_fallback_order_never_tries_entries_that_can_crash() { + let adapters = two_amd_drivers(); + // the newer RX 6800M, then the other hardware by type for high performance, then software; + // the stale RX 6800M entry is never tried + assert_eq!(ranked(&adapters, &Preference::Auto), vec![1, 3, 2, 4, 5]); + assert_eq!(ranked(&adapters, &Preference::LowPower), vec![2, 4, 1, 3, 5]); + assert_eq!(ranked(&adapters, &Preference::Software), vec![5, 1, 3, 2, 4]); + // two cards of one model on one driver, one without a Vulkan bus id: the second card's + // Vulkan entry looks like an older version, and the card is tried through DirectX 12 + let card = |bus: &str| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, 0x1002, 0x744c, bus, "AMD proprietary driver", "", 68); + let dx12 = |bus: &str| gpu("AMD Radeon RX 7900 XT", Dx12, DiscreteGpu, 0x1002, 0x744c, bus, "32.0.21045.11001", "", 36); + let twins = vec![card("0000:03:00.0"), card(""), dx12("0000:03:00.0"), dx12("0000:04:00.0")]; + assert_eq!(ranked(&twins, &Preference::Auto), vec![0, 2, 3]); + // the same bus id on both entries: one GPU, and the older version is never tried + let mut versions = vec![card("0000:03:00.0"), card("0000:03:00.0")]; + versions[1].features = 70; + assert_eq!(ranked(&versions, &Preference::Auto), vec![1]); + // a third entry without a bus id and with more features: both older entries are left out + versions.push(card("")); + versions[2].features = 80; + assert_eq!(ranked(&versions, &Preference::Auto), vec![2]); + // two GPUs on different buses are both tried + let cards = vec![card("0000:03:00.0"), card("0000:04:00.0")]; + assert_eq!(ranked(&cards, &Preference::Auto), vec![0, 1]); + // the Intel Gen 9 Vulkan entry is never tried, with or without a usable DirectX 12 entry + assert_eq!(ranked(&uhd_630(), &Preference::Auto), vec![1, 2]); + let mut dx12_unusable = uhd_630(); + dx12_unusable[1].usable = false; + assert_eq!(ranked(&dx12_unusable, &Preference::Auto), vec![2]); + assert!(ranked(&uhd_630()[..1], &Preference::Auto).is_empty()); + assert!(ranked(&[], &Preference::Auto).is_empty()); + let unusable: Vec = adapters.iter().map(|c| Candidate { usable: false, ..c.clone() }).collect(); + assert!(ranked(&unusable, &Preference::Auto).is_empty()); + } + + #[test] + fn a_laptop_with_two_vendors_keeps_the_named_gpu_across_reorders() { + let intel = gpu("Intel(R) UHD Graphics 770", Dx12, IntegratedGpu, 0x8086, 0x4680, "0000:00:02.0", "31.0.101.5186", "", 36); + let nvidia = gpu("NVIDIA GeForce RTX 4070 Laptop GPU", Dx12, DiscreteGpu, 0x10de, 0x2820, "0000:01:00.0", "32.0.15.6094", "", 36); + let a = vec![intel.clone(), nvidia.clone()]; + let b = vec![nvidia, intel]; + let picked = Preference::Adapter(key_of(&a, 0)); + assert_eq!(select(&a, &picked).map(|s| s.index), Some(0)); + assert_eq!(select(&b, &picked).map(|s| s.index), Some(1)); + assert_eq!(ranked(&b, &picked), vec![1, 0]); + } + + #[cfg(feature = "serde")] + #[test] + fn preferences_read_back_what_they_write() { + let key = AdapterKey { + name: "AMD Radeon RX 6800M".into(), + backend: "dx12".into(), + vendor: 0x1002, + device: 0x73df, + pci_bus_id: "0000:03:00.0".into(), + driver: String::new(), + }; + for p in [Preference::Auto, Preference::LowPower, Preference::Software, Preference::Adapter(key)] { + let text = serde_json::to_string(&p).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), p, "{text}"); + } + assert_eq!(serde_json::to_string(&Preference::Auto).unwrap(), r#"{"kind":"auto"}"#); + // a key written by an older version without some fields + let p: Preference = serde_json::from_str(r#"{"kind":"adapter","name":"x","backend":"vulkan"}"#).unwrap(); + assert_eq!(p, Preference::Adapter(AdapterKey { name: "x".into(), backend: "vulkan".into(), ..Default::default() })); + assert!(serde_json::from_str::(r#"{"kind":"fastest"}"#).is_err()); + } +} diff --git a/crates/gpu-device/src/recovery.rs b/crates/gpu-device/src/recovery.rs new file mode 100644 index 0000000000..2732d8c986 --- /dev/null +++ b/crates/gpu-device/src/recovery.rs @@ -0,0 +1,153 @@ +//! What to open after a device loss. +//! +//! A device is lost when the driver resets the GPU, the OS ends a long submission, the PC sleeps, +//! or the GPU is unplugged. The app drops everything it made with the device and opens a new one. +//! [`Recovery`] decides with what preference: the user's own, until the device has been lost +//! [`RecoveryPolicy::max_losses`] times within [`RecoveryPolicy::window`], and software after that, +//! so a GPU that keeps failing does not stop the app from drawing. + +use std::collections::VecDeque; +use std::time::Duration; + +use crate::preference::{Notice, Preference}; + +/// When repeated losses move drawing to software. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RecoveryPolicy { + /// Losses within [`window`](Self::window) after which the next device is a software one. + /// 0 never moves to software. + pub max_losses: u32, + pub window: Duration, +} + +impl Default for RecoveryPolicy { + fn default() -> Self { + RecoveryPolicy { max_losses: 3, window: Duration::from_secs(600) } + } +} + +/// The preference to open the next device with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecoveryStep { + pub preference: Preference, + /// [`Notice::SoftwareAfterLosses`] when this step moved drawing to software. + pub notice: Option, +} + +/// Device losses seen so far, against the user's preference. +#[derive(Clone, Debug)] +pub struct Recovery { + preference: Preference, + policy: RecoveryPolicy, + /// When each loss inside the window happened, oldest first. + losses: VecDeque, + software: bool, +} + +impl Recovery { + pub fn new(preference: Preference, policy: RecoveryPolicy) -> Self { + Recovery { preference, policy, losses: VecDeque::new(), software: false } + } + + /// The preference to open a device with now. + pub fn preference(&self) -> &Preference { + if self.software { &Preference::Software } else { &self.preference } + } + + /// The user changed the preference: losses counted so far no longer apply. + pub fn set_preference(&mut self, preference: Preference) { + self.preference = preference; + self.losses.clear(); + self.software = false; + } + + /// Record a loss at `at`, a monotonic time the caller keeps (since the app started), and + /// return what to open next. A time earlier than the last loss counts as the same time. + pub fn lost(&mut self, at: Duration) -> RecoveryStep { + let at = self.losses.back().map_or(at, |last| at.max(*last)); + self.losses.push_back(at); + // Only the last `max_losses` losses decide anything, so no more are kept. + let keep = usize::try_from(self.policy.max_losses.max(1)).unwrap_or(usize::MAX); + while self.losses.len() > keep || self.losses.front().is_some_and(|first| at.saturating_sub(*first) > self.policy.window) { + self.losses.pop_front(); + } + let count = u32::try_from(self.losses.len()).unwrap_or(u32::MAX); + let mut notice = None; + if !self.software && self.policy.max_losses > 0 && count >= self.policy.max_losses && self.preference != Preference::Software { + self.software = true; + notice = Some(Notice::SoftwareAfterLosses(count)); + } + RecoveryStep { preference: self.preference().clone(), notice } + } + + /// Losses inside the window, as of the last one, counting at most + /// [`RecoveryPolicy::max_losses`] (at least 1). + pub fn recent_losses(&self) -> usize { + self.losses.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(secs: u64) -> Duration { + Duration::from_secs(secs) + } + + #[test] + fn the_third_loss_in_ten_minutes_moves_to_software() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy::default()); + assert_eq!(r.lost(s(10)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(100)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(300)), RecoveryStep { preference: Preference::Software, notice: Some(Notice::SoftwareAfterLosses(3)) }); + // it stays on software, and says so once + assert_eq!(r.lost(s(400)), RecoveryStep { preference: Preference::Software, notice: None }); + assert_eq!(r.preference(), &Preference::Software); + } + + #[test] + fn losses_outside_the_window_are_forgotten() { + let mut r = Recovery::new(Preference::LowPower, RecoveryPolicy::default()); + r.lost(s(0)); + r.lost(s(500)); + // the first loss is more than 600 s before this one + assert_eq!(r.lost(s(601)).preference, Preference::LowPower); + assert_eq!(r.recent_losses(), 2); + // a clock that goes back counts as the last loss's time + assert_eq!(r.lost(s(1)).preference, Preference::Software); + } + + #[test] + fn changing_the_preference_starts_over() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 2, window: s(60) }); + r.lost(s(1)); + assert_eq!(r.lost(s(2)).preference, Preference::Software); + r.set_preference(Preference::LowPower); + assert_eq!(r.preference(), &Preference::LowPower); + assert_eq!(r.recent_losses(), 0); + assert_eq!(r.lost(s(3)).preference, Preference::LowPower); + } + + #[test] + fn software_and_a_zero_limit_never_add_a_notice() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy::default()); + for t in 0..5 { + assert_eq!(r.lost(s(t)), RecoveryStep { preference: Preference::Software, notice: None }); + } + let mut never = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 0, window: s(60) }); + for t in 0..10 { + assert_eq!(never.lost(s(t)).preference, Preference::Auto); + } + assert_eq!(never.recent_losses(), 1); + } + + #[test] + fn the_loss_history_stays_bounded() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy { max_losses: 3, window: Duration::MAX }); + for _ in 0..10_000 { + r.lost(s(5)); + } + assert_eq!(r.recent_losses(), 3); + } +} diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 60742bea84..3871c44891 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -46,6 +46,8 @@ fn probe_caps_native() -> DeviceCaps { max_buffer_size: limits.max_buffer_size, max_texture_dimension_2d: limits.max_texture_dimension_2d, features: Vec::new(), + vendor_id: info.vendor, + software: info.device_type == wgpu::DeviceType::Cpu, } } @@ -144,6 +146,8 @@ mod native { max_buffer_size: device_limits.max_buffer_size, max_texture_dimension_2d: device_limits.max_texture_dimension_2d, features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(), + vendor_id: info.vendor, + software: info.device_type == wgpu::DeviceType::Cpu, }; let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() }); Some((caps, backing)) diff --git a/crates/gpu-yuv/Cargo.toml b/crates/gpu-yuv/Cargo.toml new file mode 100644 index 0000000000..28053d83b1 --- /dev/null +++ b/crates/gpu-yuv/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "craft-gpu-yuv" +description = "RGBA to NV12, P010 and I420 on the GPU with scaling, in BT.601, BT.709 and BT.2020 at limited or full range, as a craft-gpu provider, with a CPU reference of the same conversion" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } +wgpu = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true } + +# The device tests (src/tests.rs) open a native adapter. The backends are on for this crate's own +# tests only; crates that depend on craft-gpu-yuv get the workspace wgpu with `std` and `wgsl`. +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +wgpu = { workspace = true, features = ["dx12", "metal", "vulkan", "gles"] } + +[dev-dependencies] +craft-gpu-null = { workspace = true } +pollster = { workspace = true } +# The independent reference the oracle tests compare with (BSD-3-Clause OR Apache-2.0). +yuv = { version = "0.8.20", default-features = false, features = ["professional_mode"] } diff --git a/crates/gpu-yuv/README.md b/crates/gpu-yuv/README.md new file mode 100644 index 0000000000..9a39ce0ff3 --- /dev/null +++ b/crates/gpu-yuv/README.md @@ -0,0 +1,148 @@ +# craft-gpu-yuv + +RGBA to 4:2:0 Y'CbCr for the Craft apps' encoders and scopes: NV12, P010 and I420, scaled to the +output size, in the BT.601, BT.709 and BT.2020 matrices at limited or full range. `YuvProvider` is +the `craft.yuv` provider of the `craft-gpu` job layer. `Converter` records the same conversion as +render passes into a caller's own encoder, and `cpu::convert` is the same conversion on the CPU. + +Licensed under MIT OR Apache-2.0. + +## Contents + +| Item | What | +|---|---| +| `YuvProvider` | the `craft.yuv` `GpuProvider`; `new()` converts on the CPU on any `GpuContext`, `with_device(device, queue)` converts with the render passes on that device (not on `wasm32`) | +| `YuvJob` | one job's conversion, source size and output size; `params()` writes them, `parse` reads them, `job(input)` makes the `GpuJob` | +| `PROVIDER_ID` | `"craft.yuv"` | +| `Format` | `Nv12` (8-bit luma, then interleaved Cb and Cr), `P010` (10-bit values in the high bits of little-endian 16-bit words, same planes as NV12) and `I420` (8-bit luma, Cb, then Cr) | +| `Matrix`, `Range` | BT.601, BT.709 and BT.2020 non-constant luminance; limited range (luma 16 to 235, chroma 16 to 240, times 4 at 10 bits) or full range (every code, chroma centered on 128 or 512) | +| `Conversion` | one format, matrix and range | +| `Converter::new(device, conversion)` | the two render pipelines of one conversion; no per-frame state | +| `Converter::bind(device, view)` | a source texture view bound once, as a `Source` | +| `Converter::planes(device, width, height)` | the plane textures of one output size, as `Planes` | +| `Converter::draw(encoder, source, planes)` | records a luma pass and a chroma pass | +| `Planes::copy_to_buffer(encoder, buffer, offset)` | records the copies of every plane into a read-back buffer | +| `FrameLayout` | each plane's size, its offset and row pitch in a read-back buffer (`buffer_size`), and the size of a packed frame (`frame_bytes`); `unpack` copies a mapped buffer into a packed frame | +| `cpu::convert(rgba, src_width, src_height, conversion, width, height)` | the conversion of an RGBA8 picture on the CPU, as one packed frame | + +## Jobs + +A host registers `YuvProvider` in a `ProviderRegistry` and dispatches jobs made by `YuvJob::job`: + +```rust +let mut registry = craft_gpu::ProviderRegistry::new(); +registry.register(Box::new(craft_gpu_yuv::YuvProvider::new())); +let input = ctx.upload_buffer("rgba", &rgba)?; +let job = craft_gpu_yuv::YuvJob::new(conversion, 1920, 1080, 1280, 720).job(input); +let outcome = registry.dispatch(&mut ctx, &job)?; +let frame = ctx.read_buffer(outcome.outputs[0])?; +``` + +A job has one input, an RGBA8 buffer of exactly `src_width × src_height × 4` bytes, and no +outputs; its outcome has one output, a new buffer that holds the packed frame. The parameters are +ASCII `key:value` fields separated by `;`: +`fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or +`i420`, `matrix` is `bt601`, `bt709` or `bt2020`, `range` is `limited` or `full`, and the four sides +are decimal digits. + +The provider checks the job against the context's `DeviceCaps` on every context, the null one +included: each source and output side must be at most `max_texture_dimension_2d`, and the +read-back layout with its padded rows (`FrameLayout::buffer_size`) and the RGBA8 input at most +`max_buffer_size` bytes. Each output side must also be at most `cpu::MAX_SIDE` (16384), with or +without a device. It checks the input's length before reading it. A +malformed, missing, repeated or unknown parameter, a wrong input count or length, and a size the +caps or the conversion do not allow are `GpuFault::InvalidJob`. With a device, the provider also +checks the device's own limits, and an error the device reports during the job is +`GpuFault::Operation`. Each conversion's pipelines are made once per provider. + +`YuvProvider::new()` runs `cpu::convert`, so a consumer's tests and CI run on `craft-gpu-null` +without a graphics adapter. `YuvProvider::with_device` runs the render passes on the given device +and waits for each job to finish; the input and the output still move through the context's +buffers. + +## Plane layout + +A packed frame of `w × h` (both even) holds its planes one after another, each row without +padding: + +| Format | Plane | Offset | Row bytes | Rows | +|---|---|---|---|---| +| NV12 | Y' | 0 | `w` | `h` | +| NV12 | Cb, Cr interleaved | `w·h` | `w` | `h/2` | +| P010 | Y' | 0 | `2w` | `h` | +| P010 | Cb, Cr interleaved | `2w·h` | `2w` | `h/2` | +| I420 | Y' | 0 | `w` | `h` | +| I420 | Cb | `w·h` | `w/2` | `h/2` | +| I420 | Cr | `w·h + w·h/4` | `w/2` | `h/2` | + +A frame is `1.5·w·h` bytes in NV12 and I420 and `3·w·h` bytes in P010. Each P010 word holds the +10-bit value in its high bits, with the 6 low bits zero. NV12 and I420 follow the W3C WebCodecs +definitions (), and NV12 and P010 follow +the Linux media API's sample images +(). + +In a read-back buffer, `FrameLayout` pads each row to a multiple of +`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT` (256) bytes, as a texture-to-buffer copy needs, and puts each +plane right after the previous plane's padded rows. `FrameLayout::unpack` removes the padding. + +## Code values + +Luma and chroma follow BT.601-7 section 2.5, BT.709-6 items 3.2 to 3.5 and BT.2020-2 tables 4 and +5 at limited range, and BT.2100-3 table 9 at full range. A half rounds away from zero, as `INT` in +BT.709 and BT.2020 and `Round` in BT.2100 do, so a full-range Cb or Cr that computes to 0.5 is +code 1. + +## Sampling + +The source is scaled to the output size; the caller keeps the aspect ratio. Each output texel +(luma at the output size, chroma at half the output size in both directions) takes the average +of up to 4 × 4 bilinear taps spread over the part of the source it covers: 1 tap per axis while +the source is at most twice the plane's size, and one more for each further 2:1 of reduction. +At the same size, each chroma sample is the average of the 2 × 2 pixels it covers, and its +position is the center of those pixels. A reduction of more than 8:1 along an axis skips part of +the source between taps. + +`cpu::convert` scales with these same taps rather than with a resampling crate such as +`fast_image_resize`, because it is the reference the shader is tested against, and a different +kernel would differ from the shader at every edge. A caller that wants another filter on the CPU +can resize first with such a crate and convert at the same size. + +The passes write unsigned-integer textures (`R8Uint`, `Rg8Uint`, `R16Uint`, `Rg16Uint`), so P010 +does not need wgpu's 16-bit norm feature. + +## Limits + +- The matrix applies to the stored values: the source must already be in the output's primaries + and transfer function. An sRGB view of the source gives linear values, which the matrix does + not expect; bind a non-sRGB view. Alpha is ignored, so premultiplied pixels convert as if they + were over black. +- Output sides must be even and not zero (`Error::OutputSize`), and no larger than the device's + largest 2D texture (`Error::TooLarge`). A layout whose byte sizes do not fit in `u32` rows, `u64` + offsets or a `usize` frame is `Error::Overflow`. `Converter::planes` refuses a read-back layout + larger than the device's largest buffer (`Error::BufferLimit`), and `cpu::convert` refuses an + output side over `cpu::MAX_SIDE` (16384). +- The source view must be a 2D view of a filterable float format, such as `Rgba8Unorm`, + `Bgra8Unorm` or `Rgba16Float`. +- `copy_to_buffer` needs an offset that is a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT` + (`Error::Offset`) and a buffer of at least `buffer_size` bytes from it (`Error::BufferSize`). + `draw` refuses planes made for another format (`Error::Mismatch`). + +## Tests + +- `oracle_tests.rs` checks the conversion against sources outside the crate. It computes the + code values of 729 colors in `f64` from each recommendation's Kr, Kb and quantization, and + checks the nominal levels the recommendations state (white, black, neutral chroma and the + chroma extremes). It compares every format, matrix and range with the `yuv` crate's conversion + of the same pictures (`yuv` 0.8, a dev-dependency), within 1 code value at 8 bits and 2 at + 10 bits. It checks the packed plane sizes against the planes `yuv` allocates, and a 4 × 4 frame + against the byte offsets of the public format definitions. The GPU passes are checked against + the same equations, within 1 code value. +- `job_tests.rs` runs `craft.yuv` through a `ProviderRegistry` on `craft-gpu-null`, and with a + device. It checks the parameters, the inputs and outputs, the caps limits, and a device whose + limits are smaller than the context's. +- `tests.rs` checks standard code values, each format's plane order, the area average of a + reduction and the read-back layout. It also compares the GPU passes with `cpu::convert` on + pictures with hard edges at the same size and on smooth pictures at five scales, within 2 code + values at 8 bits and 6 at 10 bits. + +A machine without a graphics adapter skips the GPU tests and prints that it did so. diff --git a/crates/gpu-yuv/src/cpu.rs b/crates/gpu-yuv/src/cpu.rs new file mode 100644 index 0000000000..b96bc90ed3 --- /dev/null +++ b/crates/gpu-yuv/src/cpu.rs @@ -0,0 +1,142 @@ +//! The conversion on the CPU, sample for sample the rule the GPU passes follow. Tests compare the +//! two, and a caller without a GPU can use it directly. +//! +//! Each output texel (luma at the output size, chroma at half of it) takes the area of the source +//! under it: up to 4 × 4 bilinear taps spread over the texel's footprint, 1 per axis while the +//! source is at most twice the plane's size, one more for each further 2:1 of reduction. The +//! average of the taps goes through the matrix. At the same size the chroma tap lands between +//! four source pixels, so each chroma sample is the average of the 2 × 2 pixels it covers. +//! +//! The scaler here takes the shader's taps at the shader's positions instead of using a +//! resampling crate such as `fast_image_resize`: this function is the reference the shader is +//! tested against, and another kernel would differ from the shader at every edge. For another +//! filter, resize with such a crate first and convert at the same size. + +use crate::layout::FrameLayout; +use crate::spec::{Coefficients, Conversion, Error}; + +/// The largest output side [`convert`] takes. +pub const MAX_SIDE: u32 = 16384; + +/// The taps along one axis for a reduction of `r` (source size over plane size). +pub(crate) fn taps(r: f32) -> u32 { + ((r * 0.5 - 0.001).ceil() as i32).clamp(1, 4) as u32 +} + +struct Image<'a> { + rgba: &'a [u8], + width: usize, + height: usize, +} + +impl Image<'_> { + fn pixel(&self, x: i64, y: i64) -> [f32; 3] { + let x = x.clamp(0, self.width as i64 - 1) as usize; + let y = y.clamp(0, self.height as i64 - 1) as usize; + let i = (y * self.width + x) * 4; + match self.rgba.get(i..i + 3) { + Some(p) => [f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0], + None => [0.0; 3], + } + } + + /// The linear filter at `(x, y)` in pixels (pixel centers at .5), clamped to the edges. + fn bilinear(&self, x: f32, y: f32) -> [f32; 3] { + let (x, y) = (x - 0.5, y - 0.5); + let (x0, y0) = (x.floor(), y.floor()); + let (fx, fy) = (x - x0, y - y0); + let (xi, yi) = (x0 as i64, y0 as i64); + let [a, b, c, d] = [self.pixel(xi, yi), self.pixel(xi + 1, yi), self.pixel(xi, yi + 1), self.pixel(xi + 1, yi + 1)]; + let mut out = [0.0; 3]; + for k in 0..3 { + let top = a[k] + (b[k] - a[k]) * fx; + let bottom = c[k] + (d[k] - c[k]) * fx; + out[k] = top + (bottom - top) * fy; + } + out + } + + /// The average color under the texel centered at `pos` of a plane of `size` texels. + fn area(&self, pos: [f32; 2], size: [f32; 2]) -> [f32; 3] { + let s = [self.width as f32, self.height as f32]; + let r = [s[0] / size[0], s[1] / size[1]]; + let n = [taps(r[0]), taps(r[1])]; + let nf = [n[0] as f32, n[1] as f32]; + let step = [r[0] / nf[0], r[1] / nf[1]]; + let center = [pos[0] / size[0] * s[0], pos[1] / size[1] * s[1]]; + let mut sum = [0.0f32; 3]; + for j in 0..n[1] { + for i in 0..n[0] { + let px = center[0] + (i as f32 + 0.5 - nf[0] * 0.5) * step[0]; + let py = center[1] + (j as f32 + 0.5 - nf[1] * 0.5) * step[1]; + let c = self.bilinear(px, py); + for k in 0..3 { + sum[k] += c[k]; + } + } + } + let count = nf[0] * nf[1]; + [sum[0] / count, sum[1] / count, sum[2] / count] + } +} + +/// An empty vector with room for `len` values, or [`Error::Memory`] when the room cannot be +/// allocated. +pub(crate) fn reserve(len: usize) -> Result, Error> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| Error::Memory { bytes: len.saturating_mul(size_of::()) })?; + Ok(v) +} + +/// `rgba` (`src_width × src_height`, 4 bytes per pixel; alpha is ignored, so premultiplied +/// pixels convert as if over black) scaled to `width × height` and converted, as one tightly +/// packed frame in [`FrameLayout`] order. +pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Conversion, width: u32, height: u32) -> Result, Error> { + let bytes = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4)); + if src_width == 0 || src_height == 0 || bytes != Some(rgba.len()) { + return Err(Error::Source { width: src_width, height: src_height, bytes: rgba.len() }); + } + if width > MAX_SIDE || height > MAX_SIDE { + return Err(Error::TooLarge { width, height, limit: MAX_SIDE }); + } + let layout = FrameLayout::new(conversion.format, width, height)?; + let image = Image { rgba, width: src_width as usize, height: src_height as usize }; + let c = Coefficients::of(conversion); + let (shift, wide) = (conversion.format.shift(), conversion.format.sample_bytes() == 2); + let (cw, ch) = (width / 2, height / 2); + let mut out = reserve(layout.frame_bytes())?; + let mut cr: Vec = if conversion.format == crate::Format::I420 { reserve(cw as usize * ch as usize)? } else { Vec::new() }; + let mut put = |v: u16| { + let v = v << shift; + if wide { + out.extend_from_slice(&v.to_le_bytes()); + } else { + out.push(v as u8); + } + }; + let plane = |pw: u32, ph: u32, pick: &mut dyn FnMut([u16; 3])| { + let size = [pw as f32, ph as f32]; + for j in 0..ph { + for i in 0..pw { + pick(c.codes(image.area([i as f32 + 0.5, j as f32 + 0.5], size))); + } + } + }; + plane(width, height, &mut |v| put(v[0])); + match conversion.format { + crate::Format::Nv12 | crate::Format::P010 => plane(cw, ch, &mut |v| { + put(v[1]); + put(v[2]); + }), + crate::Format::I420 => { + plane(cw, ch, &mut |v| { + put(v[1]); + cr.push(v[2]); + }); + for v in cr { + put(v); + } + } + } + Ok(out) +} diff --git a/crates/gpu-yuv/src/gpu.rs b/crates/gpu-yuv/src/gpu.rs new file mode 100644 index 0000000000..a77e3316c5 --- /dev/null +++ b/crates/gpu-yuv/src/gpu.rs @@ -0,0 +1,360 @@ +//! The conversion as render passes: one pass draws the luma plane, one draws the chroma plane or +//! planes, each into unsigned-integer textures that hold the exact stored words. + +use wgpu::util::DeviceExt; + +use crate::layout::FrameLayout; +use crate::spec::{Coefficients, Conversion, Error, Format}; + +/// The render pipelines of one [`Conversion`]. Make it once per device and conversion; it holds +/// no per-frame state. +pub struct Converter { + conversion: Conversion, + plane_layout: wgpu::BindGroupLayout, + source_layout: wgpu::BindGroupLayout, + luma: wgpu::RenderPipeline, + chroma: wgpu::RenderPipeline, + sampler: wgpu::Sampler, +} + +/// A source texture view bound for a [`Converter`]. Keep one per texture that is converted more +/// than once. +pub struct Source { + bind: wgpu::BindGroup, +} + +/// The plane textures of one output size, and their read-back layout. +pub struct Planes { + layout: FrameLayout, + textures: Vec, + views: Vec, + luma_bind: wgpu::BindGroup, + chroma_bind: wgpu::BindGroup, +} + +fn plane_formats(format: Format) -> &'static [wgpu::TextureFormat] { + use wgpu::TextureFormat as T; + match format { + Format::Nv12 => &[T::R8Uint, T::Rg8Uint], + Format::P010 => &[T::R16Uint, T::Rg16Uint], + Format::I420 => &[T::R8Uint, T::R8Uint, T::R8Uint], + } +} + +fn attachment(view: &wgpu::TextureView) -> Option> { + Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + }) +} + +fn vec3(w: [f32; 3]) -> String { + format!("vec3({:?}, {:?}, {:?})", w[0], w[1], w[2]) +} + +/// The WGSL of `conversion`, with its weights and scale written in as constants. +pub(crate) fn shader(conversion: Conversion) -> String { + let k = Coefficients::of(conversion); + let chroma = match conversion.format { + Format::Nv12 | Format::P010 => { + "@fragment fn fs_chroma(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = area(pos.xy); + return vec4(code(dot(c, CB) * CS + CO), code(dot(c, CR) * CS + CO), 0u, 0u); +}" + } + Format::I420 => { + "struct Chroma { @location(0) cb: vec4, @location(1) cr: vec4 } +@fragment fn fs_chroma(@builtin(position) pos: vec4) -> Chroma { + let c = area(pos.xy); + var o: Chroma; + o.cb = vec4(code(dot(c, CB) * CS + CO), 0u, 0u, 0u); + o.cr = vec4(code(dot(c, CR) * CS + CO), 0u, 0u, 0u); + return o; +}" + } + }; + format!( + "const KY = {ky}; +const CB = {cb}; +const CR = {cr}; +const YS = {ys:?}; +const YO = {yo:?}; +const CS = {cs:?}; +const CO = {co:?}; +const MAX = {max:?}; +const SHIFT = {shift}u; + +struct Plane {{ size: vec2, pad: vec2 }} +@group(0) @binding(0) var plane: Plane; +@group(1) @binding(0) var tex: texture_2d; +@group(1) @binding(1) var samp: sampler; + +@vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 {{ + let x = f32((vi << 1u) & 2u); + let y = f32(vi & 2u); + return vec4(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0); +}} + +fn taps(r: f32) -> i32 {{ + return clamp(i32(ceil(r * 0.5 - 0.001)), 1, 4); +}} + +// The average color under the texel centered at `pos`: up to 4 x 4 bilinear taps over its +// footprint in the source. +fn area(pos: vec2) -> vec3 {{ + let src = vec2(textureDimensions(tex)); + let r = src / plane.size; + let n = vec2(taps(r.x), taps(r.y)); + let nf = vec2(n); + let step = r / nf; + let center = pos / plane.size * src; + var sum = vec3(0.0); + for (var j = 0; j < n.y; j++) {{ + for (var i = 0; i < n.x; i++) {{ + let p = center + (vec2(f32(i), f32(j)) + 0.5 - nf * 0.5) * step; + sum += textureSampleLevel(tex, samp, p / src, 0.0).rgb; + }} + }} + return sum / (nf.x * nf.y); +}} + +// A half rounds up, as INT and Round do in the recommendations; WGSL's round() takes it to the +// even neighbor. The fraction v - floor(v) is exact in f32, while floor(v + 0.5) takes a value +// just below a half up, because v + 0.5 rounds to the next integer. Values below 0 clamp to 0. +fn code(v: f32) -> u32 {{ + let f = floor(v); + return u32(clamp(select(f, f + 1.0, v - f >= 0.5), 0.0, MAX)) << SHIFT; +}} + +@fragment fn fs_luma(@builtin(position) pos: vec4) -> @location(0) vec4 {{ + return vec4(code(dot(area(pos.xy), KY) * YS + YO), 0u, 0u, 0u); +}} + +{chroma} +", + ky = vec3(k.y), + cb = vec3(k.cb), + cr = vec3(k.cr), + ys = k.y_scale, + yo = k.y_offset, + cs = k.c_scale, + co = k.c_offset, + max = k.max, + shift = conversion.format.shift(), + ) +} + +impl Converter { + /// The pipelines of `conversion` on `device`. + pub fn new(device: &wgpu::Device, conversion: Conversion) -> Converter { + let plane_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("yuv plane"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new(16), + }, + count: None, + }], + }); + let source_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("yuv source"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("yuv"), + bind_group_layouts: &[Some(&plane_layout), Some(&source_layout)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(conversion.format.name()), + source: wgpu::ShaderSource::Wgsl(shader(conversion).into()), + }); + let target = |format| Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL }); + let formats = plane_formats(conversion.format); + let pipeline = |label: &str, fs: &str, targets: &[Option]| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(fs), targets, compilation_options: Default::default() }), + multiview_mask: None, + cache: None, + }) + }; + let luma = pipeline("yuv luma", "fs_luma", &[target(formats[0])]); + let chroma_targets: Vec<_> = formats[1..].iter().map(|f| target(*f)).collect(); + let chroma = pipeline("yuv chroma", "fs_chroma", &chroma_targets); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("yuv linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + Converter { conversion, plane_layout, source_layout, luma, chroma, sampler } + } + + pub fn conversion(&self) -> Conversion { + self.conversion + } + + /// Bind `view` as a source. The view must be a 2D view of a filterable float format, such as + /// `Rgba8Unorm` or `Bgra8Unorm`; an sRGB view gives linear values, which the matrix does not + /// expect. + pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> Source { + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("yuv source"), + layout: &self.source_layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + ], + }); + Source { bind } + } + + /// Plane textures for frames of `width × height`. Both sides must be even, not zero, and no + /// larger than the device's largest 2D texture. + pub fn planes(&self, device: &wgpu::Device, width: u32, height: u32) -> Result { + let limit = device.limits().max_texture_dimension_2d; + if width > limit || height > limit { + return Err(Error::TooLarge { width, height, limit }); + } + let layout = FrameLayout::new(self.conversion.format, width, height)?; + let max = device.limits().max_buffer_size; + if layout.buffer_size > max { + return Err(Error::BufferLimit { needed: layout.buffer_size, limit: max }); + } + let formats = plane_formats(self.conversion.format); + let textures: Vec = layout + .planes + .iter() + .zip(formats) + .map(|(p, format)| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some("yuv plane"), + size: wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: *format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }) + }) + .collect(); + let views = textures.iter().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default())).collect(); + let uniform = |w: u32, h: u32| { + let mut bytes = [0u8; 16]; + bytes[..4].copy_from_slice(&(w as f32).to_le_bytes()); + bytes[4..8].copy_from_slice(&(h as f32).to_le_bytes()); + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("yuv plane size"), + contents: &bytes, + usage: wgpu::BufferUsages::UNIFORM, + }); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("yuv plane"), + layout: &self.plane_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }], + }) + }; + let luma_bind = uniform(width, height); + let chroma_bind = uniform(width / 2, height / 2); + Ok(Planes { layout, textures, views, luma_bind, chroma_bind }) + } + + /// Record the passes that convert `source` into `planes`. + pub fn draw(&self, encoder: &mut wgpu::CommandEncoder, source: &Source, planes: &Planes) -> Result<(), Error> { + if planes.layout.format != self.conversion.format { + return Err(Error::Mismatch { converter: self.conversion.format, planes: planes.layout.format }); + } + // No allocation per frame: one luma view, then one or two chroma views. + let chroma_count = planes.views.len().saturating_sub(1).min(2); + let luma = [planes.views.first().and_then(attachment)]; + let chroma = [planes.views.get(1).and_then(attachment), planes.views.get(2).and_then(attachment)]; + let passes: [(&wgpu::RenderPipeline, &wgpu::BindGroup, &[Option>]); 2] = + [(&self.luma, &planes.luma_bind, &luma), (&self.chroma, &planes.chroma_bind, &chroma[..chroma_count])]; + for (pipeline, plane, attachments) in passes { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("yuv"), + color_attachments: attachments, + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, plane, &[]); + pass.set_bind_group(1, &source.bind, &[]); + pass.draw(0..3, 0..1); + } + Ok(()) + } +} + +impl Planes { + pub fn layout(&self) -> &FrameLayout { + &self.layout + } + + /// The plane textures, luma first. + pub fn textures(&self) -> &[wgpu::Texture] { + &self.textures + } + + /// Record copies of every plane into `buffer` from `offset`, in the [`FrameLayout`]'s + /// places. `offset` must be a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`, and the + /// buffer must hold `layout().buffer_size` bytes from it. + pub fn copy_to_buffer(&self, encoder: &mut wgpu::CommandEncoder, buffer: &wgpu::Buffer, offset: u64) -> Result<(), Error> { + if !offset.is_multiple_of(u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)) { + return Err(Error::Offset(offset)); + } + let needed = offset.saturating_add(self.layout.buffer_size); + if buffer.size() < needed { + return Err(Error::BufferSize { needed, actual: buffer.size() }); + } + for (texture, p) in self.textures.iter().zip(&self.layout.planes) { + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: offset + p.offset, + bytes_per_row: Some(p.bytes_per_row), + rows_per_image: Some(p.height), + }, + }, + wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + ); + } + Ok(()) + } +} diff --git a/crates/gpu-yuv/src/job.rs b/crates/gpu-yuv/src/job.rs new file mode 100644 index 0000000000..4f98dccca8 --- /dev/null +++ b/crates/gpu-yuv/src/job.rs @@ -0,0 +1,365 @@ +//! The conversion as a `craft-gpu` job: [`YuvProvider`] answers [`GpuJob`]s whose provider id is +//! [`PROVIDER_ID`], dispatched through a [`craft_gpu::ProviderRegistry`]. +//! +//! A job has one input, an RGBA8 buffer of `src_width × src_height × 4` bytes in the context, and +//! [`YuvJob::params`] as its parameters. Its outcome has one output: a new buffer that holds the +//! packed frame in [`FrameLayout`] order. Every side must be no larger than the context's +//! [`DeviceCaps::max_texture_dimension_2d`](craft_gpu::DeviceCaps), and the input and the frame no +//! larger than its `max_buffer_size`, on every context, so that a job that runs on the null context +//! also runs on a device with the same caps. + +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuJobParams, GpuProvider, HandleId}; + +use crate::cpu; +use crate::layout::FrameLayout; +use crate::spec::{Conversion, Error, Format, Matrix, Range}; + +/// The provider id of [`YuvProvider`]. +pub const PROVIDER_ID: &str = "craft.yuv"; + +/// The parameter keys, in the order [`YuvJob::params`] writes them. +const KEYS: [&str; 7] = ["fmt", "matrix", "range", "sw", "sh", "w", "h"]; + +/// The parameters of one `craft.yuv` job: the conversion, the source size and the output size. +/// +/// They are written as ASCII `key:value` fields separated by `;`, for example +/// `fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or +/// `i420`; `matrix` is `bt601`, `bt709` or `bt2020`; `range` is `limited` or `full`; the sides are +/// decimal digits. A missing, repeated or unknown key, or a value outside these, is +/// [`GpuFault::InvalidJob`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct YuvJob { + pub conversion: Conversion, + pub src_width: u32, + pub src_height: u32, + pub width: u32, + pub height: u32, +} + +fn invalid(message: impl std::fmt::Display) -> GpuFault { + GpuFault::InvalidJob(format!("{PROVIDER_ID}: {message}")) +} + +/// A conversion error as a fault: device errors and allocation failures are +/// [`GpuFault::Operation`], the rest describe a job that cannot run and are +/// [`GpuFault::InvalidJob`]. +fn fault(e: Error) -> GpuFault { + match e { + Error::Device(_) | Error::Memory { .. } => GpuFault::Operation(format!("{PROVIDER_ID}: {e}")), + _ => invalid(e), + } +} + +fn format_token(f: Format) -> &'static str { + match f { + Format::Nv12 => "nv12", + Format::P010 => "p010", + Format::I420 => "i420", + } +} + +fn matrix_token(m: Matrix) -> &'static str { + match m { + Matrix::Bt601 => "bt601", + Matrix::Bt709 => "bt709", + Matrix::Bt2020 => "bt2020", + } +} + +fn range_token(r: Range) -> &'static str { + match r { + Range::Limited => "limited", + Range::Full => "full", + } +} + +impl YuvJob { + pub fn new(conversion: Conversion, src_width: u32, src_height: u32, width: u32, height: u32) -> YuvJob { + YuvJob { conversion, src_width, src_height, width, height } + } + + /// The job's parameters. + pub fn params(&self) -> GpuJobParams { + let c = self.conversion; + let text = format!( + "fmt:{};matrix:{};range:{};sw:{};sh:{};w:{};h:{}", + format_token(c.format), + matrix_token(c.matrix), + range_token(c.range), + self.src_width, + self.src_height, + self.width, + self.height + ); + GpuJobParams(text.into_bytes()) + } + + /// A `craft.yuv` job that converts the RGBA8 buffer `input`. + pub fn job(&self, input: HandleId) -> GpuJob { + GpuJob { provider_id: PROVIDER_ID.into(), params: self.params(), inputs: vec![input], outputs: Vec::new() } + } + + /// Read parameters written by [`YuvJob::params`]. + pub fn parse(params: &GpuJobParams) -> Result { + let text = std::str::from_utf8(¶ms.0).map_err(|_| invalid("the parameters are not UTF-8"))?; + let mut values: [Option<&str>; KEYS.len()] = [None; KEYS.len()]; + for field in text.split(';') { + let (key, value) = field.split_once(':').ok_or_else(|| invalid(format!("`{field}` is not a key:value field")))?; + let i = KEYS.iter().position(|k| *k == key).ok_or_else(|| invalid(format!("unknown key `{key}`")))?; + if values[i].replace(value).is_some() { + return Err(invalid(format!("`{key}` is given twice"))); + } + } + let get = |i: usize| values[i].ok_or_else(|| invalid(format!("`{}` is missing", KEYS[i]))); + let token = |i: usize, value: &str| invalid(format!("`{value}` is not a value of `{}`", KEYS[i])); + let format = match get(0)? { + "nv12" => Format::Nv12, + "p010" => Format::P010, + "i420" => Format::I420, + v => return Err(token(0, v)), + }; + let matrix = match get(1)? { + "bt601" => Matrix::Bt601, + "bt709" => Matrix::Bt709, + "bt2020" => Matrix::Bt2020, + v => return Err(token(1, v)), + }; + let range = match get(2)? { + "limited" => Range::Limited, + "full" => Range::Full, + v => return Err(token(2, v)), + }; + let side = |i: usize| -> Result { + let v = get(i)?; + if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) { + return Err(token(i, v)); + } + v.parse().map_err(|_| token(i, v)) + }; + Ok(YuvJob { + conversion: Conversion::new(format, matrix, range), + src_width: side(3)?, + src_height: side(4)?, + width: side(5)?, + height: side(6)?, + }) + } +} + +/// The `craft.yuv` provider. +/// +/// [`YuvProvider::new`] converts with [`cpu::convert`], on any context: the null context in tests +/// and CI, or a context whose device a provider cannot reach. [`YuvProvider::with_device`] +/// converts with the render passes on a device the caller holds, such as the one it already draws +/// with; the RGBA8 input and the output frame still move through the context's buffers. Both give +/// the same frame within the tolerance the crate's tests state. +pub struct YuvProvider { + device: Option, +} + +impl Default for YuvProvider { + fn default() -> Self { + Self::new() + } +} + +impl YuvProvider { + /// A provider that converts on the CPU. + pub fn new() -> YuvProvider { + YuvProvider { device: None } + } + + /// A provider that converts with the render passes on `device`. Each job waits for the device + /// to finish, so this is not available on `wasm32`, where a buffer map completes only from the + /// browser's event loop. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_device(device: wgpu::Device, queue: wgpu::Queue) -> YuvProvider { + YuvProvider { device: Some(device::DeviceRunner::new(device, queue)) } + } + + /// Whether jobs run on a device. + pub fn has_device(&self) -> bool { + self.device.is_some() + } + + fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result, Error> { + match &self.device { + Some(d) => d.convert(rgba, job), + None => cpu::convert(rgba, job.src_width, job.src_height, job.conversion, job.width, job.height), + } + } +} + +impl GpuProvider for YuvProvider { + fn id(&self) -> &'static str { + PROVIDER_ID + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let spec = YuvJob::parse(&job.params)?; + let [input] = job.inputs.as_slice() else { + return Err(invalid(format!("expects one RGBA8 input, not {}", job.inputs.len()))); + }; + if !job.outputs.is_empty() { + return Err(invalid("makes its own output buffer, so the job names no outputs")); + } + let YuvJob { conversion, src_width, src_height, width, height } = spec; + let layout = FrameLayout::new(conversion.format, width, height).map_err(fault)?; + let caps = ctx.caps(); + // An output side is also held to `cpu::MAX_SIDE`, so that both provider modes take the + // same jobs. + let limit = caps.max_texture_dimension_2d; + for (w, h, limit) in [(src_width, src_height, limit), (width, height, limit.min(cpu::MAX_SIDE))] { + if w > limit || h > limit { + return Err(fault(Error::TooLarge { width: w, height: h, limit })); + } + } + // The read-back buffer with its padded rows is the largest buffer a device run makes, so + // the null context refuses the same jobs a device with these caps does. + let needed = layout.buffer_size.max(layout.frame_bytes() as u64); + if needed > caps.max_buffer_size { + return Err(fault(Error::BufferLimit { needed, limit: caps.max_buffer_size })); + } + // The input's size is checked before its bytes are read. + let bytes = ctx.buffer_len(*input)?; + let expected = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4)); + if src_width == 0 || src_height == 0 || expected != Some(bytes) { + return Err(fault(Error::Source { width: src_width, height: src_height, bytes })); + } + let input_bytes = bytes as u64; + if input_bytes > caps.max_buffer_size { + return Err(fault(Error::BufferLimit { needed: input_bytes, limit: caps.max_buffer_size })); + } + let rgba = ctx.read_buffer(*input)?; + let frame = self.convert(&rgba, &spec).map_err(fault)?; + let output = ctx.upload_buffer("craft.yuv.frame", &frame)?; + Ok(GpuJobOutcome { outputs: vec![output], data: None }) + } +} + +#[cfg(not(target_arch = "wasm32"))] +mod device { + use std::sync::Mutex; + + use crate::gpu::{Converter, Planes}; + use crate::spec::{Conversion, Error}; + + use super::YuvJob; + + /// A device, its queue, and the converters made on it so far, one per conversion. + pub(super) struct DeviceRunner { + device: wgpu::Device, + queue: wgpu::Queue, + converters: Mutex>, + } + + fn device_error(e: impl std::fmt::Display) -> Error { + Error::Device(e.to_string()) + } + + impl DeviceRunner { + pub(super) fn new(device: wgpu::Device, queue: wgpu::Queue) -> DeviceRunner { + DeviceRunner { device, queue, converters: Mutex::new(Vec::new()) } + } + + /// `rgba` converted on the device, as one packed frame. Errors the device reports go to + /// error scopes and come back as [`Error::Device`]; a frame that cannot be allocated is + /// [`Error::Memory`]. + pub(super) fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result, Error> { + let (sw, sh) = (job.src_width, job.src_height); + let limit = self.device.limits().max_texture_dimension_2d; + if sw > limit || sh > limit { + return Err(Error::TooLarge { width: sw, height: sh, limit }); + } + // A converter leaves the cache while a job uses it, and goes back only when the device + // reported no error, so a converter whose pipelines failed is not used again. + let mut converters = self.converters.lock().map_err(|_| device_error("the converter cache lock is poisoned"))?; + let cached = take(&mut converters, job.conversion); + drop(converters); + let oom = self.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal = self.device.push_error_scope(wgpu::ErrorFilter::Internal); + let converter = cached.unwrap_or_else(|| Converter::new(&self.device, job.conversion)); + let recorded = self.record(&converter, rgba, job); + // The scopes are popped on every path, in the reverse of the order they were pushed, + // so that none stays open on the device. + let errors = [pollster::block_on(internal.pop()), pollster::block_on(validation.pop()), pollster::block_on(oom.pop())]; + if let Some(e) = errors.into_iter().flatten().next() { + return Err(device_error(e)); + } + if let Ok(mut converters) = self.converters.lock() { + converters.push(converter); + } + let (planes, buffer) = recorded?; + let (tx, rx) = std::sync::mpsc::channel(); + buffer.map_async(wgpu::MapMode::Read, .., move |result| { + let _ = tx.send(result); + }); + self.device.poll(wgpu::PollType::wait_indefinitely()).map_err(device_error)?; + rx.try_recv().map_err(|_| device_error("the read-back map did not complete"))?.map_err(device_error)?; + let mapped = buffer.get_mapped_range(..).map_err(device_error)?; + let bytes = planes.layout().frame_bytes(); + let mut frame = crate::cpu::reserve(bytes)?; + frame.resize(bytes, 0u8); + let unpacked = planes.layout().unpack(&mapped, &mut frame); + drop(mapped); + buffer.unmap(); + unpacked.map(|()| frame) + } + + /// Upload `rgba` and record and submit the passes and the copy into a read-back buffer. + fn record(&self, converter: &Converter, rgba: &[u8], job: &YuvJob) -> Result<(Planes, wgpu::Buffer), Error> { + // The output size is checked against the device before the source is uploaded, so a + // rejected job queues no upload. + let planes = converter.planes(&self.device, job.width, job.height)?; + let (sw, sh) = (job.src_width, job.src_height); + let size = wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }; + let texture = self.device.create_texture(&wgpu::TextureDescriptor { + label: Some("craft.yuv source"), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let layout = wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) }; + self.queue.write_texture(texture.as_image_copy(), rgba, layout, size); + let source = converter.bind(&self.device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("craft.yuv read-back"), + size: planes.layout().buffer_size, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft.yuv") }); + converter.draw(&mut encoder, &source, &planes)?; + planes.copy_to_buffer(&mut encoder, &buffer, 0)?; + self.queue.submit([encoder.finish()]); + Ok((planes, buffer)) + } + } + + /// Remove and return the converter of `conversion` from `converters`, if there is one. + fn take(converters: &mut Vec, conversion: Conversion) -> Option { + let i = converters.iter().position(|c| c.conversion() == conversion)?; + Some(converters.swap_remove(i)) + } +} + +#[cfg(target_arch = "wasm32")] +mod device { + use crate::spec::Error; + + use super::YuvJob; + + /// No device runs jobs on `wasm32`: [`super::YuvProvider::with_device`] is native only. + pub(super) enum DeviceRunner {} + + impl DeviceRunner { + pub(super) fn convert(&self, _rgba: &[u8], _job: &YuvJob) -> Result, Error> { + match *self {} + } + } +} diff --git a/crates/gpu-yuv/src/job_tests.rs b/crates/gpu-yuv/src/job_tests.rs new file mode 100644 index 0000000000..c1a723da4b --- /dev/null +++ b/crates/gpu-yuv/src/job_tests.rs @@ -0,0 +1,261 @@ +//! `craft.yuv` through the job contract: on `craft-gpu-null`, which needs no hardware, and with a +//! device when the machine has a graphics adapter. + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, ReadOutcome, ReadRequest, WorkerKind}; +use craft_gpu_null::NullContext; + +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +/// A null context with caps of the test's choosing, which counts the buffers read. +struct Capped { + inner: NullContext, + caps: DeviceCaps, + reads: usize, +} + +impl Capped { + fn new(caps: DeviceCaps) -> Capped { + Capped { inner: NullContext::new(WorkerKind::Main), caps, reads: 0 } + } +} + +impl GpuContext for Capped { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + fn worker_kind(&self) -> WorkerKind { + self.inner.worker_kind() + } + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result { + self.inner.upload_buffer(label, bytes) + } + fn buffer_len(&self, handle: HandleId) -> Result { + self.inner.buffer_len(handle) + } + fn request_read(&mut self, handle: HandleId) -> Result { + self.reads += 1; + self.inner.request_read(handle) + } + fn poll_reads(&mut self) -> Vec { + self.inner.poll_reads() + } + fn free_buffer(&mut self, handle: HandleId) { + self.inner.free_buffer(handle); + } + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + self.reads += 1; + self.inner.read_buffer(handle) + } +} + +fn registry(provider: YuvProvider) -> ProviderRegistry { + let mut r = ProviderRegistry::new(); + r.register(Box::new(provider)); + r +} + +/// Run `job` on `ctx` and read its one output back. +fn dispatch(r: &ProviderRegistry, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result, GpuFault> { + let outcome = r.dispatch(ctx, job)?; + assert_eq!(outcome.outputs.len(), 1); + assert_eq!(outcome.data, None); + ctx.read_buffer(outcome.outputs[0]) +} + +fn invalid(result: Result) -> String { + match result { + Err(GpuFault::InvalidJob(message)) => message, + other => panic!("expected an invalid job, got {other:?}"), + } +} + +#[test] +fn the_registry_runs_craft_yuv_on_the_null_context() { + let r = registry(YuvProvider::new()); + let mut ctx = NullContext::new(WorkerKind::Main); + let px = tests::noise(64, 36); + let input = ctx.upload_buffer("rgba", &px).unwrap(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + for (w, h) in [(64, 36), (32, 18), (100, 50)] { + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, w, h).job(input)).unwrap(); + assert_eq!(frame, cpu::convert(&px, 64, 36, c, w, h).unwrap(), "{c:?} {w}×{h}"); + assert_eq!(frame.len(), FrameLayout::new(format, w, h).unwrap().frame_bytes()); + } + } + } + } +} + +#[test] +fn parameters_read_back_as_written() { + let job = YuvJob::new(Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 1920, 1080, 1280, 720); + assert_eq!(job.params().0, b"fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720"); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let job = YuvJob::new(Conversion::new(format, matrix, range), 7, u32::MAX, 0, 4); + assert_eq!(YuvJob::parse(&job.params()), Ok(job)); + } + } + } + let job = YuvJob::new(Conversion::new(Format::P010, Matrix::Bt2020, Range::Full), 3, 5, 8, 6).job(HandleId(9)); + assert_eq!((job.provider_id.as_str(), job.inputs.as_slice(), job.outputs.len()), (PROVIDER_ID, [HandleId(9)].as_slice(), 0)); +} + +#[test] +fn bad_parameters_are_invalid_jobs() { + let good = "fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4"; + let cases: [(&[u8], &str); 14] = [ + (b"", "is not a key:value field"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4", "`h` is missing"), + (b"fmt:nv12;fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`fmt` is given twice"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;alpha:1", "unknown key `alpha`"), + (b"fmt:NV12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`NV12` is not a value of `fmt`"), + (b"fmt:nv12;matrix:bt2100;range:limited;sw:4;sh:4;w:4;h:4", "`bt2100` is not a value of `matrix`"), + (b"fmt:nv12;matrix:bt709;range:studio;sw:4;sh:4;w:4;h:4", "`studio` is not a value of `range`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:+4;sh:4;w:4;h:4", "`+4` is not a value of `sw`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:-4;w:4;h:4", "`-4` is not a value of `sh`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:;h:4", "`` is not a value of `w`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4294967296", "`4294967296` is not a value of `h`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;", "`` is not a key:value field"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4.0", "`4.0` is not a value of `h`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:\xff", "not UTF-8"), + ]; + assert!(YuvJob::parse(&GpuJobParams(good.as_bytes().to_vec())).is_ok()); + for (params, want) in cases { + let message = invalid(YuvJob::parse(&GpuJobParams(params.to_vec()))); + assert!(message.starts_with("craft.yuv: ") && message.contains(want), "{message:?} for {:?}", String::from_utf8_lossy(params)); + } +} + +#[test] +fn inputs_outputs_and_sizes_are_checked_before_any_read() { + let r = registry(YuvProvider::new()); + let mut ctx = Capped::new(DeviceCaps::default()); + let c = Conversion::new(Format::I420, Matrix::Bt601, Range::Limited); + let input = ctx.upload_buffer("rgba", &tests::noise(8, 4)).unwrap(); + let mut job = YuvJob::new(c, 8, 4, 8, 4).job(input); + job.inputs.clear(); + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("expects one RGBA8 input, not 0")); + job.inputs = vec![input, input]; + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("not 2")); + job.inputs = vec![input]; + job.outputs = vec![input]; + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("names no outputs")); + // A buffer whose size is not the source's, an odd or zero side, and a missing buffer. + let wrong = [ + YuvJob::new(c, 8, 8, 8, 4).job(input), + YuvJob::new(c, 0, 4, 8, 4).job(input), + YuvJob::new(c, 8, 4, 7, 4).job(input), + YuvJob::new(c, 8, 4, 8, 0).job(input), + YuvJob::new(c, u32::MAX, u32::MAX, 8, 4).job(input), + ]; + for job in &wrong { + invalid(r.dispatch(&mut ctx, job)); + } + assert!(matches!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(HandleId(99))), Err(GpuFault::InvalidJob(_)))); + assert_eq!(ctx.reads, 0, "no job above reads its input"); + assert!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(input)).is_ok()); + assert_eq!(ctx.reads, 1); +} + +#[test] +fn jobs_past_the_context_caps_are_refused() { + let r = registry(YuvProvider::new()); + let caps = DeviceCaps { max_texture_dimension_2d: 64, max_buffer_size: 16128, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let small = ctx.upload_buffer("small", &tests::noise(64, 4)).unwrap(); + let wide = ctx.upload_buffer("wide", &tests::noise(66, 2)).unwrap(); + // The source and the output sides against the largest texture side. + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 66, 2, 64, 2).job(wide))).contains("66×2 is larger than the largest texture side, 64")); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 66, 4).job(small))).contains("66×4")); + // NV12 read-back rows at width 64 are padded to 256 bytes: 64 × 44 packs into 4224 bytes + // but reads back through 256 × (44 + 22) = 16896, more than the 16128-byte limit; 64 × 42 + // reads back through exactly 16128. + assert_eq!(FrameLayout::new(Format::Nv12, 64, 44).unwrap().frame_bytes(), 4224); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 64, 44).job(small))); + assert!(refused.contains("16896 bytes is larger than the largest buffer, 16128"), "{refused}"); + assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 4, 64, 42).job(small)).is_ok()); +} + +#[test] +fn an_output_side_past_the_cpu_limit_is_refused_before_the_input_is_read() { + let r = registry(YuvProvider::new()); + let side = cpu::MAX_SIDE + 2; + let caps = DeviceCaps { max_texture_dimension_2d: side, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let input = ctx.upload_buffer("input", &tests::noise(2, 2)).unwrap(); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 2, 2, side, 2).job(input))); + assert!(refused.contains(&format!("{side}×2 is larger than the largest texture side, {}", cpu::MAX_SIDE)), "{refused}"); + assert_eq!(ctx.reads, 0, "the refused input is not read"); +} + +#[test] +fn an_input_past_the_buffer_limit_is_refused_before_it_is_read() { + let r = registry(YuvProvider::new()); + let caps = DeviceCaps { max_texture_dimension_2d: 64, max_buffer_size: 16128, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + // 64 × 64 × 4 = 16384 bytes, more than the 16128-byte limit; 64 × 63 × 4 is exactly 16128. + let large = ctx.upload_buffer("large", &tests::noise(64, 64)).unwrap(); + let at_limit = ctx.upload_buffer("at limit", &tests::noise(64, 63)).unwrap(); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 64, 64, 4).job(large))); + assert!(refused.contains("16384 bytes is larger than the largest buffer, 16128"), "{refused}"); + assert_eq!(ctx.reads, 0, "the refused input is not read"); + assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 63, 64, 4).job(at_limit)).is_ok()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_provider_with_a_device_matches_the_cpu_through_the_registry() { + let Some((device, queue)) = tests::device() else { return }; + let provider = YuvProvider::with_device(device, queue); + assert!(provider.has_device() && !YuvProvider::new().has_device()); + let r = registry(provider); + let mut ctx = NullContext::new(WorkerKind::Main); + let (noise, ramps) = (tests::noise(64, 36), tests::ramps(160, 90)); + let (n, s) = (ctx.upload_buffer("noise", &noise).unwrap(), ctx.upload_buffer("ramps", &ramps).unwrap()); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, 64, 36).job(n)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&noise, 64, 36, c, 64, 36).unwrap(), c, "64×36 through the registry"); + } + } + // Each conversion's converter is made once and used again: the second run of a + // conversion gives the same frame. + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + for (w, h) in [(80, 46), (240, 136)] { + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&ramps, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h} through the registry")); + assert_eq!(frame, dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap()); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_device_smaller_than_the_context_caps_refuses_the_job_without_a_device_error() { + let Some((device, queue)) = tests::device_with(|l| wgpu::Limits { max_texture_dimension_2d: 64, ..l }) else { return }; + let r = registry(YuvProvider::with_device(device, queue)); + // The null context's caps allow 8192, so only the device's own limit stops these. + let mut ctx = NullContext::new(WorkerKind::Main); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let big = ctx.upload_buffer("big", &tests::noise(128, 2)).unwrap(); + let small = ctx.upload_buffer("small", &tests::noise(8, 2)).unwrap(); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 128, 2, 8, 2).job(big))).contains("128×2 is larger than the largest texture side, 64")); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 2, 128, 2).job(small))).contains("128×2")); + // The device still runs a job that fits after refusing two. + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 8, 2, 8, 2).job(small)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&tests::noise(8, 2), 8, 2, c, 8, 2).unwrap(), c, "8×2 after two refusals"); +} diff --git a/crates/gpu-yuv/src/layout.rs b/crates/gpu-yuv/src/layout.rs new file mode 100644 index 0000000000..93b3f77269 --- /dev/null +++ b/crates/gpu-yuv/src/layout.rs @@ -0,0 +1,123 @@ +//! Where each plane sits in a read-back buffer and in a tightly packed frame. + +use crate::spec::{Error, Format}; + +/// One plane: its size in texels, the bytes of one texel, and where its rows start in a +/// read-back buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlaneLayout { + pub width: u32, + pub height: u32, + /// Bytes per texel: 1 or 2 for one sample, 2 or 4 for an interleaved Cb and Cr pair. + pub texel_bytes: u32, + /// The plane's first byte in the read-back buffer. + pub offset: u64, + /// Bytes from one row to the next in the read-back buffer, a multiple of + /// `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`. + pub bytes_per_row: u32, +} + +impl PlaneLayout { + /// Bytes of one row in a packed frame, or `u32::MAX` when the fields give more. + pub fn row_bytes(&self) -> u32 { + self.width.saturating_mul(self.texel_bytes) + } +} + +/// The planes of one frame of `format` at `width × height`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FrameLayout { + pub format: Format, + pub width: u32, + pub height: u32, + pub planes: Vec, + /// Bytes a read-back buffer needs from its offset. + pub buffer_size: u64, +} + +fn aligned(n: u32) -> Option { + let a = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + n.div_ceil(a).checked_mul(a) +} + +/// The planes of `format` at `width × height` (the first `count` of the array) and the read-back +/// buffer size. +fn planes_of(format: Format, width: u32, height: u32) -> Result<([PlaneLayout; 3], usize, u64), Error> { + if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 { + return Err(Error::OutputSize { width, height }); + } + let s = format.sample_bytes(); + let (cw, ch) = (width / 2, height / 2); + let (sizes, count) = match format { + Format::Nv12 | Format::P010 => ([(width, height, s), (cw, ch, 2 * s), (0, 0, 0)], 2), + Format::I420 => ([(width, height, s), (cw, ch, s), (cw, ch, s)], 3), + }; + let overflow = Error::Overflow { width, height }; + let mut offset = 0u64; + let mut tight = 0u64; + let mut planes = [PlaneLayout { width: 0, height: 0, texel_bytes: 0, offset: 0, bytes_per_row: 0 }; 3]; + for (plane, (w, h, texel_bytes)) in planes.iter_mut().zip(sizes).take(count) { + let row = w.checked_mul(texel_bytes).ok_or(overflow.clone())?; + let bytes_per_row = aligned(row).ok_or(overflow.clone())?; + *plane = PlaneLayout { width: w, height: h, texel_bytes, offset, bytes_per_row }; + offset = offset.checked_add(u64::from(bytes_per_row) * u64::from(h)).ok_or(overflow.clone())?; + tight = tight.checked_add(u64::from(row) * u64::from(h)).ok_or(overflow.clone())?; + } + // A packed frame must also fit in memory on this target. + usize::try_from(tight).map_err(|_| overflow)?; + Ok((planes, count, offset)) +} + +impl FrameLayout { + /// The layout of `format` at `width × height`; both sides must be even and not zero. + pub fn new(format: Format, width: u32, height: u32) -> Result { + let (planes, count, buffer_size) = planes_of(format, width, height)?; + Ok(FrameLayout { format, width, height, planes: planes[..count].to_vec(), buffer_size }) + } + + /// Whether the fields are what [`FrameLayout::new`] gives for the format and size. It does not + /// allocate, so a frame loop can call it. + fn is_valid(&self) -> bool { + matches!(planes_of(self.format, self.width, self.height), + Ok((planes, count, size)) if planes[..count] == self.planes[..] && size == self.buffer_size) + } + + /// Bytes of one tightly packed frame: the planes one after another, each row without padding. + /// Fields changed after [`FrameLayout::new`] that give more than `usize::MAX` give + /// `usize::MAX`. + pub fn frame_bytes(&self) -> usize { + self.planes + .iter() + .fold(0usize, |n, p| n.saturating_add((p.width as usize).saturating_mul(p.texel_bytes as usize).saturating_mul(p.height as usize))) + } + + /// Copy the planes from `padded` (a mapped read-back buffer, from the offset it was copied to) + /// into `frame` without the row padding. `frame` must be [`FrameLayout::frame_bytes`] long. + /// A layout whose fields differ from what [`FrameLayout::new`] gives is [`Error::Layout`]. + pub fn unpack(&self, padded: &[u8], frame: &mut [u8]) -> Result<(), Error> { + if !self.is_valid() { + return Err(Error::Layout); + } + if (padded.len() as u64) < self.buffer_size { + return Err(Error::BufferSize { needed: self.buffer_size, actual: padded.len() as u64 }); + } + let tight = self.frame_bytes(); + if frame.len() != tight { + return Err(Error::BufferSize { needed: tight as u64, actual: frame.len() as u64 }); + } + let mut out = frame; + for p in &self.planes { + let (row, padded_row) = (p.row_bytes() as usize, p.bytes_per_row as usize); + let (dst, rest) = out.split_at_mut(row * p.height as usize); + let src = padded.get(p.offset as usize..).unwrap_or_default(); + for (d, s) in dst.chunks_exact_mut(row).zip(src.chunks(padded_row)) { + // The layout and size checks above leave every row whole. + if let Some(s) = s.get(..row) { + d.copy_from_slice(s); + } + } + out = rest; + } + Ok(()) + } +} diff --git a/crates/gpu-yuv/src/lib.rs b/crates/gpu-yuv/src/lib.rs new file mode 100644 index 0000000000..24afb1a4aa --- /dev/null +++ b/crates/gpu-yuv/src/lib.rs @@ -0,0 +1,36 @@ +//! RGBA to 4:2:0 Y'CbCr on the GPU, for encoders and scopes. +//! +//! - [`YuvProvider`] is the `craft.yuv` [`craft_gpu::GpuProvider`]: a host registers it in a +//! [`craft_gpu::ProviderRegistry`] and dispatches [`YuvJob`]s, on the null context or on a device. +//! - [`Converter`] holds the render pipelines of one [`Conversion`]: a [`Format`] (NV12, P010 or +//! I420), a [`Matrix`] (BT.601, BT.709 or BT.2020) and a [`Range`] (limited or full), for a +//! caller that records the passes into its own command encoder. +//! - [`Converter::bind`] binds a source texture view once; [`Converter::planes`] makes the plane +//! textures of one output size; [`Converter::draw`] records the two passes. The source is scaled +//! to the output size. +//! - [`Planes::copy_to_buffer`] records the copies into a read-back buffer, and +//! [`FrameLayout::unpack`] turns the mapped buffer into one tightly packed frame. +//! - [`cpu::convert`] is the same conversion on the CPU. +//! +//! The matrix applies to the stored values as they are: the input must already be in the +//! output's primaries and transfer, and alpha is ignored. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod cpu; +mod gpu; +mod job; +mod layout; +mod spec; + +pub use gpu::{Converter, Planes, Source}; +pub use job::{PROVIDER_ID, YuvJob, YuvProvider}; +pub use layout::{FrameLayout, PlaneLayout}; +pub use spec::{Conversion, Error, Format, Matrix, Range}; + +#[cfg(test)] +mod job_tests; +#[cfg(test)] +mod oracle_tests; +#[cfg(test)] +mod tests; diff --git a/crates/gpu-yuv/src/oracle_tests.rs b/crates/gpu-yuv/src/oracle_tests.rs new file mode 100644 index 0000000000..303abad3c7 --- /dev/null +++ b/crates/gpu-yuv/src/oracle_tests.rs @@ -0,0 +1,350 @@ +//! Checks against sources outside this crate: code values computed here in `f64` from the Kr and +//! Kb values and the quantization each ITU-R recommendation states, the `yuv` crate's conversion +//! of the same pictures, and the plane layouts the formats' public definitions give. None of these +//! checks reads `spec::Coefficients`. +//! +//! - BT.601-7 section 2.5, : Kr 0.299, Kb 0.114. +//! - BT.709-6 items 3.2 to 3.5, : Kr 0.2126, Kb 0.0722; +//! limited range `INT[(219 E'Y + 16) 2^(n-8)]` and `INT[(224 E'C + 128) 2^(n-8)]`, where INT +//! rounds a fraction of 0.5 up. +//! - BT.2020-2 tables 4 and 5, : Kr 0.2627, Kb 0.0593, +//! quantized as in BT.709. +//! - BT.2100-3 table 9, : full range +//! `Round[(2^n - 1) E'Y]` and `Round[(2^n - 1) E'C + 2^(n-1)]`, with +//! `Round(x) = Sign(x) Floor(|x| + 0.5)`. +//! - NV12 and I420: the W3C WebCodecs `VideoPixelFormat` definitions, +//! . +//! - NV12 and P010: the Linux media API's semi-planar YUV formats and their sample 4×4 images, +//! . + +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +/// Kr and Kb as each recommendation states them. +fn kr_kb(m: Matrix) -> (f64, f64) { + match m { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020 => (0.2627, 0.0593), + } +} + +/// The unrounded luma, Cb and Cr code values of an 8-bit RGB color. +fn exact(rgb: [f64; 3], c: Conversion) -> [f64; 3] { + let (kr, kb) = kr_kb(c.matrix); + let [r, g, b] = rgb.map(|v| v / 255.0); + let y = kr * r + (1.0 - kr - kb) * g + kb * b; + let pb = (b - y) / (2.0 * (1.0 - kb)); + let pr = (r - y) / (2.0 * (1.0 - kr)); + let n = c.format.bits() as i32; + match c.range { + Range::Limited => { + let s = 2f64.powi(n - 8); + [(219.0 * y + 16.0) * s, (224.0 * pb + 128.0) * s, (224.0 * pr + 128.0) * s] + } + Range::Full => { + let m = 2f64.powi(n) - 1.0; + let half = 2f64.powi(n - 1); + [m * y, m * pb + half, m * pr + half] + } + } +} + +/// `Round(x) = Sign(x) Floor(|x| + 0.5)`, clamped to the codes of `bits`. `f64::round` is that +/// function; adding 0.5 in `f64` would take the largest value below a half up to 1. +fn round(x: f64, bits: u32) -> u16 { + x.round().clamp(0.0, f64::from((1u32 << bits) - 1)) as u16 +} + +/// Whether `got` is the rounded `exact` value. A value within 0.001 of a half may round either +/// way in `f32`, so there the floor and the ceiling of `exact`, clamped to the codes, both pass. +fn rounds_to(got: u16, exact: f64, bits: u32) -> bool { + let near_half = ((exact - exact.floor()) - 0.5).abs() < 1e-3; + let code = |v: f64| v.clamp(0.0, f64::from((1u32 << bits) - 1)) as u16; + got == round(exact, bits) || near_half && (got == code(exact.floor()) || got == code(exact.ceil())) +} + +#[test] +fn a_value_near_a_half_passes_only_as_its_floor_or_ceiling() { + assert!(rounds_to(128, 128.5, 8)); + assert!(rounds_to(129, 128.5, 8)); + assert!(!rounds_to(130, 128.5, 8)); + assert!(!rounds_to(127, 128.5, 8)); + assert!(rounds_to(255, 254.9995, 8)); + assert!(!rounds_to(254, 254.9, 8)); + assert!(rounds_to(0, -0.5, 8)); + assert!(!rounds_to(1, -0.5, 8)); + assert_eq!(round(0.5 - f64::EPSILON / 4.0, 8), 0); + assert_eq!(round(2.5, 8), 3); +} + +/// Every sample of a frame as its value (P010 words shifted down by 6). +fn samples(frame: &[u8], format: Format) -> Vec { + match format { + Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(), + Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(), + } +} + +/// The luma sample of pixel `(x, y)` and the Cb and Cr samples of the chroma texel over it, in +/// a packed frame of `w × h`. +fn at(s: &[u16], format: Format, w: usize, h: usize, x: usize, y: usize) -> [u16; 3] { + let luma = w * h; + let (cw, ch) = (w / 2, h / 2); + let c = (y / 2) * cw + x / 2; + match format { + Format::Nv12 | Format::P010 => [s[y * w + x], s[luma + 2 * c], s[luma + 2 * c + 1]], + Format::I420 => [s[y * w + x], s[luma + c], s[luma + cw * ch + c]], + } +} + +/// Channel values that include black, white, the 75% level (191), the limited-range nominal +/// levels and values one step from the ends. +const LEVELS: [u8; 9] = [0, 1, 16, 64, 128, 191, 235, 254, 255]; + +/// A picture of every color whose channels are in [`LEVELS`], each as a 2 × 2 block, so that no +/// sample depends on how chroma is subsampled. Returns the pixels, the side and the colors. +fn blocks() -> (Vec, u32, Vec<[u8; 3]>) { + let colors: Vec<[u8; 3]> = LEVELS.iter().flat_map(|&r| LEVELS.iter().flat_map(move |&g| LEVELS.iter().map(move |&b| [r, g, b]))).collect(); + let per_row = 27usize; + let side = per_row * 2; + let mut px = vec![0u8; side * side * 4]; + for (k, rgb) in colors.iter().enumerate() { + let (bx, by) = (k % per_row, k / per_row); + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let i = ((by * 2 + dy) * side + bx * 2 + dx) * 4; + px[i..i + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], 255]); + } + } + (px, side as u32, colors) +} + +/// Every block of `frame` against the equations. `slack` is 0 for the CPU and 1 for the GPU. +fn check_blocks(frame: &[u8], c: Conversion, side: u32, colors: &[[u8; 3]], slack: u16, what: &str) { + let s = samples(frame, c.format); + let side = side as usize; + for (k, rgb) in colors.iter().enumerate() { + let (x, y) = ((k % 27) * 2, (k / 27) * 2); + let got = at(&s, c.format, side, side, x, y); + let want = exact(rgb.map(f64::from), c); + for i in 0..3 { + let ok = rounds_to(got[i], want[i], c.format.bits()) || got[i].abs_diff(round(want[i], c.format.bits())) <= slack; + assert!(ok, "{what} {c:?} {rgb:?}: component {i} is {} where the equations give {:.4}", got[i], want[i]); + } + } +} + +#[test] +fn the_cpu_gives_the_codes_of_the_published_equations() { + let (px, side, colors) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = cpu::convert(&px, side, side, c, side, side).unwrap(); + check_blocks(&frame, c, side, &colors, 0, "CPU"); + } + } + } +} + +#[test] +fn nominal_levels_have_the_codes_the_recommendations_state() { + // White, black and neutral chroma are 235, 16 and 128 at limited range, 255, 0 and 128 at + // full range, times 4 (and 1023 for full white) at 10 bits. Chroma reaches 240 (960) for blue's + // Cb and red's Cr, and 16 (64) for yellow's Cb and cyan's Cr. At full range those are + // Round(255.5) and Round(0.5), clamped to 255 (1023) and 1. + for format in ALL { + let ten = format.bits() == 10; + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let (white, black, mid, high, low) = match (range, ten) { + (Range::Limited, false) => (235, 16, 128, 240, 16), + (Range::Limited, true) => (940, 64, 512, 960, 64), + (Range::Full, false) => (255, 0, 128, 255, 1), + (Range::Full, true) => (1023, 0, 512, 1023, 1), + }; + let code = |rgb: [u8; 3]| { + let frame = cpu::convert(&(0..4).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect::>(), 2, 2, c, 2, 2).unwrap(); + at(&samples(&frame, format), format, 2, 2, 0, 0) + }; + assert_eq!(code([255, 255, 255]), [white, mid, mid], "{c:?} white"); + assert_eq!(code([0, 0, 0]), [black, mid, mid], "{c:?} black"); + assert_eq!(code([0, 0, 255])[1], high, "{c:?} blue Cb"); + assert_eq!(code([255, 0, 0])[2], high, "{c:?} red Cr"); + assert_eq!(code([255, 255, 0])[1], low, "{c:?} yellow Cb"); + assert_eq!(code([0, 255, 255])[2], low, "{c:?} cyan Cr"); + } + } + } +} + +fn yuv_range(r: Range) -> yuv::YuvRange { + match r { + Range::Limited => yuv::YuvRange::Limited, + Range::Full => yuv::YuvRange::Full, + } +} + +fn yuv_matrix(m: Matrix) -> yuv::YuvStandardMatrix { + match m { + Matrix::Bt601 => yuv::YuvStandardMatrix::Bt601, + Matrix::Bt709 => yuv::YuvStandardMatrix::Bt709, + Matrix::Bt2020 => yuv::YuvStandardMatrix::Bt2020, + } +} + +/// The `yuv` crate's conversion of `px` (`w × h`) as one packed frame in this crate's order. +/// P010 takes 10-bit RGB there, so each channel is scaled to 0..=1023 and rounded first. +fn yuv_convert(px: &[u8], w: u32, h: u32, c: Conversion) -> Vec { + use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvConversionMode, YuvPlanarImageMut}; + let (range, matrix, mode) = (yuv_range(c.range), yuv_matrix(c.matrix), YuvConversionMode::Professional); + match c.format { + Format::Nv12 => { + let mut img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba_to_yuv_nv12(&mut img, px, w * 4, range, matrix, mode).unwrap(); + [img.y_plane.borrow(), img.uv_plane.borrow()].concat() + } + Format::I420 => { + let mut img = YuvPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba_to_yuv420(&mut img, px, w * 4, range, matrix, mode).unwrap(); + [img.y_plane.borrow(), img.u_plane.borrow(), img.v_plane.borrow()].concat() + } + Format::P010 => { + let wide: Vec = px.iter().map(|&v| (f64::from(v) * 1023.0 / 255.0).round() as u16).collect(); + let mut img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba10_to_p010(&mut img, &wide, w * 4, range, matrix).unwrap(); + [img.y_plane.borrow(), img.uv_plane.borrow()].concat().iter().flat_map(|v| v.to_le_bytes()).collect() + } + } +} + +/// The largest difference allowed from the `yuv` crate: 1 code value at 8 bits, and 2 at 10 bits, +/// where its input was rounded to 10 bits first. +fn yuv_tolerance(format: Format) -> u16 { + if format.bits() == 10 { 2 } else { 1 } +} + +#[test] +fn the_cpu_matches_the_yuv_crate() { + let (px, side, _) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let ours = samples(&cpu::convert(&px, side, side, c, side, side).unwrap(), format); + let theirs = samples(&yuv_convert(&px, side, side, c), format); + assert_eq!(ours.len(), theirs.len(), "{c:?}"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + assert!(a.abs_diff(*b) <= yuv_tolerance(format), "{c:?}: sample {i} is {a} here and {b} in the yuv crate"); + } + } + } + } +} + +#[test] +fn packed_planes_have_the_sizes_the_yuv_crate_allocates() { + use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvPlanarImageMut}; + for (w, h) in [(2, 2), (4, 4), (16, 10), (1920, 1080), (3840, 2160)] { + for format in ALL { + let l = FrameLayout::new(format, w, h).unwrap(); + let s = format.sample_bytes() as usize; + let packed: Vec<(usize, usize)> = l.planes.iter().map(|p| (p.row_bytes() as usize, p.row_bytes() as usize * p.height as usize)).collect(); + let theirs: Vec<(usize, usize)> = match format { + Format::Nv12 | Format::P010 => { + let img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + vec![(img.y_stride as usize * s, img.y_plane.borrow().len() * s), (img.uv_stride as usize * s, img.uv_plane.borrow().len() * s)] + } + Format::I420 => { + let img = YuvPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + vec![ + (img.y_stride as usize, img.y_plane.borrow().len()), + (img.u_stride as usize, img.u_plane.borrow().len()), + (img.v_stride as usize, img.v_plane.borrow().len()), + ] + } + }; + assert_eq!(packed, theirs, "{format} {w}×{h}: row bytes and plane bytes"); + assert_eq!(l.frame_bytes(), theirs.iter().map(|p| p.1).sum::(), "{format} {w}×{h}"); + } + } +} + +/// Sixteen different colors for a 4 × 4 picture. +fn sixteen() -> Vec<[u8; 3]> { + (0..16u32).map(|k| [(k * 17) as u8, ((k * 53 + 30) % 256) as u8, ((k * 91 + 60) % 256) as u8]).collect() +} + +/// The byte offset of luma sample `(x, y)`. +type LumaAt = fn(usize, usize) -> usize; +/// The byte offsets of the Cb and Cr samples of chroma texel `(x, y)`. +type ChromaAt = fn(usize, usize) -> (usize, usize); + +/// Where the public definitions put each sample of a 4 × 4 frame. +fn documented_offsets(format: Format) -> (LumaAt, ChromaAt) { + match format { + // "start + 0: Y'00 Y'01 Y'02 Y'03 ... start + 16: Cb00 Cr00 Cb01 Cr01, start + 20: Cb10 Cr10 Cb11 Cr11" + Format::Nv12 => (|x, y| y * 4 + x, |x, y| (16 + y * 4 + x * 2, 17 + y * 4 + x * 2)), + // Rows of 8 bytes: "start + 8: Y'10 ... start + 32: Cb00 Cr00 Cb01 Cr01, start + 40: Cb10 ..." + Format::P010 => (|x, y| y * 8 + x * 2, |x, y| (32 + y * 8 + x * 4, 34 + y * 8 + x * 4)), + // Y, then U, then V; each chroma plane has 2 rows of 2 samples. + Format::I420 => (|x, y| y * 4 + x, |x, y| (16 + y * 2 + x, 20 + y * 2 + x)), + } +} + +#[test] +fn a_4x4_frame_puts_each_sample_where_the_format_definitions_do() { + let colors = sixteen(); + let px: Vec = colors.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect(); + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + let frame = cpu::convert(&px, 4, 4, c, 4, 4).unwrap(); + assert_eq!(frame.len(), 4 * 4 * 3 / 2 * format.sample_bytes() as usize, "{format}"); + let read = |offset: usize| match format { + Format::P010 => { + let word = u16::from_le_bytes([frame[offset], frame[offset + 1]]); + assert_eq!(word & 0x3f, 0, "{format}: the 6 low bits are zero"); + word >> 6 + } + Format::Nv12 | Format::I420 => u16::from(frame[offset]), + }; + let (luma, chroma) = documented_offsets(format); + for y in 0..4 { + for x in 0..4 { + let want = exact(colors[y * 4 + x].map(f64::from), c)[0]; + assert!(rounds_to(read(luma(x, y)), want, format.bits()), "{format}: luma {x},{y}"); + } + } + for y in 0..2 { + for x in 0..2 { + // Each chroma sample is the code of the average of the 2 × 2 pixels under it. + let quad = [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(dx, dy)| colors[(y * 2 + dy) * 4 + x * 2 + dx]); + let mean = [0, 1, 2].map(|i| quad.iter().map(|p| f64::from(p[i])).sum::() / 4.0); + let want = exact(mean, c); + let (cb, cr) = chroma(x, y); + assert!(rounds_to(read(cb), want[1], format.bits()), "{format}: Cb {x},{y}"); + assert!(rounds_to(read(cr), want[2], format.bits()), "{format}: Cr {x},{y}"); + } + } + } +} + +#[test] +fn the_gpu_gives_the_codes_of_the_published_equations() { + let Some((device, queue)) = tests::device() else { return }; + let (px, side, colors) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = tests::gpu_convert(&device, &queue, (&px, side, side), c, (side, side)); + check_blocks(&frame, c, side, &colors, 1, "GPU"); + } + } + } +} diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs new file mode 100644 index 0000000000..2e311a9401 --- /dev/null +++ b/crates/gpu-yuv/src/spec.rs @@ -0,0 +1,193 @@ +//! What a conversion produces: the plane format, the matrix and the range, and the code values +//! they give. + +use std::fmt; + +/// The 4:2:0 layout a conversion writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Format { + /// 8 bits: the luma plane, then one plane of interleaved Cb and Cr samples. + Nv12, + /// 10 bits in the high bits of little-endian 16-bit words: the luma plane, then one plane of + /// interleaved Cb and Cr samples. + P010, + /// 8 bits: the luma plane, then the Cb plane, then the Cr plane. + I420, +} + +impl Format { + /// Bits per sample value. + pub fn bits(self) -> u32 { + match self { + Format::P010 => 10, + Format::Nv12 | Format::I420 => 8, + } + } + + /// Bytes each sample takes in memory. + pub fn sample_bytes(self) -> u32 { + match self { + Format::P010 => 2, + Format::Nv12 | Format::I420 => 1, + } + } + + /// The left shift from a sample value to the stored word: 6 for P010, else 0. + pub fn shift(self) -> u32 { + match self { + Format::P010 => 6, + Format::Nv12 | Format::I420 => 0, + } + } + + /// The format's usual name: `NV12`, `P010` or `I420`. + pub fn name(self) -> &'static str { + match self { + Format::Nv12 => "NV12", + Format::P010 => "P010", + Format::I420 => "I420", + } + } +} + +impl fmt::Display for Format { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// The RGB to Y'CbCr matrix (ITU-R BT.601, BT.709 and BT.2020 non-constant luminance). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Matrix { + Bt601, + Bt709, + Bt2020, +} + +impl Matrix { + /// The red and blue luma weights, Kr and Kb. + pub fn kr_kb(self) -> (f32, f32) { + match self { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020 => (0.2627, 0.0593), + } + } +} + +/// The code values the signal spans. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Range { + /// Luma from 16 to 235 and chroma from 16 to 240, scaled by 4 at 10 bits. + Limited, + /// Every code value, from 0 to 255 (1023 at 10 bits); chroma is centered on 128 (512). + Full, +} + +/// One conversion: the plane format, the matrix and the range. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Conversion { + pub format: Format, + pub matrix: Matrix, + pub range: Range, +} + +impl Conversion { + pub fn new(format: Format, matrix: Matrix, range: Range) -> Conversion { + Conversion { format, matrix, range } + } +} + +/// The weights and the scale of one conversion. The code value of luma is +/// `dot(y, rgb) * y_scale + y_offset`, of Cb `dot(cb, rgb) * c_scale + c_offset`, and of Cr +/// `dot(cr, rgb) * c_scale + c_offset`, rounded with halves away from zero and clamped to +/// `0..=max`, for `rgb` from 0 to 1. That rounding is `INT` in BT.709 and BT.2020 and `Round` in +/// BT.2100. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Coefficients { + pub y: [f32; 3], + pub cb: [f32; 3], + pub cr: [f32; 3], + pub y_scale: f32, + pub y_offset: f32, + pub c_scale: f32, + pub c_offset: f32, + pub max: f32, +} + +impl Coefficients { + pub fn of(c: Conversion) -> Coefficients { + let (kr, kb) = c.matrix.kr_kb(); + let kg = 1.0 - kr - kb; + let (db, dr) = (2.0 * (1.0 - kb), 2.0 * (1.0 - kr)); + let bits = c.format.bits(); + let max = ((1u32 << bits) - 1) as f32; + let step = (1u32 << (bits - 8)) as f32; + let (y_scale, y_offset, c_scale, c_offset) = match c.range { + Range::Limited => (219.0 * step, 16.0 * step, 224.0 * step, 128.0 * step), + Range::Full => (max, 0.0, max, (1u32 << (bits - 1)) as f32), + }; + Coefficients { y: [kr, kg, kb], cb: [-kr / db, -kg / db, 0.5], cr: [0.5, -kg / dr, -kb / dr], y_scale, y_offset, c_scale, c_offset, max } + } + + /// The code values of luma, Cb and Cr for `rgb`. + pub fn codes(&self, rgb: [f32; 3]) -> [u16; 3] { + let dot = |w: [f32; 3]| w[0] * rgb[0] + w[1] * rgb[1] + w[2] * rgb[2]; + let code = |v: f32| v.round().clamp(0.0, self.max) as u16; + [ + code(dot(self.y) * self.y_scale + self.y_offset), + code(dot(self.cb) * self.c_scale + self.c_offset), + code(dot(self.cr) * self.c_scale + self.c_offset), + ] + } +} + +/// What a conversion cannot do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// An output side is zero or odd; 4:2:0 needs both sides even. + OutputSize { width: u32, height: u32 }, + /// A side is larger than the device's largest 2D texture. + TooLarge { width: u32, height: u32, limit: u32 }, + /// The frame's byte sizes do not fit in the integer types that hold them. + Overflow { width: u32, height: u32 }, + /// A buffer the job uses (the RGBA8 input, or the read-back buffer for the frame) would be + /// larger than the device's largest buffer. + BufferLimit { needed: u64, limit: u64 }, + /// A source side is zero, or the pixels are not `width × height × 4` bytes. + Source { width: u32, height: u32, bytes: usize }, + /// A buffer or a frame does not have the size the layout needs. + BufferSize { needed: u64, actual: u64 }, + /// A buffer offset is not a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`. + Offset(u64), + /// The planes were made for another format than the converter's. + Mismatch { converter: Format, planes: Format }, + /// A frame layout's fields are not what [`crate::FrameLayout::new`] gives for its format and + /// size. + Layout, + /// A buffer of `bytes` bytes for the frame could not be allocated. + Memory { bytes: usize }, + /// The device reported an error (validation, out of memory, a failed map or poll) while + /// [`crate::YuvProvider`] ran a job on it. + Device(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::OutputSize { width, height } => write!(f, "a 4:2:0 picture of {width}×{height} needs both sides even and not zero"), + Error::TooLarge { width, height, limit } => write!(f, "{width}×{height} is larger than the largest texture side, {limit}"), + Error::Overflow { width, height } => write!(f, "a frame of {width}×{height} is too large to hold"), + Error::BufferLimit { needed, limit } => write!(f, "a buffer of {needed} bytes is larger than the largest buffer, {limit}"), + Error::Source { width, height, bytes } => write!(f, "{bytes} bytes are not an RGBA picture of {width}×{height}"), + Error::BufferSize { needed, actual } => write!(f, "{actual} bytes where {needed} are needed"), + Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), + Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"), + Error::Layout => f.write_str("the frame layout does not match its format and size"), + Error::Memory { bytes } => write!(f, "a buffer of {bytes} bytes could not be allocated"), + Error::Device(message) => write!(f, "the device reported an error: {message}"), + } + } +} + +impl std::error::Error for Error {} diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs new file mode 100644 index 0000000000..b0c601e773 --- /dev/null +++ b/crates/gpu-yuv/src/tests.rs @@ -0,0 +1,468 @@ +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +fn solid(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + (0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect() +} + +/// The first luma sample and the first Cb and Cr samples of a converted frame, as values. +fn first(frame: &[u8], format: Format, w: u32, h: u32) -> [u16; 3] { + let s = samples(frame, format); + let luma = (w * h) as usize; + let quarter = luma / 4; + match format { + Format::Nv12 | Format::P010 => [s[0], s[luma], s[luma + 1]], + Format::I420 => [s[0], s[luma], s[luma + quarter]], + } +} + +/// Every sample of a frame as its value (P010 words shifted down by 6). +fn samples(frame: &[u8], format: Format) -> Vec { + match format { + Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(), + Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(), + } +} + +fn cpu(rgb: [u8; 3], c: Conversion) -> [u16; 3] { + let frame = cpu::convert(&solid(2, 2, rgb), 2, 2, c, 2, 2).unwrap(); + first(&frame, c.format, 2, 2) +} + +#[test] +fn bt709_limited_colors_have_their_standard_codes() { + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + assert_eq!(cpu([255, 255, 255], c), [235, 128, 128]); + assert_eq!(cpu([0, 0, 0], c), [16, 128, 128]); + assert_eq!(cpu([255, 0, 0], c), [63, 102, 240]); + assert_eq!(cpu([0, 0, 255], c), [32, 240, 118]); +} + +#[test] +fn each_matrix_weights_red_by_its_kr() { + let red = |m| cpu([255, 0, 0], Conversion::new(Format::Nv12, m, Range::Limited)); + assert_eq!(red(Matrix::Bt601), [81, 90, 240]); + assert_eq!(red(Matrix::Bt2020), [74, 97, 240]); +} + +#[test] +fn full_range_spans_every_code() { + let c = Conversion::new(Format::I420, Matrix::Bt709, Range::Full); + assert_eq!(cpu([255, 255, 255], c), [255, 128, 128]); + assert_eq!(cpu([0, 0, 0], c), [0, 128, 128]); + assert_eq!(cpu([255, 0, 0], c), [54, 99, 255]); +} + +#[test] +fn p010_holds_ten_bit_codes_in_the_high_bits() { + let limited = Conversion::new(Format::P010, Matrix::Bt2020, Range::Limited); + assert_eq!(cpu([255, 255, 255], limited), [940, 512, 512]); + assert_eq!(cpu([0, 0, 0], limited), [64, 512, 512]); + let full = Conversion::new(Format::P010, Matrix::Bt2020, Range::Full); + assert_eq!(cpu([255, 255, 255], full), [1023, 512, 512]); + let frame = cpu::convert(&solid(2, 2, [255, 255, 255]), 2, 2, limited, 2, 2).unwrap(); + assert_eq!(&frame[..2], &(940u16 << 6).to_le_bytes()); + assert_eq!(frame.len(), 12); +} + +#[test] +fn planes_follow_each_format_s_order() { + let red = solid(4, 2, [255, 0, 0]); + let nv12 = cpu::convert(&red, 4, 2, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 4, 2).unwrap(); + assert_eq!(nv12, [63, 63, 63, 63, 63, 63, 63, 63, 102, 240, 102, 240]); + let i420 = cpu::convert(&red, 4, 2, Conversion::new(Format::I420, Matrix::Bt709, Range::Limited), 4, 2).unwrap(); + assert_eq!(i420, [63, 63, 63, 63, 63, 63, 63, 63, 102, 102, 240, 240]); +} + +#[test] +fn chroma_at_the_same_size_averages_the_four_pixels_it_covers() { + // Red over blue: chroma is the code of their average, magenta at half strength. + let mut px = solid(2, 1, [255, 0, 0]); + px.extend(solid(2, 1, [0, 0, 255])); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full); + let frame = cpu::convert(&px, 2, 2, c, 2, 2).unwrap(); + let half = cpu([128, 0, 128], c); + assert!(frame[4].abs_diff(half[1] as u8) <= 1 && frame[5].abs_diff(half[2] as u8) <= 1, "{frame:?} {half:?}"); +} + +#[test] +fn a_reduction_averages_the_area_under_each_texel() { + // One white column in four: a 4:1 reduction gives a quarter of white, where one bilinear tap + // at the texel's center would land between two black columns. + let px: Vec = (0..16).flat_map(|i| if i % 4 == 0 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect(); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full); + let frame = cpu::convert(&px, 8, 2, c, 2, 2).unwrap(); + assert_eq!(&frame[..4], &[64, 64, 64, 64]); +} + +#[test] +fn the_tap_count_grows_with_the_reduction_up_to_four() { + assert_eq!([0.5, 1.0, 2.0, 2.01, 4.0, 4.5, 8.0, 100.0].map(cpu::taps), [1, 1, 1, 2, 2, 3, 4, 4]); +} + +#[test] +fn bad_sizes_are_errors() { + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let px = solid(2, 2, [0, 0, 0]); + assert_eq!(cpu::convert(&px, 2, 2, c, 3, 2).unwrap_err(), Error::OutputSize { width: 3, height: 2 }); + assert_eq!(cpu::convert(&px, 2, 2, c, 0, 0).unwrap_err(), Error::OutputSize { width: 0, height: 0 }); + assert_eq!(cpu::convert(&px, 2, 3, c, 2, 2).unwrap_err(), Error::Source { width: 2, height: 3, bytes: 16 }); + assert_eq!(cpu::convert(&[], 0, 0, c, 2, 2).unwrap_err(), Error::Source { width: 0, height: 0, bytes: 0 }); + assert_eq!(FrameLayout::new(Format::P010, 4, 5).unwrap_err(), Error::OutputSize { width: 4, height: 5 }); + let big = cpu::MAX_SIDE + 2; + assert_eq!(cpu::convert(&px, 2, 2, c, big, 2).unwrap_err(), Error::TooLarge { width: big, height: 2, limit: cpu::MAX_SIDE }); + // Byte sizes past the integer types are an error, not an overflow. + let huge = u32::MAX - 1; + assert_eq!(FrameLayout::new(Format::P010, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 }); + assert_eq!(FrameLayout::new(Format::Nv12, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 }); + assert_eq!(Error::OutputSize { width: 3, height: 2 }.to_string(), "a 4:2:0 picture of 3×2 needs both sides even and not zero"); +} + +#[test] +fn a_frame_buffer_that_cannot_be_allocated_is_an_error() { + // A request past `isize::MAX` bytes fails on every allocator, so the failure path runs + // without exhausting memory. + assert_eq!(cpu::reserve::(usize::MAX).unwrap_err(), Error::Memory { bytes: usize::MAX }); + assert_eq!(cpu::reserve::(usize::MAX / 2).unwrap_err(), Error::Memory { bytes: usize::MAX - 1 }); + let room = cpu::reserve::(4096).unwrap(); + assert!(room.is_empty() && room.capacity() >= 4096); + assert_eq!(Error::Memory { bytes: 16 }.to_string(), "a buffer of 16 bytes could not be allocated"); +} + +#[test] +fn layouts_pad_rows_for_copies_and_unpack_without_the_padding() { + let l = FrameLayout::new(Format::Nv12, 1920, 1080).unwrap(); + assert_eq!( + l.planes.iter().map(|p| (p.width, p.height, p.offset, p.bytes_per_row)).collect::>(), + [(1920, 1080, 0, 2048), (960, 540, 2048 * 1080, 2048)] + ); + assert_eq!((l.buffer_size, l.frame_bytes()), (2048 * 1620, 1920 * 1620)); + let p = FrameLayout::new(Format::P010, 640, 360).unwrap(); + assert_eq!((p.planes[0].bytes_per_row, p.planes[1].texel_bytes, p.frame_bytes()), (1280, 4, 640 * 360 * 3)); + let i = FrameLayout::new(Format::I420, 4, 2).unwrap(); + assert_eq!(i.planes.iter().map(|p| p.offset).collect::>(), [0, 512, 768]); + let mut padded = vec![0u8; i.buffer_size as usize]; + padded[..4].copy_from_slice(&[1, 2, 3, 4]); + padded[256..260].copy_from_slice(&[5, 6, 7, 8]); + padded[512..514].copy_from_slice(&[9, 10]); + padded[768..770].copy_from_slice(&[11, 12]); + let mut frame = vec![0u8; i.frame_bytes()]; + i.unpack(&padded, &mut frame).unwrap(); + assert_eq!(frame, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + assert_eq!(i.unpack(&padded[..100], &mut frame).unwrap_err(), Error::BufferSize { needed: 1024, actual: 100 }); + assert_eq!(i.unpack(&padded, &mut [0; 3]).unwrap_err(), Error::BufferSize { needed: 12, actual: 3 }); +} + +#[test] +fn unpack_refuses_a_layout_that_was_changed_after_it_was_made() { + let l = FrameLayout::new(Format::I420, 4, 2).unwrap(); + let padded = vec![0u8; l.buffer_size as usize]; + let changes: [fn(&mut FrameLayout); 6] = [ + |l| l.planes[0].bytes_per_row = 0, + |l| l.planes[0].width = 0, + |l| l.planes[0].texel_bytes = 0, + |l| l.planes[0].offset = 768, + |l| l.planes[0].bytes_per_row = 2, + |l| l.planes.truncate(1), + ]; + for (n, change) in changes.iter().enumerate() { + let mut bad = l.clone(); + change(&mut bad); + let mut frame = vec![0u8; bad.frame_bytes()]; + assert_eq!(bad.unpack(&padded, &mut frame), Err(Error::Layout), "change {n}"); + } + assert_eq!(Error::Layout.to_string(), "the frame layout does not match its format and size"); +} + +#[test] +fn sizes_of_a_changed_layout_saturate_instead_of_overflowing() { + let mut l = FrameLayout::new(Format::I420, 4, 2).unwrap(); + let huge = PlaneLayout { width: u32::MAX, height: u32::MAX, texel_bytes: 4, offset: 0, bytes_per_row: 0 }; + assert_eq!(huge.row_bytes(), u32::MAX); + l.planes = vec![PlaneLayout { height: 1, ..huge }]; + let full = usize::try_from(u64::from(u32::MAX) * 4).unwrap_or(usize::MAX); + assert_eq!(l.frame_bytes(), full, "a row past u32::MAX bytes counts in full"); + l.planes = vec![huge; 3]; + assert_eq!(l.frame_bytes(), usize::MAX); + assert_eq!(l.unpack(&[], &mut []), Err(Error::Layout)); +} + +#[test] +fn an_enlarged_solid_color_keeps_its_codes() { + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + let frame = cpu::convert(&solid(3, 1, [10, 200, 90]), 3, 1, c, 8, 6).unwrap(); + let expect = cpu([10, 200, 90], c); + let s = samples(&frame, format); + assert_eq!(s.len(), 8 * 6 * 3 / 2); + assert!(s[..48].iter().all(|&v| v == expect[0]), "{format}"); + } +} + +#[test] +fn shaders_write_no_value_wgsl_cannot_read() { + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let s = gpu::shader(Conversion::new(format, matrix, range)); + assert!(!s.contains("NaN") && !s.contains("inf"), "{s}"); + assert!(s.contains("fn fs_chroma") && s.contains("fn fs_luma")); + } + } + } +} + +// The GPU half: the passes against the CPU reference. A machine without a graphics adapter skips +// these comparisons and says so on stderr. + +pub(crate) fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + device_with(|l| l) +} + +/// A device with the adapter's limits as `limits` changes them. +pub(crate) fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgpu::Device, wgpu::Queue)> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { + eprintln!("no graphics adapter: the GPU half of this test is skipped"); + return None; + }; + let desc = wgpu::DeviceDescriptor { required_limits: limits(adapter.limits()), ..Default::default() }; + match pollster::block_on(adapter.request_device(&desc)) { + Ok(d) => Some(d), + Err(e) => { + eprintln!("the graphics adapter did not open ({e}): the GPU half of this test is skipped"); + None + } + } +} + +/// `src` (its pixels, width and height) converted on the GPU to `out` (width and height). +pub(crate) fn gpu_convert(device: &wgpu::Device, queue: &wgpu::Queue, src: (&[u8], u32, u32), c: Conversion, out: (u32, u32)) -> Vec { + let ((rgba, sw, sh), (w, h)) = (src, out); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + texture.as_image_copy(), + rgba, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) }, + wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }, + ); + let converter = Converter::new(device, c); + let source = converter.bind(device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let planes = converter.planes(device, w, h).unwrap(); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 256 + planes.layout().buffer_size, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + converter.draw(&mut enc, &source, &planes).unwrap(); + planes.copy_to_buffer(&mut enc, &buffer, 256).unwrap(); + queue.submit([enc.finish()]); + buffer.map_async(wgpu::MapMode::Read, 256.., |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let view = buffer.get_mapped_range(256..).unwrap(); + let mut frame = vec![0; planes.layout().frame_bytes()]; + planes.layout().unpack(&view, &mut frame).unwrap(); + frame +} + +/// The tolerance in code values: 2 at 8 bits and 6 at 10 bits. GPUs filter with fewer bits of +/// weight than `f32` and may round a half the other way. +fn tolerance(format: Format) -> u16 { + if format.bits() == 10 { 6 } else { 2 } +} + +pub(crate) fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { + assert_eq!(gpu.len(), cpu.len(), "{what}"); + let (g, k) = (samples(gpu, c.format), samples(cpu, c.format)); + let worst = g.iter().zip(&k).enumerate().max_by_key(|(_, (a, b))| a.abs_diff(**b)); + if let Some((i, (a, b))) = worst { + assert!(a.abs_diff(*b) <= tolerance(c.format), "{what} {c:?}: sample {i} is {a} on the GPU and {b} on the CPU"); + } +} + +/// A picture with hard edges: each pixel's channels from a fixed pseudo-random sequence. +pub(crate) fn noise(w: u32, h: u32) -> Vec { + let mut x = 0x2545_f491_u32; + (0..w * h * 4) + .map(|i| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + if i % 4 == 3 { 255 } else { (x >> 24) as u8 } + }) + .collect() +} + +/// A smooth picture: three ramps at different angles. +pub(crate) fn ramps(w: u32, h: u32) -> Vec { + (0..h) + .flat_map(|y| { + (0..w).flat_map(move |x| { + let (u, v) = (x as f32 / w as f32, y as f32 / h as f32); + [(u * 255.0) as u8, (v * 255.0) as u8, ((1.0 - (u + v) * 0.5) * 255.0) as u8, 255] + }) + }) + .collect() +} + +#[test] +fn the_gpu_matches_the_cpu_at_the_same_size() { + let Some((device, queue)) = device() else { return }; + let px = noise(64, 36); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let g = gpu_convert(&device, &queue, (&px, 64, 36), c, (64, 36)); + assert_close(&g, &cpu::convert(&px, 64, 36, c, 64, 36).unwrap(), c, "64×36 at the same size"); + } + } + } +} + +#[test] +fn the_gpu_matches_the_cpu_when_scaling() { + let Some((device, queue)) = device() else { return }; + let px = ramps(160, 90); + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + for (w, h) in [(80, 46), (32, 18), (16, 10), (240, 136)] { + let g = gpu_convert(&device, &queue, (&px, 160, 90), c, (w, h)); + assert_close(&g, &cpu::convert(&px, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h}")); + } + let odd = ramps(37, 23); + let g = gpu_convert(&device, &queue, (&odd, 37, 23), c, (20, 12)); + assert_close(&g, &cpu::convert(&odd, 37, 23, c, 20, 12).unwrap(), c, "37×23 to 20×12"); + } +} + +#[test] +fn the_gpu_rounds_a_value_just_below_a_half_down() { + let Some((device, queue)) = device() else { return }; + // The shader's own code(), driven by one extra entry point. The values are built from the + // texel position so that no compiler folds them: k is 0 at the only texel's center. + // 0x3effffff is 0.49999997, the largest f32 below 0.5, and 0x3f7fffff is 0.99999994. + let probe = "@fragment fn fs_probe(@builtin(position) pos: vec4) -> @location(0) vec4 { + let k = u32(pos.x); + let z = f32(k); + return vec4(code(bitcast(0x3effffffu + k)), code(0.5 + z), code(2.5 + z), code(bitcast(0x3f7fffffu + k))); +}"; + let wgsl = gpu::shader(Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full)) + probe; + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(wgsl.into()) }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: None, + layout: None, + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs_probe"), + targets: &[Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba8Uint, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Uint, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 256, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + { + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&pipeline); + pass.draw(0..3, 0..1); + } + enc.copy_texture_to_buffer( + texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: Some(1) }, + }, + wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + ); + queue.submit([enc.finish()]); + buffer.map_async(wgpu::MapMode::Read, .., |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let got = buffer.get_mapped_range(..4).unwrap().to_vec(); + assert_eq!(got, [0, 1, 3, 1], "code() of 0.49999997, 0.5, 2.5 and 0.99999994"); +} + +#[test] +fn planes_larger_than_the_device_allows_are_errors() { + // The queue stays alive: a device whose queue was dropped cannot make an encoder. + let Some((device, _queue)) = device() else { return }; + let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited)); + let limit = device.limits().max_texture_dimension_2d; + let too_big = (limit + 2) & !1; + assert_eq!(converter.planes(&device, too_big, 2).err(), Some(Error::TooLarge { width: too_big, height: 2, limit })); + let planes = converter.planes(&device, 4, 2).unwrap(); + let other = Converter::new(&device, Conversion::new(Format::P010, Matrix::Bt709, Range::Limited)); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 4, height: 2, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + let source = other.bind(&device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + assert_eq!(other.draw(&mut enc, &source, &planes).unwrap_err(), Error::Mismatch { converter: Format::P010, planes: Format::Nv12 }); + let small = + device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 256, usage: wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + assert_eq!(planes.copy_to_buffer(&mut enc, &small, 0).unwrap_err(), Error::BufferSize { needed: 768, actual: 256 }); + assert_eq!(planes.copy_to_buffer(&mut enc, &small, 4).unwrap_err(), Error::Offset(4)); +} + +#[test] +fn planes_whose_read_back_is_larger_than_the_largest_buffer_are_errors() { + let Some((device, _queue)) = device_with(|l| wgpu::Limits { max_buffer_size: 1 << 20, ..l }) else { return }; + let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited)); + // 1024 × 1024 NV12 reads back 1.5 MiB. + assert_eq!(converter.planes(&device, 1024, 1024).err(), Some(Error::BufferLimit { needed: 1024 * 1536, limit: 1 << 20 })); + assert!(converter.planes(&device, 512, 512).is_ok()); +} diff --git a/crates/gpu/src/caps.rs b/crates/gpu/src/caps.rs index 75dcf173d0..1ae87a0d30 100644 --- a/crates/gpu/src/caps.rs +++ b/crates/gpu/src/caps.rs @@ -20,6 +20,20 @@ pub struct DeviceCaps { /// never on what the adapter merely advertised. #[serde(default)] pub features: Vec, + /// The PCI vendor id of the device's adapter (or the Khronos vendor id some Vulkan drivers + /// report instead); 0 when unknown or on backends with no device. + #[serde(default)] + pub vendor_id: u32, + /// The device draws on the CPU (a software adapter such as WARP, llvmpipe or lavapipe). + #[serde(default)] + pub software: bool, +} + +impl DeviceCaps { + /// Whether the feature named `name` (as in [`features`](Self::features)) is enabled. + pub fn has_feature(&self, name: &str) -> bool { + self.features.iter().any(|f| f == name) + } } impl Default for DeviceCaps { @@ -31,6 +45,8 @@ impl Default for DeviceCaps { max_buffer_size: 256 * 1024 * 1024, max_texture_dimension_2d: 8192, features: Vec::new(), + vendor_id: 0, + software: false, } } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 528b2e587d..25ee131bc3 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -126,3 +126,15 @@ fn chunk_buffer_splits_on_storage_binding_limit() { let chunks = chunk_buffer(&caps, b"abcdef").expect("chunk_buffer"); assert_eq!(chunks, vec![&b"abcd"[..], &b"ef"[..]]); } + +#[test] +fn caps_without_vendor_or_software_read_as_unknown_hardware() { + let json = r#"{"backend_name":"Vulkan","device_name":"gpu","max_storage_buffer_binding_size":1,"max_buffer_size":2,"max_texture_dimension_2d":3,"features":["TEXTURE_FORMAT_NV12"]}"#; + let caps: DeviceCaps = serde_json::from_str(json).expect("caps"); + assert_eq!((caps.vendor_id, caps.software), (0, false)); + assert!(caps.has_feature("TEXTURE_FORMAT_NV12")); + assert!(!caps.has_feature("TEXTURE_FORMAT_P010") && !caps.has_feature("")); + let software = DeviceCaps { vendor_id: 0x10005, software: true, ..caps }; + let back: DeviceCaps = serde_json::from_str(&serde_json::to_string(&software).expect("json")).expect("caps"); + assert_eq!(back, software); +} diff --git a/crates/host/src/queue.rs b/crates/host/src/queue.rs index 8133d17e64..2dc1d34f60 100644 --- a/crates/host/src/queue.rs +++ b/crates/host/src/queue.rs @@ -47,9 +47,20 @@ impl Priority { /// The cancel flag a running job reads. The queue sets it when the job's key is dropped /// ([`JobQueue::reprioritize`] returning `None`, [`JobQueue::shutdown`], dropping the queue); a /// long job checks [`is_cancelled`](Cancel::is_cancelled) between steps and returns early. A -/// cancelled job's result is never delivered. Cloning shares the flag. +/// cancelled job's result is never delivered. A job that has nothing to do until it is cancelled +/// blocks in [`wait`](Cancel::wait) or [`wait_timeout`](Cancel::wait_timeout). Cloning shares the +/// flag. #[derive(Clone, Debug, Default)] -pub struct Cancel(Arc); +pub struct Cancel(Arc); + +/// The shared state behind a [`Cancel`]: the flag, and the lock and condition variable that wake +/// its waiters when it is set. +#[derive(Debug, Default)] +struct CancelFlag { + set: AtomicBool, + lock: Mutex<()>, + changed: Condvar, +} impl Cancel { /// A flag that is not set (tests call a decoder with it). @@ -59,12 +70,32 @@ impl Cancel { /// Whether the job should stop. pub fn is_cancelled(&self) -> bool { - self.0.load(Ordering::Relaxed) + self.0.set.load(Ordering::Relaxed) } - /// Sets the flag. + /// Sets the flag and wakes every thread blocked in [`wait`](Cancel::wait) or + /// [`wait_timeout`](Cancel::wait_timeout). pub fn cancel(&self) { - self.0.store(true, Ordering::Relaxed); + let guard = self.0.lock.lock().unwrap_or_else(|e| e.into_inner()); + self.0.set.store(true, Ordering::Relaxed); + drop(guard); + self.0.changed.notify_all(); + } + + /// Blocks the calling thread until the flag is set, and returns at once when it already is. + /// Another thread must call [`cancel`](Cancel::cancel): on wasm32, where a job runs on the + /// thread that would cancel it, a call that has to wait never returns. + pub fn wait(&self) { + let guard = self.0.lock.lock().unwrap_or_else(|e| e.into_inner()); + drop(self.0.changed.wait_while(guard, |_| !self.0.set.load(Ordering::Relaxed)).unwrap_or_else(|e| e.into_inner())); + } + + /// Blocks the calling thread until the flag is set or `timeout` has passed, and returns + /// whether the flag is set. A zero `timeout` reads the flag without waiting. + pub fn wait_timeout(&self, timeout: Duration) -> bool { + let guard = self.0.lock.lock().unwrap_or_else(|e| e.into_inner()); + drop(self.0.changed.wait_timeout_while(guard, timeout, |_| !self.0.set.load(Ordering::Relaxed)).unwrap_or_else(|e| e.into_inner())); + self.is_cancelled() } } diff --git a/crates/host/src/queue_tests.rs b/crates/host/src/queue_tests.rs index 86565c9792..bbd4ca99a7 100644 --- a/crates/host/src/queue_tests.rs +++ b/crates/host/src/queue_tests.rs @@ -1,9 +1,12 @@ //! `JobQueue` and `ManualJobs`: order, replacement, one job per key, cancellation, wakes and //! inline runs. Every test drives lanes with `ManualJobs` (or `lanes: 0`), so nothing depends on -//! thread timing. +//! thread timing. The tests of `Cancel::wait` block a second thread and hand off over channels. use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{self, TryRecvError}; +use std::thread; +use std::time::Duration; use crate::queue::{Cancel, Finished, JobQueue, Priority, QueueOptions, QueueOrder}; use crate::{ManualJobs, Wake}; @@ -83,6 +86,62 @@ fn queue_dropped_keys_are_cancelled() { assert!(!queue.contains(&"waiting") && !queue.contains(&"running")); } +// `wait_timeout` reads the flag, a clone shares it, and `wait` returns at once on a set flag. +#[test] +fn cancel_wait_timeout_reports_the_flag() { + let cancel = Cancel::new(); + let shared = cancel.clone(); + assert!(!cancel.wait_timeout(Duration::ZERO)); + shared.cancel(); + assert!(cancel.is_cancelled()); + assert!(cancel.wait_timeout(Duration::ZERO)); + cancel.wait(); +} + +// A thread blocked in `wait` returns once another thread cancels. The 60-second bound only fails +// the test when the wake never comes. +#[test] +fn cancel_wait_returns_once_another_thread_cancels() { + let cancel = Cancel::new(); + let (started, has_started) = mpsc::channel(); + let (returned, has_returned) = mpsc::channel(); + let waiter = { + let cancel = cancel.clone(); + thread::spawn(move || { + let _ = started.send(()); + cancel.wait(); + let _ = returned.send(()); + }) + }; + has_started.recv().expect("the waiter starts"); + assert_eq!(has_returned.try_recv(), Err(TryRecvError::Empty), "wait returned before the cancel"); + cancel.cancel(); + has_returned.recv_timeout(Duration::from_secs(60)).expect("wait returns after the cancel"); + waiter.join().expect("the waiter ends"); +} + +// A running job blocked in `wait` ends when the queue drops its key, and its result never arrives. +#[test] +fn a_job_waiting_on_its_cancel_ends_when_its_key_is_dropped() { + let (queue, jobs, wakes) = queue(1); + let (started, has_started) = mpsc::channel(); + queue.submit("running", Priority::VISIBLE, move |cancel: &Cancel| { + let _ = started.send(()); + cancel.wait(); + "running" + }); + let (ran, has_run) = mpsc::channel(); + let lane = thread::spawn(move || { + let _ = ran.send(jobs.run_all()); + }); + has_started.recv().expect("the job starts"); + assert_eq!(queue.reprioritize(|_, _| None), ["running"]); + assert_eq!(has_run.recv_timeout(Duration::from_secs(60)), Ok(1), "the job ends after the cancel"); + lane.join().expect("the lane ends"); + assert!(drain(&queue).is_empty()); + assert_eq!(wakes.load(Ordering::Relaxed), 0); +} + // The wake is called once per finished job, never for a dropped or cancelled one. // With `lanes == 0` nothing runs on submit; `run_inline(1)` runs the best job and returns 1. diff --git a/crates/image-codecs/src/codecs/avif.rs b/crates/image-codecs/src/codecs/avif.rs index 042b5684b1..062b3f0539 100644 --- a/crates/image-codecs/src/codecs/avif.rs +++ b/crates/image-codecs/src/codecs/avif.rs @@ -225,7 +225,7 @@ pub fn encode_avif_hdr( mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn sdr_avif_uses_requested_alpha_quality() { + fn feature_config_sdr_avif_uses_requested_alpha_quality() { use crate::{ChannelLayout, Image}; let pixels: Vec = (0..1024).map(|i| ravif::RGBA8::new(100, 120, 140, ((i * 37) % 256) as u8)).collect(); @@ -246,7 +246,7 @@ mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn sdr_avif_keeps_exif_metadata() { + fn feature_config_sdr_avif_keeps_exif_metadata() { use crate::{ChannelLayout, Image}; let exif = b"II*\0shared-avif-exif".to_vec(); @@ -259,7 +259,7 @@ mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn hlg_mapping_matches_reference_white_and_peak() { + fn feature_config_hlg_mapping_matches_reference_white_and_peak() { let white = super::hlg_signal([1.0; 3]); assert!(white.iter().all(|&value| (value - 0.75).abs() < 0.005), "{white:?}"); @@ -272,7 +272,7 @@ mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn hlg_encoded_output_signals_bt2020_hlg() { + fn feature_config_hlg_encoded_output_signals_bt2020_hlg() { let avif = super::encode_avif_hdr(1, 1, &[1.0; 3], 100, 10, None, super::HdrTransfer::Hlg).unwrap(); let nclx = avif.windows(4).position(|window| window == b"nclx").expect("the AVIF has nclx color metadata"); let color = avif.get(nclx + 4..nclx + 11).expect("complete nclx color metadata"); @@ -284,7 +284,7 @@ mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn hlg_encoded_pixels_preserve_reference_white_and_peak() { + fn feature_config_hlg_encoded_pixels_preserve_reference_white_and_peak() { let mut rgb = Vec::new(); for _ in 0..32 { for x in 0..64 { diff --git a/crates/image-codecs/src/codecs/avif_decode.rs b/crates/image-codecs/src/codecs/avif_decode.rs index 4435da66bf..22f1f8aaec 100644 --- a/crates/image-codecs/src/codecs/avif_decode.rs +++ b/crates/image-codecs/src/codecs/avif_decode.rs @@ -1004,7 +1004,7 @@ mod tests { } #[test] - fn libaom_420_limited_range_matches_dav1d() { + fn feature_config_libaom_420_limited_range_matches_dav1d() { let img = crate::decode(QUAD_420).unwrap(); assert_eq!((img.width(), img.height(), img.layout(), img.sample_type()), (33, 17, ChannelLayout::Rgb, SampleType::U8)); assert_eq!(img.cicp.map(|c| (c.matrix, c.full_range)), Some((1, false)), "BT.709 matrix, limited range"); @@ -1025,7 +1025,7 @@ mod tests { } #[test] - fn libaom_lossless_identity_matrix_is_exact() { + fn feature_config_libaom_lossless_identity_matrix_is_exact() { let img = crate::decode(QUAD_GBR_LOSSLESS).unwrap(); assert_eq!((img.width(), img.height(), img.sample_type()), (33, 17, SampleType::U8)); assert_eq!(img.cicp.map(|c| (c.matrix, c.full_range)), Some((0, true))); @@ -1033,7 +1033,7 @@ mod tests { } #[test] - fn limits_are_checked_before_decoding() { + fn feature_config_limits_are_checked_before_decoding() { let tight = |max_pixels, max_alloc| DecodeOptions { limits: Limits { max_pixels, max_alloc, ..Limits::default() }, ..Default::default() }; assert!(matches!(crate::decode_with(QUAD_420, &tight(33 * 17 - 1, u64::MAX)), Err(CodecError::LimitExceeded(_)))); // The 16-bit intermediate counts: 33 × 17 RGB at 2 bytes. @@ -1049,14 +1049,14 @@ mod tests { } #[test] - fn a_picture_that_differs_from_its_ispe_is_refused() { + fn feature_config_a_picture_that_differs_from_its_ispe_is_refused() { let (av1, cfg) = av1_of(QUAD_420); let file = build(&[(1, b"av01", &av1, &[1, 2])], &[ispe(32, 17), bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat())], &[]); assert!(matches!(crate::decode(&file), Err(CodecError::Malformed { .. }))); } #[test] - fn a_grid_is_assembled_from_its_tiles_and_cropped() { + fn feature_config_a_grid_is_assembled_from_its_tiles_and_cropped() { // Two copies of the 33 × 17 picture side by side, cropped to 60 × 15 by the grid. let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); @@ -1087,7 +1087,7 @@ mod tests { } #[test] - fn container_rotation_and_mirror_are_applied_unless_kept() { + fn feature_config_container_rotation_and_mirror_are_applied_unless_kept() { let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); let file = build(&[(1, b"av01", &av1, &[1, 2, 3, 4])], &[ispe(33, 17), av1c, bx(b"irot", &[1]), bx(b"imir", &[0])], &[]); @@ -1112,7 +1112,7 @@ mod tests { } #[test] - fn clean_aperture_sizes_are_unsigned() { + fn feature_config_clean_aperture_sizes_are_unsigned() { let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); // A 2 × 2 aperture with its width written as 0x80000000 / 0x40000000, centred one pixel @@ -1134,7 +1134,7 @@ mod tests { } #[test] - fn repeated_transforms_are_refused() { + fn feature_config_repeated_transforms_are_refused() { let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); // the same irot associated twice, and through two ipma entries for the item @@ -1171,7 +1171,7 @@ mod tests { } #[test] - fn alpha_with_transforms_of_its_own_is_refused() { + fn feature_config_alpha_with_transforms_of_its_own_is_refused() { let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); let auxc = fbx(b"auxC", b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha\0"); @@ -1188,7 +1188,7 @@ mod tests { } #[test] - fn transforms_rotate_mirror_and_crop() { + fn feature_config_transforms_rotate_mirror_and_crop() { // 3 × 2, one channel, value = index let cv = || Canvas { w: 3, h: 2, ch: 1, data: (0..6).collect() }; let r = apply_transforms(cv(), &[Transform::Rot(1)]); @@ -1206,7 +1206,7 @@ mod tests { } #[test] - fn hostile_files_are_errors_not_panics() { + fn feature_config_hostile_files_are_errors_not_panics() { for file in [QUAD_420, QUAD_GBR_LOSSLESS] { // every truncation for n in 0..file.len() { @@ -1233,14 +1233,14 @@ mod tests { } #[test] - fn an_animated_avif_is_unsupported() { + fn feature_config_an_animated_avif_is_unsupported() { let mut b = bx(b"ftyp", b"avis\0\0\0\0avis"); b.extend(bx(b"moov", &[])); assert!(matches!(crate::decode(&b), Err(CodecError::Unsupported { format: Format::Avif, .. }))); } #[test] - fn zero_width_iloc_extents_are_capped() { + fn feature_config_zero_width_iloc_extents_are_capped() { // iloc v2 with zero-byte offset/length/base/index fields: each extent costs no input bytes let mut iloc = vec![2, 0, 0, 0, 0, 0]; iloc.extend_from_slice(&3u32.to_be_bytes()); @@ -1256,7 +1256,7 @@ mod tests { } #[test] - fn item_data_larger_than_the_file_is_refused() { + fn feature_config_item_data_larger_than_the_file_is_refused() { // one item whose 1000 extents each repeat the whole file (length 0 = to the end) let mut iloc = vec![1, 0, 0, 0, 0x44, 0]; iloc.extend_from_slice(&1u16.to_be_bytes()); @@ -1275,7 +1275,7 @@ mod tests { } #[test] - fn unsupported_matrices_are_errors() { + fn feature_config_unsupported_matrices_are_errors() { for m in [8u16, 10, 11, 13, 14] { assert!(matches!(coefficients(m, 1), Err(CodecError::Unsupported { .. })), "{m}"); } @@ -1311,7 +1311,7 @@ mod tests { } #[test] - fn ravif_rgb_round_trip_is_10_bit() { + fn feature_config_ravif_rgb_round_trip_is_10_bit() { let (w, h) = (48, 32); let src = Image::from_u8(w as u32, h as u32, ChannelLayout::Rgb, card(w, h, 3)).unwrap(); let file = encode_avif_with_speed(&src, 95, 10).unwrap(); @@ -1325,7 +1325,7 @@ mod tests { } #[test] - fn ravif_alpha_round_trips() { + fn feature_config_ravif_alpha_round_trips() { let (w, h) = (40, 24); let src = Image::from_u8(w as u32, h as u32, ChannelLayout::Rgba, card(w, h, 4)).unwrap(); let file = encode_avif_with_speed(&src, 95, 10).unwrap(); @@ -1339,7 +1339,7 @@ mod tests { } #[test] - fn exif_is_read_from_its_item() { + fn feature_config_exif_is_read_from_its_item() { let mut src = Image::from_u8(16, 8, ChannelLayout::Rgb, card(16, 8, 3)).unwrap(); let exif = b"II*\0\x08\0\0\0\0\0\0\0\0\0".to_vec(); src.meta.exif = Some(exif.clone()); @@ -1349,7 +1349,7 @@ mod tests { } #[test] - fn hdr_round_trips_keep_highlights_above_white() { + fn feature_config_hdr_round_trips_keep_highlights_above_white() { let (w, h) = (32usize, 16usize); // linear BT.2020: left half grey 0.18, right half 4 × SDR white let rgb: Vec = (0..w * h).flat_map(|i| if i % w < w / 2 { [0.18f32; 3] } else { [4.0; 3] }).collect(); diff --git a/crates/image-codecs/src/codecs/heif.rs b/crates/image-codecs/src/codecs/heif.rs index c3fb33508e..40c392d20a 100644 --- a/crates/image-codecs/src/codecs/heif.rs +++ b/crates/image-codecs/src/codecs/heif.rs @@ -95,7 +95,7 @@ mod tests { #[cfg(not(feature = "heif"))] #[test] - fn without_the_feature_heif_is_a_clear_unsupported_error() { + fn feature_config_without_the_feature_heif_is_a_clear_unsupported_error() { let header = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic"; assert_eq!(crate::detect(header), Some(F), "still recognised"); let r = crate::decode(header); @@ -108,7 +108,7 @@ mod tests { #[cfg(feature = "heif")] #[test] - fn with_the_feature_heif_is_readable_and_errors_map() { + fn feature_config_with_the_feature_heif_is_readable_and_errors_map() { assert!(crate::caps(F).read); let r = crate::decode(b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc"); assert!(matches!(&r, Err(CodecError::Unsupported { format: Format::Heif, reason }) if reason.contains("sequence")), "{r:?}"); @@ -127,7 +127,7 @@ mod tests { #[cfg(feature = "heif")] #[test] - fn a_heic_rs_panic_is_a_malformed_file_error() { + fn feature_config_a_heic_rs_panic_is_a_malformed_file_error() { assert_eq!(crate::detect(&HEIC_RS_BOX_PANIC), Some(Format::Heif)); for opts in [crate::DecodeOptions::default(), crate::DecodeOptions { keep_orientation: true, ..Default::default() }] { let r = crate::decode_with(&HEIC_RS_BOX_PANIC, &opts); diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index e68c9acefe..359679cdd8 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -2365,10 +2365,15 @@ mod streamed_tests { xmp: Some("".into()), ..Default::default() }; - let img = Image::from_raw(w, h, layout, sample, noise(w as usize * h as usize * ch * bytes, 7)) - .unwrap() - .with_icc(Some((0..600u32).map(|i| (i % 251) as u8).collect())) - .with_meta(meta); + // Distinct nonconstant row runs retain carry and row-order sensitivity across pushes. + let stride = w as usize * ch * bytes; + let row = noise(stride, 7); + let mut pixels = row.repeat(h as usize); + for row in pixels.chunks_exact_mut(stride).skip(h as usize / 2) { + row[0] ^= 0x5a; + } + let img = + Image::from_raw(w, h, layout, sample, pixels).unwrap().with_icc(Some((0..600u32).map(|i| (i % 251) as u8).collect())).with_meta(meta); for level in [PngCompression::Fast, PngCompression::Default] { let opts = EncodeOptions { png_compression: level, ..Default::default() }; let one_band = [h]; diff --git a/crates/image-codecs/src/codecs/sgi.rs b/crates/image-codecs/src/codecs/sgi.rs index 64c80299c3..25a4cbf149 100644 --- a/crates/image-codecs/src/codecs/sgi.rs +++ b/crates/image-codecs/src/codecs/sgi.rs @@ -276,7 +276,7 @@ mod tests { } #[test] - fn rle_round_trips_every_layout_in_8_bits() { + fn feature_config_rle_round_trips_every_layout_in_8_bits() { for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] { let img = gradient(37, 11, layout); let plan = Plan { layout, sample: SampleType::U8 }; @@ -289,7 +289,7 @@ mod tests { } #[test] - fn rle_round_trips_16_bits_with_long_runs() { + fn feature_config_rle_round_trips_16_bits_with_long_runs() { let (w, h) = (300u32, 4u32); let samples: Vec = (0..w * h * 3).map(|i| if (i / 3) % 200 < 150 { 4242 } else { (i * 31) as u16 }).collect(); let img = Image::from_u16(w, h, ChannelLayout::Rgb, &samples).unwrap(); @@ -301,7 +301,7 @@ mod tests { /// A hand-built verbatim file: two rows, one plane, stored bottom to top. #[test] - fn verbatim_files_read_bottom_to_top() { + fn feature_config_verbatim_files_read_bottom_to_top() { let mut f = vec![0u8; HEADER]; f[0..2].copy_from_slice(&MAGIC.to_be_bytes()); f[2] = 0; // verbatim @@ -317,7 +317,7 @@ mod tests { } #[test] - fn hostile_input_is_an_error_not_a_panic() { + fn feature_config_hostile_input_is_an_error_not_a_panic() { let img = gradient(16, 8, ChannelLayout::Rgb); let good = encode(&img, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U8 }).unwrap(); // Every truncation fails cleanly. @@ -361,7 +361,7 @@ mod tests { /// The format lets table entries share one compressed row: eight rows, one payload. #[test] - fn rows_may_share_compressed_data() { + fn feature_config_rows_may_share_compressed_data() { let table = HEADER + 8 * 8; let f = rle_file(1, &[table as u32; 8], 3, &[0x81, 255, 0]); assert_eq!(f.len(), table + 3); @@ -371,7 +371,7 @@ mod tests { /// Compressed rows start after both tables: an offset into a table is refused. #[test] - fn rows_may_not_start_inside_the_offset_tables() { + fn feature_config_rows_may_not_start_inside_the_offset_tables() { // 3x1: the tables end at 520; 515 reads the table's own bytes as a packet list. let f = rle_file(3, &[515], 3, &[0, 0, 0, 0, 0]); assert!(decode(&f, &Limits::default()).is_err()); @@ -380,13 +380,13 @@ mod tests { /// FFmpeg's decoder, run as an oracle, also reads a row that ends with its last packet and no /// zero terminator; so does this one. #[test] - fn a_row_without_its_terminator_still_reads() { + fn feature_config_a_row_without_its_terminator_still_reads() { let f = rle_file(1, &[520], 2, &[0x81, 42]); assert_eq!(decode(&f, &Limits::default()).unwrap().data(), &[42]); } #[test] - fn palette_mapped_files_are_unsupported() { + fn feature_config_palette_mapped_files_are_unsupported() { let img = gradient(4, 4, ChannelLayout::Gray); let mut f = encode(&img, Plan { layout: ChannelLayout::Gray, sample: SampleType::U8 }).unwrap(); f[104..108].copy_from_slice(&1u32.to_be_bytes()); diff --git a/crates/image-codecs/src/codecs/sunraster.rs b/crates/image-codecs/src/codecs/sunraster.rs index 85c24acc51..d39af21ffd 100644 --- a/crates/image-codecs/src/codecs/sunraster.rs +++ b/crates/image-codecs/src/codecs/sunraster.rs @@ -192,7 +192,7 @@ mod tests { } #[test] - fn round_trips_gray_rgb_and_rgba_with_odd_widths() { + fn feature_config_round_trips_gray_rgb_and_rgba_with_odd_widths() { for layout in [ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Rgba] { let img = pattern(13, 7, layout); let bytes = encode(&img, Plan { layout, sample: SampleType::U8 }).unwrap(); @@ -213,7 +213,7 @@ mod tests { } #[test] - fn standard_type_is_blue_first_and_rle_expands() { + fn feature_config_standard_type_is_blue_first_and_rle_expands() { let f = file(24, 1, &[], 0, 1, 1, &[1, 2, 3, 0]); assert_eq!(decode(&f, &Limits::default()).unwrap().data(), &[3, 2, 1]); // 0x80 0x00 is a literal 0x80; 0x80 n v is n + 1 copies of v. The 2x2 image has stride 2. @@ -224,7 +224,7 @@ mod tests { } #[test] - fn colour_mapped_and_one_bit_files() { + fn feature_config_colour_mapped_and_one_bit_files() { // Two entries: red plane, green plane, blue plane. let map = [10, 20, 30, 40, 50, 60]; let f = file(8, 1, &map, 1, 2, 1, &[0, 1]); @@ -237,7 +237,7 @@ mod tests { } #[test] - fn one_bit_files_with_a_colour_map_read_as_colour() { + fn feature_config_one_bit_files_with_a_colour_map_read_as_colour() { // Two entries: red plane, green plane, blue plane; bit 0 is entry 0. let map = [10, 20, 30, 40, 50, 60]; let f = file(1, 1, &map, 1, 3, 1, &[0b0100_0000, 0]); @@ -248,7 +248,7 @@ mod tests { } #[test] - fn the_unused_first_byte_of_standard_32_bit_pixels_is_not_alpha() { + fn feature_config_the_unused_first_byte_of_standard_32_bit_pixels_is_not_alpha() { let img = decode(&file(32, 1, &[], 0, 1, 1, &[0, 30, 20, 10]), &Limits::default()).unwrap(); assert_eq!((img.layout(), img.data()), (ChannelLayout::Rgba, &[10, 20, 30, 255][..])); // In the RGB-ordered type the first byte is the alpha the writer stores there. @@ -257,13 +257,13 @@ mod tests { } #[test] - fn an_output_buffer_too_large_to_allocate_is_an_error() { + fn feature_config_an_output_buffer_too_large_to_allocate_is_an_error() { assert!(reserve(usize::MAX).is_err()); assert!(reserve(16).is_ok()); } #[test] - fn hostile_input_is_an_error_not_a_panic() { + fn feature_config_hostile_input_is_an_error_not_a_panic() { let img = pattern(9, 5, ChannelLayout::Rgb); let good = encode(&img, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U8 }).unwrap(); for len in 0..good.len() { diff --git a/crates/image-codecs/src/codecs/tiff/decode.rs b/crates/image-codecs/src/codecs/tiff/decode.rs index c365d01581..dcccadde66 100644 --- a/crates/image-codecs/src/codecs/tiff/decode.rs +++ b/crates/image-codecs/src/codecs/tiff/decode.rs @@ -747,8 +747,8 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result = REAL_FILES.iter().map(|f| f.0).collect(); let pinned: Vec<&str> = REAL_FILE_SHA256.iter().map(|p| p.0).collect(); diff --git a/crates/image-codecs/tests/it/detect_caps.rs b/crates/image-codecs/tests/it/detect_caps.rs index f6c4808ffa..1333053107 100644 --- a/crates/image-codecs/tests/it/detect_caps.rs +++ b/crates/image-codecs/tests/it/detect_caps.rs @@ -10,7 +10,7 @@ use craft_image_codecs::*; // --------------------------------------------------------------------------- #[test] -fn every_enabled_format_is_symmetric_or_whitelisted() { +fn feature_config_every_enabled_format_is_symmetric_or_whitelisted() { for f in Format::ALL { let c = caps(f); if !(c.read || c.write) { @@ -34,7 +34,7 @@ fn exceptions_are_documented_and_unique() { } #[test] -fn never_write_only_without_exception() { +fn feature_config_never_write_only_without_exception() { // Stronger form: no format may be writable-but-unreadable unless listed. for f in writable_formats() { if !caps(f).read { @@ -44,7 +44,7 @@ fn never_write_only_without_exception() { } #[test] -fn default_build_formats_all_symmetric() { +fn feature_config_default_build_formats_all_symmetric() { let expected = [ Format::Png, Format::Jpeg, @@ -74,7 +74,7 @@ fn default_build_formats_all_symmetric() { } #[test] -fn avif_is_readable_only_with_the_decode_feature() { +fn feature_config_avif_is_readable_only_with_the_decode_feature() { assert_eq!(caps(Format::Avif).read, cfg!(all(feature = "avif-decode", not(target_arch = "wasm32")))); assert_eq!(caps(Format::Avif).write, cfg!(feature = "avif")); let header = decode_as(Format::Avif, b"\0\0\0\x1cftypavif"); @@ -86,7 +86,7 @@ fn avif_is_readable_only_with_the_decode_feature() { } #[test] -fn heif_is_detected_always_and_readable_only_with_the_feature() { +fn feature_config_heif_is_detected_always_and_readable_only_with_the_feature() { let header = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic"; assert_eq!(detect(header), Some(Format::Heif)); assert_eq!(from_extension("IMG_0001.HEIC"), Some(Format::Heif)); @@ -149,7 +149,7 @@ fn caps_are_internally_consistent() { } #[test] -fn caps_function_matches_method() { +fn feature_config_caps_function_matches_method() { for f in Format::ALL { assert_eq!(caps(f), f.caps()); } @@ -160,7 +160,7 @@ fn caps_function_matches_method() { // --------------------------------------------------------------------------- #[test] -fn detect_encoded_output_of_every_format() { +fn feature_config_detect_encoded_output_of_every_format() { for f in writable_formats() { let img = test_image(ChannelLayout::Rgba, SampleType::U8); let bytes = encode(&img, f, &EncodeOptions::default()).unwrap(); @@ -258,7 +258,7 @@ fn detect_magic_iff() { } #[cfg(feature = "sgi")] #[test] -fn detect_magic_sgi() { +fn feature_config_detect_magic_sgi() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode}; let img = Image::from_u8(5, 3, ChannelLayout::Rgba, (0..60).collect()).unwrap(); let bytes = encode(&img, Format::Sgi, &EncodeOptions::default()).unwrap(); @@ -522,7 +522,7 @@ fn a_detector_keeps_its_place_between_calls() { #[cfg(feature = "sunraster")] #[test] -fn detect_magic_sun_raster() { +fn feature_config_detect_magic_sun_raster() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode}; let img = Image::from_u8(5, 3, ChannelLayout::Rgb, (0..45).collect()).unwrap(); let bytes = encode(&img, Format::SunRaster, &EncodeOptions::default()).unwrap(); @@ -626,7 +626,7 @@ fn extensions_unique_across_formats() { #[cfg(not(feature = "sgi"))] #[test] -fn sgi_requires_explicit_feature() { +fn feature_config_sgi_requires_explicit_feature() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode}; assert!(!caps(Format::Sgi).read && !caps(Format::Sgi).write); assert!(decode_as(Format::Sgi, &[]).is_err()); @@ -639,7 +639,7 @@ fn sgi_requires_explicit_feature() { #[cfg(not(feature = "sunraster"))] #[test] -fn sun_raster_disabled_by_default() { +fn feature_config_sun_raster_disabled_by_default() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode}; let bytes = [0x59, 0xa6, 0x6a, 0x95, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0]; assert_ne!(detect(&bytes), Some(Format::SunRaster)); diff --git a/crates/image-codecs/tests/it/fidelity.rs b/crates/image-codecs/tests/it/fidelity.rs index cad19485ef..317e9ec3ca 100644 --- a/crates/image-codecs/tests/it/fidelity.rs +++ b/crates/image-codecs/tests/it/fidelity.rs @@ -184,7 +184,7 @@ fn ico_oversize_is_fatal() { assert!(w.contains(&W::DimensionsExceeded { max_width: 256, max_height: 256 })); } #[test] -fn avif_default_build_write_unsupported() { +fn feature_config_avif_default_build_write_unsupported() { let w = warns(&test_image(ChannelLayout::Rgb, SampleType::U8), Format::Avif); if cfg!(feature = "avif") { assert!(w.contains(&W::LossyCompression)); @@ -221,7 +221,7 @@ fn every_warning_has_a_message() { /// The warnings must agree with what actually comes back from the file. #[test] -fn warnings_match_actual_roundtrip_behaviour() { +fn feature_config_warnings_match_actual_roundtrip_behaviour() { // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th format, layout and sample type. let step = craft_media_testkit::hostile::divisor(); let mut index = 0usize; diff --git a/crates/image-codecs/tests/it/heif.rs b/crates/image-codecs/tests/it/heif.rs index 07c15f65eb..be2abc15b1 100644 --- a/crates/image-codecs/tests/it/heif.rs +++ b/crates/image-codecs/tests/it/heif.rs @@ -61,7 +61,7 @@ fn keep() -> DecodeOptions { } #[test] -fn heif_is_read_only_and_listed() { +fn feature_config_heif_is_read_only_and_listed() { let c = caps(Format::Heif); assert!(c.read && !c.write); assert!(ASYMMETRIC_EXCEPTIONS.iter().any(|(f, _)| *f == Format::Heif)); @@ -74,14 +74,14 @@ fn heif_is_read_only_and_listed() { } #[test] -fn detect_heif_brands() { +fn feature_config_detect_heif_brands() { for f in [checker_64(), strips_96(), checker_grid(), with_exif()] { assert_eq!(detect(f), Some(Format::Heif)); } } #[test] -fn single_picture_matches_apple_decode() { +fn feature_config_single_picture_matches_apple_decode() { for (heic, png) in [(checker_64(), "heic-rs/checker-64.ref.png"), (strips_96(), "heic-rs/rgb-strips-96.ref.png")] { let img = decode(heic).unwrap(); let want = reference(&corpus(png)); @@ -93,7 +93,7 @@ fn single_picture_matches_apple_decode() { } #[test] -fn grid_tiled_photo_matches_apple_decode() { +fn feature_config_grid_tiled_photo_matches_apple_decode() { // iPhone photos are grids of 512x512 HEVC tiles: here 2x2. let img = decode(checker_grid()).unwrap(); let want = reference(&corpus("heic-rs/checker-1024.ref.png")); @@ -102,7 +102,7 @@ fn grid_tiled_photo_matches_apple_decode() { } #[test] -fn rgb_strips_keep_their_colours() { +fn feature_config_rgb_strips_keep_their_colours() { // Three vertical strips, pure red, green and blue: catches swapped channels or matrices. let img = decode(strips_96()).unwrap(); for (x, c) in [(16, 0), (48, 1), (80, 2)] { @@ -114,7 +114,7 @@ fn rgb_strips_keep_their_colours() { } #[test] -fn container_rotation_is_applied_once() { +fn feature_config_container_rotation_is_applied_once() { // irot 1 = 90° anticlockwise: the red strip (left) ends at the bottom, blue (right) on top. let rotated = with_irot(strips_96(), 1); let img = decode(&rotated).unwrap(); @@ -126,7 +126,7 @@ fn container_rotation_is_applied_once() { } #[test] -fn exif_and_xmp_survive_and_exif_orientation_is_not_applied_twice() { +fn feature_config_exif_and_xmp_survive_and_exif_orientation_is_not_applied_twice() { // HEIF's EXIF Orientation repeats what irot says; the container is the authority. let tagged = with_exif_orientation(with_exif(), 6); let img = decode(&tagged).unwrap(); @@ -142,7 +142,7 @@ fn exif_and_xmp_survive_and_exif_orientation_is_not_applied_twice() { } #[test] -fn limits_are_checked_before_decoding() { +fn feature_config_limits_are_checked_before_decoding() { let tight = |limits| DecodeOptions { limits, ..Default::default() }; let small = Limits { max_width: 512, ..Default::default() }; assert!(matches!(decode_with(checker_grid(), &tight(small)), Err(CodecError::LimitExceeded(_)))); @@ -153,7 +153,7 @@ fn limits_are_checked_before_decoding() { } #[test] -fn unsupported_and_broken_files_are_clear_errors() { +fn feature_config_unsupported_and_broken_files_are_clear_errors() { // An ftyp and nothing else: a HEIF image sequence would have a moov here instead of a meta. let r = decode(b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc"); assert!(matches!(&r, Err(CodecError::Unsupported { format: Format::Heif, reason }) if reason.contains("sequence")), "{r:?}"); @@ -162,7 +162,7 @@ fn unsupported_and_broken_files_are_clear_errors() { } #[test] -fn every_truncation_errors_or_decodes_never_panics() { +fn feature_config_every_truncation_errors_or_decodes_never_panics() { for bytes in [checker_64(), strips_96(), checker_grid()] { for cut in 0..bytes.len() { let _ = decode_as(Format::Heif, &bytes[..cut]); @@ -171,7 +171,7 @@ fn every_truncation_errors_or_decodes_never_panics() { } #[test] -fn ten_bit_with_alpha_decodes_to_16_bit_rgba() { +fn feature_config_ten_bit_with_alpha_decodes_to_16_bit_rgba() { // pillow-heif's fixture: a 16-bit RGBA gradient (the .src.png) encoded as 10-bit HEIF by libheif/x265. let img = decode(&corpus("pillow-heif/heif/RGBA_10__29x100.heif")).unwrap(); let src = decode_as(Format::Png, &corpus("pillow-heif/non_heif/RGBA_16__29x100.png")).unwrap(); diff --git a/crates/image-codecs/tests/it/jxl_decode.rs b/crates/image-codecs/tests/it/jxl_decode.rs index fad3b51d1f..10bceb4370 100644 --- a/crates/image-codecs/tests/it/jxl_decode.rs +++ b/crates/image-codecs/tests/it/jxl_decode.rs @@ -9,7 +9,7 @@ fn rgba_8bit() -> Image { } #[test] -fn an_eight_bit_export_decodes_back_to_the_same_pixels() { +fn feature_config_an_eight_bit_export_decodes_back_to_the_same_pixels() { let input = rgba_8bit(); let bytes = encode(&input, Format::Jxl, &EncodeOptions::default()).unwrap(); let out = decode(&bytes).unwrap(); @@ -18,7 +18,7 @@ fn an_eight_bit_export_decodes_back_to_the_same_pixels() { } #[test] -fn a_sixteen_bit_gray_export_decodes_back_to_the_same_samples() { +fn feature_config_a_sixteen_bit_gray_export_decodes_back_to_the_same_samples() { let samples: Vec = (0..12).map(|i| i * 5461).collect(); let input = Image::from_u16(4, 3, ChannelLayout::Gray, &samples).unwrap(); let bytes = encode(&input, Format::Jxl, &EncodeOptions::default()).unwrap(); @@ -28,7 +28,7 @@ fn a_sixteen_bit_gray_export_decodes_back_to_the_same_samples() { } #[test] -fn the_pixel_limit_is_an_error_not_an_allocation() { +fn feature_config_the_pixel_limit_is_an_error_not_an_allocation() { let bytes = encode(&rgba_8bit(), Format::Jxl, &EncodeOptions::default()).unwrap(); let opts = DecodeOptions { limits: Limits { max_pixels: 4, ..Limits::default() }, ..DecodeOptions::default() }; let err = decode_with(&bytes, &opts); @@ -36,7 +36,7 @@ fn the_pixel_limit_is_an_error_not_an_allocation() { } #[test] -fn every_prefix_of_a_file_is_an_error_or_an_image_never_a_panic() { +fn feature_config_every_prefix_of_a_file_is_an_error_or_an_image_never_a_panic() { let bytes = encode(&rgba_8bit(), Format::Jxl, &EncodeOptions::default()).unwrap(); for end in 0..bytes.len() { let _ = decode(&bytes[..end]); diff --git a/crates/image-codecs/tests/it/jxl_export.rs b/crates/image-codecs/tests/it/jxl_export.rs index 129aa1a3b2..7902814910 100644 --- a/crates/image-codecs/tests/it/jxl_export.rs +++ b/crates/image-codecs/tests/it/jxl_export.rs @@ -5,7 +5,7 @@ use craft_image_codecs::{ }; #[test] -fn jpeg_xl_is_export_only_without_the_jxl_feature_and_detects_both_signatures() { +fn feature_config_jpeg_xl_is_export_only_without_the_jxl_feature_and_detects_both_signatures() { let c = caps(Format::Jxl); assert!(c.write); assert_eq!(c.read, cfg!(feature = "jxl")); diff --git a/crates/image-codecs/tests/it/limits.rs b/crates/image-codecs/tests/it/limits.rs index ec86753ebe..32158a13fa 100644 --- a/crates/image-codecs/tests/it/limits.rs +++ b/crates/image-codecs/tests/it/limits.rs @@ -39,7 +39,7 @@ fn read_bounded_reads_one_byte_past_its_cap() { } #[test] -fn max_pixels_enforced_for_every_format() { +fn feature_config_max_pixels_enforced_for_every_format() { for f in rw_formats() { let b = encoded(f); let l = Limits { max_pixels: 1000, ..Limits::default() }; @@ -50,7 +50,7 @@ fn max_pixels_enforced_for_every_format() { } #[test] -fn max_width_enforced_for_every_format() { +fn feature_config_max_width_enforced_for_every_format() { for f in rw_formats() { let l = Limits { max_width: 63, ..Limits::default() }; assert!(is_limit(decode_with(&encoded(f), &opts(l))), "{f:?}"); @@ -58,7 +58,7 @@ fn max_width_enforced_for_every_format() { } #[test] -fn max_height_enforced_for_every_format() { +fn feature_config_max_height_enforced_for_every_format() { for f in rw_formats() { let l = Limits { max_height: 47, ..Limits::default() }; assert!(is_limit(decode_with(&encoded(f), &opts(l))), "{f:?}"); @@ -66,7 +66,7 @@ fn max_height_enforced_for_every_format() { } #[test] -fn max_alloc_enforced_for_every_format() { +fn feature_config_max_alloc_enforced_for_every_format() { for f in rw_formats() { let l = Limits { max_alloc: 64 * 48, ..Limits::default() }; assert!(decode_with(&encoded(f), &opts(l)).is_err(), "{f:?}"); @@ -74,7 +74,7 @@ fn max_alloc_enforced_for_every_format() { } #[test] -fn limits_none_accepts() { +fn feature_config_limits_none_accepts() { for f in rw_formats() { assert!(decode_with(&encoded(f), &opts(Limits::none())).is_ok(), "{f:?}"); } diff --git a/crates/image-codecs/tests/it/malformed.rs b/crates/image-codecs/tests/it/malformed.rs index bd6bd605b7..9c4166bd1a 100644 --- a/crates/image-codecs/tests/it/malformed.rs +++ b/crates/image-codecs/tests/it/malformed.rs @@ -42,7 +42,7 @@ fn no_panic(f: Format, bytes: &[u8]) { } #[test] -fn truncated_at_many_offsets() { +fn feature_config_truncated_at_many_offsets() { for (f, bytes) in samples() { let n = bytes.len(); let step = (n / 97).max(1); @@ -56,7 +56,7 @@ fn truncated_at_many_offsets() { } #[test] -fn truncated_files_mostly_error() { +fn feature_config_truncated_files_mostly_error() { // Chopping off the second half must not silently succeed for formats // with length-checked rasters. for (f, bytes) in samples() { @@ -75,7 +75,7 @@ fn truncated_files_mostly_error() { } #[test] -fn bit_flips_never_panic() { +fn feature_config_bit_flips_never_panic() { // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the flips. let rounds = 150usize.div_ceil(craft_media_testkit::hostile::divisor()); let mut rng = common::Rng::new(42); @@ -93,7 +93,7 @@ fn bit_flips_never_panic() { } #[test] -fn byte_overwrites_in_header_never_panic() { +fn feature_config_byte_overwrites_in_header_never_panic() { // CRAFT_HOSTILE_DIVISOR=N (pull requests) overwrites every N-th byte, from a different offset // for each sample, so the samples together still reach every header position. let step = craft_media_testkit::hostile::divisor(); @@ -112,7 +112,7 @@ fn byte_overwrites_in_header_never_panic() { } #[test] -fn empty_input_errors_for_every_format() { +fn feature_config_empty_input_errors_for_every_format() { for f in Format::ALL { assert!(decode_as(f, &[]).is_err(), "{f:?}"); } @@ -194,7 +194,7 @@ proptest! { } #[test] - fn random_bytes_with_magic_never_panic(idx in 0usize..14, data in proptest::collection::vec(any::(), 0..1024)) { + fn feature_config_random_bytes_with_magic_never_panic(idx in 0usize..14, data in proptest::collection::vec(any::(), 0..1024)) { let magics: [&[u8]; 14] = [ b"\x89PNG\r\n\x1a\n", &[0xFF, 0xD8, 0xFF], b"II*\0", b"RIFF\0\0\0\0WEBP", b"GIF89a", b"BM", &[0, 0, 1, 0, 1, 0], b"P6\n", b"qoif", &[0x76, 0x2F, 0x31, 0x01], b"#?RADIANCE\n", b"P7\n", b"PF\n", @@ -206,12 +206,12 @@ proptest! { } #[test] - fn random_bytes_each_format_never_panic(idx in 0usize..Format::ALL.len(), data in proptest::collection::vec(any::(), 0..512)) { + fn feature_config_random_bytes_each_format_never_panic(idx in 0usize..Format::ALL.len(), data in proptest::collection::vec(any::(), 0..512)) { let _ = decode_as_with(Format::ALL[idx], &data, &tight()); } #[test] - fn mutated_valid_files_never_panic(which in 0usize..40, pos in any::(), val in any::(), cut in any::()) { + fn feature_config_mutated_valid_files_never_panic(which in 0usize..40, pos in any::(), val in any::(), cut in any::()) { let s = samples_cached(); let (f, bytes) = &s[which % s.len()]; let mut b = bytes.clone(); diff --git a/crates/image-codecs/tests/it/orientation.rs b/crates/image-codecs/tests/it/orientation.rs index 4eaf188a89..7c44910eb8 100644 --- a/crates/image-codecs/tests/it/orientation.rs +++ b/crates/image-codecs/tests/it/orientation.rs @@ -661,7 +661,7 @@ fn long_orientation_reads_and_rewrites_in_both_byte_orders() { /// `probe_size` reads the size `decode` returns from the header alone, for every format it /// covers, and a file cut short inside its header is refused rather than given a size. #[test] -fn probe_size_matches_decode() { +fn feature_config_probe_size_matches_decode() { let img = synth(7, 5, ChannelLayout::Rgb, SampleType::U8, 3, 0.0); let probed = [ Format::Png, diff --git a/crates/image-codecs/tests/it/png_jpeg.rs b/crates/image-codecs/tests/it/png_jpeg.rs index af11f72949..cad8f33e9a 100644 --- a/crates/image-codecs/tests/it/png_jpeg.rs +++ b/crates/image-codecs/tests/it/png_jpeg.rs @@ -530,7 +530,7 @@ fn png_rows_fail_like_decode_on_damaged_files() { #[cfg(feature = "corpus")] #[test] -fn pngsuite_corpus_matches_oracle() { +fn feature_config_pngsuite_corpus_matches_oracle() { let mut checked = 0; for (name, bytes) in common::pngsuite::pngs() { let oracle = image::load_from_memory_with_format(&bytes, image::ImageFormat::Png); @@ -637,7 +637,7 @@ fn png_preflight_uses_the_output_layout() { #[cfg(feature = "corpus")] #[test] -fn png_rows_equal_decode_on_the_pngsuite_corpus() { +fn feature_config_png_rows_equal_decode_on_the_pngsuite_corpus() { let mut checked = 0; for (name, bytes) in common::pngsuite::pngs() { assert_steps_equal_decode(&bytes, &name); @@ -650,7 +650,7 @@ fn png_rows_equal_decode_on_the_pngsuite_corpus() { /// but the interlaced ones), and fails where `decode` fails. #[cfg(feature = "corpus")] #[test] -fn pngsuite_corpus_rows_match_the_whole_decode() { +fn feature_config_pngsuite_corpus_rows_match_the_whole_decode() { let opts = DecodeOptions { keep_orientation: true, ..Default::default() }; let (mut streamed, mut refused, mut skipped) = (0, 0, 0); for (name, bytes) in common::pngsuite::pngs() { diff --git a/crates/image-codecs/tests/it/roundtrip.rs b/crates/image-codecs/tests/it/roundtrip.rs index 6ff2e58187..f531a472a9 100644 --- a/crates/image-codecs/tests/it/roundtrip.rs +++ b/crates/image-codecs/tests/it/roundtrip.rs @@ -316,7 +316,7 @@ fn webp_lossy_request_is_a_lossy_file() { } #[test] -fn one_pixel_images_roundtrip() { +fn feature_config_one_pixel_images_roundtrip() { for f in rw_formats() { // The JPEG XL encoder refuses images narrower than two pixels (jxl_export.rs pins the error). if f == Format::Jxl { @@ -337,7 +337,7 @@ fn ico_rejects_oversize() { } #[test] -fn empty_image_rejected() { +fn feature_config_empty_image_rejected() { let img = Image::new(0, 5, ChannelLayout::Rgb, SampleType::U8).unwrap(); for f in writable_formats() { assert!(encode(&img, f, &EncodeOptions::default()).is_err(), "{f:?}"); diff --git a/crates/imaging/src/layer_style/draft.rs b/crates/imaging/src/layer_style/draft.rs index ecef782e2e..239338e38d 100644 --- a/crates/imaging/src/layer_style/draft.rs +++ b/crates/imaging/src/layer_style/draft.rs @@ -26,7 +26,7 @@ pub struct LayerStyleDraft { pub blend_if_channel: usize, /// The Preview check box: whether the host shows the draft on the canvas. On by default. pub preview: bool, - /// The shadow drag in progress, from its press to its release. + /// The shadow or Satin drag in progress, from its press to its release. pub shadow_drag: Option, /// The Gradient Overlay offset drag in progress, from its press to its release. pub gradient_drag: Option, @@ -245,6 +245,53 @@ impl LayerStyleDraft { self.style != before } + /// Whether a drag on the image moves the selected Satin's angle and distance. + pub fn drags_satin(&self) -> bool { + self.selected_kind() == Some(EffectKind::Satin) + } + + /// Whether a drag on the image edits the selected page: a shadow's, a Satin's or a Gradient + /// Overlay's. The host passes the canvas gesture through the dialog on these pages. + pub fn drags_on_canvas(&self) -> bool { + self.drags_shadow() || self.drags_satin() || self.drags_gradient() + } + + /// A drag on the image with a Satin page selected, as [`drag_shadow`](Self::drag_shadow) is for + /// a shadow: `defaults` are the Satin's spec defaults, `start` is the press (it records the + /// angle and distance shown) and `total` the pointer's movement since, in document pixels. The + /// values follow [`ShadowDrag::satin_moved`]. A Satin has no Use Global Light, so only this + /// instance changes. The drag shares [`shadow_drag`](Self::shadow_drag), which the host clears + /// on release. Returns whether the style changed; does nothing on other pages. + pub fn drag_satin(&mut self, defaults: &StyleParams, start: bool, total: [f64; 2]) -> bool { + let LayerStylePage::Effect(id) = self.page else { + return false; + }; + if !self.drags_satin() { + return false; + } + let Some(instance) = self.style.effect(id) else { + return false; + }; + let shown = instance.params.over(defaults); + let shown_angle = shown.number("angle").unwrap_or(19.0); + let shown_distance = shown.number("distance").unwrap_or(11.0); + if start || self.shadow_drag.is_none() { + self.shadow_drag = Some(ShadowDrag::begin(shown_angle, shown_distance)); + } + let Some((angle, distance)) = self.shadow_drag.and_then(|drag| drag.satin_moved(total, shown_angle)) else { + return false; + }; + // The values already shown (a press, or a drag back to where the page stands): write nothing, + // so a sparse instance does not gain explicit parameters it never had. + if angle == shown_angle && distance == shown_distance { + return false; + } + let before = self.style.clone(); + self.set_param(id, "angle", StyleValue::Number(angle)); + self.set_param(id, "distance", StyleValue::Number(distance)); + self.style != before + } + /// An id one past the highest `fxN`, or the lowest free number when that overflows. fn next_id(&self) -> EffectId { let max = self.style.effects.iter().map(|e| e.id.0).max().unwrap_or(0); diff --git a/crates/imaging/src/layer_style/drag.rs b/crates/imaging/src/layer_style/drag.rs index 09f65140e1..ece824f1c5 100644 --- a/crates/imaging/src/layer_style/drag.rs +++ b/crates/imaging/src/layer_style/drag.rs @@ -33,6 +33,33 @@ impl ShadowDrag { let angle = if d >= 0.5 { oy.atan2(-ox).to_degrees().round() } else { self.start_angle }; Some((angle, d.round().clamp(0.0, 30000.0))) } + + /// The Satin's `(angle, distance)` after the pointer moved `total` document pixels since the + /// press: the start offset plus `total`, as for a shadow, but the distance is its length + /// **truncated** to a whole pixel and clamped to 1..=250, and the angle `atan2(oy, −ox)` + /// truncated toward zero to a whole degree (−116.57 gives −116). A new offset at (0, 0), float + /// noise aside, keeps `shown_angle`, the angle the page shows; a quarter pixel still has a + /// direction. No travel gives the start values back unchanged, fractions included. `None` when + /// the result is not finite. + pub fn satin_moved(self, total: [f64; 2], shown_angle: f64) -> Option<(f64, f64)> { + if total == [0.0, 0.0] { + return Some((self.start_angle, self.start_distance)); + } + let a = self.start_angle.to_radians(); + let (ox, oy) = (-a.cos() * self.start_distance + total[0], a.sin() * self.start_distance + total[1]); + let d = ox.hypot(oy); + if !d.is_finite() { + return None; + } + let angle = if d > 1e-6 { + let deg = oy.atan2(-ox).to_degrees(); + // Float noise a hair under a whole degree (145.999…) must not lose that degree. + (deg + 1e-9 * deg.signum()).trunc() + } else { + shown_angle + }; + Some((angle, d.trunc().clamp(1.0, 250.0))) + } } /// The largest offset a Gradient Overlay drag writes, in layer sizes, either way. diff --git a/crates/imaging/src/layer_style/tests.rs b/crates/imaging/src/layer_style/tests.rs index b637dcbf31..1dc70affb3 100644 --- a/crates/imaging/src/layer_style/tests.rs +++ b/crates/imaging/src/layer_style/tests.rs @@ -76,6 +76,134 @@ fn shadow_drag_uses_whole_degrees_and_pixels_and_moves_the_global_angle() { assert!(!draft.drag_shadow(&defaults, true, [10.0, 10.0])); } +/// A Satin at `angle` / `distance` on its selected page, with a Drop Shadow beside it. +fn satin_draft(angle: f64, distance: f64) -> LayerStyleDraft { + let mut draft = LayerStyleDraft::new(style_with(&[(1, EffectKind::Satin), (2, EffectKind::DropShadow)])); + draft.page = LayerStylePage::Effect(EffectId(1)); + draft.set_param(EffectId(1), "angle", StyleValue::Number(angle)); + draft.set_param(EffectId(1), "distance", StyleValue::Number(distance)); + draft +} + +fn satin_shown(draft: &LayerStyleDraft) -> (Option, Option) { + let params = &draft.style.effect(EffectId(1)).expect("the Satin").params; + (params.number("angle"), params.number("distance")) +} + +// From Angle 90 / Distance 20, each drag gives the angle and distance measured in the reference +// application: both truncated (not rounded), negative angles toward zero. +#[trial] +fn satin_drag_truncates_the_angle_and_distance() { + let defaults = EffectSpec::photoshop(EffectKind::Satin).defaults; + for (total, want) in [ + ([30.0, 0.0], (146.0, 36.0)), + ([0.0, -30.0], (-90.0, 10.0)), + ([0.0, 30.0], (90.0, 50.0)), + ([-30.0, 0.0], (33.0, 36.0)), + ([20.0, -20.0], (180.0, 20.0)), + ([5.0, 0.0], (104.0, 20.0)), + ([5.0, -30.0], (-116.0, 11.0)), + ([-5.0, -30.0], (-63.0, 11.0)), + ([30.0, 10.0], (135.0, 42.0)), + ] { + let mut draft = satin_draft(90.0, 20.0); + assert!(draft.drags_satin() && draft.drags_on_canvas()); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, total); + assert_eq!(satin_shown(&draft), (Some(want.0), Some(want.1)), "drag {total:?}"); + } +} + +// The zero offset gives Distance 1 and keeps the angle shown, also when one drag passes through it; +// a quarter pixel still has a direction; Distance stays within 1..=250; a non-finite drag and a +// press change nothing, fractions included; a drag back to the press restores the start values. +#[trial] +fn satin_drag_keeps_the_angle_at_zero_and_the_values_without_travel() { + let defaults = EffectSpec::photoshop(EffectKind::Satin).defaults; + let mut draft = satin_draft(90.0, 20.0); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, [0.0, -20.0]); + assert_eq!(satin_shown(&draft), (Some(90.0), Some(1.0))); + + let mut draft = satin_draft(90.0, 20.0); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, [30.0, 0.0]); + draft.drag_satin(&defaults, false, [0.0, -20.0]); + assert_eq!(satin_shown(&draft), (Some(146.0), Some(1.0)), "the angle shown, not the press's"); + + let mut draft = satin_draft(90.0, 20.0); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, [0.25, -20.0]); + assert_eq!(satin_shown(&draft), (Some(180.0), Some(1.0))); + + let mut draft = satin_draft(90.0, 20.0); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, [0.0, 380.0]); + assert_eq!(satin_shown(&draft).1, Some(250.0)); + assert!(!draft.drag_satin(&defaults, true, [f64::NAN, 0.0])); + + let mut draft = satin_draft(90.5, 20.75); + assert!(!draft.drag_satin(&defaults, true, [0.0, 0.0]), "a press writes nothing"); + assert!(draft.shadow_drag.is_some()); + draft.drag_satin(&defaults, false, [30.0, 0.0]); + assert_eq!(satin_shown(&draft), (Some(145.0), Some(36.0))); + draft.drag_satin(&defaults, false, [0.0, 0.0]); + assert_eq!(satin_shown(&draft), (Some(90.5), Some(20.75))); + draft.end_drag(); + assert!(draft.shadow_drag.is_none()); +} + +// A press and release on a Satin whose angle and distance are not stored (they come from the spec +// defaults) leaves its parameters empty; a drag that leaves and comes back does store them. +#[trial] +fn satin_press_without_travel_keeps_a_sparse_instance_sparse() { + let defaults = EffectSpec::photoshop(EffectKind::Satin).defaults; + let mut draft = LayerStyleDraft::new(style_with(&[(1, EffectKind::Satin)])); + draft.page = LayerStylePage::Effect(EffectId(1)); + draft.style.effect_mut(EffectId(1)).expect("the Satin").params = StyleParams::default(); + let before = draft.style.clone(); + assert!(!draft.drag_satin(&defaults, true, [0.0, 0.0])); + assert!(!draft.drag_satin(&defaults, false, [0.0, 0.0])); + draft.end_drag(); + assert_eq!(draft.style, before, "the parameter map is unchanged"); + assert_eq!(satin_shown(&draft), (None, None)); + + draft.drag_satin(&defaults, true, [0.0, 0.0]); + assert!(draft.drag_satin(&defaults, false, [30.0, 0.0])); + assert!(draft.drag_satin(&defaults, false, [0.0, 0.0]), "back to the start values"); +} + +// Only the Satin page takes the Satin drag; it leaves Global Light and the shadow alone, and the +// shadow drag does not take a Satin page. Shadow, Satin and Gradient Overlay pages take canvas drags. +#[trial] +fn satin_drag_is_the_satin_pages_alone() { + let satin = EffectSpec::photoshop(EffectKind::Satin).defaults; + let shadow = EffectSpec::photoshop(EffectKind::DropShadow).defaults; + let mut draft = satin_draft(90.0, 20.0); + let light = draft.style.global_light; + let before = draft.style.effect(EffectId(2)).cloned(); + assert!(!draft.drags_shadow()); + assert!(!draft.drag_shadow(&shadow, true, [30.0, 0.0])); + assert_eq!(satin_shown(&draft), (Some(90.0), Some(20.0))); + draft.drag_satin(&satin, true, [0.0, 0.0]); + assert!(draft.drag_satin(&satin, false, [30.0, 0.0])); + assert_eq!(draft.style.global_light, light); + assert_eq!(draft.style.effect(EffectId(2)).cloned(), before); + + draft.end_drag(); + draft.page = LayerStylePage::Effect(EffectId(2)); + assert!(!draft.drags_satin() && draft.drags_on_canvas()); + assert!(!draft.drag_satin(&satin, true, [30.0, 0.0])); + assert_eq!(draft.style.effect(EffectId(2)).cloned(), before); + draft.page = LayerStylePage::Blending; + assert!(!draft.drags_on_canvas()); + let mut gradient = LayerStyleDraft::new(style_with(&[(1, EffectKind::GradientOverlay), (2, EffectKind::ColorOverlay)])); + gradient.page = LayerStylePage::Effect(EffectId(1)); + assert!(gradient.drags_on_canvas()); + gradient.page = LayerStylePage::Effect(EffectId(2)); + assert!(!gradient.drags_on_canvas()); +} + // An instance without angle and distance starts the drag from the spec's defaults, not from 120° // and 0. diff --git a/crates/imaging/src/ui/curve/editor.rs b/crates/imaging/src/ui/curve/editor.rs index 02de94f546..a1797c3edc 100644 --- a/crates/imaging/src/ui/curve/editor.rs +++ b/crates/imaging/src/ui/curve/editor.rs @@ -142,6 +142,12 @@ pub struct CurveEditor<'a> { /// The selected point, kept by the host: the editor shows it and reports changes in the output. #[prop] selection: Option>, + /// Ctrl+Tab and Ctrl+Shift+Tab select the next and the previous point, wrapping round, while a point is selected. + #[prop(flag)] + tab_steps: bool, + /// Delete and Backspace on an end point, which stays, deselect it. + #[prop(flag)] + end_delete_deselects: bool, /// The host's rows between the graph and the fields. #[prop(func = "FnMut(&mut Ui, &mut BodyCx<'_>)")] between: Option>, @@ -167,6 +173,8 @@ impl<'a> CurveEditor<'a> { histogram: None, overlays: &[], selection: None, + tab_steps: false, + end_delete_deselects: false, between: None, } } @@ -196,6 +204,8 @@ impl<'a> CurveEditor<'a> { histogram, overlays, selection: host_selection, + tab_steps, + end_delete_deselects, mut between, } = self; let words = craft_ui::runtime::env::Env::of(ui).words::(); @@ -239,6 +249,12 @@ impl<'a> CurveEditor<'a> { if percent { graph = graph.percent(); } + if tab_steps { + graph = graph.tab_steps(); + } + if end_delete_deselects { + graph = graph.end_delete_deselects(); + } let CurveGraphOutput { mut edit, selected } = graph.show(ui); if let Some(rows) = between.as_mut() { (rows.0)(ui, root); diff --git a/crates/imaging/src/ui/curve/graph.rs b/crates/imaging/src/ui/curve/graph.rs index 9a539fb4b1..f1ccdb4938 100644 --- a/crates/imaging/src/ui/curve/graph.rs +++ b/crates/imaging/src/ui/curve/graph.rs @@ -32,6 +32,9 @@ const PLUS: [Chord; 3] = [Chord::plain(Key::Plus), Chord::plain(Key::Equals), Ch const MINUS: Chord = Chord::plain(Key::Minus); const INSERT: [Chord; 3] = [Chord::plain(Key::Insert), Chord::new(Mods::CMD, Key::Enter), Chord::new(Mods::CTRL, Key::Enter)]; const DELETE: [Chord; 2] = [Chord::plain(Key::Delete), Chord::plain(Key::Backspace)]; +/// The next and the previous point with [`CurveGraph::tab_steps`]. +const NEXT_POINT: Chord = Chord::new(Mods::CTRL, Key::Tab); +const PREVIOUS_POINT: Chord = Chord::new(Mods { ctrl: true, shift: true, ..Mods::NONE }, Key::Tab); /// Levels one arrow key moves a point, and with Shift. const NUDGE: f32 = 1.0; @@ -367,6 +370,12 @@ pub struct CurveGraph<'a> { /// The selected point. #[prop] selection: Option, + /// Ctrl+Tab and Ctrl+Shift+Tab select the next and the previous point, wrapping round, while a point is selected. + #[prop(flag)] + tab_steps: bool, + /// Delete and Backspace on an end point, which stays, deselect it. + #[prop(flag)] + end_delete_deselects: bool, /// The selection after `update`, for the output. chosen: Option, } @@ -389,6 +398,8 @@ impl<'a> CurveGraph<'a> { histogram: None, overlays: &[], selection: None, + tab_steps: false, + end_delete_deselects: false, chosen: None, } .label(label) @@ -540,7 +551,7 @@ impl Component for CurveGraph<'_> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let frame = self.frame(rect, cx.style); cx.part(PLOT, frame.plot) - .sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS) + .sense(Sense::CLICK | Sense::CONTEXT_CLICK | Sense::DRAG | Sense::TAKE_FOCUS) .value_part() .pointer_only("the point keys and the arrow keys edit the points"); let shown = cx.value().cloned(); @@ -548,7 +559,7 @@ impl Component for CurveGraph<'_> { for (i, p) in points.iter().enumerate() { let reach = Rect::from_center_size(frame.map.screen(*p), Vec2::splat(2.0 * cx.style.hit)); cx.part(POINT.at(i as u64), reach) - .sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS) + .sense(Sense::CLICK | Sense::CONTEXT_CLICK | Sense::DRAG | Sense::TAKE_FOCUS) .priority(HitPriority::new(HitLevel::Body, 0)) .pointer_only("the plot's point keys select and move the points"); } @@ -669,6 +680,11 @@ impl Component for CurveGraph<'_> { for chord in PLUS.into_iter().chain([MINUS]).chain(INSERT).chain(DELETE) { cx.claim(chord); } + // Only with a point selected, after this pass's keys: otherwise Ctrl+Tab stays the app's. + if self.tab_steps && selected.is_some() { + cx.claim(NEXT_POINT); + cx.claim(PREVIOUS_POINT); + } self.chosen = selected; } @@ -765,37 +781,38 @@ impl CurveGraph<'_> { if n == 0 { return selected; } - let mut plus = 0; - for chord in PLUS { - while cx.take_claimed(chord) { - plus += 1; - } - } - for _ in 0..plus { - selected = Some(selected.map_or(0, |i| (i + 1).min(n - 1))); - } - while cx.take_claimed(MINUS) { - selected = Some(selected.map_or(n - 1, |i| i.saturating_sub(1))); - } - let mut insert = false; - for chord in INSERT { - while cx.take_claimed(chord) { - insert = true; - } - } - if insert { - // A gap too narrow for a point adds nothing and keeps the selection. - let drawn = curve.points().map(|points| self.samples(points, &curve.corner_flags())).unwrap_or_default(); - if let Some((next, i)) = rules.inserted(curve, selected, &drawn) { - cx.set(next.clone()); - *curve = next; - selected = Some(i); - } - } - let mut delete = false; - for chord in DELETE { - while cx.take_claimed(chord) { - delete = true; + // The claimed keys in the order they were pressed, each as if it came alone: a Delete and then a Ctrl+Tab in + // one frame delete the point that was selected, not the next one. + let chords: Vec = PLUS.into_iter().chain([MINUS, NEXT_POINT, PREVIOUS_POINT]).chain(INSERT).chain(DELETE).collect(); + while let Some(chord) = cx.take_first_claimed(&chords) { + let n = curve.points().map_or(0, <[_]>::len); + if PLUS.contains(&chord) { + selected = Some(selected.map_or(0, |i| (i + 1).min(n - 1))); + } else if chord == MINUS { + selected = Some(selected.map_or(n - 1, |i| i.saturating_sub(1))); + } else if chord == NEXT_POINT { + selected = selected.map(|i| (i + 1) % n); + } else if chord == PREVIOUS_POINT { + selected = selected.map(|i| (i + n - 1) % n); + } else if INSERT.contains(&chord) { + // A gap too narrow for a point adds nothing and keeps the selection. + let drawn = curve.points().map(|points| self.samples(points, &curve.corner_flags())).unwrap_or_default(); + if let Some((next, i)) = rules.inserted(curve, selected, &drawn) { + cx.set(next.clone()); + *curve = next; + selected = Some(i); + } + } else if let Some(at) = selected { + match CurveRules::deleted(curve, at) { + Some(next) => { + cx.set(next.clone()); + *curve = next; + selected = None; + } + // An end point stays, and so does the selection on it unless `end_delete_deselects`. + None if self.end_delete_deselects => selected = None, + None => {} + } } } let rtl = cx.flow.is_rtl(); @@ -816,13 +833,6 @@ impl CurveGraph<'_> { by = [by[0] + dx * steps, by[1] + dy * steps]; } let Some(at) = selected else { return selected }; - if delete { - // An end point stays, and so does the selection on it. - let Some(next) = CurveRules::deleted(curve, at) else { return selected }; - cx.set(next.clone()); - *curve = next; - return None; - } if by != [0.0, 0.0] && let Some(next) = rules.nudged(curve, at, by) { diff --git a/crates/imaging/src/ui/fill/stories.rs b/crates/imaging/src/ui/fill/stories.rs index d1de28716a..e5fa8608f1 100644 --- a/crates/imaging/src/ui/fill/stories.rs +++ b/crates/imaging/src/ui/fill/stories.rs @@ -102,12 +102,7 @@ impl FillSource for StorySource { match self.preview { Preview::Loading => Job::new(|progress, cancel| { progress.report(LOADING_PROGRESS); - for _ in 0..LOADING_SECONDS { - if cancel.is_cancelled() { - break; - } - std::thread::sleep(Duration::from_secs(1)); - } + cancel.wait_timeout(Duration::from_secs(LOADING_SECONDS)); Ok(PreviewDone::new(Duration::ZERO)) }), Preview::Failed => Job::new(|_, _| Err("nothing to sample from: the sampling area has no pixels outside the fill area".to_owned())), diff --git a/crates/imaging/src/ui/filter_gallery/stories.rs b/crates/imaging/src/ui/filter_gallery/stories.rs index 900e7cb1da..cecc8033d0 100644 --- a/crates/imaging/src/ui/filter_gallery/stories.rs +++ b/crates/imaging/src/ui/filter_gallery/stories.rs @@ -27,8 +27,6 @@ use crate::ui::wide_angle::PreviewDone; const NOTE: Duration = Duration::from_millis(120); /// How far the loading render has come, as a fraction. const PROGRESS: f32 = 0.4; -/// How often the loading render looks for its cancellation. -const POLL: Duration = Duration::from_millis(20); // --- the fake app --- @@ -136,9 +134,7 @@ impl FilterGallerySource for MockSource { if self.rendering { Job::new(|progress, cancel| { progress.report(PROGRESS); - while !cancel.is_cancelled() { - std::thread::sleep(POLL); - } + cancel.wait(); Err(String::new()) }) } else { diff --git a/crates/imaging/src/ui/layer_style/hosted.rs b/crates/imaging/src/ui/layer_style/hosted.rs index ed5c1e5ff5..2586ffad78 100644 --- a/crates/imaging/src/ui/layer_style/hosted.rs +++ b/crates/imaging/src/ui/layer_style/hosted.rs @@ -366,7 +366,7 @@ impl StackDialog for HostedLayerStyle { .show(ui, |ui, cx, draft| { if let Some(canvas) = *canvas { cx.keep_view_open(canvas); - if draft.drags_shadow() || draft.drags_gradient() { + if draft.drags_on_canvas() { cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY); } } diff --git a/crates/imaging/src/ui/select/magnetic.rs b/crates/imaging/src/ui/select/magnetic.rs index 2f49645543..fe15487cd3 100644 --- a/crates/imaging/src/ui/select/magnetic.rs +++ b/crates/imaging/src/ui/select/magnetic.rs @@ -44,7 +44,7 @@ pub trait EdgeTracer { /// The Magnetic Lasso's options bar, persisted by the app (decisions §2.4). The options bar edits /// [`MagneticLassoTool::settings_mut`]; `[` and `]` change `width` ([`step_width`](Self::step_width)): the tool while an /// outline is open, the app's shortcuts otherwise. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase", default)] #[non_exhaustive] pub struct MagneticSettings { diff --git a/crates/imaging/src/ui/select_mask/stories.rs b/crates/imaging/src/ui/select_mask/stories.rs index 2bfd781a72..3ffb2d9bb6 100644 --- a/crates/imaging/src/ui/select_mask/stories.rs +++ b/crates/imaging/src/ui/select_mask/stories.rs @@ -27,9 +27,6 @@ use crate::ui::wide_angle::PreviewDone; /// The limits a story runs under: PhotoCraft's. const LIMITS: SelectMaskLimits = SelectMaskLimits { edits: 4096, edit_points: 100_000, strokes: 4096, stroke_points: 100_000 }; -/// How often a never-finishing preview job looks for its cancellation. -const POLL: Duration = Duration::from_millis(50); - /// The app's side over `MockImage`: the picture as the view, the house as the selection. struct StorySource { image: MockImage, @@ -54,9 +51,7 @@ impl SelectMaskSource for StorySource { fn preview_job(&self, _: &SelectMaskPreviewRequest) -> Job { if self.loading { Job::new(|_, cancel| { - while !cancel.is_cancelled() { - std::thread::sleep(POLL); - } + cancel.wait(); Err("cancelled".to_owned()) }) } else { diff --git a/crates/imaging/src/ui/warp/cylinder.rs b/crates/imaging/src/ui/warp/cylinder.rs index 5262295371..a11073363e 100644 --- a/crates/imaging/src/ui/warp/cylinder.rs +++ b/crates/imaging/src/ui/warp/cylinder.rs @@ -405,7 +405,7 @@ impl Component for CylinderWarp<'_> { results.push((handle, result.press)); } } - if let Some((hover_pos, press)) = cx.part_if_declared(BODY).map(|result| (result.hover_pos, result.press)) { + if let Some((hover_pos, press)) = cx.part_if_declared(BODY).map(|result| (cx.hover_pos(BODY), result.press)) { let on_surface = hover_pos.is_some_and(|at| self.mesh.surface_at(space.view.to_doc(at)).is_some()); if on_surface { cx.cursor(CursorIcon::Move, craft_behavior::CursorPriority::Part); diff --git a/crates/imaging/src/ui/warp/grid.rs b/crates/imaging/src/ui/warp/grid.rs index 46579dacc8..8f8a764cf3 100644 --- a/crates/imaging/src/ui/warp/grid.rs +++ b/crates/imaging/src/ui/warp/grid.rs @@ -288,7 +288,11 @@ impl<'a> WarpGrid<'a> { None => cx.part_if_declared(SURFACE), }; let Some(result) = found else { continue }; - let (hover_at, press) = (result.hover_pos, result.press); + let hover_at = match point { + Some(index) => cx.hover_pos(POINT.at(index as u64)), + None => cx.hover_pos(SURFACE), + }; + let press = result.press; if hover.is_none() && let Some(at) = hover_at { diff --git a/crates/imaging/src/ui/warp/pin/overlay.rs b/crates/imaging/src/ui/warp/pin/overlay.rs index 31605062b6..78cbfb7b92 100644 --- a/crates/imaging/src/ui/warp/pin/overlay.rs +++ b/crates/imaging/src/ui/warp/pin/overlay.rs @@ -353,7 +353,7 @@ impl PinWarp<'_> { fn run_pointer(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, pins: &[Pin]) { for i in 0..pins.len() { let Some(result) = cx.part_if_declared(PIN.at(i as u64)) else { continue }; - let (press, hovered, hover_pos) = (result.press, result.hovered, result.hover_pos); + let (press, hovered, hover_pos) = (result.press, result.hovered, cx.hover_pos(PIN.at(i as u64))); if hovered { self.report.hovered = Some(i); self.report.pointer = hover_pos.map(|at| space.view.to_doc(at)); @@ -370,7 +370,7 @@ impl PinWarp<'_> { } } let Some(result) = cx.part_if_declared(MESH) else { return }; - let (press, hovered, hover_pos) = (result.press, result.hovered, result.hover_pos); + let (press, hovered, hover_pos) = (result.press, result.hovered, cx.hover_pos(MESH)); if hovered && self.report.pointer.is_none() { self.report.pointer = hover_pos.map(|at| space.view.to_doc(at)); } diff --git a/crates/imaging/tests/it/curve.rs b/crates/imaging/tests/it/curve.rs index 4d2c977a0e..0bbe116b6e 100644 --- a/crates/imaging/tests/it/curve.rs +++ b/crates/imaging/tests/it/curve.rs @@ -6,18 +6,20 @@ use craft_imaging::ui::ChannelColor; use craft_imaging::ui::curve::{Curve, CurveChannel, CurveEditor}; use craft_theme::{Contrast, Mode}; use craft_ui::contract::Bind; -use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::pointer::{moved, press, release, secondary}; use craft_ui::testing::{Fixture, Room, style, trial}; use egui::{Pos2, Vec2, pos2, vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; -struct Rig { - fixture: Fixture, +pub(crate) struct Rig { + pub(crate) fixture: Fixture, curve: Rc>, - selected: Rc>>, + pub(crate) selected: Rc>>, /// The kind of each edit event, in order. kinds: Rc>>, + /// The key presses left in egui's input after the editor, which the app reads, in order. + pub(crate) app_keys: Rc>>, origin: Pos2, scale: Vec2, } @@ -34,24 +36,42 @@ fn kind(event: &EditEvent) -> &'static str { } fn rig(points: &[[f32; 2]]) -> Rig { + rig_with(points, false) +} + +/// [`rig`] with `tab_steps` and `end_delete_deselects` when `point_keys`. +pub(crate) fn rig_with(points: &[[f32; 2]], point_keys: bool) -> Rig { let curve = Curve::smooth(points.to_vec()); let shared = Rc::new(RefCell::new(curve.clone())); let selected = Rc::new(Cell::new(None)); let kinds = Rc::new(RefCell::new(Vec::new())); - let (c, s, k) = (shared.clone(), selected.clone(), kinds.clone()); + let app_keys = Rc::new(RefCell::new(Vec::new())); + let (c, s, k, a) = (shared.clone(), selected.clone(), kinds.clone(), app_keys.clone()); let channels = [CurveChannel::new("RGB", ChannelColor::Neutral), CurveChannel::new("Red", ChannelColor::Red)]; let mut fixture = Fixture::new(move |ui| { let mut value = c.borrow().clone(); - let out = CurveEditor::new("Curve", Bind::bound(&mut value)).channels(&channels).channel(0).selection(s.get()).show(ui); + let mut editor = CurveEditor::new("Curve", Bind::bound(&mut value)).channels(&channels).channel(0).selection(s.get()); + if point_keys { + editor = editor.tab_steps().end_delete_deselects(); + } + let out = editor.show(ui); for event in &out.edit.events { k.borrow_mut().push(kind(event)); } s.set(out.selected); *c.borrow_mut() = value; + let pressed = ui.input(|input| { + input + .events + .iter() + .filter_map(|event| if let egui::Event::Key { key, pressed: true, .. } = event { Some(*key) } else { None }) + .collect::>() + }); + a.borrow_mut().extend(pressed); }); fixture.room(room()); fixture.settle(); - let mut rig = Rig { fixture, curve: shared, selected, kinds, origin: Pos2::ZERO, scale: Vec2::ZERO }; + let mut rig = Rig { fixture, curve: shared, selected, kinds, app_keys, origin: Pos2::ZERO, scale: Vec2::ZERO }; rig.calibrate(&curve); rig } @@ -72,7 +92,7 @@ impl Rig { pos2(self.origin.x + q[0] * self.scale.x, self.origin.y + q[1] * self.scale.y) } - fn points(&self) -> Vec<[f32; 2]> { + pub(crate) fn points(&self) -> Vec<[f32; 2]> { self.curve.borrow().points().map(<[_]>::to_vec).unwrap_or_default() } @@ -80,7 +100,7 @@ impl Rig { self.kinds.borrow().clone() } - fn press_at(&mut self, q: [f32; 2]) { + pub(crate) fn press_at(&mut self, q: [f32; 2]) { let pos = self.at(q); self.fixture.frame(vec![moved(pos)]); self.fixture.frame(vec![press(pos)]); @@ -102,10 +122,18 @@ impl Rig { self.fixture.frame(vec![moved(self.at(q))]); } - fn release_at(&mut self, q: [f32; 2]) { + pub(crate) fn release_at(&mut self, q: [f32; 2]) { self.fixture.frame(vec![release(self.at(q))]); self.fixture.idle(1); } + + fn right_click_at(&mut self, q: [f32; 2]) { + let pos = self.at(q); + self.fixture.frame(vec![moved(pos)]); + self.fixture.frame(vec![secondary(pos, true)]); + self.fixture.frame(vec![secondary(pos, false)]); + self.fixture.idle(1); + } } /// The room is this many plot widths wide and tall: the editor at its greatest size and the rows under it. @@ -173,6 +201,20 @@ fn a_press_near_a_point_grabs_it_and_a_press_far_from_it_adds_one() { assert_eq!(rig.points().len(), 4, "a press 30 px away adds a point"); } +/// A right-click on the empty graph drops the selection and adds no point; a right-click on an inner point removes it. +#[trial] +fn a_right_click_on_the_empty_graph_deselects_and_on_a_point_removes_it() { + let mut rig = rig(&THREE); + rig.press_at([100.0, 100.0]); + rig.release_at([100.0, 100.0]); + assert_eq!(rig.selected.get(), Some(1)); + rig.right_click_at([180.0, 20.0]); + assert_eq!(rig.selected.get(), None, "a right-click on the empty graph deselects"); + assert_eq!(rig.points(), THREE.to_vec(), "and adds no point"); + rig.right_click_at([100.0, 100.0]); + assert_eq!(rig.points(), vec![[0.0, 0.0], [255.0, 255.0]], "a right-click on a point removes it"); +} + /// Where two points are closer than the grab radius, a press nearer the second grabs the second. #[trial] fn where_grab_areas_overlap_the_nearest_point_is_grabbed() { diff --git a/crates/imaging/tests/it/curve_point_keys.rs b/crates/imaging/tests/it/curve_point_keys.rs new file mode 100644 index 0000000000..29dd91b651 --- /dev/null +++ b/crates/imaging/tests/it/curve_point_keys.rs @@ -0,0 +1,81 @@ +//! The curve editor's opt-in point keys: Ctrl+Tab and Ctrl+Shift+Tab step through the points with `tab_steps`, and +//! Delete on an end point deselects it with `end_delete_deselects`. + +use super::curve::{Rig, rig_with}; +use craft_ui::testing::input::key_press; +use craft_ui::testing::trial; +use egui::{Key, Modifiers}; + +const FOUR: [[f32; 2]; 4] = [[0.0, 0.0], [64.0, 64.0], [192.0, 192.0], [255.0, 255.0]]; + +/// Selects the point at `q` with a click on it, which also focuses the graph. +fn click_point(rig: &mut Rig, q: [f32; 2]) { + rig.press_at(q); + rig.release_at(q); +} + +/// Ctrl+Tab steps right through the points and wraps; Ctrl+Shift+Tab steps left. The curve stays as it is. +#[trial] +fn tab_steps_selects_the_next_and_previous_point_round_the_curve() { + let mut rig = rig_with(&FOUR, true); + click_point(&mut rig, [64.0, 64.0]); + assert_eq!(rig.selected.get(), Some(1)); + let mut seen = Vec::new(); + for _ in 0..3 { + rig.fixture.key(egui::Key::Tab, egui::Modifiers::CTRL).idle(1); + seen.push(rig.selected.get()); + } + assert_eq!(seen, [Some(2), Some(3), Some(0)], "right, then round to the first"); + seen.clear(); + for _ in 0..3 { + rig.fixture.key(egui::Key::Tab, egui::Modifiers::CTRL | egui::Modifiers::SHIFT).idle(1); + seen.push(rig.selected.get()); + } + assert_eq!(seen, [Some(3), Some(2), Some(1)], "round to the last, then left"); + assert_eq!(rig.points(), FOUR.to_vec(), "no point moved"); +} + +/// Without the option Ctrl+Tab leaves the selection. +#[trial] +fn without_tab_steps_ctrl_tab_leaves_the_selection() { + let mut rig = rig_with(&FOUR, false); + click_point(&mut rig, [64.0, 64.0]); + rig.fixture.key(egui::Key::Tab, egui::Modifiers::CTRL).idle(1); + assert_eq!(rig.selected.get(), Some(1)); +} + +/// Delete on an end point keeps the point; with the option it deselects it, without it the point stays selected. +/// Delete on an inner point removes it either way. +#[trial] +fn end_delete_deselects_an_end_point_and_inner_points_still_go() { + for (point_keys, after) in [(false, Some(0)), (true, None)] { + let mut rig = rig_with(&FOUR, point_keys); + click_point(&mut rig, [0.0, 0.0]); + assert_eq!(rig.selected.get(), Some(0)); + rig.fixture.key(egui::Key::Delete, egui::Modifiers::NONE).idle(1); + assert_eq!(rig.points(), FOUR.to_vec(), "an end point stays"); + assert_eq!(rig.selected.get(), after, "end_delete_deselects: {point_keys}"); + click_point(&mut rig, [192.0, 192.0]); + rig.fixture.key(egui::Key::Delete, egui::Modifiers::NONE).idle(1); + assert_eq!(rig.points(), vec![[0.0, 0.0], [64.0, 64.0], [255.0, 255.0]], "an inner point goes"); + } +} + +/// Delete and then Ctrl+Tab in one frame act in the order they were pressed: on an inner point the selected point goes, +/// not the next one, and on an end point Delete only deselects, so the Ctrl+Tab after it has no point to step from. A +/// shortcut the graph doesn't claim, pressed in the same frame, still reaches the app. +#[trial] +fn delete_then_ctrl_tab_in_one_frame_act_in_order_and_other_shortcuts_reach_the_app() { + let inner_gone = vec![[0.0, 0.0], [192.0, 192.0], [255.0, 255.0]]; + for (at, after) in [([64.0, 64.0], inner_gone), ([0.0, 0.0], FOUR.to_vec())] { + let mut rig = rig_with(&FOUR, true); + click_point(&mut rig, at); + rig.app_keys.borrow_mut().clear(); + let keys = [(Key::Delete, Modifiers::NONE), (Key::Tab, Modifiers::CTRL), (Key::S, Modifiers::CTRL)]; + rig.fixture.frame_through(keys.iter().map(|(key, mods)| key_press(*key, *mods)).collect()).idle(1); + assert_eq!(rig.points(), after, "Delete acts on the point selected at {at:?}"); + assert_eq!(rig.selected.get(), None, "nothing is selected after the Delete"); + let app = rig.app_keys.borrow(); + assert!(app.contains(&Key::S) && !app.contains(&Key::Delete) && !app.contains(&Key::Tab), "the app gets only Ctrl+S: {app:?}"); + } +} diff --git a/crates/imaging/tests/it/filter_gallery.rs b/crates/imaging/tests/it/filter_gallery.rs index 6824f7586c..a58b4a783f 100644 --- a/crates/imaging/tests/it/filter_gallery.rs +++ b/crates/imaging/tests/it/filter_gallery.rs @@ -146,9 +146,7 @@ impl FilterGallerySource for Flat { Job::new(|_, _| Ok(PreviewDone::new(Duration::from_millis(12)))) } else { Job::new(|_, cancel| { - while !cancel.is_cancelled() { - std::thread::sleep(Duration::from_millis(10)); - } + cancel.wait(); Err(String::new()) }) } diff --git a/crates/imaging/tests/it/main.rs b/crates/imaging/tests/it/main.rs index 2509982365..02844e5f72 100644 --- a/crates/imaging/tests/it/main.rs +++ b/crates/imaging/tests/it/main.rs @@ -8,6 +8,7 @@ pub(crate) mod channels_memo; pub(crate) mod color_range; pub(crate) mod contour_field; pub(crate) mod curve; +pub(crate) mod curve_point_keys; pub(crate) mod fill; pub(crate) mod filter_gallery; pub(crate) mod histogram; diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 8fd2b48ab0..21691ac881 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -305,6 +305,9 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File are applied in file order; the earlier key is listed in `skipped`), and an entry without keys can clear its command. It clears it only when no entry matched to the same command has keys, whatever the order of the entries. +- Conflicts removed from one command are saved as one final binding list. An intermediate + list that cannot be stored does not block an import whose final list fits. If that final + list cannot be saved, the entries taking those keys fail and keep their previous bindings. - Keys read approximately (a numeric keypad key bound as the main key) are listed in `approximated`. - With `ImportOptions.suggest`, unmatched entries get fuzzy candidates (`import::namematch`); diff --git a/crates/keymap/src/editor.rs b/crates/keymap/src/editor.rs index af8a2929f3..fbb2acafc9 100644 --- a/crates/keymap/src/editor.rs +++ b/crates/keymap/src/editor.rs @@ -104,8 +104,8 @@ impl EditSession { new: Binding, policy: Policy, ) -> Result { - let list: Vec = keymap.bindings(command).into_iter().map(|b| if b == *old { new.clone() } else { b }).collect(); - self.edit(keymap, |km| km.set_bindings(command, list, policy)) + let bindings = replacing(keymap, command, old, &new); + self.edit(keymap, |km| km.set_bindings(command, bindings, policy)) } /// Removes one binding of a command as one undo step. @@ -180,6 +180,16 @@ impl EditSession { } } +/// Checks whether the replacement that [`EditSession::replace`] would make can be saved under `policy`. +/// This leaves the keymap and its undo history untouched. +pub fn check_replace(keymap: &Keymap, command: &CommandRef, old: &Binding, new: &Binding, policy: Policy) -> Result<(), AssignError> { + keymap.check_set_bindings(command, replacing(keymap, command, old, new), policy) +} + +fn replacing(keymap: &Keymap, command: &CommandRef, old: &Binding, new: &Binding) -> Vec { + keymap.bindings(command).into_iter().map(|binding| if binding == *old { new.clone() } else { binding }).collect() +} + /// The other commands whose bindings clash with `binding` given to `command`: what /// [`Policy::Steal`] would take and [`Policy::Keep`] would leave clashing. Tools of the command's /// group and twins sharing a default key are not listed. A dialog shows these while the user diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 55347f4e5f..11eb1fcc96 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -745,6 +745,8 @@ impl ImportPlan { /// earlier entry stays with that entry. That includes taking a chord from another command, /// or from a command whose own change failed: both commands keep the bindings they had. With /// [`Start::Defaults`] that cannot happen. + /// All conflicts removed from one command are saved together, so only its final binding + /// list must fit in the overrides, rather than each intermediate list. pub fn apply(&self, keymap: &mut Keymap) -> ImportReport { let before: Vec> = self.commands.iter().map(|p| keymap.bindings(&p.command)).collect(); // Dropping every entry leaves room for all of them: each catalog command takes at most one @@ -802,7 +804,9 @@ impl ImportPlan { // A command that cannot take a chord from another command is dropped, so both keep // the bindings they had. That includes a command whose own change failed: freeing an // entry later must not take its chord away. - let mut unbind_failed = false; + let mut removals: Vec<(CommandRef, Vec, Vec)> = Vec::new(); + let mut removal_index = HashMap::new(); + let mut cleared = Vec::new(); for (c, (p, list)) in self.commands.iter().zip(&accepted).enumerate() { if list.is_empty() || !decided.contains(&p.command.key()) { continue; @@ -811,12 +815,27 @@ impl ImportPlan { if decided.contains(&h.command.key()) { continue; } - let home = home_of(keymap, &h.command); - let label = label_of(keymap, &h.command); - let shortcut = h.binding.text(&home); - if !failed_here.contains(&h.command.key()) && keymap.remove(&h.command, &h.binding) { - report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); - } else { + let index = *removal_index.entry(h.command.key()).or_insert_with(|| { + removals.push((h.command.clone(), Vec::new(), Vec::new())); + removals.len() - 1 + }); + let Some((_, bindings, claimants)) = removals.get_mut(index) else { continue }; + if !claimants.contains(&c) { + claimants.push(c); + } + if !bindings.contains(&h.binding) { + bindings.push(h.binding.clone()); + cleared.push(h); + } + } + } + let mut unbind_failed = false; + for (command, bindings, claimants) in removals { + let remaining = keymap.bindings(&command).into_iter().filter(|binding| !bindings.contains(binding)).collect(); + if failed_here.contains(&command.key()) || keymap.set_bindings(&command, remaining, Policy::Keep).is_err() { + for c in claimants { + let Some(p) = self.commands.get(c) else { continue }; + let Some(list) = accepted.get(c) else { continue }; let home = home_of(keymap, &p.command); let list = in_default_order(keymap, &p.command, list); let shortcuts = list.iter().map(|b| b.text(&home)).collect(); @@ -824,15 +843,21 @@ impl ImportPlan { c, Failed { command: p.command.clone(), label: label_of(keymap, &p.command), change: FailedChange::Bind, shortcuts }, ); - unbind_failed = true; - break; } + unbind_failed = true; + break; } } if unbind_failed { *keymap = start.clone(); continue 'attempt; } + for h in cleared { + let home = home_of(keymap, &h.command); + let label = label_of(keymap, &h.command); + let shortcut = h.binding.text(&home); + report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); + } for (p, from) in self.commands.iter().zip(&before) { if !decided.contains(&p.command.key()) { diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 31ed74a36d..025cd2c391 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -27,7 +27,7 @@ mod binding; mod command; pub use binding::{Binding, BindingError}; -pub use command::{CommandDef, CommandKind, DeleteKeys, ModalRule, TypingRule}; +pub use command::{CommandDef, CommandKind, DeleteKeys, Dispatch, ModalRule, TypingRule}; mod editing; pub use editing::text_editing_chords; @@ -229,6 +229,8 @@ pub struct Conflict { /// A binding with its scope resolved. type Bound = (Trigger, Scope); +type BindingWrites = Vec<(usize, Vec)>; +type StoredBindingWrites = Vec<(usize, Vec, Option>)>; /// Whether `trigger` can start a command: any press can; a hold needs a chord that types a character, alone or with /// Shift, since the others are taken by the system and by text fields. @@ -398,7 +400,9 @@ impl Keymap { self.find(command).map(|i| &self.catalog[i]) } - /// The effective bindings of a command; empty for an unknown one. + /// The effective bindings of a command; empty for an unknown one. A command the app runs itself + /// ([`Dispatch::App`]) lists its bindings too, as the shortcut editor shows and edits them, though nothing here + /// matches them. pub fn bindings(&self, command: &CommandRef) -> Vec { self.find(command).map(|i| self.current[i].iter().filter(|b| self.counts(b)).map(|b| self.public(i, b)).collect()).unwrap_or_default() } @@ -453,7 +457,8 @@ impl Keymap { } } - /// The command `chord` (pressed twice when `double`) runs with `active` focus. + /// The command `chord` (pressed twice when `double`) runs with `active` focus. A command the app runs itself + /// ([`Dispatch::App`]) is none of them: its chords belong to the app's own key handling. pub fn lookup(&self, chord: &Chord, double: bool, active: &Active) -> Lookup { self.lookup_nested(chord, double, active, &[]) } @@ -520,6 +525,9 @@ impl Keymap { /// applies (an application binding with no panel focused, a panel binding with its panel focused, a context /// binding with its context active), gives the command or a cycle that holds it. `None` when every binding is /// shadowed or the command has none. Read from a table the keymap builds when its bindings change. + /// + /// A command the app runs itself ([`Dispatch::App`]) shows its first single-press binding wherever it is, home + /// scope first: nothing here matches its chords, so nothing here can shadow them. pub fn shown_chord(&self, command: &CommandRef) -> Option { self.find(command).and_then(|i| self.shown[i]) } @@ -535,6 +543,15 @@ impl Keymap { fn shown_of(&self, i: usize) -> Option { let home = &self.catalog[i].scope; let single = || self.current[i].iter().filter(|(trigger, _)| trigger.press == PressKind::Single); + // The app runs a command marked `Dispatch::App` on its own, so the keymap cannot tell whether a chord it also + // binds takes the key first: it shows the command's first binding rather than dropping it as shadowed. + if self.catalog[i].dispatch == Dispatch::App { + return single() + .filter(|(_, scope)| scope == home) + .chain(single().filter(|(_, scope)| scope != home)) + .map(|(trigger, _)| trigger.chord) + .next(); + } let runs = |(trigger, scope): &&Bound| { let name = [scope.as_str()]; let active = match self.scopes.kind(scope) { @@ -592,11 +609,24 @@ impl Keymap { } let mut list = self.current[i].clone(); list.push(new.clone()); - self.apply(i, list, &[new], policy) + let (assigned, writes) = self.plan_writes(i, list, &[new], policy)?; + self.commit(writes)?; + Ok(assigned) } /// Replaces all bindings of a command. pub fn set_bindings(&mut self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result { + let (assigned, writes) = self.plan_set_bindings(command, bindings, policy)?; + self.commit(writes)?; + Ok(assigned) + } + + pub(crate) fn check_set_bindings(&self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result<(), AssignError> { + let (_, writes) = self.plan_set_bindings(command, bindings, policy)?; + self.prepare_writes(writes).map(|_| ()) + } + + fn plan_set_bindings(&self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result<(Assigned, BindingWrites), AssignError> { let i = self.find(command).ok_or(AssignError::UnknownCommand)?; if bindings.len() > MAX_BINDINGS { return Err(AssignError::TooMany); @@ -606,7 +636,7 @@ impl Keymap { let kept: Vec = self.hidden(i).into_iter().filter(|h| !list.iter().any(|b| self.same(b, h))).collect(); list.extend(kept); let new: Vec = list.iter().filter(|b| !self.current[i].iter().any(|c| self.same(c, b))).cloned().collect(); - self.apply(i, list, &new, policy) + self.plan_writes(i, list, &new, policy) } /// Removes one binding (matched by effective trigger and scope). `false` when the command does @@ -898,7 +928,7 @@ impl Keymap { out.len() < MAX_CONFLICTS } - fn apply(&mut self, i: usize, list: Vec, new: &[Bound], policy: Policy) -> Result { + fn plan_writes(&self, i: usize, list: Vec, new: &[Bound], policy: Policy) -> Result<(Assigned, BindingWrites), AssignError> { if list.len() > MAX_BINDINGS { return Err(AssignError::TooMany); } @@ -916,7 +946,7 @@ impl Keymap { let holders: Vec = clashes.iter().map(|(j, b)| Holder { command: self.catalog[*j].command.clone(), binding: self.public(*j, b) }).collect(); let mut done = Assigned::default(); - let mut writes: Vec<(usize, Vec)> = Vec::new(); + let mut writes = Vec::new(); match policy { Policy::Refuse if !holders.is_empty() => return Err(AssignError::Taken(holders)), Policy::Refuse => {} @@ -940,12 +970,11 @@ impl Keymap { } } writes.push((i, list)); - self.commit(writes)?; - Ok(done) + Ok((done, writes)) } /// Prepares all entries before replacing live or stored bindings, including commands whose bindings were taken. - fn commit(&mut self, writes: Vec<(usize, Vec)>) -> Result<(), AssignError> { + fn prepare_writes(&self, writes: BindingWrites) -> Result { let mut prepared = Vec::with_capacity(writes.len()); for (i, list) in writes { let texts = self.store_texts(i, &list)?; @@ -955,7 +984,11 @@ impl Keymap { if self.overrides.len() + needed > MAX_COMMANDS { return Err(AssignError::Full); } - for (i, list, texts) in prepared { + Ok(prepared) + } + + fn commit(&mut self, writes: BindingWrites) -> Result<(), AssignError> { + for (i, list, texts) in self.prepare_writes(writes)? { self.remove_entries(i); if let Some(texts) = texts { self.overrides.insert(self.keys[i].clone(), texts); @@ -1043,6 +1076,11 @@ impl Keymap { fn index_command(&mut self, i: usize) { let Some(list) = self.current.get(i) else { return }; + // A command the app runs itself matches nothing here: its chords stay in the app's hands, as the raw input + // holds them. + if self.catalog[i].dispatch == Dispatch::App { + return; + } let holds = self.holds; for (k, (t, _)) in list.iter().enumerate().filter(|(_, (t, _))| holds || !t.is_hold()) { self.by_trigger.entry(t.effective(self.platform)).or_default().insert((i, k)); diff --git a/crates/keymap/src/keymap/command.rs b/crates/keymap/src/keymap/command.rs index e29300cdd7..b97c7c6d6f 100644 --- a/crates/keymap/src/keymap/command.rs +++ b/crates/keymap/src/keymap/command.rs @@ -28,6 +28,27 @@ pub enum CommandKind { Momentary, } +/// Who runs a command's keys. +/// +/// A command the app runs itself keeps its place in the catalog and its bindings: menus, tooltips, rails and buttons +/// show its chords ([`Keymap::shown_chord`](crate::Keymap::shown_chord)) and the shortcut editor lists them, and the +/// keymap matches none of them, so the press goes to the app as it would for a command with no binding here. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub enum Dispatch { + /// This keymap runs the command on its chords ([`Keymap::lookup`](crate::Keymap::lookup)). + #[default] + Keymap, + /// The app runs the command from its own key handling (a canvas editor with its own keymap). + App, +} + +/// Whether a command's keys are the keymap's, which written catalogs leave out as the default. +fn is_keymap(dispatch: &Dispatch) -> bool { + *dispatch == Dispatch::Keymap +} + /// Whether a command fires while a dialog is open. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -82,6 +103,10 @@ pub struct CommandDef { /// Whether the command fires while a dialog is open. #[serde(default)] pub modal: ModalRule, + /// Who runs the command's keys: this keymap, or the app, which shows them and matches none of them + /// ([`Dispatch`]). + #[serde(default, skip_serializing_if = "is_keymap")] + pub dispatch: Dispatch, } impl CommandDef { @@ -99,6 +124,7 @@ impl CommandDef { defaults: Vec::new(), icon: None, modal: ModalRule::default(), + dispatch: Dispatch::Keymap, } } @@ -137,6 +163,12 @@ impl CommandDef { self } + /// Sets the [`dispatch`](CommandDef::dispatch). + pub fn with_dispatch(mut self, dispatch: Dispatch) -> CommandDef { + self.dispatch = dispatch; + self + } + /// Adds a default binding. pub fn with_default(mut self, binding: Binding) -> CommandDef { self.defaults.push(binding); diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs index 02a8abc3e2..df067d7cea 100644 --- a/crates/keymap/src/lib.rs +++ b/crates/keymap/src/lib.rs @@ -62,6 +62,10 @@ //! assert_eq!(press("M", &editing), Lookup::None, "plain keys go to the text field"); //! ``` //! +//! A command whose keys the app runs itself keeps its bindings and shows their chords, and the keymap matches none of +//! them: `CommandDef::new(..).with_dispatch(Dispatch::App)` tells the surfaces what to show for a command whose keys +//! the app's own key handling takes (a canvas's tool keys), so the menus and the shortcut editor still read the catalog. +//! //! # Storing overrides //! //! [`Overrides`] is a field of the app's craft-settings type, marked @@ -158,8 +162,8 @@ pub use import::{ ContextRule, DecodedCode, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, NotRead, Start, plan, }; pub use keymap::{ - AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, DropReason, Holder, Keymap, Lookup, - MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords, + AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, Dispatch, DropReason, Holder, Keymap, + Lookup, MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords, }; pub use layout::{COMMON_SYMBOLS, KeyInput, Layout, SYMBOL_TABLE, SymbolLayout}; pub use matcher::{Hit, Matcher, Press}; diff --git a/crates/keymap/tests/editor.rs b/crates/keymap/tests/editor.rs index 3de26a98d5..4cda2cb526 100644 --- a/crates/keymap/tests/editor.rs +++ b/crates/keymap/tests/editor.rs @@ -1,6 +1,7 @@ //! Integration tests of craft-keymap: editor. -use craft_keymap::{Binding, CommandDef, CommandRef, EditSession, Keymap, Platform, Policy, Scope, Scopes}; +use craft_keymap::editor::check_replace; +use craft_keymap::{AssignError, Binding, CommandDef, CommandRef, EditSession, Keymap, Platform, Policy, Scope, Scopes}; fn b(text: &str) -> Binding { Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) @@ -20,6 +21,19 @@ fn keys(km: &Keymap, id: &str) -> Vec { km.bindings(&CommandRef::new(id)).iter().map(|b| b.to_string()).collect() } +#[test] +fn checking_a_replacement_does_not_take_the_other_commands_shortcut() { + let km = keymap(Platform::Mac); + let save = CommandRef::new("file.save"); + let old = b("Cmd+S"); + let new = b("Cmd+C"); + assert!(matches!(check_replace(&km, &save, &old, &new, Policy::Refuse), Err(AssignError::Taken(_)))); + assert!(check_replace(&km, &save, &old, &new, Policy::Steal).is_ok()); + assert_eq!(keys(&km, "file.save"), ["Cmd+S"]); + assert_eq!(keys(&km, "edit.copy"), ["Cmd+C"]); + assert!(km.overrides().is_empty()); +} + #[test] fn edits_undo_redo_and_cancel() { let mut km = keymap(Platform::Windows); diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index a48cd968c8..667385a3ba 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -203,6 +203,88 @@ fn a_failed_change_keeps_its_shortcut_when_a_later_change_frees_room() { assert_eq!(r.imported, 1); } +#[test] +fn an_import_removes_conflicts_using_each_commands_final_binding_list() { + let a = "A".repeat(64); + let b = "B".repeat(64); + let scopes = || Scopes::new().with_context(&a).with_context(&b); + let scope_a = Scope::new(&a).unwrap(); + let scope_b = Scope::new(&b).unwrap(); + let trigger = craft_keymap::Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap(); + let other = craft_keymap::Trigger::parse("Cmd+K").unwrap(); + let old = CommandRef::new("old.command"); + let first = CommandRef::new("new.first"); + let second = CommandRef::new("new.second"); + let catalog = || { + vec![ + CommandDef::new(old.clone(), "Old", Scope::app()) + .with_default(Binding::in_scope(trigger, scope_a.clone())) + .with_default(Binding::in_scope(other, scope_b.clone())), + CommandDef::new(first.clone(), "First", scope_a.clone()), + CommandDef::new(second.clone(), "Second", scope_b.clone()), + ] + }; + let mut km = Keymap::new(catalog(), scopes(), Platform::Mac); + assert_eq!(km.bindings(&old).len(), 2); + assert!(km.bindings(&old).iter().any(|binding| binding.text(&Scope::app()).len() > craft_keymap::MAX_BINDING_TEXT)); + // A reader can supply an already parsed sequence through the public import API. + let key = |trigger: craft_keymap::Trigger| ForeignKey { context: None, text: trigger.to_string(), trigger: Ok(trigger), notes: Vec::new() }; + let set = ForeignSet::new(vec![ + ForeignEntry::new(None, ["Second"]).with_id("new.second").with_key(key(other)), + ForeignEntry::new(None, ["First"]).with_id("new.first").with_key(key(trigger)), + ]); + let report = plan(&set, &km, &ImportOptions::default()).apply(&mut km); + assert!(report.failed.is_empty(), "the final cleared list is savable: {report:?}"); + assert_eq!(report.imported, 2); + assert_eq!(report.conflicts_cleared.len(), 2); + assert!(km.bindings(&old).is_empty()); + assert_eq!(km.bindings(&first), [Binding::new(trigger)]); + assert_eq!(km.bindings(&second), [Binding::new(other)]); + let reopened = Keymap::new(catalog(), scopes(), Platform::Mac).with_overrides(km.overrides().clone()); + for command in [&old, &first, &second] { + assert_eq!(reopened.bindings(command), km.bindings(command), "the imported bindings persist in the same contexts"); + } +} + +#[test] +fn an_unsavable_final_conflict_list_keeps_all_claimants_and_applies_other_entries() { + let context = "A".repeat(64); + let scope = Scope::new(&context).unwrap(); + let long = craft_keymap::Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap(); + let old = CommandRef::new("old.command"); + let catalog = vec![ + CommandDef::new(old.clone(), "Old", Scope::app()) + .with_default(Binding::in_scope(long, scope.clone())) + .with_default(b("Cmd+K")) + .with_default(b("Cmd+L")), + command("new.first", "First", &[], &["Cmd+1"]), + command("new.second", "Second", &[], &["Cmd+2"]), + command("new.other", "Other", &[], &[]), + command("old.other", "Old Other", &[], &["Cmd+J"]), + ]; + let mut overrides = Overrides::new(); + for n in 0..MAX_COMMANDS - 3 { + overrides.insert(format!("junk.{n}"), vec!["Cmd+9".into()]); + } + let mut km = Keymap::new(catalog, Scopes::new().with_context(&context), Platform::Mac).with_overrides(overrides); + let before = km.bindings(&old); + let set = ForeignSet::new(vec![ + ForeignEntry::new(None, ["First"]).with_id("new.first").with_key(ForeignKey::read(None, "Cmd+K", Flavor::Mac)), + ForeignEntry::new(None, ["Second"]).with_id("new.second").with_key(ForeignKey::read(None, "Cmd+L", Flavor::Mac)), + ForeignEntry::new(None, ["Other"]).with_id("new.other").with_key(ForeignKey::read(None, "Cmd+J", Flavor::Mac)), + ]); + let report = plan(&set, &km, &ImportOptions::default()).apply(&mut km); + assert_eq!(report.failed.iter().map(|failed| failed.command.id.as_str()).collect::>(), ["new.first", "new.second"]); + assert_eq!(report.imported, 1); + assert_eq!(report.conflicts_cleared.len(), 1); + assert_eq!(report.conflicts_cleared[0].command.id, "old.other"); + assert_eq!(km.bindings(&old), before); + has(&km, "new.first", &["Cmd+1"]); + has(&km, "new.second", &["Cmd+2"]); + has(&km, "new.other", &["Cmd+J"]); + has(&km, "old.other", &[]); +} + /// A Mac keymap of `catalog` with no reserved chords, for sets read with [`kys::read`]. fn mac_keymap(catalog: Vec) -> Keymap { Keymap::new(catalog, Scopes::new(), Platform::Mac) diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 215668bdd7..64ceb0f7e2 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -1,8 +1,8 @@ //! Integration tests of craft-keymap: keymap. use craft_keymap::{ - Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, Mods, - Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger, + Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, Dispatch, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, + Mods, Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger, }; use serde_json::json; @@ -152,6 +152,35 @@ fn a_command_shows_only_the_chords_the_lookup_runs_it_for() { assert_eq!(alone.shown_chord(&cmd("edit.settings")), None, "every key shadowed"); } +/// A command the app runs itself keeps its bindings and the chord they show, and matching passes over it: the lookup +/// finds nothing for its chords, the command holds none, another command on a chord it binds still shows it, and an +/// assignment takes nothing from it. +#[test] +fn a_command_the_app_runs_itself_shows_its_chords_and_matches_none() { + let own = |id: &str, keys: &[&str]| app(id, keys).with_dispatch(Dispatch::App); + let km = Keymap::new(vec![own("tool.brush", &["J", "B"])], Scopes::new(), Platform::Mac); + assert_eq!(km.shown_chord(&cmd("tool.brush")), Some(chord("J")), "its first binding shows"); + assert_eq!(km.bindings(&cmd("tool.brush")), [b("J"), b("B")], "and the shortcut editor lists them"); + assert_eq!(press(&km, "J", &Active::NONE), Lookup::None, "the lookup passes over its chords"); + assert_eq!(press(&km, "B", &Active::NONE), Lookup::None); + assert_eq!(km.holder(&chord("J")), None, "it holds no chord"); + assert!(km.holders(&chord("J")).is_empty()); + + // Another command on a chord it binds runs, and it still shows its own chord: nothing here shadows it. + let shared = Keymap::new(vec![own("tool.brush", &["J"]), app("view.grid", &["J"])], Scopes::new(), Platform::Mac); + assert_eq!(press(&shared, "J", &Active::NONE), run("view.grid"), "the chord is the other command's"); + assert_eq!(shared.shown_chord(&cmd("tool.brush")), Some(chord("J"))); + assert_eq!(shared.shown_chord(&cmd("view.grid")), Some(chord("J"))); + assert!(shared.conflicts().is_empty(), "a chord the app runs clashes with nothing here"); + + // Assigning a chord it binds to another command takes nothing from it. + let mut stealer = Keymap::new(vec![own("tool.brush", &["B"]), app("view.grid", &["J"])], Scopes::new(), Platform::Mac); + let done = stealer.assign(&cmd("view.grid"), b("B"), Policy::Steal).expect("the assignment is taken"); + assert!(done.taken_from.is_empty(), "the command the app runs keeps its binding"); + assert_eq!(stealer.bindings(&cmd("tool.brush")), [b("B")]); + assert_eq!(press(&stealer, "B", &Active::NONE), run("view.grid")); +} + /// The shown chords are worked out when the bindings change, not per call, and follow every change: a key freed by one /// command shows on the command it no longer shadows, and a stolen key leaves the command it was taken from. #[test] diff --git a/crates/latex/src/parser.rs b/crates/latex/src/parser.rs index 12971f1d05..d502e73976 100644 --- a/crates/latex/src/parser.rs +++ b/crates/latex/src/parser.rs @@ -5,6 +5,12 @@ use super::units::{length_pt, parse_color, size_of}; use super::{Align, Document, FBlock, Flow, Fmt, Inline, Kind, ListInfo, Para, model}; use craft_math::latex_text::latex_to_linear; +// Each visit in the two backward bookmark scans, not the number of source bytes. +#[cfg(test)] +std::thread_local! { + static LABEL_SCAN_STEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + // ============================================================================================= // Import @@ -184,7 +190,18 @@ impl<'a> Parser<'a> { /// [`MAX_ANCHOR_RUN`] in a row further ones are left out (thousands of labels with no text /// between them made reading a file take time quadratic in its size). fn anchor(&mut self, name: String) { - let run = self.para.inlines.iter().rev().take(MAX_ANCHOR_RUN).take_while(|i| matches!(i, Inline::Anchor(_))).count(); + let run = self + .para + .inlines + .iter() + .rev() + .take(MAX_ANCHOR_RUN) + .take_while(|i| { + #[cfg(test)] + LABEL_SCAN_STEPS.with(|steps| steps.set(steps.get().saturating_add(1))); + matches!(i, Inline::Anchor(_)) + }) + .count(); if run < MAX_ANCHOR_RUN { self.para.inlines.push(Inline::Anchor(name)); } @@ -192,7 +209,11 @@ impl<'a> Parser<'a> { fn text(&mut self, s: &str) { // Spaces collapse, and none start a paragraph (as in TeX). - let after_space = match self.para.inlines.iter().rev().find(|i| !matches!(i, Inline::Anchor(_))) { + let after_space = match self.para.inlines.iter().rev().find(|i| { + #[cfg(test)] + LABEL_SCAN_STEPS.with(|steps| steps.set(steps.get().saturating_add(1))); + !matches!(i, Inline::Anchor(_)) + }) { Some(Inline::Text(t, _)) => t.is_empty() || t.ends_with([' ', '\n']), Some(_) => false, None => true, @@ -988,3 +1009,43 @@ pub fn parse(src: &str) -> Flow { fn squash(s: &str) -> String { s.split_whitespace().collect::>().join(" ") } + +#[cfg(test)] +mod tests { + use super::*; + + /// The backward bookmark scans grow linearly with a run of labels. + /// Count the actual scan visits so machine speed cannot decide whether this test passes. + #[test] + fn latex_labels_in_a_row_are_read_in_linear_time() -> Result<(), &'static str> { + let counted = |src: &str| { + LABEL_SCAN_STEPS.with(|steps| steps.set(0)); + assert!(import(src.as_bytes()).body.len() <= 2); + LABEL_SCAN_STEPS.with(std::cell::Cell::get) + }; + let cases: [fn(usize) -> String; 3] = + [|n| "\\label{a} ".repeat(n) + "x", |n| "\\label{a}".repeat(n) + "x", |n| "\\hypertarget{a}{} ".repeat(n)]; + let counts: Vec<_> = cases + .into_iter() + .map(|make| { + let n = 128; + (counted(&make(n)), counted(&make(n * 8))) + }) + .collect(); + let d = import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()); + let p = d.para_at(&craft_wordmodel::Pos::body(0, 0)).ok_or("the imported paragraph is missing")?; + let names: Vec<&str> = p + .objects + .iter() + .filter_map(|o| if let craft_wordmodel::InlineObject::BookmarkStart { name } = o { Some(name.as_str()) } else { None }) + .collect(); + assert_eq!(names, ["one", "two", "three"]); + assert_eq!(d.plain_text(craft_wordmodel::StoryRef::Body).replace('\u{FFFC}', ""), "First second third."); + for (shape, (small, large)) in counts.into_iter().enumerate() { + // Eight times the labels may double the linear ratio while the bounded scans + // reach their steady state; a quadratic rescan instead approaches 64 times. + assert!(small > 0 && large > small && large <= small * 16, "label shape {shape}: {small} scan visits at n, {large} at 8n"); + } + Ok(()) + } +} diff --git a/crates/latex/tests/hostile.rs b/crates/latex/tests/hostile.rs index 40755bc285..fe31be9eef 100644 --- a/crates/latex/tests/hostile.rs +++ b/crates/latex/tests/hostile.rs @@ -66,28 +66,6 @@ fn fastest(src: &str) -> Duration { .unwrap_or_default() } -/// Labels in a row are read in linear time: four times as many take well under the sixteen times -/// as long a quadratic read would (a ratio, so a busy machine does not fail it). -#[test] -fn latex_labels_in_a_row_are_read_in_linear_time() { - let cases: [fn(usize) -> String; 3] = [|n| "\\label{a} ".repeat(n) + "x", |n| "\\label{a}".repeat(n) + "x", |n| "\\hypertarget{a}{} ".repeat(n)]; - // The gate reads half the labels; nightly the full counts. - let size = |n: usize| n / craft_testkit::hostile::divisor().min(2); - for make in cases { - let (small, large) = (fastest(&make(size(25_000))), fastest(&make(size(100_000)))); - assert!(large < small * 8 + Duration::from_millis(50), "{small:?} for 25,000, {large:?} for 100,000"); - } - let d = import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()); - let p = d.para_at(&craft_wordmodel::Pos::body(0, 0)).unwrap(); - let names: Vec<&str> = p - .objects - .iter() - .filter_map(|o| if let craft_wordmodel::InlineObject::BookmarkStart { name } = o { Some(name.as_str()) } else { None }) - .collect(); - assert_eq!(names, ["one", "two", "three"]); - assert_eq!(d.plain_text(craft_wordmodel::StoryRef::Body).replace('\u{FFFC}', ""), "First second third."); -} - /// Empty optional arguments in a row after a definition are skipped in linear time: the text after /// each `]` is read where it lies in the token, not copied, and a run of no-break spaces at the /// token's end is not read again for each argument. diff --git a/crates/layers/src/ui/panel/mod.rs b/crates/layers/src/ui/panel/mod.rs index 02a8cf1574..d5491ae469 100644 --- a/crates/layers/src/ui/panel/mod.rs +++ b/crates/layers/src/ui/panel/mod.rs @@ -237,6 +237,10 @@ pub struct LayersOutput { pub hovered: Option, /// Key focus is in the rows this pass. pub focused: bool, + /// The pass's real run applied its one-time requests ([`start_rename`](LayersPanel::start_rename), + /// [`reveal`](LayersPanel::reveal), [`focus_filter_name`](LayersPanel::focus_filter_name)). A measuring run or a + /// replay applies none, so the host keeps them and passes them again until this is set. + pub requests_taken: bool, /// The panel. pub response: Response, } @@ -457,7 +461,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { let current = RefCell::new(LayerFilter::default()); let unlock_label = words.unlock_layer.clone(); - let shown = Stack::new() + let mut shown = Stack::new() .fill() .command_scope(LayersPanelKeys::SCOPE) .header(|ui, stack| { @@ -536,11 +540,12 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { } (reported, body.drop_preview, body.hovered, focused) }); + let requests_taken = shown.settle(|_, _| ()).is_some(); // Only the real run's result comes back, so the reveal's opens and the list's events are reported once. let mut events = events.into_inner(); let (body, drop_preview, hovered, focused) = shown.inner.unwrap_or_default(); events.extend(body); - LayersOutput { events, drop_preview, hovered, focused, response: shown.output } + LayersOutput { events, drop_preview, hovered, focused, requests_taken, response: shown.output } } } diff --git a/crates/layers/tests/it/panel_memo.rs b/crates/layers/tests/it/panel_memo.rs index 0de36e2fd3..e733658654 100644 --- a/crates/layers/tests/it/panel_memo.rs +++ b/crates/layers/tests/it/panel_memo.rs @@ -4,7 +4,7 @@ use craft_layers::ui::filter::{FilterBy, LayerFilter}; use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayersEvent, LayersPanel}; use craft_ui::contract::{Bind, MemoProps, MemoView, Outbox, Tracked}; -use craft_ui::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, pointer, trial}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_runs, pointer, trial}; use egui::{Ui, Vec2}; use std::cell::RefCell; use std::rc::Rc; @@ -73,6 +73,11 @@ impl Rig { (count(MemoRun::Ran), count(MemoRun::Replayed)) } + /// The real runs in the last pass of the memoized views whose type name holds `name`. + fn real_runs(&self, name: &str) -> u32 { + last_pass_memo_runs(self.fixture.ctx()).iter().filter(|(ty, _, run)| ty.contains(name) && *run == MemoRun::Ran).count() as u32 + } + /// One frame with no input, after the edit of the trial. fn frame(&mut self) -> &mut Self { self.fixture.frame(Vec::new()); @@ -184,7 +189,9 @@ fn a_pointer_over_the_rows_replays_the_blend_rows() { } } -/// A new blend mode on the active layer runs the blend rows, so they never show a stale value. +/// A new blend mode on the active layer runs the blend rows, so they never show a stale value. The edit is a new +/// version of the panel's view, so the header measures its content afresh in the frame's one pass: the blend rows run +/// in that measuring run and once more in the real run. #[trial] fn the_active_layers_blend_mode_runs_the_blend_rows() { let mut rig = rig(FakeLayers::fifty()); @@ -195,7 +202,9 @@ fn the_active_layers_blend_mode_runs_the_blend_rows() { layer.info.blend_key = String::from("multiply"); } rig.frame(); - assert_eq!(rig.view_runs("BlendProps").0, 1, "the edit runs the blend rows"); + assert_eq!(rig.fixture.passes(), 1, "the edit runs one pass"); + assert_eq!(rig.real_runs("BlendProps"), 1, "the edit runs the blend rows in the real run"); + assert!(rig.view_runs("BlendProps").0 <= 2, "and at most once more, in the header's measuring run"); rig.frame(); assert_eq!(rig.host_runs(), (0, 1), "and the panel replays after it"); } diff --git a/crates/materialx/src/lib.rs b/crates/materialx/src/lib.rs index 99701366f9..e9c98a51c8 100644 --- a/crates/materialx/src/lib.rs +++ b/crates/materialx/src/lib.rs @@ -7,7 +7,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use craft_xml::{Doctype, El, Error as XmlError, Limits, Options, UnknownEntity}; @@ -65,6 +65,31 @@ pub enum Value { Image(String), } +/// The value connected to a shader input, as [`Document::read_material_strict`] resolves it. +#[derive(Clone, Debug, PartialEq)] +pub enum Resolved { + /// One to four finite numbers, kept in the source color space. The numbers may be separated + /// by commas, spaces or both, a `boolean` input's `true` and `false` are 1 and 0, and an + /// `integer` input holds one whole number. A `convert` node's output holds the converted channels. `colorspace` is the color + /// space in effect where the value is written: the input's own `colorspace`, else that of the + /// nearest enclosing element (the node, then its nodegraph), else the document's. A value + /// written on an input with a boolean, integer, float or vector type, on such a `constant` + /// node, or with no type on a `convert` node's input, is in the document's working color + /// space (the root element's `colorspace`). A `convert` node, and a `constant` node whose + /// value is connected, keep the color space of their input. + Constant { values: Vec, colorspace: Option }, + /// A file from an image node, with the file prefix in effect applied: the `file` input's + /// `fileprefix`, else the node's, its nodegraph's or the document's. `colorspace` is the + /// color space in effect on the node's `file` input, found the same way as for a constant, + /// and `uv_tiling` is the node's `uvtiling` as written. A `uvtiling` value that is not two + /// finite numbers is [`Error::Malformed`]. An image node with a boolean, integer, float or + /// vector type is in the document's working color space. + Image { file: String, colorspace: Option, uv_tiling: Option<[f32; 2]> }, + /// This variant stores an encoded tangent-space image connected through a `normalmap` node. + /// The fields have the same meaning as [`Self::Image`]. + NormalMap { file: String, colorspace: Option, uv_tiling: Option<[f32; 2]> }, +} + /// A surface material resolved from a MaterialX document. #[derive(Clone, Debug, PartialEq)] pub struct Material { @@ -82,12 +107,41 @@ pub struct Material { pub warnings: Vec, } +/// A surface material resolved by [`Document::read_material_strict`]. +#[derive(Clone, Debug, PartialEq)] +pub struct StrictMaterial { + /// Material name, or `Material` when omitted. + pub name: String, + /// Shader dialect represented by the material. + pub shader: Shader, + /// Resolved inputs in the shader table's deterministic order. + pub inputs: Vec<(String, Resolved)>, + /// Resolved scalar displacement input, if present. Vector displacement is reported as unsupported. + pub displacement: Option, + /// First image tiling of two positive numbers, kept in `0.001..=1000`, or `[1, 1]`. + pub uv_tiling: [f32; 2], + /// Unsupported or ignored constructs encountered while resolving values, and shader inputs + /// that are not in the shader's table and so are not read. + pub warnings: Vec, +} + #[derive(Clone, Debug)] struct Found { value: Value, tiling: Option<[f32; 2]>, } +/// The material, its surface shader and the document's nodes, found for a read. +struct Located<'a> { + mat: &'a El, + shader: &'a El, + scope: Option, + kind: Shader, + nodes: HashMap, + graphs: HashMap<&'a str, &'a El>, + outputs: Vec<(String, String)>, +} + const OPEN_PBR_INPUTS: &[&str] = &[ "base_color", "base_metalness", @@ -138,6 +192,76 @@ const GLTF_INPUTS: &[&str] = &[ "transmission", ]; +const OPEN_PBR_STRICT_INPUTS: &[&str] = &[ + "base_color", + "base_metalness", + "specular_roughness", + "geometry_normal", + "geometry_opacity", + "emission_color", + "coat_weight", + "coat_roughness", + "geometry_coat_normal", + "fuzz_weight", + "fuzz_color", + "fuzz_roughness", + "specular_roughness_anisotropy", + "transmission_weight", + "subsurface_weight", + "base_weight", + "specular_weight", + "specular_color", + "specular_ior", + "coat_color", + "coat_ior", + "emission_luminance", +]; +const STANDARD_STRICT_INPUTS: &[&str] = &[ + "base_color", + "metalness", + "specular_roughness", + "normal", + "opacity", + "emission_color", + "coat", + "coat_roughness", + "coat_normal", + "sheen", + "sheen_color", + "sheen_roughness", + "specular_anisotropy", + "transmission", + "subsurface", + "base", + "specular", + "specular_color", + "specular_IOR", + "coat_color", + "coat_IOR", + "emission", +]; +const GLTF_STRICT_INPUTS: &[&str] = &[ + "base_color", + "metallic", + "roughness", + "normal", + "alpha", + "emissive", + "occlusion", + "clearcoat", + "clearcoat_roughness", + "clearcoat_normal", + "sheen_color", + "sheen_roughness", + "transmission", + "emissive_strength", + "ior", + "specular", + "specular_color", + "alpha_mode", + "alpha_cutoff", +]; + /// OpenPBR input kind accepted by [`write_open_pbr`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum InputKind { @@ -253,49 +377,13 @@ impl Document { /// Resolves a surface material into shader inputs, image paths and warnings. pub fn read_material(&self, material: Option<&str>) -> Result { - let materials: Vec<&El> = self.root.children("surfacematerial").collect(); - let mat = match material { - Some(name) => materials.iter().copied().find(|m| m.attr("name") == Some(name)).ok_or_else(|| Error::MissingMaterial(name.to_owned()))?, - None => materials.first().copied().ok_or_else(|| Error::Unsupported("document has no surfacematerial".into()))?, + let Located { mat, shader, kind, nodes, outputs, .. } = self.locate(material, false)?; + let inputs = match kind { + Shader::OpenPbr => OPEN_PBR_INPUTS, + Shader::StandardSurface => STANDARD_INPUTS, + Shader::GltfPbr => GLTF_INPUTS, }; - let mut nodes = HashMap::new(); - let mut outputs = Vec::new(); - for child in self.root.elements() { - if child.name == "nodegraph" { - let Some(graph) = child.attr("name") else { continue }; - for node in child.elements() { - let Some(name) = node.attr("name") else { continue }; - if node.name == "output" { - if let Some(from) = node.attr("nodename") { - outputs.push((format!("{graph}/{name}"), format!("{graph}/{from}"))); - } - } else { - nodes.insert(format!("{graph}/{name}"), node); - } - } - } else if let Some(name) = child.attr("name") { - nodes.insert(name.to_owned(), child); - } - } - let shader_name = mat.children("input").find(|i| i.attr("name") == Some("surfaceshader")).and_then(|i| i.attr("nodename")); - let shader = shader_name.and_then(|n| nodes.get(n).copied()).ok_or_else(|| Error::Malformed("material has no surface shader".into()))?; - let (kind, inputs) = match shader.name.as_str() { - "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR_INPUTS), - "standard_surface" => (Shader::StandardSurface, STANDARD_INPUTS), - "gltf_pbr" => (Shader::GltfPbr, GLTF_INPUTS), - other => return Err(Error::Unsupported(format!("surface shader is {other}"))), - }; - let emission_gate = match kind { - Shader::OpenPbr => Some(("emission_luminance", true)), - Shader::StandardSurface => Some(("emission", true)), - Shader::GltfPbr => None, - }; - let emission_enabled = emission_gate.is_none_or(|(name, _)| { - shader - .children("input") - .find(|i| i.attr("name") == Some(name)) - .is_some_and(|i| i.attr("value").is_none_or(|v| parse_numbers(v).and_then(|n| n.first().copied()).is_some_and(|v| v > 0.0))) - }); + let emission_enabled = emission_enabled(kind, shader, parse_numbers); let mut warnings = Vec::new(); let base_weight_name = match kind { Shader::OpenPbr => Some("base_weight"), @@ -343,6 +431,166 @@ impl Document { warnings, }) } + + /// Resolves a surface material like [`Document::read_material`], with a wider input table, the + /// color space in effect and the UV tiling of each image, and stricter checks. + /// + /// The tables add each shader's weight, specular, IOR and coat color inputs, OpenPBR's + /// `emission_luminance`, and glTF PBR's `emissive_strength` and alpha mode inputs; glTF PBR's + /// emission color is read from `emissive`, the name its node definition gives it. Values may + /// be separated by commas, spaces or both, `convert` nodes follow the Standard Nodes rules, + /// and an image inside a nodegraph takes the nodegraph's `fileprefix`. A repeated shader + /// input, a value that is not one to four finite numbers or does not fit its type, and a + /// `uvtiling` that is not two finite numbers are [`Error::Malformed`]. A shader input that is + /// not in the table gives the warning `input is not read`; the base weight warning of + /// [`Document::read_material`] is not given, since the weight is read. A `normalmap` node's + /// `scale` other than 1 and authored `normal`, `tangent`, and `bitangent` inputs are not applied + /// and give warnings. Image inputs of `normalmap` nodes resolve as [`Resolved::NormalMap`]. + /// Three-component literal normal-map inputs are unsupported and give warnings. Other literal + /// sizes return [`Error::Malformed`]. + /// Surface shaders may connect through graph outputs. A graph with several outputs needs a + /// named selection; a graph with one output uses it regardless of the selection attribute. + /// Missing node and graph-output references are errors. Supported numeric `constant` nodes + /// use their typed zero values when `value` is omitted. Emission colors remain resolved when + /// their strength is zero. Nonzero image `uvoffset`, nonidentity displacement `scale`, and + /// vector displacement are reported as unsupported. + pub fn read_material_strict(&self, material: Option<&str>) -> Result { + let Located { mat, shader, scope, kind, nodes, graphs, outputs } = self.locate(material, true)?; + let inputs = match kind { + Shader::OpenPbr => OPEN_PBR_STRICT_INPUTS, + Shader::StandardSurface => STANDARD_STRICT_INPUTS, + Shader::GltfPbr => GLTF_STRICT_INPUTS, + }; + let mut warnings = Vec::new(); + let mut seen = HashSet::new(); + for name in shader.children("input").filter_map(|i| i.attr("name")) { + if !seen.insert(name) { + return Err(Error::Malformed(format!("the shader has more than one {name} input"))); + } + if !inputs.contains(&name) { + warnings.push(format!("input {name} is not read")); + } + } + let resolver = Resolver { root: &self.root, nodes: &nodes, graphs: &graphs, outputs: &outputs }; + let shader_space = resolver.space_of(shader, scope.as_deref()); + let mut resolved = Vec::new(); + let mut tiling = None; + for name in inputs { + let Some(input) = shader.children("input").find(|i| i.attr("name") == Some(*name)) else { continue }; + if let Some(value) = resolver.value(input, scope.as_deref(), shader_space, 0, &mut warnings)? { + if tiling.is_none() { + tiling = image_tiling(&value); + } + resolved.push(((*name).to_owned(), value)); + } + } + let mut displacement = None; + if let Some(connection) = mat.children("input").find(|i| i.attr("name") == Some("displacementshader")) { + let target = resolver.target(connection, None)?; + if let Some(node) = target.as_ref().and_then(|name| nodes.get(name).copied()) { + let node_scope = target.as_deref().and_then(|name| name.split_once('/')).map(|(graph, _)| graph); + let space = resolver.space_of(node, node_scope); + if let Some(input) = node.children("input").find(|i| i.attr("name") == Some("displacement")) { + let value = resolver.value(input, node_scope, space, 0, &mut warnings)?; + if resolver.value_type(input, node_scope)? == Some("vector3") + || matches!(&value, Some(Resolved::Constant { values, .. }) if values.len() == 3) + { + warnings.push("vector displacement is not supported; its input was skipped".into()); + } else { + displacement = value; + } + } + if let Some(scale) = node.children("input").find(|i| i.attr("name") == Some("scale")).filter(|i| has_authored_value(i)) { + let value = resolver.value(scale, node_scope, space, 0, &mut warnings)?; + match value { + Some(Resolved::Constant { values, .. }) if values.len() != 1 => { + return Err(Error::Malformed("displacement scale is not one finite number".into())); + } + Some(Resolved::Constant { values, .. }) if values == [1.0] => {} + _ => warnings.push("the scale of the displacement node is not read".into()), + } + } + if tiling.is_none() { + tiling = displacement.as_ref().and_then(image_tiling); + } + } + } + Ok(StrictMaterial { + name: mat.attr("name").unwrap_or("Material").to_owned(), + shader: kind, + inputs: resolved, + displacement, + uv_tiling: tiling.unwrap_or([1.0, 1.0]), + warnings, + }) + } + + /// The surface material named `material` (or the first one), its surface shader, and the + /// document's nodes, nodegraphs and graph outputs. + fn locate(&self, material: Option<&str>, strict: bool) -> Result, Error> { + let materials: Vec<&El> = self.root.children("surfacematerial").collect(); + let mat = match material { + Some(name) => materials.iter().copied().find(|m| m.attr("name") == Some(name)).ok_or_else(|| Error::MissingMaterial(name.to_owned()))?, + None => materials.first().copied().ok_or_else(|| Error::Unsupported("document has no surfacematerial".into()))?, + }; + let mut nodes = HashMap::new(); + let mut graphs = HashMap::new(); + let mut outputs = Vec::new(); + for child in self.root.elements() { + if child.name == "nodegraph" { + let Some(graph) = child.attr("name") else { continue }; + graphs.insert(graph, child); + for node in child.elements() { + let Some(name) = node.attr("name") else { continue }; + if node.name == "output" { + if let Some(from) = node.attr("nodename") { + outputs.push((format!("{graph}/{name}"), format!("{graph}/{from}"))); + } else if strict { + outputs.push((format!("{graph}/{name}"), String::new())); + } + } else { + nodes.insert(format!("{graph}/{name}"), node); + } + } + } else if let Some(name) = child.attr("name") { + nodes.insert(name.to_owned(), child); + } + } + let connection = mat.children("input").find(|i| i.attr("name") == Some("surfaceshader")); + let shader_name = if strict { + let resolver = Resolver { root: &self.root, nodes: &nodes, graphs: &graphs, outputs: &outputs }; + connection.map(|input| resolver.target(input, None)).transpose()?.flatten() + } else { + connection.and_then(|input| input.attr("nodename")).map(str::to_owned) + }; + let shader = + shader_name.as_ref().and_then(|n| nodes.get(n).copied()).ok_or_else(|| Error::Malformed("material has no surface shader".into()))?; + let scope = shader_name.as_deref().and_then(|name| name.split_once('/')).map(|(graph, _)| graph.to_owned()); + let kind = match shader.name.as_str() { + "open_pbr_surface" => Shader::OpenPbr, + "standard_surface" => Shader::StandardSurface, + "gltf_pbr" => Shader::GltfPbr, + other => return Err(Error::Unsupported(format!("surface shader is {other}"))), + }; + Ok(Located { mat, shader, scope, kind, nodes, graphs, outputs }) + } +} + +/// Whether the shader's emission is on: its strength input (`emission_luminance` or +/// `emission`) is connected or holds a value above 0, read with `parse`. glTF PBR has no such +/// input, so its emission is always on. +fn emission_enabled(kind: Shader, shader: &El, parse: fn(&str) -> Option>) -> bool { + let gate = match kind { + Shader::OpenPbr => Some("emission_luminance"), + Shader::StandardSurface => Some("emission"), + Shader::GltfPbr => None, + }; + gate.is_none_or(|name| { + shader + .children("input") + .find(|i| i.attr("name") == Some(name)) + .is_some_and(|i| i.attr("value").is_none_or(|v| parse(v).and_then(|n| n.first().copied()).is_some_and(|v| v > 0.0))) + }) } fn numeric_input(shader: &El, name: &str) -> Option { @@ -424,6 +672,373 @@ fn resolve_value( } } +fn image_tiling(value: &Resolved) -> Option<[f32; 2]> { + match value { + Resolved::Image { uv_tiling, .. } | Resolved::NormalMap { uv_tiling, .. } => { + uv_tiling.filter(|n| n.iter().all(|v| *v > 0.0)).map(|n| [n[0].clamp(0.001, 1000.0), n[1].clamp(0.001, 1000.0)]) + } + Resolved::Constant { .. } => None, + } +} + +fn has_authored_value(input: &El) -> bool { + ["value", "nodename", "nodegraph", "interfacename"].iter().any(|name| input.attr(name).is_some()) +} + +/// One to four finite numbers separated by commas, spaces or both, as MaterialX's own value +/// reader splits vector and color values. +fn parse_values(text: &str) -> Option> { + let nums: Option> = text + .split(|c: char| c == ',' || c.is_whitespace()) + .filter(|part| !part.is_empty()) + .map(|part| part.parse::().ok().filter(|v| v.is_finite())) + .collect(); + nums.filter(|v| !v.is_empty() && v.len() <= 4) +} + +/// The value of the input `input`, read as a `boolean` (`true` or `false`, as 1 or 0) or an +/// `integer` (one whole number) when its type says so, and as numbers otherwise. A `float`, +/// vector or color type needs as many numbers as it has channels. +fn input_numbers(input: &El, text: &str) -> Option> { + match input.attr("type") { + Some("boolean") => match text.trim() { + "true" => Some(vec![1.0]), + "false" => Some(vec![0.0]), + _ => None, + }, + Some("integer") => text.trim().parse::().ok().map(|v| vec![v as f32]), + ty => parse_values(text).filter(|v| ty.and_then(channels).is_none_or(|n| v.len() == n)), + } +} + +/// The number of channels of a MaterialX numeric type. +fn channels(ty: &str) -> Option { + match ty { + "float" | "integer" | "boolean" => Some(1), + "vector2" => Some(2), + "color3" | "vector3" => Some(3), + "color4" | "vector4" => Some(4), + _ => None, + } +} + +/// Whether `ty` is a numeric MaterialX type that is not a color: a boolean, integer, float or +/// vector. A `colorspace` does not apply to values of these types. +fn is_numeric_non_color(ty: Option<&str>) -> bool { + ty.is_some_and(|ty| channels(ty).is_some() && !matches!(ty, "color3" | "color4")) +} + +/// The type of `count` numbers whose type is not written: a float, or a vector. +fn untyped(count: usize) -> &'static str { + match count { + 1 => "float", + 2 => "vector2", + 3 => "vector3", + _ => "vector4", + } +} + +/// `values` of type `from` converted to type `to` by the `convert` node's rules in the MaterialX +/// Standard Nodes: a boolean becomes a float or integer of 0 or 1, an integer becomes a float or +/// a boolean (1 for any value that is not 0), a boolean, float or integer is copied to every +/// channel of a color or vector, and a color or vector keeps its first channels and fills +/// missing ones with 0 (1 in the fourth). `None` for a pair the node does not define, such as a +/// float to an integer or a color to a float, and for values that do not fit `from`. +fn converted(values: &[f32], from: &str, to: &str) -> Option> { + if channels(from)? != values.len() { + return None; + } + let out = channels(to)?; + match (from, to) { + _ if from == to => Some(values.to_vec()), + ("boolean", "float" | "integer") | ("integer", "float") => Some(values.to_vec()), + ("integer", "boolean") => Some(vec![if values[0] != 0.0 { 1.0 } else { 0.0 }]), + ("boolean" | "float" | "integer", _) if out > 1 => Some(vec![values[0]; out]), + _ if values.len() > 1 && out > 1 => Some((0..out).map(|c| values.get(c).copied().unwrap_or(if c == 3 { 1.0 } else { 0.0 })).collect()), + _ => None, + } +} + +/// The document's nodes, nodegraphs and graph outputs, for following input connections. +struct Resolver<'a> { + root: &'a El, + nodes: &'a HashMap, + graphs: &'a HashMap<&'a str, &'a El>, + outputs: &'a [(String, String)], +} + +impl<'a> Resolver<'a> { + /// The color space in effect on `element`: its own, else its nodegraph's when `scope` names + /// one, else the document's. + fn space_of(&self, element: &'a El, scope: Option<&str>) -> Option<&'a str> { + element + .attr("colorspace") + .or_else(|| scope.and_then(|g| self.graphs.get(g)).and_then(|g| g.attr("colorspace"))) + .or_else(|| self.root.attr("colorspace")) + } + + /// The document's working color space, the root element's `colorspace`. + fn working(&self) -> Option<&'a str> { + self.root.attr("colorspace") + } + + /// The value of `input`, an input of an element in nodegraph `scope` (or at the top level) + /// whose color space in effect is `space`. A `value` that is not one to four finite numbers, + /// or that does not fit a `boolean` or `integer` type, is [`Error::Malformed`]; an + /// unsupported connection is skipped with a warning. + fn value( + &self, + input: &'a El, + scope: Option<&str>, + space: Option<&'a str>, + hops: usize, + warnings: &mut Vec, + ) -> Result, Error> { + if hops > 16 { + warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); + return Ok(None); + } + if let Some(interface) = input.attr("interfacename") { + warnings.push(format!("interface input {interface:?} is not supported; its value was skipped")); + return Ok(None); + } + if let Some(value) = input.attr("value") { + let Some(values) = input_numbers(input, value) else { + let name = input.attr("name").unwrap_or(""); + return Err(Error::Malformed(format!("input {name} has a value that is not one to four finite numbers or does not fit its type"))); + }; + let colorspace = if is_numeric_non_color(input.attr("type")) { self.working() } else { input.attr("colorspace").or(space) }; + return Ok(Some(Resolved::Constant { values, colorspace: colorspace.map(str::to_owned) })); + } + let target = self.target(input, scope)?; + let Some(node) = target.as_ref().and_then(|t| self.nodes.get(t).copied()) else { return Ok(None) }; + let node_scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g); + let node_space = self.space_of(node, node_scope); + let child = |name: &str| node.children("input").find(|i| i.attr("name") == Some(name)); + let node_name = node.attr("name").unwrap_or(""); + match node.name.as_str() { + "image" | "tiledimage" => { + let file = child("file").and_then(|input| input.attr("value").filter(|file| !file.is_empty()).map(|file| (input, file))); + let Some((file_input, file)) = file else { + warnings.push(format!("image node {node_name:?} has no nonempty literal file value; its image was skipped")); + return Ok(None); + }; + let prefix = file_input + .attr("fileprefix") + .or_else(|| node.attr("fileprefix")) + .or_else(|| node_scope.and_then(|g| self.graphs.get(g)).and_then(|g| g.attr("fileprefix"))) + .or_else(|| self.root.attr("fileprefix")) + .unwrap_or(""); + let uv_tiling = match child("uvtiling").filter(|input| has_authored_value(input)) { + None => None, + Some(input) => match self.value(input, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if values.len() == 2 => Some([values[0], values[1]]), + Some(Resolved::Constant { .. }) => { + return Err(Error::Malformed(format!("the uvtiling of image {node_name:?} is not two finite numbers"))); + } + _ => { + warnings.push(format!("the uvtiling of image {node_name:?} is not read")); + None + } + }, + }; + if let Some(offset) = child("uvoffset").filter(|input| has_authored_value(input)) { + match self.value(offset, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if values.len() != 2 => { + return Err(Error::Malformed(format!("the uvoffset of image {node_name:?} is not two finite numbers"))); + } + Some(Resolved::Constant { values, .. }) if values == [0.0, 0.0] => {} + _ => warnings.push(format!("the uvoffset of image {node_name:?} is not read")), + } + } + for mode in ["uaddressmode", "vaddressmode"] { + if let Some(input) = child(mode).filter(|input| has_authored_value(input)) { + match input.attr("value") { + Some("periodic") => {} + Some("constant" | "clamp" | "mirror") | None => warnings.push(format!("the {mode} of image {node_name:?} is not read")), + Some(_) => return Err(Error::Malformed(format!("the {mode} of image {node_name:?} is not a supported addressing mode"))), + } + } + } + let colorspace = if is_numeric_non_color(node.attr("type")) { self.working() } else { file_input.attr("colorspace").or(node_space) } + .map(str::to_owned); + Ok(Some(Resolved::Image { file: format!("{prefix}{file}"), colorspace, uv_tiling })) + } + "normalmap" => { + for name in ["normal", "tangent", "bitangent"] { + if child(name).is_some_and(has_authored_value) { + warnings.push(format!("the {name} of normalmap node {node_name:?} is not read")); + } + } + // The normal is passed on without the node's scale, so a scale other than 1 is + // reported. + if let Some(scale) = child("scale").filter(|input| has_authored_value(input)) { + let resolved = self.value(scale, node_scope, node_space, hops + 1, &mut Vec::new())?; + if !matches!(resolved, Some(Resolved::Constant { ref values, .. }) if values.iter().all(|s| *s == 1.0)) { + warnings.push(format!("the scale of normalmap node {node_name:?} is not read")); + } + } + match child("in") { + Some(i) => Ok(match self.value(i, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Image { file, colorspace, uv_tiling }) => Some(Resolved::NormalMap { file, colorspace, uv_tiling }), + Some(Resolved::Constant { values, .. }) if values.len() != 3 => { + return Err(Error::Malformed(format!("the input of normalmap node {node_name:?} is not three finite numbers"))); + } + Some(Resolved::Constant { .. }) => { + warnings.push(format!("the literal input of normalmap node {node_name:?} is not supported; its value was skipped")); + None + } + Some(Resolved::NormalMap { .. }) => { + warnings.push(format!("the nested normalmap input of node {node_name:?} is not supported; its value was skipped")); + None + } + value => value, + }), + None => Ok(None), + } + } + "convert" => { + let Some(i) = child("in").filter(|input| has_authored_value(input)) else { + let definition = node.attr("nodedef").and_then(|name| name.strip_prefix("ND_convert_")).and_then(|name| name.split_once('_')); + if let Some((from, to)) = definition + && from != to + && node.attr("type").is_none_or(|ty| ty == to) + && let Some(count) = channels(from) + && let Some(values) = converted(&vec![0.0; count], from, to) + { + return Ok(Some(Resolved::Constant { values, colorspace: self.working().map(str::to_owned) })); + } + warnings.push(format!("the input default of convert node {node_name:?} cannot be identified; its value was skipped")); + return Ok(None); + }; + let Some(value) = self.value(i, node_scope, node_space, hops + 1, warnings)? else { return Ok(None) }; + let to = node.attr("type").unwrap_or(""); + let from = self.value_type(i, node_scope)?; + match value { + Resolved::Constant { values, colorspace } => { + // A value with no type is a float or a vector, so it is in the working + // color space like a typed one. + let colorspace = if from.is_none() && i.attr("value").is_some() { self.working().map(str::to_owned) } else { colorspace }; + let from = from.unwrap_or_else(|| untyped(values.len())); + match converted(&values, from, to) { + Some(values) => Ok(Some(Resolved::Constant { values, colorspace })), + None => { + warnings.push(format!( + "a convert node ({node_name:?}) from type {from:?} to type {to:?} is not supported; its input was skipped" + )); + Ok(None) + } + } + } + // An image keeps its own channels, so only a convert that copies every + // channel as it is passes it on. + image @ (Resolved::Image { .. } | Resolved::NormalMap { .. }) => { + let copies = from.is_some_and(|from| from == to || channels(from).is_some_and(|n| n > 1 && channels(to) == Some(n))); + if copies { + Ok(Some(image)) + } else { + warnings.push(format!( + "a convert node ({node_name:?}) changes an image's channels to type {to:?}, which is not supported; its input was skipped" + )); + Ok(None) + } + } + } + } + "constant" => { + let value = child("value").filter(|input| has_authored_value(input)); + match value { + // A connected value keeps the color space it resolved; only a written value takes + // the working color space. + Some(i) => match self.constant_value(i, node, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if is_numeric_non_color(node.attr("type")) && i.attr("value").is_some() => { + Ok(Some(Resolved::Constant { values, colorspace: self.working().map(str::to_owned) })) + } + value => Ok(value), + }, + None => match node.attr("type").and_then(channels) { + Some(count) => { + let space = if is_numeric_non_color(node.attr("type")) { self.working() } else { node_space }; + Ok(Some(Resolved::Constant { values: vec![0.0; count], colorspace: space.map(str::to_owned) })) + } + None => { + warnings.push(format!("the default of constant node {node_name:?} has an unsupported type")); + Ok(None) + } + }, + } + } + other => { + warnings.push(format!("a {other} node ({node_name:?}) is not supported; its input was skipped")); + Ok(None) + } + } + } + + fn constant_value( + &self, + input: &'a El, + node: &'a El, + scope: Option<&str>, + space: Option<&'a str>, + hops: usize, + warnings: &mut Vec, + ) -> Result, Error> { + if input.attr("type").is_none() + && input.attr("interfacename").is_none() + && let Some(text) = input.attr("value") + && let Some(ty) = node.attr("type") + { + let typed = El::new("input").with_attr("type", ty); + let values = input_numbers(&typed, text) + .ok_or_else(|| Error::Malformed(format!("constant {:?} has a value that does not fit {ty}", node.attr("name").unwrap_or(""))))?; + let colorspace = if is_numeric_non_color(Some(ty)) { self.working() } else { input.attr("colorspace").or(space) }; + return Ok(Some(Resolved::Constant { values, colorspace: colorspace.map(str::to_owned) })); + } + self.value(input, scope, space, hops, warnings) + } + + /// The key in `nodes` of the node that `input`, an input of an element in nodegraph `scope` + /// (or at the top level), connects to. + fn target(&self, input: &El, scope: Option<&str>) -> Result, Error> { + let target = if let Some(graph) = input.attr("nodegraph") { + let prefix = format!("{graph}/"); + let outputs: Vec<_> = self.outputs.iter().filter(|(name, _)| name.starts_with(&prefix)).collect(); + let selected = if outputs.len() == 1 { + outputs.first().copied() + } else { + input.attr("output").and_then(|output| outputs.iter().rev().copied().find(|(name, _)| name == &format!("{graph}/{output}"))) + }; + Some( + selected + .ok_or_else(|| { + Error::Malformed(format!("input {:?} has no selected output in nodegraph {graph:?}", input.attr("name").unwrap_or(""))) + })? + .1 + .clone(), + ) + } else if let Some(name) = input.attr("nodename") { + let qualified = scope.map(|g| format!("{g}/{name}")); + Some(qualified.unwrap_or_else(|| name.to_owned())) + } else { + None + }; + if let Some(name) = target.as_ref() + && !self.nodes.contains_key(name) + { + return Err(Error::Malformed(format!("input {:?} references missing node {name:?}", input.attr("name").unwrap_or("")))); + } + Ok(target) + } + + fn value_type(&self, input: &'a El, scope: Option<&str>) -> Result, Error> { + if input.attr("type").is_some() || input.attr("value").is_some() { + return Ok(input.attr("type")); + } + Ok(self.target(input, scope)?.as_ref().and_then(|name| self.nodes.get(name).copied()).and_then(|node| node.attr("type"))) + } +} + /// Writes an OpenPBR MaterialX document for the supplied textures. /// /// Unknown inputs and duplicate inputs are skipped; the first texture for an input wins. Color @@ -566,9 +1181,13 @@ mod tests { "#; - let material = Document::parse(xml).unwrap().read_material(None).unwrap(); + let doc = Document::parse(xml).unwrap(); + let material = doc.read_material(None).unwrap(); assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); assert_eq!(material.uv_tiling, [4.0, 2.0]); + let strict = doc.read_material_strict(None).unwrap(); + assert_eq!(strict.displacement, Some(Resolved::Image { file: "height.png".into(), colorspace: None, uv_tiling: Some([4.0, 2.0]) })); + assert_eq!(strict.uv_tiling, [4.0, 2.0]); } #[test] @@ -594,6 +1213,22 @@ mod tests { assert_eq!(material.inputs[2].1, Value::Constant { values: vec![1.0, 0.5, 0.25], colorspace: None }); assert_eq!(material.displacement, Some(Value::Constant { values: vec![0.25], colorspace: None })); assert_eq!(material.uv_tiling, [2.0, 4.0]); + assert!(matches!(doc.read_material_strict(None), Err(Error::Malformed(_)))); + let mut explicit = doc.clone(); + let normalmap = explicit.root.elements_mut().find(|node| node.attr("name") == Some("N")).unwrap(); + normalmap.child_mut("input").unwrap().set_attr("output", "first"); + let strict = explicit.read_material_strict(None).unwrap(); + assert_eq!( + strict.inputs[0], + ("base_color".into(), Resolved::Image { file: "tex/albedo.png".into(), colorspace: None, uv_tiling: Some([2.0, 4.0]) }) + ); + assert_eq!( + strict.inputs[1], + ("geometry_normal".into(), Resolved::NormalMap { file: "tex/normal.png".into(), colorspace: None, uv_tiling: None }) + ); + assert_eq!(strict.inputs[2].1, Resolved::Constant { values: vec![1.0, 0.5, 0.25], colorspace: None }); + assert_eq!(strict.displacement, Some(Resolved::Constant { values: vec![0.25], colorspace: None })); + assert_eq!(strict.uv_tiling, [2.0, 4.0]); } #[test] @@ -612,8 +1247,423 @@ mod tests { assert_eq!(material.inputs[1], ("specular_roughness".into(), Value::Image("rough.png".into()))); assert_eq!(material.inputs[2], ("geometry_normal".into(), Value::Image("normal.png".into()))); assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); + let strict = doc.read_material_strict(None).unwrap(); + let image = |file: &str, space: &str| Resolved::Image { file: file.into(), colorspace: Some(space.into()), uv_tiling: None }; + assert_eq!(strict.inputs[0], ("base_color".into(), image("albedo<&.png", "srgb_texture"))); + assert_eq!(strict.inputs[1], ("specular_roughness".into(), image("rough.png", "lin_rec709"))); + assert_eq!( + strict.inputs[2], + ("geometry_normal".into(), Resolved::NormalMap { file: "normal.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }) + ); + assert_eq!(strict.displacement, Some(image("height.png", "lin_rec709"))); assert!(xml.contains("colorspace=\"srgb_texture\"")); assert!(xml.contains("doc=\"Tiles every 100 x 50 cm\"")); assert!(!xml.contains("colorspace=\"ignored\"")); } + + #[test] + fn read_material_keeps_its_input_table_values_and_lenient_checks() { + // `read_material` reads glTF PBR's `emission`, keeps the base weight warning, skips + // repeated inputs, bad values and bad `uvtiling` instead of failing, and gives a + // constant only its own `colorspace`; `read_material_strict` is the stricter read. + let xml = r#" + + + + + + + "#; + let doc = Document::parse(xml.as_bytes()).unwrap(); + let gltf = doc.read_material(Some("M")).unwrap(); + assert_eq!( + gltf.inputs, + vec![ + ("base_color".into(), Value::Image("a.png".into())), + ("roughness".into(), Value::Constant { values: vec![0.25], colorspace: None }), + ("alpha".into(), Value::Constant { values: vec![0.5], colorspace: None }), + ("emission".into(), Value::Constant { values: vec![1.0, 0.5, 0.0], colorspace: None }), + ] + ); + assert_eq!(gltf.uv_tiling, [1.0, 1.0]); + assert!(gltf.warnings.is_empty(), "{:?}", gltf.warnings); + assert!(matches!(doc.read_material_strict(Some("M")), Err(Error::Malformed(_)))); + let open = doc.read_material(Some("N")).unwrap(); + assert_eq!(open.warnings, vec!["the base weight isn't 1; it was ignored".to_owned()]); + assert!(open.inputs.is_empty(), "{:?}", open.inputs); + let strict = doc.read_material_strict(Some("N")).unwrap(); + assert!(strict.warnings.is_empty(), "{:?}", strict.warnings); + assert_eq!(input(&strict, "base_weight"), Some(&constant(&[0.5], Some("srgb_texture")))); + assert_eq!(input(&strict, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + } + + fn read(xml: &str) -> Result { + Document::parse(xml.as_bytes())?.read_material_strict(None) + } + + fn input<'m>(material: &'m StrictMaterial, name: &str) -> Option<&'m Resolved> { + material.inputs.iter().find(|(n, _)| n == name).map(|(_, v)| v) + } + + fn constant(values: &[f32], space: Option<&str>) -> Resolved { + Resolved::Constant { values: values.to_vec(), colorspace: space.map(str::to_owned) } + } + + #[test] + fn gltf_pbr_reads_the_emissive_input_its_definition_names() { + // The gltf_pbr node definition calls its emission color `emissive` + // (https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/gltf_pbr.mtlx). + let m = read( + r#" + "#, + ) + .unwrap(); + assert_eq!(input(&m, "emissive"), Some(&constant(&[0.5, 0.25, 0.0], None))); + assert_eq!(input(&m, "emissive_strength"), Some(&constant(&[2.0], None))); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + } + + #[test] + fn weights_ior_and_alpha_inputs_are_read_for_each_shader() { + let open = read( + r#" + + + "#, + ) + .unwrap(); + for (name, values) in [ + ("base_weight", &[0.5][..]), + ("specular_weight", &[2.0]), + ("specular_color", &[1.0, 0.5, 0.5]), + ("specular_ior", &[1.33]), + ("coat_color", &[0.9, 0.9, 1.0]), + ("coat_ior", &[1.4]), + ("emission_luminance", &[10.0]), + ] { + assert_eq!(input(&open, name), Some(&constant(values, None)), "{name}"); + } + assert!(open.warnings.is_empty(), "{:?}", open.warnings); + let standard = read( + r#" + + "#, + ) + .unwrap(); + for (name, value) in [("base", 0.8), ("specular", 0.5), ("specular_IOR", 1.6), ("coat_IOR", 1.3), ("emission", 0.0)] { + assert_eq!(input(&standard, name), Some(&constant(&[value], None)), "{name}"); + } + let gltf = read( + r#" + + "#, + ) + .unwrap(); + for (name, values) in + [("alpha_mode", &[1.0][..]), ("alpha_cutoff", &[0.25]), ("ior", &[1.7]), ("specular", &[0.5]), ("specular_color", &[1.0, 1.0, 0.0])] + { + assert_eq!(input(&gltf, name), Some(&constant(values, None)), "{name}"); + } + } + + #[test] + fn constants_and_images_carry_the_color_space_in_effect_where_they_are_written() { + // An untagged value takes the nearest enclosing element's color space, then the + // document's (MaterialX specification, Color Spaces and Color Management Systems). + let m = read( + r#" + + + + + + + + + + "#, + ) + .unwrap(); + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + assert_eq!(input(&m, "specular_color"), Some(&constant(&[0.5; 3], Some("lin_rec709")))); + assert_eq!(input(&m, "coat_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("g22_rec709")))); + assert_eq!( + input(&m, "fuzz_color"), + Some(&Resolved::Image { file: "fuzz.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }) + ); + let doc = Document::parse( + br#" + "#, + ) + .unwrap(); + let tagged = doc.read_material_strict(Some("N")).unwrap(); + assert_eq!(input(&tagged, "base_color"), Some(&constant(&[0.2; 3], Some("acescg")))); + } + + #[test] + fn duplicate_inputs_and_values_that_are_not_finite_numbers_are_malformed() { + let shader = |inputs: &str| { + format!( + r#"{inputs}"# + ) + }; + let dup = read(&shader(r#""#)); + assert!(matches!(dup, Err(Error::Malformed(ref m)) if m.contains("base_metalness")), "{dup:?}"); + for bad in ["nan", "inf", "-inf", "1e40", "0.5,x", "", "1,2,3,4,5"] { + let r = read(&shader(&format!(r#""#))); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("specular_roughness")), "{bad}: {r:?}"); + } + } + + #[test] + fn a_normalmap_scale_other_than_1_gives_a_warning() { + let with_scale = |scale: &str| { + read(&open_pbr( + r#""#, + &format!(r#"{scale}"#), + )) + .unwrap() + }; + let scaled = with_scale(r#""#); + assert_eq!(scaled.warnings, vec![r#"the scale of normalmap node "N" is not read"#.to_owned()]); + assert!(matches!(input(&scaled, "geometry_normal"), Some(Resolved::NormalMap { .. }))); + for plain in ["", r#""#, r#""#] { + assert!(with_scale(plain).warnings.is_empty(), "{plain}"); + } + // A scale connected to a constant node is read through it. + let connected = |value: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + .unwrap() + }; + assert!(connected("1").warnings.is_empty(), "{:?}", connected("1").warnings); + assert_eq!(connected("2").warnings.len(), 1, "{:?}", connected("2").warnings); + } + + #[test] + fn shader_inputs_that_are_not_read_give_a_warning() { + let m = read( + r#" + "#, + ) + .unwrap(); + assert_eq!(m.warnings, vec!["input thin_film_weight is not read".to_owned()]); + assert_eq!(input(&m, "base_metalness"), Some(&constant(&[1.0], None))); + } + + fn open_pbr(inputs: &str, rest: &str) -> String { + format!( + r#"{inputs}{rest}"# + ) + } + + #[test] + fn vector_values_may_be_separated_by_commas_spaces_or_both() { + // MaterialX's value reader splits vector and color values on commas and spaces + // (ARRAY_VALID_SEPARATORS, ", ", in source/MaterialXCore/Types.cpp). + for text in ["0.5 0.25 0.125", "0.5, 0.25, 0.125", "0.5,0.25,0.125", " 0.5 0.25 ,0.125 "] { + let m = read(&open_pbr(&format!(r#""#), "")).unwrap(); + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5, 0.25, 0.125], None)), "{text:?}"); + } + // A color3 holds three numbers. + for bad in ["0.5 x 1", "0.5 0.25 0.125 1 2", " ", "0.5", "0.5, 0.25", "0.5 0.25 0.125 1"] { + let r = read(&open_pbr(&format!(r#""#), "")); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("base_color")), "{bad:?}: {r:?}"); + } + } + + #[test] + fn a_nodegraph_file_prefix_applies_to_the_images_inside_it() { + // The nearest enclosing fileprefix applies (MaterialX specification, File Prefixes). + let m = read(&open_pbr( + r#""#, + r#" + + + + + "#, + ) + .replacen("", r#""#, 1)) + .unwrap(); + let file = |name: &str| match input(&m, name) { + Some(Resolved::Image { file, .. }) => file.clone(), + other => panic!("{name}: {other:?}"), + }; + assert_eq!( + (file("base_color"), file("specular_roughness"), file("base_metalness")), + ("stone/albedo.png".into(), "own/rough.png".into(), "shared/metal.png".into()) + ); + } + + #[test] + fn uv_tiling_is_kept_as_written_and_malformed_tiling_is_an_error() { + let tiled = |tiling: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + }; + let tiling_of = |m: &StrictMaterial| match input(m, "base_color") { + Some(Resolved::Image { uv_tiling, .. }) => *uv_tiling, + other => panic!("{other:?}"), + }; + let wide = tiled("2000, 2").unwrap(); + assert_eq!((tiling_of(&wide), wide.uv_tiling), (Some([2000.0, 2.0]), [1000.0, 2.0])); + let flat = tiled("0 2").unwrap(); + assert_eq!((tiling_of(&flat), flat.uv_tiling), (Some([0.0, 2.0]), [1.0, 1.0])); + for bad in ["x", "1", "1,2,3", "nan,1"] { + let r = tiled(bad); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("uvtiling")), "{bad:?}: {r:?}"); + } + } + + #[test] + fn convert_nodes_change_the_number_of_channels() { + // The convert node's rules in the MaterialX Standard Nodes: a float is copied to every + // channel, a shorter color or vector is filled with 0 (1 in the fourth channel), a + // longer one keeps its first channels, and a boolean is 0 or 1. + let via = |ty: &str, in_ty: &str, value: &str| { + read(&open_pbr( + r#""#, + &format!(r#""#), + )) + .unwrap() + }; + assert_eq!(input(&via("color3", "float", "0.25"), "base_color"), Some(&constant(&[0.25; 3], None))); + assert_eq!(input(&via("color4", "color3", "0.1,0.2,0.3"), "base_color"), Some(&constant(&[0.1, 0.2, 0.3, 1.0], None))); + assert_eq!(input(&via("color3", "color4", "0.1,0.2,0.3,0.4"), "base_color"), Some(&constant(&[0.1, 0.2, 0.3], None))); + assert_eq!(input(&via("vector3", "vector2", "0.1,0.2"), "base_color"), Some(&constant(&[0.1, 0.2, 0.0], None))); + assert_eq!(input(&via("float", "boolean", "true"), "base_color"), Some(&constant(&[1.0], None))); + assert_eq!(input(&via("float", "integer", "3"), "base_color"), Some(&constant(&[3.0], None))); + assert_eq!(input(&via("boolean", "integer", "2"), "base_color"), Some(&constant(&[1.0], None))); + // An input with no type is a float or a vector by its count. + let untyped = read(&open_pbr( + r#""#, + r#""#, + )) + .unwrap(); + assert_eq!(input(&untyped, "base_color"), Some(&constant(&[0.5; 3], None))); + // A color to a float and a float to an integer are not conversions the node defines. + for (ty, in_ty, value) in [("float", "color3", "0.1,0.2,0.3"), ("integer", "float", "0.5"), ("boolean", "float", "1")] { + let unsupported = via(ty, in_ty, value); + assert_eq!(input(&unsupported, "base_color"), None, "{in_ty} to {ty}"); + assert!(unsupported.warnings.iter().any(|w| w.contains("convert node")), "{:?}", unsupported.warnings); + } + // An integer is one whole number. + for bad in ["1.5", "1.00000001", "1 2"] { + let r = read(&open_pbr( + r#""#, + &format!(r#""#), + )); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("input in ")), "{bad:?}: {r:?}"); + } + let image = |ty: &str, image_ty: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + .unwrap() + }; + let g = Resolved::Image { file: "g.png".into(), colorspace: None, uv_tiling: None }; + assert_eq!(input(&image("float", "float"), "base_color"), Some(&g)); + assert_eq!(input(&image("vector3", "color3"), "base_color"), Some(&g)); + for (ty, image_ty) in [("color3", "float"), ("color3", "color4")] { + let changed = image(ty, image_ty); + assert_eq!(input(&changed, "base_color"), None, "{image_ty} to {ty}"); + assert!(changed.warnings.iter().any(|w| w.contains("convert node")), "{:?}", changed.warnings); + } + } + + #[test] + fn a_color_converted_from_another_type_is_in_the_working_color_space() { + // A colorspace applies to color values and color image files (MaterialX specification, + // Color Spaces and Color Management Systems), so a float or vector copied into a color + // by a convert node holds working-space channels; a color keeps its own color space. + let m = read( + r#" + + + + + + + + + + + + + + + + + "#, + ) + .unwrap(); + let image = |file: &str, space: &str| Resolved::Image { file: file.into(), colorspace: Some(space.into()), uv_tiling: None }; + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5; 3], Some("lin_rec709")))); + assert_eq!(input(&m, "specular_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("lin_rec709")))); + assert_eq!(input(&m, "coat_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("srgb_texture")))); + assert_eq!(input(&m, "fuzz_color"), Some(&image("v.png", "lin_rec709"))); + assert_eq!(input(&m, "emission_color"), Some(&image("c.png", "srgb_texture"))); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + // A color passed through a vector, also by way of a vector constant node, keeps its color + // space, and a float constant node or an untyped value is in the working color space. + let chain = read( + r#" + + + + + + + + + + + + + + + + "#, + ) + .unwrap(); + assert_eq!(input(&chain, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + assert_eq!(input(&chain, "specular_color"), Some(&constant(&[0.25; 3], Some("lin_rec709")))); + assert_eq!(input(&chain, "coat_color"), Some(&constant(&[0.75; 3], Some("lin_rec709")))); + assert_eq!(input(&chain, "fuzz_color"), Some(&constant(&[0.4; 3], Some("srgb_texture")))); + assert!(chain.warnings.is_empty(), "{:?}", chain.warnings); + // A document without a working color space leaves the converted color untagged. + let plain = read(&open_pbr( + r#""#, + r#""#, + )) + .unwrap(); + assert_eq!(input(&plain, "base_color"), Some(&constant(&[0.5; 3], None))); + } + + #[test] + fn an_emission_color_is_checked_while_the_emission_is_0() { + let standard = |color: &str| { + read(&format!( + r#" + "# + )) + }; + let r = standard("0.5,x,1"); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("emission_color")), "{r:?}"); + let m = standard("0.5,0.5,1").unwrap(); + assert_eq!(input(&m, "emission_color"), Some(&constant(&[0.5, 0.5, 1.0], None))); + assert!(m.warnings.is_empty()); + } } diff --git a/crates/mcp/README.md b/crates/mcp/README.md index 53e4c6550b..1fb8d2d7da 100644 --- a/crates/mcp/README.md +++ b/crates/mcp/README.md @@ -1,6 +1,8 @@ # craft-mcp -Transport-independent MCP 2025-03-26 server initialization and tool result helpers. +Transport-independent MCP server initialization and tool result helpers. +Transport-independent MCP 2025-03-26 server initialization and result helpers for tools, +resources, prompts and completion. Use one `Session` per client connection with `craft-jsonrpc` for message parsing and batch dispatch. The caller owns transport, tool definitions and execution, response size limits, and shutdown. Pass the outer envelope's batch status to `Session::request`. @@ -13,9 +15,18 @@ request IDs that MCP forbids. `process` does not check the message size. initialization, initialization can occur in a batch, and client information needs only to be an object. `Policy::Strict` requires initialization first (except ping), rejects batched or repeated initialization, and requires client name and version. -Both respond with the sole supported version, 2025-03-26, even if the client offered -a different version. Instructions set with `Session::set_instructions` are returned by -every initialize response, in either policy and with or without legacy initialization. +By default both respond with 2025-03-26, even if the client offered a different version. +`Session::with_versions` sets the accepted versions, in order of preference, from +`SUPPORTED_PROTOCOL_VERSIONS` (2025-06-18, 2025-03-26 and 2024-11-05). A client that +asks for one of them gets it back, and any other request gets the first. +`Session::negotiated_version` returns the version the session answered with, for +features that depend on it, such as the `MCP-Protocol-Version` HTTP header. Once +2025-06-18 is negotiated, `Policy::Strict` rejects every batched request and +`Session::accepts_batches` returns false. Reject a batch envelope with -32600 before +dispatching it when `accepts_batches` is false, because `Session::notification` cannot +tell a batched notification from a single one. Instructions set with +`Session::set_instructions` are returned by every initialize response, in either policy +and with or without legacy initialization. An initialized notification moves the session to `Ready`. This crate does not enforce every MCP lifecycle or capability rule; applications must validate any additional requirements they depend on. @@ -39,4 +50,27 @@ roots without both kinds. A path is checked before it is opened, so another program that replaces a folder with a link between the two steps can still reach outside the roots. -See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle). +See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle) +and the [2025-06-18 changes](https://modelcontextprotocol.io/specification/2025-06-18/changelog). + +The crate also checks the parameters of the resource, prompt and completion methods and +builds their results, for a server that routes those methods itself: + +- `page` takes one page of a list from the request's `cursor`, and `resource_list`, + `resource_template_list` and `prompt_list` wrap the page with its `nextCursor`. A + cursor must be a canonical positive decimal offset divisible by the page size; + malformed cursors are rejected with -32602. The helper returns an empty last page + for a cursor past the list's end, including after the list shrinks. +- `resource_read` returns the requested URI. `text_contents`, `blob_contents` and + `read_result` build the `resources/read` result, and `resource_not_found` is the + -32002 error with the URI in its data. +- `prompt_get` returns the prompt name and its string arguments. `prompt_result` and + `text_message` build the `prompts/get` result. +- `completion_request` returns the prompt or resource reference and the argument being + completed. `completion_result` keeps the first 100 values and sets `total` and `hasMore`. + +See the [pagination](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/pagination), +[resources](https://modelcontextprotocol.io/specification/2025-03-26/server/resources), +[prompts](https://modelcontextprotocol.io/specification/2025-03-26/server/prompts) and +[completion](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/completion) +specifications. diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index 43685c9b56..c13cab4d78 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -1,17 +1,28 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -//! MCP 2025-03-26 server initialization and tool envelopes, independent of transport and tools. +//! MCP server initialization and the envelopes of tools, resources, prompts and completion, +//! independent of transport and of what the server serves. Sessions answer 2025-03-26 by default +//! and can negotiate any of `SUPPORTED_PROTOCOL_VERSIONS`. //! The caller owns routing, transport and JSON-RPC batching. Compatibility mode preserves servers //! that accepted calls before initialization and initialize in a batch; strict mode enforces the //! initialization ordering and batch prohibition. Create one session per connection. +use std::collections::BTreeMap; + use craft_jsonrpc::{Limits, Request, RpcError}; use serde_json::{Value, json}; pub mod roots; +/// The version a session answers with unless `Session::with_versions` sets others. pub const PROTOCOL_VERSION: &str = "2025-03-26"; +/// Protocol versions whose initialization this crate implements, newest first. +pub const SUPPORTED_PROTOCOL_VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"]; + +/// Versions that removed JSON-RPC batching. +const BATCHLESS_VERSIONS: [&str; 1] = ["2025-06-18"]; + /// JSON-RPC limits for an MCP connection. MCP requires a string or integer request ID, so /// `craft_jsonrpc::process` answers a null or fractional ID with an invalid-request error and does /// not call the request handler. The size bounds are `Limits::default()`'s; override them with @@ -48,6 +59,7 @@ pub struct Session { permissive_initialize: bool, server_info: Option, instructions: Option, + negotiated: Option, initialized: bool, } @@ -63,10 +75,30 @@ impl Session { permissive_initialize: false, server_info: None, instructions: None, + negotiated: None, initialized: false, } } + /// Set the protocol versions the session accepts, in order of preference. A client that asks + /// for one of them gets it back; any other request gets the first. Each version must be in + /// `SUPPORTED_PROTOCOL_VERSIONS`, and the list must be non-empty and free of repeats. + pub fn with_versions(mut self, versions: &[&str]) -> Result { + if versions.is_empty() { + return Err(RpcError::new(-32602, "Protocol versions must not be empty")); + } + for (i, version) in versions.iter().enumerate() { + if !SUPPORTED_PROTOCOL_VERSIONS.contains(version) { + return Err(RpcError::new(-32602, format!("Unsupported protocol version {version}"))); + } + if versions[..i].contains(version) { + return Err(RpcError::new(-32602, format!("Repeated protocol version {version}"))); + } + } + self.versions = versions.iter().map(|v| (*v).to_owned()).collect(); + Ok(self) + } + /// Set the server capabilities returned at initialization. The value must be an object. pub fn with_capabilities(mut self, capabilities: Value) -> Result { if !capabilities.is_object() { @@ -101,9 +133,32 @@ impl Session { self.state } + /// The protocol version the last successful initialize answered with. + pub fn negotiated_version(&self) -> Option<&str> { + self.negotiated.as_deref() + } + + fn answer_version(&self, asked: Option<&str>) -> String { + asked + .filter(|v| self.versions.iter().any(|supported| supported == v)) + .unwrap_or_else(|| self.versions.first().map(String::as_str).unwrap_or(PROTOCOL_VERSION)) + .to_owned() + } + + /// Whether the caller may dispatch a JSON-RPC batch. False in strict mode once a version + /// without batching (2025-06-18) is negotiated; reject such a batch envelope with + /// -32600 before dispatching it, since `notification` cannot tell a batched notification apart. + pub fn accepts_batches(&self) -> bool { + self.policy != Policy::Strict || !self.negotiated.as_deref().is_some_and(|v| BATCHLESS_VERSIONS.contains(&v)) + } + /// Handles `initialize` and `ping`. Returns `None` for a request the app should route. - /// `in_batch` must describe the outer JSON-RPC envelope. + /// `in_batch` must describe the outer JSON-RPC envelope. A batched request is rejected + /// when `accepts_batches` is false. pub fn request(&mut self, request: Request<'_>, in_batch: bool) -> Option> { + if in_batch && !self.accepts_batches() { + return Some(Err(RpcError::new(-32600, "Invalid Request"))); + } if request.method == "ping" { return Some(Ok(json!({}))); } @@ -113,27 +168,29 @@ impl Session { } if self.permissive_initialize { let asked = request.params.and_then(|p| p.get("protocolVersion")).and_then(Value::as_str); - let version = asked - .filter(|v| self.versions.iter().any(|supported| supported == v)) - .unwrap_or_else(|| self.versions.first().map(String::as_str).unwrap_or(PROTOCOL_VERSION)); + let version = self.answer_version(asked); let result = json!({"protocolVersion": version, "capabilities": self.capabilities, "serverInfo": self.server_info}); self.state = State::AwaitingInitialized; + self.negotiated = Some(version); return Some(Ok(self.with_instructions(result))); } let Some(params) = request.params.and_then(Value::as_object) else { return Some(Err(invalid_initialize())); }; - let valid = params.get("protocolVersion").and_then(Value::as_str).is_some() - && params.get("capabilities").is_some_and(Value::is_object) - && params.get("clientInfo").is_some_and(Value::is_object); + let asked = params.get("protocolVersion").and_then(Value::as_str); + let valid = + asked.is_some() && params.get("capabilities").is_some_and(Value::is_object) && params.get("clientInfo").is_some_and(Value::is_object); let identity = params.get("clientInfo").and_then(Value::as_object); let strict_identity = identity .is_some_and(|info| info.get("name").and_then(Value::as_str).is_some() && info.get("version").and_then(Value::as_str).is_some()); if !valid || (self.policy == Policy::Strict && !strict_identity) { return Some(Err(invalid_initialize())); } + let version = self.answer_version(asked); + let result = + json!({"protocolVersion": version, "capabilities": self.capabilities, "serverInfo": {"name": self.name, "version": self.version}}); self.state = State::AwaitingInitialized; - let result = json!({"protocolVersion": PROTOCOL_VERSION, "capabilities": self.capabilities, "serverInfo": {"name": self.name, "version": self.version}}); + self.negotiated = Some(version); return Some(Ok(self.with_instructions(result))); } if self.policy == Policy::Strict && self.state == State::New { @@ -184,6 +241,196 @@ pub fn text_tool_result(text: &str, is_error: bool) -> Value { json!({"content": [{"type": "text", "text": text}], "isError": is_error}) } +/// Most values one `completion/complete` result may carry. +pub const MAX_COMPLETIONS: usize = 100; + +/// One page of a `resources/list`, `resources/templates/list` or `prompts/list` result. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Page { + pub items: Vec, + /// The cursor a client sends to get the next page; `None` on the last page. + pub next_cursor: Option, +} + +impl Page { + /// Every item in one page, for a server that does not paginate. + pub fn all(items: Vec) -> Self { + Self { items, next_cursor: None } + } +} + +/// Take the page of `items` that starts at the `cursor` in a list request's parameters, with at most +/// `page_size` items (0 puts every item in one page). The helper accepts canonical positive +/// decimal offsets divisible by `page_size`. Parameters that are not an object, and malformed +/// cursors, are rejected with -32602. The helper returns an empty last page for a cursor past +/// the list's end, including after the list shrinks. +pub fn page(params: Option<&Value>, mut items: Vec, page_size: usize) -> Result { + if params.is_some_and(|p| !p.is_object()) { + return Err(RpcError::new(-32602, "List parameters must be an object")); + } + let start = match params.and_then(|p| p.get("cursor")) { + None => 0, + Some(Value::String(cursor)) => match cursor.parse::() { + Ok(offset) if page_size > 0 && offset > 0 && offset % page_size == 0 && offset.to_string() == *cursor => offset, + _ => return Err(invalid_cursor()), + }, + Some(_) => return Err(invalid_cursor()), + }; + let start = start.min(items.len()); + items.drain(..start); + let mut next_cursor = None; + if page_size > 0 && items.len() > page_size { + items.truncate(page_size); + next_cursor = Some((start + page_size).to_string()); + } + Ok(Page { items, next_cursor }) +} + +fn invalid_cursor() -> RpcError { + RpcError::new(-32602, "Invalid cursor") +} + +/// Wrap a page of MCP `Resource` objects in the `resources/list` result. +pub fn resource_list(page: Page) -> Value { + list_result("resources", page) +} + +/// Wrap a page of MCP `ResourceTemplate` objects in the `resources/templates/list` result. +pub fn resource_template_list(page: Page) -> Value { + list_result("resourceTemplates", page) +} + +/// Wrap a page of MCP `Prompt` objects in the `prompts/list` result. +pub fn prompt_list(page: Page) -> Value { + list_result("prompts", page) +} + +fn list_result(key: &str, page: Page) -> Value { + let mut result = serde_json::Map::new(); + result.insert(key.to_owned(), Value::Array(page.items)); + if let Some(cursor) = page.next_cursor { + result.insert("nextCursor".to_owned(), Value::String(cursor)); + } + Value::Object(result) +} + +/// Validate `resources/read` parameters and return the requested URI. +pub fn resource_read(params: &Value) -> Result<&str, RpcError> { + params.get("uri").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing resource URI")) +} + +/// The error MCP specifies for a `resources/read` of a URI the server does not have. +pub fn resource_not_found(uri: &str) -> RpcError { + RpcError { code: -32002, message: "Resource not found".into(), data: Some(json!({"uri": uri})) } +} + +/// Text contents of a resource, for [`read_result`]. +pub fn text_contents(uri: &str, mime_type: Option<&str>, text: &str) -> Value { + contents(uri, mime_type, "text", text) +} + +/// Binary contents of a resource, for [`read_result`]. `base64` is the data in standard base64. +pub fn blob_contents(uri: &str, mime_type: Option<&str>, base64: &str) -> Value { + contents(uri, mime_type, "blob", base64) +} + +fn contents(uri: &str, mime_type: Option<&str>, key: &str, value: &str) -> Value { + let mut result = serde_json::Map::new(); + result.insert("uri".to_owned(), json!(uri)); + if let Some(mime_type) = mime_type { + result.insert("mimeType".to_owned(), json!(mime_type)); + } + result.insert(key.to_owned(), json!(value)); + Value::Object(result) +} + +/// Wrap resource contents in the `resources/read` result. +pub fn read_result(contents: Vec) -> Value { + json!({"contents": contents}) +} + +/// Validate `prompts/get` parameters and return the prompt name and its arguments. MCP prompt +/// arguments are strings, so an argument of any other type is rejected with -32602. +pub fn prompt_get(params: &Value) -> Result<(&str, BTreeMap<&str, &str>), RpcError> { + let name = params.get("name").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing prompt name"))?; + let arguments = match params.get("arguments") { + None => BTreeMap::new(), + Some(Value::Object(map)) => map + .iter() + .map(|(key, value)| value.as_str().map(|v| (key.as_str(), v))) + .collect::>>() + .ok_or_else(|| RpcError::new(-32602, "Prompt arguments must be strings"))?, + Some(_) => return Err(RpcError::new(-32602, "Prompt arguments must be an object")), + }; + Ok((name, arguments)) +} + +/// Wrap prompt messages (MCP `PromptMessage` objects) in the `prompts/get` result. +pub fn prompt_result(description: Option<&str>, messages: Vec) -> Value { + let mut result = json!({"messages": messages}); + if let Some(description) = description { + result["description"] = json!(description); + } + result +} + +/// A prompt message with one text block, from `"user"` or `"assistant"`. +pub fn text_message(role: &str, text: &str) -> Value { + json!({"role": role, "content": {"type": "text", "text": text}}) +} + +/// What a `completion/complete` request refers to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompletionRef<'a> { + /// A prompt, by name (`ref/prompt`). + Prompt(&'a str), + /// A resource or resource template, by URI or URI template (`ref/resource`). + Resource(&'a str), +} + +/// The parameters of a `completion/complete` request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Completion<'a> { + pub reference: CompletionRef<'a>, + /// The name of the argument being completed. + pub argument: &'a str, + /// What the user has typed for it so far. + pub value: &'a str, +} + +/// Validate `completion/complete` parameters. +pub fn completion_request(params: &Value) -> Result, RpcError> { + let invalid = |message: &str| RpcError::new(-32602, message); + let reference = params.get("ref").ok_or_else(|| invalid("Missing completion reference"))?; + let field = |key: &str| reference.get(key).and_then(Value::as_str); + let reference = match reference.get("type").and_then(Value::as_str) { + Some("ref/prompt") => CompletionRef::Prompt(field("name").ok_or_else(|| invalid("Missing prompt name"))?), + Some("ref/resource") => CompletionRef::Resource(field("uri").ok_or_else(|| invalid("Missing resource URI"))?), + _ => return Err(invalid("Unknown completion reference type")), + }; + let argument = params.get("argument"); + let text = |key: &str| argument.and_then(|a| a.get(key)).and_then(Value::as_str); + let (Some(name), Some(value)) = (text("name"), text("value")) else { + return Err(invalid("Completion argument needs a name and a value")); + }; + Ok(Completion { reference, argument: name, value }) +} + +/// Build the `completion/complete` result from every matching value. The result carries the first +/// [`MAX_COMPLETIONS`] values, the number of matches in `total`, and whether any were left out in +/// `hasMore`. +pub fn completion_result(values: impl IntoIterator) -> Value { + let mut kept = Vec::new(); + let mut total = 0usize; + for value in values { + if kept.len() < MAX_COMPLETIONS { + kept.push(value); + } + total += 1; + } + json!({"completion": {"values": kept, "total": total, "hasMore": total > MAX_COMPLETIONS}}) +} + #[cfg(test)] mod tests { use super::*; @@ -205,6 +452,7 @@ mod tests { assert_eq!(result["protocolVersion"], expected); assert_eq!(result["serverInfo"]["title"], "Title"); assert_eq!(result["instructions"], "help"); + assert_eq!(s.negotiated_version(), Some(expected)); } } @@ -266,6 +514,54 @@ mod tests { } } + #[test] + fn validated_initialize_negotiates_configured_versions() { + let mut s = Session::new("test", "1", Policy::Compatible).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert_eq!(s.negotiated_version(), None); + for (asked, expected) in [("2024-11-05", "2024-11-05"), ("2025-03-26", "2025-03-26"), ("2025-06-18", "2025-06-18"), ("1.0.0", "2025-06-18")] { + let p = json!({"protocolVersion": asked, "capabilities": {}, "clientInfo": {}}); + let r = s.request(call("initialize", Some(&p)), false).unwrap().unwrap(); + assert_eq!(r["protocolVersion"], expected); + assert_eq!(s.negotiated_version(), Some(expected)); + } + let mut old_first = Session::new("test", "1", Policy::Compatible).with_versions(&["2025-03-26", "2025-06-18"]).unwrap(); + let p = json!({"protocolVersion": "2099-01-01", "capabilities": {}, "clientInfo": {}}); + assert_eq!(old_first.request(call("initialize", Some(&p)), false).unwrap().unwrap()["protocolVersion"], "2025-03-26"); + } + + #[test] + fn version_lists_reject_empty_unknown_and_repeated_entries() { + let new = || Session::new("test", "1", Policy::Compatible); + assert!(new().with_versions(&[]).is_err()); + assert!(new().with_versions(&["2099-01-01"]).is_err()); + assert!(new().with_versions(&["2025-06-18", "2025-06-18"]).is_err()); + let mut s = new(); + let p = json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {}}); + assert!(s.request(call("initialize", Some(&json!({}))), false).unwrap().is_err()); + assert_eq!(s.negotiated_version(), None); + assert_eq!(s.request(call("initialize", Some(&p)), false).unwrap().unwrap()["protocolVersion"], PROTOCOL_VERSION); + } + + #[test] + fn strict_rejects_batches_after_negotiating_a_version_without_them() { + let p = |v: &str| json!({"protocolVersion": v, "capabilities": {}, "clientInfo": {"name": "client", "version": "1"}}); + let mut s = Session::new("test", "1", Policy::Strict).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert!(s.accepts_batches()); + assert!(s.request(call("initialize", Some(&p("2025-06-18"))), false).unwrap().is_ok()); + assert!(!s.accepts_batches()); + assert_eq!(s.request(call("ping", None), true).unwrap().unwrap_err().code, -32600); + assert_eq!(s.request(call("tools/list", None), true).unwrap().unwrap_err().code, -32600); + assert!(s.request(call("tools/list", None), false).is_none()); + let mut older = Session::new("test", "1", Policy::Strict).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert!(older.request(call("initialize", Some(&p("2025-03-26"))), false).unwrap().is_ok()); + assert!(older.accepts_batches()); + assert!(older.request(call("tools/list", None), true).is_none()); + let mut compatible = Session::new("test", "1", Policy::Compatible).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert!(compatible.request(call("initialize", Some(&p("2025-06-18"))), false).unwrap().is_ok()); + assert!(compatible.accepts_batches()); + assert!(compatible.request(call("tools/list", None), true).is_none()); + } + #[test] fn tool_envelopes_validate_arguments_and_preserve_results() { let p = json!({"name":"open"}); @@ -320,4 +616,89 @@ mod tests { assert_eq!(reply[1]["result"]["tools"], json!([])); assert_eq!(session.borrow().state(), State::Ready); } + + #[test] + fn list_pages_follow_their_cursors_to_the_end() { + let items: Vec = (0..5).map(|i| json!({"name": i})).collect(); + let mut params = None; + let mut names = Vec::new(); + let mut pages = 0; + loop { + let page = page(params.as_ref(), items.clone(), 2).unwrap(); + let result = prompt_list(page); + pages += 1; + names.extend(result["prompts"].as_array().unwrap().iter().map(|p| p["name"].clone())); + match result.get("nextCursor") { + Some(cursor) => params = Some(json!({"cursor": cursor})), + None => break, + } + } + assert_eq!((pages, names), (3, (0..5).map(|i| json!(i)).collect::>())); + assert_eq!(resource_list(page(None, items.clone(), 0).unwrap()), json!({"resources": items})); + let past_the_end = page(Some(&json!({"cursor": "8"})), items, 2).unwrap(); + assert_eq!(resource_template_list(past_the_end), json!({"resourceTemplates": []})); + } + + #[test] + fn list_cursors_that_were_not_handed_out_are_invalid_params() { + for cursor in [json!(""), json!("-1"), json!("+1"), json!("1.0"), json!("abc"), json!(2), json!(null), json!("99999999999999999999999")] { + let error = page(Some(&json!({"cursor": cursor})), vec![json!(1)], 1).unwrap_err(); + assert_eq!(error.code, -32602, "{cursor}"); + } + for cursor in ["1", "02", "0"] { + assert_eq!(page(Some(&json!({"cursor": cursor})), vec![json!(1); 5], 2).unwrap_err().code, -32602, "{cursor}"); + } + assert_eq!(page(Some(&json!({"cursor": "2"})), vec![json!(1); 5], 0).unwrap_err().code, -32602); + for params in [json!(null), json!([]), json!("0")] { + assert_eq!(page(Some(¶ms), vec![json!(1)], 1).unwrap_err().code, -32602, "{params}"); + } + } + + #[test] + fn resource_reads_validate_the_uri_and_build_contents() { + assert_eq!(resource_read(&json!({"uri": "x://a"})).unwrap(), "x://a"); + assert_eq!(resource_read(&json!({"uri": 1})).unwrap_err().code, -32602); + let missing = resource_not_found("x://b"); + assert_eq!((missing.code, missing.data), (-32002, Some(json!({"uri": "x://b"})))); + let result = read_result(vec![text_contents("x://a", Some("text/markdown"), "# A"), blob_contents("x://c", None, "AAE=")]); + assert_eq!(result, json!({"contents": [{"uri": "x://a", "mimeType": "text/markdown", "text": "# A"}, {"uri": "x://c", "blob": "AAE="}]})); + } + + #[test] + fn prompt_arguments_must_be_strings() { + let params = json!({"name": "describe", "arguments": {"part": "bracket"}}); + let (name, args) = prompt_get(¶ms).unwrap(); + assert_eq!((name, args.get("part").copied()), ("describe", Some("bracket"))); + assert!(prompt_get(&json!({"name": "describe"})).unwrap().1.is_empty()); + for params in [json!({}), json!({"name": "d", "arguments": {"n": 1}}), json!({"name": "d", "arguments": ["x"]})] { + assert_eq!(prompt_get(¶ms).unwrap_err().code, -32602, "{params}"); + } + let result = prompt_result(Some("Describe a part"), vec![text_message("user", "Describe bracket")]); + assert_eq!(result["messages"][0]["content"], json!({"type": "text", "text": "Describe bracket"})); + assert_eq!(result["description"], "Describe a part"); + } + + #[test] + fn completion_requests_name_a_prompt_or_a_resource() { + let prompt = json!({"ref": {"type": "ref/prompt", "name": "describe"}, "argument": {"name": "part", "value": "br"}}); + assert_eq!(completion_request(&prompt).unwrap(), Completion { reference: CompletionRef::Prompt("describe"), argument: "part", value: "br" }); + let resource = json!({"ref": {"type": "ref/resource", "uri": "lib://parts/{part}"}, "argument": {"name": "part", "value": ""}}); + assert_eq!(completion_request(&resource).unwrap().reference, CompletionRef::Resource("lib://parts/{part}")); + for params in [ + json!({"ref": {"type": "ref/tool", "name": "x"}, "argument": {"name": "a", "value": ""}}), + json!({"ref": {"type": "ref/prompt"}, "argument": {"name": "a", "value": ""}}), + json!({"ref": {"type": "ref/prompt", "name": "x"}, "argument": {"name": "a"}}), + json!({"argument": {"name": "a", "value": ""}}), + ] { + assert_eq!(completion_request(¶ms).unwrap_err().code, -32602, "{params}"); + } + } + + #[test] + fn completion_results_carry_at_most_a_hundred_values() { + let result = completion_result((0..150).map(|i| i.to_string())); + assert_eq!(result["completion"]["values"].as_array().map(Vec::len), Some(MAX_COMPLETIONS)); + assert_eq!((&result["completion"]["total"], &result["completion"]["hasMore"]), (&json!(150), &json!(true))); + assert_eq!(completion_result(["a".to_owned()]), json!({"completion": {"values": ["a"], "total": 1, "hasMore": false}})); + } } diff --git a/crates/media/README.md b/crates/media/README.md index 38c0ced3f7..bbbe121a5a 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -467,6 +467,10 @@ not apply to it; damage is skipped with the same budget and warnings as `open`. in `streams()`, where a later link of a chained file appears as a new stream when its pages are reached. `OggFile::read_packet_into` reads a packet into a reused buffer. `OpusTiming` gives each Opus packet's start, the pre-skip and the end trimming of the final page. +`VorbisTiming` gives each Vorbis packet's start and duration (from the block sizes of the modes that +`VorbisModes` reads from the setup header), the samples to discard before a negative starting +position, the offset of a stream that starts after 0, and the end trimming of the final page +(Vorbis I §4.3.8 and §A.2). The muxer side is `PageWriter`, from FilmCraft's `filmcraft-oggmux` by @JordyUSA (storytold/filmcraft#4481): it laces the packets of one logical stream into pages (continued @@ -625,9 +629,10 @@ let au: Vec = file.read_unit(&bytes, v, 0)?; // the first access unit - **Program streams**: MPEG-2 and MPEG-1 packs, system headers, the program stream map (stream types for elementary stream ids), padding, private stream 2 (DVD navigation) skipped, private stream 1 split by sub-stream id. Garbage resynchronises on the next pack or PES start code. -- **Streams**: MPEG-1/2 video, H.264, HEVC, MPEG audio, AAC (ADTS, LATM/LOAS), AC-3, E-AC-3, - DTS, TrueHD, Blu-ray LPCM, DVD LPCM (format from the sub-stream header), PGS / DVB / teletext - subtitles; ISO 639 language from the PMT. +- **Streams**: MPEG-1/2 video, H.264, HEVC, MPEG-4 Part 2 (stream type 0x10), AV1 and Opus + (stream type 0x06 with the `AV01` or `Opus` registration descriptor), MPEG audio, AAC (ADTS, + LATM/LOAS), AC-3, E-AC-3, DTS, TrueHD, Blu-ray LPCM, DVD LPCM (format from the sub-stream + header), PGS / DVB / teletext subtitles; ISO 639 language from the PMT. - **Access units**, found while the file is scanned (one pass, streaming; only a few bytes of each stream are buffered): - MPEG-1/2 video: a coded frame — a frame picture, or two field pictures (paired by @@ -639,6 +644,17 @@ let au: Vec = file.read_unit(&bytes, v, 0)?; // the first access unit - Audio: one frame per unit from the frame headers (sync re-hunted after garbage; a header found while hunting is confirmed by the next one); a PTS belongs to the first frame starting in the PES. + - MPEG-4 Part 2: PES packets with a timestamp, as for H.264; the first VOP's coding type + gives the key (I-VOP) and disposable (B-VOP) flags. + - Opus: one access unit per unit, cut by its control header's payload size; `read_unit` + returns the Opus packet without the header, and the start and end trims are in + `Stream::opus` (`OpusConfig::trims`). An access unit without a control header runs to the + end of its PES packet; one whose size runs past its PES packet is dropped and counted in + `skipped_bytes`. + - AV1: one PES packet per unit, a key unit when the TS packet that starts it sets the random + access indicator. `read_unit` returns the OBUs in the low overhead bitstream format (start + codes, emulation prevention bytes and temporal delimiters removed, `obu_size` added where it + is missing), as Matroska and ISOBMFF store them. - LPCM and everything else: one PES packet per unit. - **Timestamps**: 33-bit PTS/DTS unwrapped across the wrap (and back, for B pictures shown before a wrap that came earlier); PCR / SCR range. @@ -652,8 +668,12 @@ MPEG audio or AC-3 frames in chunks that do not follow them (AVI) find the frame `Codec::codec_id()` and `Stream::codec_params()` give the crate-wide `CodecId` / `CodecParams`. MPEG-1 video reports `Mpeg2Video`; MPEG audio reports `Mp2` whatever its layer (the layer is in each frame header: `frame_info(..).variant`); ADTS and LATM AAC both report `Aac`; DTS, TrueHD and -subtitles have no identifier (`Unknown`). The streams carry their configuration in band, so -`extradata` is empty; DVD LPCM fills `sample_rate`, `channels` and `pcm`. +subtitles have no identifier (`Unknown`). Opus fills `sample_rate` (48 kHz), `channels` and an +`OpusHead` header in `extradata`, built from the PMT's Opus audio descriptor (`Stream::opus`) with +the start trims of the units that open the stream as its pre-skip. AV1 puts the first four bytes of an `av1C` record, +from the PMT's AV1 video descriptor (`Stream::av1c`), in `extradata`. The other streams carry +their configuration in band, so `extradata` is empty; DVD LPCM fills `sample_rate`, `channels` +and `pcm`. Limits, each with a test: 2²³ access units per stream (the rest are not indexed, with a warning), 128 MiB per unit read (`MAX_UNIT_BYTES`), a PES header given up after 1024 bytes, 16 stuffing bytes @@ -670,6 +690,9 @@ at least 8 bytes. | DVD-Video private stream 1 sub-stream layout (AC-3 / DTS 0x80-0x8F with a 3-byte header, LPCM 0xA0-0xAF with a 6-byte header, sub-pictures 0x20-0x3F) | public descriptions | `.vob` | | ETSI EN 300 468 (descriptors 0x56, 0x59, 0x6A, 0x7A, 0x7B), ATSC A/52 Annex A (AC-3 in TS) | — | identifying private PES streams | | ISO/IEC 11172-3, 13818-3 (frame headers), ISO/IEC 13818-7 (ADTS), 14496-3 (LOAS), ATSC A/52 (syncinfo, E-AC-3 frmsiz) | — | audio frame lengths for splitting | +| ISO/IEC 14496-2 | any edition | MPEG-4 Part 2 VOP coding types | +| Opus Interactive Audio Codec Transport Multiplexing Standard | draft TS V0.1.3 (2015-10) | Opus control headers, the Opus audio descriptor and its channel configurations; RFC 7845 for the `OpusHead` header and the channel mapping families | +| Carriage of AV1 in MPEG-2 TS (Alliance for Open Media) | working draft | the AV1 video descriptor, start codes and emulation prevention; the AV1 Bitstream & Decoding Process Specification for OBU headers and `obu_size` | ### Gaps @@ -688,9 +711,10 @@ Differences from `filmcraft-mpegts`: `ByteSource` is `craft_media::ByteSource`; Tests: a small TS muxer and PS writer (every access unit reads back byte-identical with its PTS, key and disposable flags), 33-bit unwrap, truncation and mutation, streams of every codec filled with random start codes and sync words, damaged PSI sections with valid CRCs, and the frame-header -helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares ten ffmpeg-made files (MPEG-2, H.264 -and HEVC video; MP2, ADTS and LATM AAC, AC-3, E-AC-3, Blu-ray and DVD LPCM; TS, M2TS, VOB and -MPEG-1 system streams) with ffprobe's packets: unit counts, sizes, timestamps and key flags. +helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares eleven ffmpeg-made files (MPEG-2, +H.264, HEVC and MPEG-4 Part 2 video; MP2, ADTS and LATM AAC, AC-3, E-AC-3, Opus, Blu-ray and DVD +LPCM; TS, M2TS, VOB and MPEG-1 system streams) with ffprobe's packets: unit counts, sizes, +timestamps and key flags. ### Transport stream writer @@ -783,9 +807,7 @@ the first stream) every 40 ms and 700 ms behind the DTS, the PAT and PMT every 1 keyframes, and writes of 7 packets. Gaps: one program per stream; no null packets (no constant bit rate); not written: LPCM (H.222.0 -defines no LPCM stream type for transport streams), AAC in LATM, DTS, subtitles and teletext. The -demuxer reads Opus and AV1 streams as `Unknown(6)` and MPEG-4 Part 2 as `Unknown(0x10)`, one unit -per PES packet. +defines no LPCM stream type for transport streams), AAC in LATM, DTS, subtitles and teletext. Specifications: the ones above, and Opus Interactive Audio Codec Transport Multiplexing Standard, draft TS V0.1.3 (2015-10), for the Opus control header and descriptors; RFC 6716 for Opus packet @@ -796,7 +818,8 @@ descriptors. Tests: `tests/mpegts_mux_readback.rs` reads the output back with the demuxer: streams, codecs, languages, every frame's bytes, PTS and DTS, keyframes and the PCR range, with no continuity or -CRC warnings, including AV1 units, Opus with an explicit mapping and a start trim, both sides of a +CRC warnings, including AV1 units as OBUs with their `av1C` fields, Opus packets with fixed +and explicit channel configurations and their start and end trims, MPEG-4 Part 2, both sides of a discontinuity, and the output that follows an I/O error. `tests/mpegts_mux_fuzz.rs` muxes random programs and timelines with idle gaps and output swaps and reads them back, and feeds random bytes to every codec. Unit tests check every PES header's fixed bits, the sections' CRC, and that every diff --git a/crates/media/src/mpegts/es.rs b/crates/media/src/mpegts/es.rs index 8568c7cba2..c17f086484 100644 --- a/crates/media/src/mpegts/es.rs +++ b/crates/media/src/mpegts/es.rs @@ -7,7 +7,7 @@ use std::collections::VecDeque; -use super::{Codec, PictureInfo, Unit}; +use super::{Codec, OpusTrim, PictureInfo, Unit}; /// How a stream is cut into units. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -19,6 +19,16 @@ enum Mode { Nal { hevc: bool }, /// Framed audio with self-describing frame headers. Audio(AudioSync), + /// Opus: one access unit per unit, cut by its control header's payload size and starting + /// after the header; an access unit without a control header runs to the end of its PES + /// packet (Opus transport draft §6). + Opus, + /// MPEG-4 Part 2 video: a PES packet with a timestamp starts a unit; the first VOP's coding + /// type gives the flags. + Mpeg4, + /// AV1: one PES packet per unit (Carriage of AV1 in MPEG-2 TS §3.4), a key unit where the + /// packet that starts it sets the random access indicator. + Av1, /// One PES packet per unit. Pes, } @@ -41,6 +51,9 @@ impl Mode { Codec::AacAdts => Mode::Audio(AudioSync::Adts), Codec::AacLatm => Mode::Audio(AudioSync::Loas), Codec::Ac3 | Codec::Eac3 => Mode::Audio(AudioSync::Ac3), + Codec::Opus => Mode::Opus, + Codec::Mpeg4Part2 => Mode::Mpeg4, + Codec::Av1 => Mode::Av1, _ => Mode::Pes, } } @@ -101,8 +114,16 @@ pub(crate) struct Splitter { gop: Option<(bool, bool)>, pending: Option, open_field: Option, - // audio state + // audio state; for Opus, where the next access unit's control header starts (None: the + // rest of the PES packet belongs to the open unit) or, once one is read, where its payload + // ends next_frame: Option, + /// Opus: how far the payload size of a control header cut off by the end of a chunk was read. + opus_scan: OpusSizeScan, + /// Opus: the open unit's start and end trims. + open_trim: (u16, u16), + /// Opus: the trims of the units so far. + pub trims: Vec, } /// AC-3 frame sizes in 16-bit words for 48 / 44.1 / 32 kHz (A/52 Table 5.18), by @@ -331,6 +352,158 @@ pub(crate) const MAX_UNITS: usize = 1 << 23; /// Full-bandwidth channels per AC-3 audio coding mode (A/52 Table 5.8). const AC3_CHANNELS: [u32; 8] = [2, 1, 2, 3, 3, 4, 4, 5]; +/// What starts an Opus access unit. +#[derive(Debug, PartialEq, Eq)] +enum OpusHeader { + /// More bytes are needed to tell. + Incomplete, + /// No control header: the access unit is the rest of the PES packet. + Absent, + /// A control header whose payload size is past [`super::MAX_UNIT_BYTES`]. + Invalid, + /// A control header of `len` bytes, then `size` bytes of payload with these start and end + /// trims. + Found { len: usize, size: u64, trim: (u16, u16) }, +} + +/// How far the payload size of the control header at ES offset `at` was read: `next` is the +/// header index of the next size byte to read, and `size` is the sum of the bytes before it. +#[derive(Debug, Default)] +struct OpusSizeScan { + at: u64, + next: usize, + size: u64, + /// Size bytes read, by every header. + #[cfg(test)] + reads: u64, +} + +/// The opus_control_header at the start of `b`, which is ES offset `at` (Opus transport draft +/// §6.2): the 11-bit prefix 0x3FF, the start trim, end trim and extension flags, the payload size +/// as bytes of 0xFF and a last byte, then the 13-bit trims and the extension. When `b` ends +/// before the header does, `scan` keeps the size read so far, and a call with more bytes of the +/// same header goes on from there, so each size byte is read once. +fn opus_control_header(b: &[u8], at: u64, scan: &mut OpusSizeScan) -> OpusHeader { + match b { + [] => return OpusHeader::Incomplete, + [0x7F] => return OpusHeader::Incomplete, + [0x7F, b1, ..] if b1 & 0xE0 == 0xE0 => {} + _ => return OpusHeader::Absent, + } + let flags = b[1]; + if scan.at != at || scan.next < 2 { + scan.at = at; + scan.next = 2; + scan.size = 0; + } + let mut i = scan.next; + let mut size = scan.size; + loop { + let Some(&x) = b.get(i) else { + scan.next = i; + scan.size = size; + return OpusHeader::Incomplete; + }; + #[cfg(test)] + { + scan.reads += 1; + } + if size + u64::from(x) > u64::from(super::MAX_UNIT_BYTES) { + return OpusHeader::Invalid; + } + if x != 0xFF { + // the trims or the extension may still be cut off: a later call reads this last + // size byte again + scan.next = i; + scan.size = size; + size += u64::from(x); + i += 1; + break; + } + size += u64::from(x); + i += 1; + } + let mut trim = [0u16; 2]; + for (k, bit) in [0x10u8, 0x08].into_iter().enumerate() { + if flags & bit != 0 { + let Some(v) = b.get(i..i + 2) else { return OpusHeader::Incomplete }; + trim[k] = u16::from_be_bytes([v[0], v[1]]) & 0x1FFF; + i += 2; + } + } + if flags & 0x04 != 0 { + let Some(&n) = b.get(i) else { return OpusHeader::Incomplete }; + i += 1 + usize::from(n); + if i > b.len() { + return OpusHeader::Incomplete; + } + } + OpusHeader::Found { len: i, size, trim: (trim[0], trim[1]) } +} + +/// Rewrites an AV1 access unit from the start code form of Carriage of AV1 in MPEG-2 TS §3.2 to +/// the low overhead bitstream format: each OBU follows a start code 0x000001, and the 0x03 of +/// every 0x000003 in it is an emulation prevention byte. Temporal delimiters and bytes before the +/// first start code are left out, as Matroska and ISOBMFF store AV1. An OBU that carries +/// obu_size ends there; one without gets an obu_size for the bytes up to the next start code. +pub(crate) fn av1_obus(es: &mut Vec) { + let mut out = Vec::with_capacity(es.len() + 16); + let mut obu = Vec::new(); + let start_code = |i: usize| es.get(i..i + 3) == Some(&[0, 0, 1][..]); + let mut i = (0..es.len()).find(|&i| start_code(i)).unwrap_or(es.len()); + while i < es.len() { + // `i` is at a start code + i += 3; + obu.clear(); + let mut zeros = 0; + while i < es.len() && !start_code(i) { + let b = es[i]; + i += 1; + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + obu.push(b); + } + let Some(&h) = obu.first() else { continue }; + let header = 1 + usize::from(h & 0x04 != 0); + if obu.len() < header || (h >> 3) & 0x0F == 2 { + continue; + } + if h & 0x02 != 0 { + // obu_size, leb128 (AV1 §4.10.5) + let mut size = 0u64; + let mut at = header; + for k in 0..8 { + let Some(&b) = obu.get(at) else { break }; + at += 1; + size |= u64::from(b & 0x7F) << (7 * k); + if b & 0x80 == 0 { + break; + } + } + let end = usize::try_from(size).ok().and_then(|s| at.checked_add(s)).filter(|&e| e <= obu.len()).unwrap_or(obu.len()); + out.extend_from_slice(&obu[..end]); + } else { + out.push(h | 0x02); + out.extend_from_slice(&obu[1..header]); + let mut size = obu.len() - header; + loop { + let b = (size & 0x7F) as u8; + size >>= 7; + if size == 0 { + out.push(b); + break; + } + out.push(b | 0x80); + } + out.extend_from_slice(&obu[header..]); + } + } + *es = out; +} + /// Frame length at the start of `b` for the given sync type (`None`: no valid header; `Some(0)` /// is never returned). fn frame_len(sync: AudioSync, b: &[u8]) -> Option { @@ -388,6 +561,9 @@ impl Splitter { pending: None, open_field: None, next_frame: None, + opus_scan: OpusSizeScan::default(), + open_trim: (0, 0), + trims: Vec::new(), } } @@ -398,12 +574,48 @@ impl Splitter { self.pes.pop_front(); } match self.mode { - Mode::Pes => self.begin_pes_unit(true), - Mode::Nal { .. } => self.begin_pes_unit(pts.is_some() || dts.is_some()), + Mode::Pes | Mode::Av1 => self.begin_pes_unit(true), + Mode::Nal { .. } | Mode::Mpeg4 => self.begin_pes_unit(pts.is_some() || dts.is_some()), + Mode::Opus => { + // a PES packet holds whole access units: the next one starts here + self.close_opus(self.es_pos); + self.next_frame = Some(self.es_pos); + } _ => {} } } + /// The packet that started the PES packet set the random access indicator: an AV1 unit + /// that the packet starts is a key unit. + pub fn random_access(&mut self) { + if self.mode == Mode::Av1 + && let Some(o) = self.open.as_mut() + && o.start == self.es_pos + { + o.key = true; + } + } + + /// Opus: end the open unit before ES byte `limit` (the end of its PES packet). A unit whose + /// payload size runs past `limit` is dropped, and so are the bytes of a control header that + /// the PES packet cuts off. + fn close_opus(&mut self, limit: u64) { + match self.next_frame { + Some(end) if end > limit => { + if let Some(o) = self.open.take() { + self.skipped += limit.saturating_sub(o.start); + } + self.open_trim = (0, 0); + } + Some(end) => { + self.close(end); + self.skipped += limit - end; + } + None => self.close(limit), + } + self.next_frame = None; + } + /// PES-delimited units: a packet with a timestamp (or any packet in plain PES mode) starts a /// new unit; one without continues the previous unit. fn begin_pes_unit(&mut self, new: bool) { @@ -443,6 +655,7 @@ impl Splitter { /// End the open unit at `end`. fn close(&mut self, end: u64) { let Some(o) = self.open.take() else { return }; + let (start_trim, end_trim) = std::mem::take(&mut self.open_trim); if end <= o.start || o.pos == u64::MAX { return; } @@ -450,6 +663,9 @@ impl Splitter { self.truncated = true; return; } + if (start_trim, end_trim) != (0, 0) { + self.trims.push(OpusTrim { unit: self.units.len(), start: start_trim, end: end_trim }); + } let size = (end - o.start).min(u32::MAX as u64) as u32; self.units.push(Unit { pts: o.pts, @@ -469,9 +685,9 @@ impl Splitter { return; } // PES-delimited modes resolve a unit's position from `pos` right here and never look a - // chunk up again, so remembering chunks there would only grow without bound (NAL streams - // keep theirs: an access unit can start inside a PES; `keep_from` prunes them) - if matches!(self.mode, Mode::MpegVideo | Mode::Audio(_) | Mode::Nal { .. }) { + // chunk up again, so remembering chunks there would only grow without bound (NAL and Opus + // streams keep theirs: an access unit can start inside a PES; `keep_from` prunes them) + if matches!(self.mode, Mode::MpegVideo | Mode::Audio(_) | Mode::Nal { .. } | Mode::Opus) { self.chunks.push_back((pos, self.es_pos)); } if let Some(o) = self.open.as_mut() @@ -484,10 +700,12 @@ impl Splitter { let start = self.es_pos; self.es_pos += data.len() as u64; match self.mode { - Mode::Pes => {} + Mode::Pes | Mode::Av1 => {} Mode::Nal { hevc } => self.scan_nal(start, data, hevc), Mode::MpegVideo => self.scan_mpeg(start, data), + Mode::Mpeg4 => self.scan_mpeg4(start, data), Mode::Audio(sync) => self.scan_audio(start, data, sync), + Mode::Opus => self.scan_opus(start, data), } // forget chunks no pending position can refer to let keep_from = self.buf_start.min(self.pending.map_or(u64::MAX, |p| p.unit_start.min(p.at))).min(self.header_start.unwrap_or(u64::MAX)); @@ -789,8 +1007,115 @@ impl Splitter { frame_len(sync, &self.buf[j..]).is_some() } + /// Opus access units: each control header gives the payload size, so the unit starts after + /// the header and ends where the next header starts. + fn scan_opus(&mut self, start: u64, data: &[u8]) { + let end = start + data.len() as u64; + let Some(next) = self.next_frame else { + // the rest of the PES packet belongs to the open unit, or is not Opus at all + if self.open.is_none() { + self.skipped += data.len() as u64; + } + // no later header can refer back to these bytes: `feed` may forget their chunks + self.buf.clear(); + self.buf_start = end; + return; + }; + if next >= end { + // inside the open unit's payload + self.buf.clear(); + self.buf_start = end; + return; + } + self.window(start, data); + while let Some(at) = self.next_frame { + if at < self.buf_start { + self.next_frame = None; + break; + } + let i = (at - self.buf_start) as usize; + if i >= self.buf.len() { + break; + } + match opus_control_header(&self.buf[i..], at, &mut self.opus_scan) { + OpusHeader::Incomplete => { + self.trim(self.buf.len() - i); + return; + } + OpusHeader::Absent => { + // no control header: the access unit runs to the end of the PES packet + self.close(at); + self.open_opus(at, at, (0, 0)); + self.next_frame = None; + } + OpusHeader::Invalid => { + self.close(at); + self.skipped += end - at; + self.next_frame = None; + } + OpusHeader::Found { len, size, trim } => { + self.close(at); + let payload = at + len as u64; + self.open_opus(at, payload, trim); + self.next_frame = Some(payload + size); + } + } + } + self.buf.clear(); + self.buf_start = end; + } + + /// Open an Opus unit at `start` for the access unit whose header (if any) starts at `at`. + fn open_opus(&mut self, at: u64, start: u64, trim: (u16, u16)) { + // a payload that starts with the next chunk is placed when that chunk arrives + let (pos, offset) = if start < self.es_pos { self.locate(start).unwrap_or((u64::MAX, 0)) } else { (u64::MAX, 0) }; + let mut o = Open { start, pos, offset, pts: None, dts: None, key: true, disposable: false, vcl: false, picture: None }; + if let Some((pts, dts)) = self.timestamps_at(at) { + o.pts = pts; + o.dts = dts; + } + self.open = Some(o); + self.open_trim = trim; + } + + /// MPEG-4 Part 2 video: the unit's first VOP header gives its coding type (ISO/IEC 14496-2 + /// §6.2.5: 0 I, 1 P, 2 B, 3 S). + fn scan_mpeg4(&mut self, start: u64, data: &[u8]) { + self.window(start, data); + if self.open.is_some_and(|o| o.vcl) { + // the unit's flags are known: keep only where a start code may begin + self.trim(3); + return; + } + let mut i = 0; + let mut blocked = None; + while let Some(k) = self.next_start_code(i) { + if k + 5 > self.buf.len() { + blocked = Some(k); + break; + } + let at = self.buf_start + k as u64; + if self.buf[k + 3] == 0xB6 + && let Some(o) = self.open.as_mut() + && !o.vcl + && at >= o.start + { + let coding_type = self.buf[k + 4] >> 6; + o.key = coding_type == 0; + o.disposable = coding_type == 2; + o.vcl = true; + } + i = k + 3; + } + self.keep_tail(i, blocked); + } + /// End of stream: close the open unit. pub fn finish(&mut self) { + if self.mode == Mode::Opus { + self.close_opus(self.es_pos); + return; + } self.settle_pending(); let end = match (self.mode, self.next_frame) { (Mode::Audio(_), Some(n)) => n.min(self.es_pos), @@ -884,6 +1209,48 @@ mod tests { } } + #[test] + fn a_long_opus_control_header_is_read_once() { + // a payload size of 100,000 bytes of 0xFF, cut into transport stream payloads + let mut s = Splitter::new(&Codec::Opus); + s.pes_start(Some(0), None); + let mut es = vec![0x7F, 0xE0]; + es.extend(std::iter::repeat_n(0xFF, 100_000)); + es.push(0); + for (k, c) in es.chunks(184).enumerate() { + s.feed(k as u64 * 188, c); + } + assert!(s.opus_scan.reads <= es.len() as u64, "{} size bytes read for a {}-byte header", s.opus_scan.reads, es.len()); + assert_eq!(s.next_frame, Some(es.len() as u64 + 255 * 100_000)); + } + + #[test] + fn opus_chunks_are_forgotten_inside_a_unit_and_after_a_headerless_one() { + // an access unit whose payload spans 500 chunks, then a PES packet without a control + // header + let mut s = Splitter::new(&Codec::Opus); + s.pes_start(Some(0), None); + let size = 184 * 500; + let mut es = vec![0x7F, 0xE0]; + es.extend(std::iter::repeat_n(0xFF, size / 255)); + es.push((size % 255) as u8); + es.resize(es.len() + size, 0x11); + let mut pos = 0; + for (k, c) in es.chunks(184).enumerate() { + s.feed(pos, c); + pos += 188; + assert!(k < 3 || s.chunks.len() <= 2, "chunk {k}: {} chunks retained", s.chunks.len()); + } + s.pes_start(Some(1800), None); + for k in 0..500 { + s.feed(pos, &[0xFC; 184]); + pos += 188; + assert!(s.chunks.len() <= 2, "headerless chunk {k}: {} chunks retained", s.chunks.len()); + } + s.finish(); + assert_eq!(s.units.iter().map(|u| u.size as usize).collect::>(), [size, 184 * 500]); + } + #[test] fn unit_table_is_capped() { let frame = |k: u8| { diff --git a/crates/media/src/mpegts/mod.rs b/crates/media/src/mpegts/mod.rs index 32356be02d..3e0570fa29 100644 --- a/crates/media/src/mpegts/mod.rs +++ b/crates/media/src/mpegts/mod.rs @@ -9,10 +9,11 @@ //! LPCM). //! - **Elementary streams** are split into access units on open — coded frames for MPEG-1/2 //! video (picture start codes, field pairs), H.264 and HEVC (access unit delimiters / first -//! slice of a picture), audio frames for MPEG audio, ADTS / LATM AAC, AC-3 and E-AC-3, PES -//! packets for LPCM — each with its PTS/DTS (a PES timestamp belongs to the first access unit -//! that starts in the packet), random-access flag and, for MPEG video, picture type, temporal -//! reference and field structure. That index is the seeking table. +//! slice of a picture), audio frames for MPEG audio, ADTS / LATM AAC, AC-3 and E-AC-3, Opus +//! access units (by their control headers), PES packets for LPCM, AV1 and MPEG-4 Part 2 video. +//! Each unit has its PTS/DTS (a PES timestamp belongs to the first access unit that starts in +//! the packet), random-access flag and, for MPEG video, picture type, temporal reference and field +//! structure. That index is the seeking table. //! - Units are read back on demand by re-reading the file from the unit's first packet, so the //! index costs a few dozen bytes per access unit. //! - [`mux`] writes one program as a transport stream to any `io::Write`, frame by frame. @@ -162,6 +163,13 @@ pub enum Codec { H264, /// H.265 / HEVC, Annex B. Hevc, + /// MPEG-4 Part 2 visual (ISO/IEC 14496-2), stream type 0x10. + Mpeg4Part2, + /// AV1 (stream type 0x06 with the registration descriptor "AV01"). [`File::read_unit`] + /// returns each access unit in the low overhead bitstream format, without start codes, + /// emulation prevention bytes or temporal delimiters; the AV1 video descriptor is in + /// [`Stream::av1c`]. + Av1, /// MPEG-1/2 audio (layers I-III; the layer is in each frame header). MpegAudio, /// AAC in ADTS frames. @@ -174,6 +182,10 @@ pub enum Codec { Eac3, /// DTS. Dts, + /// Opus (stream type 0x06 with the registration descriptor "Opus"). Each unit is one Opus + /// access unit without its control header; the channel configuration and the trims are in + /// [`Stream::opus`]. + Opus, /// Dolby TrueHD. TrueHd, /// Blu-ray / AVCHD LPCM (a 4-byte header per PES packet, big-endian samples). @@ -194,12 +206,15 @@ impl Codec { Codec::Mpeg2Video => "MPEG-2 Video".into(), Codec::H264 => "H.264".into(), Codec::Hevc => "HEVC".into(), + Codec::Mpeg4Part2 => "MPEG-4 Part 2".into(), + Codec::Av1 => "AV1".into(), Codec::MpegAudio => "MPEG Audio".into(), Codec::AacAdts => "AAC (ADTS)".into(), Codec::AacLatm => "AAC (LATM)".into(), Codec::Ac3 => "AC-3".into(), Codec::Eac3 => "E-AC-3".into(), Codec::Dts => "DTS".into(), + Codec::Opus => "Opus".into(), Codec::TrueHd => "Dolby TrueHD".into(), Codec::LpcmBluray => "LPCM (Blu-ray)".into(), Codec::LpcmDvd => "LPCM (DVD)".into(), @@ -220,10 +235,13 @@ impl Codec { Codec::Mpeg1Video | Codec::Mpeg2Video => Id::Mpeg2Video, Codec::H264 => Id::H264, Codec::Hevc => Id::Hevc, + Codec::Mpeg4Part2 => Id::Mpeg4Video, + Codec::Av1 => Id::Av1, Codec::MpegAudio => Id::Mp2, Codec::AacAdts | Codec::AacLatm => Id::Aac, Codec::Ac3 => Id::Ac3, Codec::Eac3 => Id::Eac3, + Codec::Opus => Id::Opus, Codec::LpcmBluray | Codec::LpcmDvd => Id::Pcm, Codec::Dts | Codec::TrueHd | Codec::Subtitle(_) | Codec::Unknown(_) => Id::Unknown, } @@ -232,13 +250,14 @@ impl Codec { /// The kind of media. pub fn kind(&self) -> Kind { match self { - Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::H264 | Codec::Hevc => Kind::Video, + Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::H264 | Codec::Hevc | Codec::Mpeg4Part2 | Codec::Av1 => Kind::Video, Codec::MpegAudio | Codec::AacAdts | Codec::AacLatm | Codec::Ac3 | Codec::Eac3 | Codec::Dts + | Codec::Opus | Codec::TrueHd | Codec::LpcmBluray | Codec::LpcmDvd => Kind::Audio, @@ -280,11 +299,14 @@ pub struct Unit { pub pts: Option, /// See `pts`. pub dts: Option, - /// Decoding can start here (I / IDR / IRAP pictures; every audio frame). + /// Decoding can start here (I / IDR / IRAP pictures, MPEG-4 Part 2 I-VOPs, AV1 units whose + /// packet sets the random access indicator; every audio frame). pub key: bool, - /// No other unit depends on it (B pictures of MPEG-1/2 video, non-reference H.264/HEVC). + /// No other unit depends on it (B pictures of MPEG-1/2 video, MPEG-4 Part 2 B-VOPs, + /// non-reference H.264/HEVC). pub disposable: bool, - /// Bytes of elementary stream. + /// Bytes of elementary stream (for AV1, with its start codes and emulation prevention + /// bytes). pub size: u32, /// TS: byte offset of the packet holding the first byte; PS: byte offset of its PES packet. pub(crate) pos: u64, @@ -305,6 +327,59 @@ pub struct LpcmFormat { pub bits: u32, } +/// An Opus stream's channel configuration (the Opus audio descriptor of the Opus transport +/// draft, with the fixed configurations of its table 4-3 written out) and its trims. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OpusConfig { + /// Output channels. + pub channels: u8, + /// Channel mapping family (RFC 7845 §5.1.1): 0, 1 or 255. + pub family: u8, + /// Opus streams in each access unit. + pub streams: u8, + /// Streams that decode to two channels. + pub coupled: u8, + /// For each output channel, the coded channel it is taken from, or 255 for silence. + pub mapping: Vec, + /// The units whose control header carries a start or end trim, in unit order. + pub trims: Vec, +} + +/// Samples at 48 kHz that a unit's control header says to discard. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OpusTrim { + /// Index of the unit in [`Stream::units`]. + pub unit: usize, + /// Samples to discard from the start of the unit. + pub start: u16, + /// Samples to discard from the end of the unit. + pub end: u16, +} + +impl OpusConfig { + /// The `OpusHead` identification header (RFC 7845 §5.1) for this configuration. Its pre-skip + /// is the sum of the start trims of the units that open the stream (units 0, 1, 2 and so on, + /// as long as each one has a start trim), at most 65 535; a start trim later in the stream, + /// after a discontinuity, stays in [`OpusConfig::trims`] only. Its input sample rate is 48 kHz + /// and its output gain 0. + pub fn opus_head(&self) -> Vec { + let pre_skip = + self.trims.iter().enumerate().take_while(|&(k, t)| t.unit == k && t.start > 0).fold(0u16, |a, (_, t)| a.saturating_add(t.start)); + let mut v = b"OpusHead".to_vec(); + v.push(1); + v.push(self.channels); + v.extend_from_slice(&pre_skip.to_le_bytes()); + v.extend_from_slice(&48_000u32.to_le_bytes()); + v.extend_from_slice(&0i16.to_le_bytes()); + v.push(self.family); + if self.family != 0 { + v.extend_from_slice(&[self.streams, self.coupled]); + v.extend_from_slice(&self.mapping); + } + v + } +} + /// Where a stream's PES packets come from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StreamId { @@ -334,6 +409,13 @@ pub struct Stream { pub units: Vec, /// DVD LPCM: the sample format. pub lpcm: Option, + /// Opus: the channel configuration from the PMT's Opus audio descriptor, and the trims of the + /// units' control headers. `None` when the descriptor is missing or not valid. + pub opus: Option, + /// AV1: the first four bytes of an ISOBMFF `av1C` record, from the PMT's AV1 video + /// descriptor (marker and version, profile and level, tier and color format, initial + /// presentation delay). `None` without a valid descriptor. + pub av1c: Option<[u8; 4]>, /// PES packets seen. pub pes_packets: u64, /// Bytes of payload ignored because the stream could not be split (e.g. before the first @@ -347,16 +429,24 @@ impl Stream { self.codec.kind() } /// What a decoder needs for this stream, in the container-neutral form the codec crates take: - /// the codec ([`Codec::codec_id`]) and, for DVD LPCM, the sample format (big-endian). These - /// streams carry their configuration in band, so `extradata` is empty: H.264 and HEVC are - /// Annex B with their parameter sets, AAC is ADTS or LATM frames, and a Blu-ray LPCM packet - /// starts with its own 4-byte format header. + /// the codec ([`Codec::codec_id`]) and, for DVD LPCM, the sample format (big-endian). Opus + /// gets its `OpusHead` header ([`OpusConfig::opus_head`]), 48 kHz and its channel count, and + /// AV1 the four bytes of [`Stream::av1c`]. The other streams carry their configuration in + /// band, so `extradata` is empty: H.264 and HEVC are Annex B with their parameter sets, + /// MPEG-4 Part 2 has its configuration headers before its keyframes, AAC is ADTS or LATM + /// frames, and a Blu-ray LPCM packet starts with its own 4-byte format header. pub fn codec_params(&self) -> crate::CodecParams { let mut p = crate::CodecParams::new(self.codec.codec_id()); if let Some(f) = self.lpcm { let n = |v: u32| u16::try_from(v).unwrap_or(0); p = p.with_sample_rate(f.sample_rate).with_channels(n(f.channels)).with_pcm(crate::PcmFormat::int(n(f.bits), true, true)); } + if let (Codec::Opus, Some(o)) = (&self.codec, &self.opus) { + p = p.with_sample_rate(48_000).with_channels(u16::from(o.channels)).with_extradata(o.opus_head()); + } + if let (Codec::Av1, Some(c)) = (&self.codec, self.av1c) { + p = p.with_extradata(c.to_vec()); + } p } /// First and last presentation timestamps (90 kHz) of the stream's units. @@ -397,7 +487,8 @@ impl File { self.streams.iter().position(|s| s.kind() == kind && !s.units.is_empty() && f(&s.codec)) } - /// Read access unit `i` of stream `s`. + /// Read access unit `i` of stream `s`. An AV1 unit comes back in the low overhead bitstream + /// format ([`Codec::Av1`]), so it can be shorter than [`Unit::size`]. pub fn read_unit(&self, src: &S, s: usize, i: usize) -> Result> { let st = self.streams.get(s).ok_or_else(|| Error::Invalid("no such stream".into()))?; let u = st.units.get(i).ok_or_else(|| Error::Invalid("no such unit".into()))?; @@ -413,6 +504,9 @@ impl File { if out.len() < u.size as usize { return Err(Error::Invalid(format!("unit {i} truncated ({} of {} bytes)", out.len(), u.size))); } + if st.codec == Codec::Av1 { + es::av1_obus(&mut out); + } Ok(out) } } diff --git a/crates/media/src/mpegts/mux/mod.rs b/crates/media/src/mpegts/mux/mod.rs index 7e7ced7918..89f5ba8fd8 100644 --- a/crates/media/src/mpegts/mux/mod.rs +++ b/crates/media/src/mpegts/mux/mod.rs @@ -51,6 +51,8 @@ mod av1; mod pes; mod psi; +pub(crate) use psi::OPUS_DESCRIPTOR_EXTENSION; + use std::fmt; use std::io::{self, Write}; diff --git a/crates/media/src/mpegts/ps.rs b/crates/media/src/mpegts/ps.rs index d044c01f45..effc7b92c0 100644 --- a/crates/media/src/mpegts/ps.rs +++ b/crates/media/src/mpegts/ps.rs @@ -247,6 +247,8 @@ pub(crate) fn scan(src: &S, mpeg1: bool) -> Result language: None, units: Vec::new(), lpcm, + opus: None, + av1c: None, pes_packets: 0, skipped_bytes: 0, }; diff --git a/crates/media/src/mpegts/tests.rs b/crates/media/src/mpegts/tests.rs index b9cb1af3b7..842dc43625 100644 --- a/crates/media/src/mpegts/tests.rs +++ b/crates/media/src/mpegts/tests.rs @@ -5,6 +5,7 @@ use super::*; mod hostile; +mod opus_av1_mpeg4; fn ts_bytes(prefix: u8, v: i64) -> [u8; 5] { let v = v & ((1 << 33) - 1); @@ -1035,6 +1036,8 @@ fn oversized_unit_is_refused_without_reserving_it() { language: None, units: vec![Unit { pts: None, dts: None, key: true, disposable: false, size: u32::MAX, pos: 0, offset: 0, picture: None }], lpcm: None, + opus: None, + av1c: None, pes_packets: 0, skipped_bytes: 0, }], diff --git a/crates/media/src/mpegts/tests/hostile.rs b/crates/media/src/mpegts/tests/hostile.rs index a0503fc0c1..5f4d09b4b5 100644 --- a/crates/media/src/mpegts/tests/hostile.rs +++ b/crates/media/src/mpegts/tests/hostile.rs @@ -57,13 +57,13 @@ fn ps_seed() -> Vec { #[test] fn hostile_input_never_panics() { - let mut seeds = vec![ts_seed(false), ts_seed(true), ps_seed()]; + let mut seeds = vec![ts_seed(false), ts_seed(true), ps_seed(), super::opus_av1_mpeg4::seed()]; seeds.push(work_tests::big_program_stream(false, 8).0); seeds.push(work_tests::big_program_stream(true, 8).0); // fewer rounds than FilmCraft's 40 000: tests here build without optimisation, and the two // large program streams cost a megabyte of window refill per unit read for (i, s) in seeds.iter().enumerate() { - craft_media_testkit::hostile::hammer(&format!("mpegts seed {i}"), s, if i < 3 { 4_000 } else { 150 }, exercise); + craft_media_testkit::hostile::hammer(&format!("mpegts seed {i}"), s, if i < 4 { 4_000 } else { 150 }, exercise); } } @@ -83,6 +83,9 @@ fn elementary_stream_frame_parsers_never_panic() { Codec::TrueHd, Codec::LpcmBluray, Codec::LpcmDvd, + Codec::Mpeg4Part2, + Codec::Av1, + Codec::Opus, Codec::Unknown(0x55), ]; let mut ac3 = vec![0x0B, 0x77, 0, 0, 30, 0x40]; diff --git a/crates/media/src/mpegts/tests/opus_av1_mpeg4.rs b/crates/media/src/mpegts/tests/opus_av1_mpeg4.rs new file mode 100644 index 0000000000..6375fb3981 --- /dev/null +++ b/crates/media/src/mpegts/tests/opus_av1_mpeg4.rs @@ -0,0 +1,279 @@ +//! Opus, AV1 and MPEG-4 Part 2 streams built by hand from the carriage rules: the Opus transport +//! draft (control headers, the Opus audio descriptor), Carriage of AV1 in MPEG-2 TS (start codes, +//! emulation prevention, the AV1 video descriptor) and stream type 0x10. + +use super::super::ts::opus_config; +use super::*; + +const OPUS_PID: u16 = 0x1100; +const AV1_PID: u16 = 0x1200; +const MPEG4_PID: u16 = 0x1300; + +/// The registration descriptor "Opus" and an Opus audio descriptor with this channel_config_code +/// and the bytes after it. +fn opus_desc(code: &[u8]) -> Vec { + let mut d = vec![0x05, 4, b'O', b'p', b'u', b's', 0x7F, 1 + code.len() as u8, 0x80]; + d.extend_from_slice(code); + d +} + +/// An opus_control_header for `size` payload bytes. +fn control(size: usize, start: Option, end: Option, ext: Option<&[u8]>) -> Vec { + let flags = 0xE0 | if start.is_some() { 0x10 } else { 0 } | if end.is_some() { 0x08 } else { 0 } | if ext.is_some() { 0x04 } else { 0 }; + let mut v = vec![0x7F, flags]; + v.extend(std::iter::repeat_n(0xFF, size / 255)); + v.push((size % 255) as u8); + for t in [start, end].into_iter().flatten() { + v.extend_from_slice(&t.to_be_bytes()); + } + if let Some(e) = ext { + v.push(e.len() as u8); + v.extend_from_slice(e); + } + v +} + +/// `n` bytes of an Opus packet: a TOC byte, then filler. +fn opus_packet(n: usize, seed: u8) -> Vec { + let mut v = vec![0xFC]; + v.extend((1..n).map(|i| (i as u8).wrapping_mul(7) ^ seed)); + v +} + +fn opus_mux(code: &[u8]) -> TsMux { + let mut mux = TsMux::new(false); + mux.psi_full(&[(0x06, OPUS_PID, opus_desc(code))], OPUS_PID); + mux +} + +/// A transport stream packet on `pid` that starts a PES packet and sets the random access +/// indicator; `payload` is at most 182 bytes. +fn random_access_packet(mux: &mut TsMux, pid: u16, payload: &[u8]) { + let cc = mux.cc.entry(pid).or_insert(0); + let al = 183 - payload.len(); + let mut p = vec![0x47, 0x40 | (pid >> 8) as u8, pid as u8, 0x30 | *cc, al as u8, 0x40]; + p.extend(std::iter::repeat_n(0xFF, al - 1)); + p.extend_from_slice(payload); + *cc = (*cc + 1) & 15; + mux.out.extend(p); +} + +/// A transport stream packet on `pid` that sets the unit start indicator and carries only an +/// adaptation field, with the random access indicator set when `random_access` is. +fn adaptation_only_start(mux: &mut TsMux, pid: u16, random_access: bool) { + let cc = *mux.cc.entry(pid).or_insert(0); + let mut p = vec![0x47, 0x40 | (pid >> 8) as u8, pid as u8, 0x20 | cc, 183, if random_access { 0x40 } else { 0 }]; + p.extend(std::iter::repeat_n(0xFF, 182)); + mux.out.extend(p); +} + +/// Opus, AV1 and MPEG-4 Part 2 streams in one program, for the hostile-input sweep. +pub(super) fn seed() -> Vec { + let mut mux = TsMux::new(false); + let av1 = vec![0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x08, 0x0C, 0xC0]; + mux.psi_full(&[(0x06, OPUS_PID, opus_desc(&[0x02])), (0x06, AV1_PID, av1), (0x10, MPEG4_PID, Vec::new())], OPUS_PID); + for k in 0..6i64 { + let mut au = control(40, (k == 0).then_some(312), None, Some(&[1, 2])); + au.extend(opus_packet(40, k as u8)); + au.extend(control(3, None, None, None)); + au.extend(opus_packet(3, k as u8)); + mux.pes(OPUS_PID, &pes(0xBD, Some(1800 * k), None, &au, true)); + let tu = [0, 0, 1, 0x12, 0x00, 0, 0, 1, 0x0A, 0x04, 0, 0, 3, 0, 0x7F, 0, 0, 1, 0x30, 0x10, 0x20]; + mux.pes(AV1_PID, &pes(0xBD, Some(3600 * k), None, &tu, true)); + let vop = [0, 0, 1, 0xB6, if k == 0 { 0x10 } else { 0x50 }, 1, 2, 3]; + mux.pes(MPEG4_PID, &pes(0xE0, Some(3600 * k), None, &vop, true)); + } + mux.out +} + +#[test] +fn opus_access_units_are_cut_by_their_control_headers() { + let mut mux = opus_mux(&[0x02]); + let (a, b, c, d) = (opus_packet(600, 1), opus_packet(5, 2), opus_packet(7, 3), opus_packet(10, 4)); + // one PES packet: an access unit with a start trim and a control extension, a plain one, and + // one without a control header that runs to the end of the packet + let mut first = control(a.len(), Some(312), None, Some(&[9, 9, 9])); + first.extend(&a); + first.extend(control(b.len(), None, None, None)); + first.extend(&b); + first.extend(&c); + mux.pes(OPUS_PID, &pes(0xBD, Some(90_000), None, &first, true)); + let mut second = control(d.len(), None, Some(100), None); + second.extend(&d); + mux.pes(OPUS_PID, &pes(0xBD, Some(91_800), None, &second, true)); + let f = open(&mux.out).unwrap(); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + let s = &f.streams[0]; + assert_eq!((s.codec.clone(), s.kind(), s.skipped_bytes), (Codec::Opus, Kind::Audio, 0)); + let units: Vec> = (0..s.units.len()).map(|n| f.read_unit(&mux.out, 0, n).unwrap()).collect(); + assert_eq!(units, [a, b, c, d]); + // the PES timestamps belong to the first access unit of each packet + assert_eq!(s.units.iter().map(|u| u.pts).collect::>(), [Some(90_000), None, None, Some(91_800)]); + assert!(s.units.iter().all(|u| u.key)); + let o = s.opus.as_ref().unwrap(); + assert_eq!(o.trims, [OpusTrim { unit: 0, start: 312, end: 0 }, OpusTrim { unit: 3, start: 0, end: 100 }]); +} + +#[test] +fn an_opus_control_header_may_cross_packet_boundaries() { + // the second header starts at every offset around the end of the first TS packet's payload + for len in 150..200 { + let mut mux = opus_mux(&[0x01]); + let (a, b) = (opus_packet(len, 5), opus_packet(300, 6)); + let mut au = control(a.len(), None, None, None); + au.extend(&a); + au.extend(control(b.len(), Some(80), Some(20), None)); + au.extend(&b); + mux.pes(OPUS_PID, &pes(0xBD, Some(1000), None, &au, true)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 2, "len {len}"); + assert_eq!((f.read_unit(&mux.out, 0, 0).unwrap(), f.read_unit(&mux.out, 0, 1).unwrap()), (a, b), "len {len}"); + assert_eq!(s.opus.as_ref().unwrap().trims, [OpusTrim { unit: 1, start: 80, end: 20 }], "len {len}"); + } +} + +#[test] +fn opus_access_units_past_their_packet_are_dropped() { + let mut mux = opus_mux(&[0x02]); + // a payload size of 1000 in a packet that holds 50 bytes of it + let mut cut = control(1000, None, None, None); + cut.extend(opus_packet(50, 1)); + mux.pes(OPUS_PID, &pes(0xBD, Some(0), None, &cut, true)); + // a payload size past the largest unit: 0xFF bytes for 130 MiB, then the packet ends + let mut huge = vec![0x7F, 0xE0]; + huge.extend(std::iter::repeat_n(0xFF, 535_000)); + mux.pes(OPUS_PID, &pes(0xBD, Some(1800), None, &huge, false)); + let good = opus_packet(20, 2); + let mut au = control(good.len(), None, None, None); + au.extend(&good); + mux.pes(OPUS_PID, &pes(0xBD, Some(3600), None, &au, true)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 1); + assert_eq!(s.units[0].pts, Some(3600)); + assert_eq!(f.read_unit(&mux.out, 0, 0).unwrap(), good); + assert!(s.skipped_bytes >= 50 + 535_000, "{} bytes skipped", s.skipped_bytes); +} + +#[test] +fn opus_channel_configurations_follow_the_draft_table() { + let config = |code: &[u8]| opus_config(&opus_desc(code)).map(|o| (o.channels, o.family, o.streams, o.coupled, o.mapping)); + // dual mono as one coupled stream and as two mono streams + assert_eq!(config(&[0x00]), Some((2, 255, 1, 1, vec![0, 1]))); + assert_eq!(config(&[0x80]), Some((2, 255, 2, 0, vec![0, 1]))); + assert_eq!(config(&[0x03]), Some((3, 1, 2, 1, vec![0, 2, 1]))); + assert_eq!(config(&[0x07]), Some((7, 1, 4, 3, vec![0, 4, 1, 2, 3, 5, 6]))); + // the same orders with a mono stream per channel + assert_eq!(config(&[0x82]), Some((2, 1, 2, 0, vec![0, 1]))); + assert_eq!(config(&[0x88]), Some((8, 1, 8, 0, vec![0, 1, 2, 3, 4, 5, 6, 7]))); + for reserved in [0x09, 0x7F, 0x89, 0xFF] { + assert_eq!(config(&[reserved]), None, "{reserved:#x}"); + } + // explicit: 3 channels, family 1, 2 streams (01), 1 coupled (01), mapping 0 2 1 (00 10 01) + assert_eq!(config(&[0x81, 3, 1, 0b0101_0010, 0b0100_0000]), Some((3, 1, 2, 1, vec![0, 2, 1]))); + // a silent channel is the all-ones mapping value: 2 streams (1), none coupled (00), mapping + // silence 0 (11 00) + assert_eq!(config(&[0x81, 2, 255, 0b1001_1000]), Some((2, 255, 2, 0, vec![255, 0]))); + // no channels, a reserved family, more streams than channels, a mapping past the coded + // channels, too few bytes + assert_eq!(config(&[0x81, 0, 0]), None); + assert_eq!(config(&[0x81, 2, 2, 0]), None); + assert_eq!(config(&[0x81, 3, 1, 0xFF, 0xFF]), None); + // two streams, none coupled: mapping values take 2 bits, and 2 names no coded channel + // (1, 00, then 10 00) + assert_eq!(config(&[0x81, 2, 255, 0b1001_0000]), None); + assert_eq!(config(&[0x81, 3, 1]), None); + // family 1 stops at 8 channels; family 0 at 2 + assert_eq!(config(&[0x81, 9, 1, 0, 0, 0, 0, 0]), None); + assert_eq!(config(&[0x81, 3, 0]), None); +} + +#[test] +fn the_pre_skip_counts_only_the_start_trims_that_open_the_stream() { + let pre_skip = |trims: &[(usize, u16, u16)]| { + let mut o = opus_config(&opus_desc(&[0x02])).unwrap(); + o.trims = trims.iter().map(|&(unit, start, end)| OpusTrim { unit, start, end }).collect(); + let head = o.opus_head(); + u16::from_le_bytes([head[10], head[11]]) + }; + assert_eq!(pre_skip(&[]), 0); + // a lead-in longer than one access unit, then a start trim after a discontinuity + assert_eq!(pre_skip(&[(0, 960, 0), (1, 960, 0), (2, 312, 0), (40, 500, 0)]), 2232); + // an end trim on the first unit stops the lead-in + assert_eq!(pre_skip(&[(0, 0, 100), (1, 312, 0)]), 0); + assert_eq!(pre_skip(&[(3, 312, 0)]), 0); + assert_eq!(pre_skip(&[(0, 60_000, 0), (1, 60_000, 0)]), u16::MAX); +} + +#[test] +fn av1_units_come_back_as_obus() { + let mut mux = TsMux::new(false); + // hdr_wcg_idc 3 (11), a reserved bit (0), initial_presentation_delay_present (1), delay 3 + // (0011) + let desc = vec![0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x08, 0x0C, 0b1101_0011]; + mux.psi_full(&[(0x06, AV1_PID, desc)], AV1_PID); + // a temporal delimiter; a sequence header with obu_size 4 whose payload 00 00 00 7F carries + // an emulation prevention byte, and a stray byte after it; a frame OBU without obu_size + let key = [0, 0, 1, 0x12, 0x00, 0, 0, 1, 0x0A, 0x04, 0, 0, 3, 0, 0x7F, 0x55, 0, 0, 1, 0x30, 0x10, 0x20, 0x30]; + random_access_packet(&mut mux, AV1_PID, &pes(0xBD, Some(3600), None, &key, true)); + let next = [0, 0, 1, 0x32, 0x02, 0xAA, 0xBB]; + mux.pes(AV1_PID, &pes(0xBD, Some(7200), None, &next, true)); + // null packets, so the file holds the five packets the probe looks for + mux.pes(0x1FFF, &[0xFF; 184 * 2]); + let f = open(&mux.out).unwrap(); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + let s = &f.streams[0]; + assert_eq!((s.codec.clone(), s.kind(), s.codec.codec_id()), (Codec::Av1, Kind::Video, crate::CodecId::Av1)); + assert_eq!(s.av1c, Some([0x81, 0x08, 0x0C, 0b0001_0011])); + assert_eq!(s.codec_params().extradata, [0x81, 0x08, 0x0C, 0b0001_0011]); + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [true, false]); + assert_eq!(f.read_unit(&mux.out, 0, 0).unwrap(), [0x0A, 0x04, 0, 0, 0, 0x7F, 0x32, 0x03, 0x10, 0x20, 0x30]); + assert_eq!(f.read_unit(&mux.out, 0, 1).unwrap(), [0x32, 0x02, 0xAA, 0xBB]); +} + +#[test] +fn an_adaptation_field_only_unit_start_keeps_the_random_access_indicator_of_the_pes_packet() { + let tu = [0, 0, 1, 0x12, 0x00, 0, 0, 1, 0x32, 0x02, 0xAA, 0xBB]; + for first_is_key in [true, false] { + let mut mux = TsMux::new(false); + let desc = vec![0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x08, 0x0C, 0xC0]; + mux.psi_full(&[(0x06, AV1_PID, desc)], AV1_PID); + // the PES header ends in the next packet; an adaptation-field-only unit start with the + // other indicator comes between the two + let first = pes(0xBD, Some(3600), None, &tu, true); + if first_is_key { + random_access_packet(&mut mux, AV1_PID, &first[..5]); + } else { + mux.packet(AV1_PID, true, &first[..5]); + } + adaptation_only_start(&mut mux, AV1_PID, !first_is_key); + mux.packet(AV1_PID, false, &first[5..]); + mux.pes(AV1_PID, &pes(0xBD, Some(7200), None, &tu, true)); + mux.pes(0x1FFF, &[0xFF; 184 * 2]); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [first_is_key, false], "first is key: {first_is_key}"); + } +} + +#[test] +fn mpeg4_part2_units_take_their_flags_from_the_first_vop() { + let mut mux = TsMux::new(false); + mux.psi(&[(0x10, MPEG4_PID)]); + // visual object sequence and VOL headers, then an I-VOP; a P-VOP whose data goes on in a PES + // packet without a timestamp; a B-VOP + let i_vop = [0, 0, 1, 0xB0, 0x01, 0, 0, 1, 0x00, 0, 0, 1, 0x20, 0x00, 0x84, 0, 0, 1, 0xB6, 0x10, 1, 2]; + let p_vop = [0, 0, 1, 0xB6, 0x50, 3, 4]; + let more = [5u8; 300]; + let b_vop = [0, 0, 1, 0xB6, 0x90, 6, 7]; + mux.pes(MPEG4_PID, &pes(0xE0, Some(3600), None, &i_vop, true)); + mux.pes(MPEG4_PID, &pes(0xE0, Some(7200), None, &p_vop, true)); + mux.pes(MPEG4_PID, &pes(0xE0, None, None, &more, true)); + mux.pes(MPEG4_PID, &pes(0xE0, Some(10_800), None, &b_vop, true)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!((s.codec.clone(), s.kind(), s.codec.codec_id()), (Codec::Mpeg4Part2, Kind::Video, crate::CodecId::Mpeg4Video)); + assert_eq!(s.units.iter().map(|u| (u.key, u.disposable)).collect::>(), [(true, false), (false, false), (false, true)]); + assert_eq!(f.read_unit(&mux.out, 0, 1).unwrap(), [&p_vop[..], &more].concat()); +} diff --git a/crates/media/src/mpegts/ts.rs b/crates/media/src/mpegts/ts.rs index 1d28bb736a..7c9ea716ef 100644 --- a/crates/media/src/mpegts/ts.rs +++ b/crates/media/src/mpegts/ts.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use super::es::Splitter; use super::pes::{self, PesHeader}; -use super::{ByteSource, ClockRange, Codec, Error, File, Format, Result, Stream, StreamId, Unit, Unwrap, read_some}; +use super::{ByteSource, ClockRange, Codec, Error, File, Format, OpusConfig, Result, Stream, StreamId, Unit, Unwrap, read_some}; /// Byte-wise table for the MSB-first CRC-32 (polynomial 0x04C11DB7): entry `i` is the CRC register /// after shifting the byte `i` through eight bit steps. @@ -40,6 +40,8 @@ struct Packet<'a> { cc: u8, has_payload: bool, discontinuity: bool, + /// random_access_indicator of the adaptation field. + random_access: bool, pcr: Option, payload: &'a [u8], } @@ -65,6 +67,7 @@ fn packet(p: &[u8]) -> std::result::Result, Bad> { let mut start = 4; let mut pcr = None; let mut discontinuity = false; + let mut random_access = false; if afc & 2 != 0 { let al = p[4] as usize; start = 5 + al; @@ -74,6 +77,7 @@ fn packet(p: &[u8]) -> std::result::Result, Bad> { if al > 0 { let flags = p[5]; discontinuity = flags & 0x80 != 0; + random_access = flags & 0x40 != 0; if flags & 0x10 != 0 && al >= 7 { let base = ((p[6] as i64) << 25) | ((p[7] as i64) << 17) | ((p[8] as i64) << 9) | ((p[9] as i64) << 1) | (p[10] as i64 >> 7); let ext = (((p[10] & 1) as i64) << 8) | p[11] as i64; @@ -82,7 +86,7 @@ fn packet(p: &[u8]) -> std::result::Result, Bad> { } } let has_payload = afc & 1 != 0; - Ok(Packet { pusi, pid, cc, has_payload, discontinuity, pcr, payload: if has_payload { &p[start..188] } else { &[] } }) + Ok(Packet { pusi, pid, cc, has_payload, discontinuity, random_access, pcr, payload: if has_payload { &p[start..188] } else { &[] } }) } /// `(transport_error_indicator, scrambled)` of a packet whose first byte is the sync byte (H.222.0 @@ -230,6 +234,31 @@ struct EsState { asm: PesAsm, cc: Option, dup: DupGuard, + /// The packet that started the PES packet being assembled set random_access_indicator. + random_access: bool, +} + +impl EsState { + /// Reassemble PES packets from packet `pk` (at file offset `pos`) and pass their payload to + /// the splitter. + fn feed(&mut self, pk: &Packet<'_>, pos: u64, unwrap: &mut Unwrap) { + // `PesAsm` passes over an adaptation-field-only unit start, so its indicator does not + // belong to the PES packet being assembled + if pk.pusi && !pk.payload.is_empty() { + self.random_access = pk.random_access; + } + let (hdr, bytes) = self.asm.packet(pk.pusi, pk.payload); + if let Some(h) = hdr { + self.stream.pes_packets += 1; + let pts = h.pts.map(|t| unwrap.unwrap(t)); + let dts = h.dts.map(|t| unwrap.unwrap(t)); + self.split.pes_start(pts, dts); + if std::mem::take(&mut self.random_access) { + self.split.random_access(); + } + } + self.split.feed(pos, bytes); + } } /// Map a PMT stream_type (and the ES descriptors) to a codec. `hdmv`: a Blu-ray / AVCHD stream @@ -253,6 +282,7 @@ pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { 0x03 | 0x04 => Codec::MpegAudio, 0x0F => Codec::AacAdts, 0x11 => Codec::AacLatm, + 0x10 => Codec::Mpeg4Part2, 0x1B => Codec::H264, 0x24 => Codec::Hevc, 0x80 if hdmv => Codec::LpcmBluray, @@ -264,6 +294,10 @@ pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { 0x87 => Codec::Eac3, 0x90 if hdmv => Codec::Subtitle("PGS subtitles"), 0x92 if hdmv => Codec::Subtitle("Text subtitles"), + // the registration descriptors of the Opus transport draft (§4.3) and of Carriage of + // AV1 in MPEG-2 TS (§2.1) + 0x06 if reg == Some(*b"Opus") => Codec::Opus, + 0x06 if reg == Some(*b"AV01") => Codec::Av1, 0x06 => { if tags.contains(&0x6A) || reg == Some(*b"AC-3") { Codec::Ac3 @@ -283,6 +317,131 @@ pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { } } +/// The body of the first descriptor with this tag (and, for tag 0x7F, this extension tag, which +/// the returned body leaves out). +fn descriptor(desc: &[u8], tag: u8, extension: Option) -> Option<&[u8]> { + let mut i = 0; + while i + 2 <= desc.len() { + let (t, len) = (desc[i], desc[i + 1] as usize); + let body = desc.get(i + 2..i + 2 + len)?; + match extension { + None if t == tag => return Some(body), + Some(e) if t == tag && body.first() == Some(&e) => return Some(&body[1..]), + _ => {} + } + i += 2 + len; + } + None +} + +/// Bits needed for the values 0 to `n - 1`: ceil(log2(n)). +fn bits_for(n: u32) -> u32 { + if n <= 1 { 0 } else { 32 - (n - 1).leading_zeros() } +} + +/// The channel configuration of the Opus audio descriptor (Opus transport draft §5.3: tag 0x7F, +/// extension tag 0x80, the value the writer uses): a fixed configuration of table 4-3, or one +/// coded in full (channel_config_code 0x81). `None` for a reserved code or fields out of range. +pub(crate) fn opus_config(desc: &[u8]) -> Option { + let body = descriptor(desc, 0x7F, Some(super::mux::OPUS_DESCRIPTOR_EXTENSION))?; + let code = *body.first()?; + let fixed = |channels: u8, family: u8, streams: u8, coupled: u8, mapping: &[u8]| OpusConfig { + channels, + family, + streams, + coupled, + mapping: mapping.to_vec(), + trims: Vec::new(), + }; + let c = match code { + // two channels as one coupled stream, or as two mono streams, in no speaker order + 0x00 => fixed(2, 255, 1, 1, &[0, 1]), + 0x80 => fixed(2, 255, 2, 0, &[0, 1]), + 0x01 => fixed(1, 0, 1, 0, &[0]), + 0x02 => fixed(2, 0, 1, 1, &[0, 1]), + // the RFC 7845 §5.1.1.2 surround orders, with as many coupled streams as fit + 0x03 => fixed(3, 1, 2, 1, &[0, 2, 1]), + 0x04 => fixed(4, 1, 2, 2, &[0, 1, 2, 3]), + 0x05 => fixed(5, 1, 3, 2, &[0, 4, 1, 2, 3]), + 0x06 => fixed(6, 1, 4, 2, &[0, 4, 1, 2, 3, 5]), + 0x07 => fixed(7, 1, 4, 3, &[0, 4, 1, 2, 3, 5, 6]), + 0x08 => fixed(8, 1, 5, 3, &[0, 6, 1, 2, 3, 4, 5, 7]), + // the same orders with every channel in a mono stream + 0x82..=0x88 => { + let ch = code - 0x80; + fixed(ch, 1, ch, 0, &(0..ch).collect::>()) + } + 0x81 => opus_explicit(body.get(1..)?)?, + _ => return None, + }; + Some(c) +} + +/// An explicit Opus channel configuration: channel_count, mapping_family and, for a family above +/// 0, stream_count_minus_one, coupled_stream_count and the channel mapping in as few bits as the +/// draft gives each. +fn opus_explicit(b: &[u8]) -> Option { + let (&channels, &family) = (b.first()?, b.get(1)?); + if channels == 0 { + return None; + } + if family == 0 { + // one mono or stereo stream in coded order + return (channels <= 2).then(|| OpusConfig { + channels, + family, + streams: 1, + coupled: channels - 1, + mapping: (0..channels).collect(), + trims: Vec::new(), + }); + } + // family 1 is defined for 1 to 8 channels (RFC 7845 §5.1.1.2) + if !(family == 255 || family == 1 && channels <= 8) { + return None; + } + let bits = &b[2..]; + let mut at = 0u32; + let mut take = |n: u32| -> Option { + let mut v = 0u32; + for _ in 0..n { + let byte = *bits.get((at / 8) as usize)?; + v = v << 1 | u32::from(byte >> (7 - at % 8) & 1); + at += 1; + } + Some(v) + }; + let ch = u32::from(channels); + let streams = take(bits_for(ch))? + 1; + let coupled = take(bits_for(streams + 1))?; + // a mapping entry is one byte, 255 meaning silence (RFC 7845 §5.1.1) + if streams > ch || coupled > streams || streams + coupled > 255 { + return None; + } + let width = bits_for(streams + coupled + 1); + let silence = (1u32 << width) - 1; + let mut mapping = Vec::with_capacity(usize::from(channels)); + for _ in 0..channels { + let m = take(width)?; + match m { + m if m == silence => mapping.push(255), + m if m < streams + coupled => mapping.push(m as u8), + _ => return None, + } + } + Some(OpusConfig { channels, family, streams: streams as u8, coupled: coupled as u8, mapping, trims: Vec::new() }) +} + +/// The AV1 video descriptor (Carriage of AV1 in MPEG-2 TS §2.2: tag 0x80, marker and version 1) +/// as the first four bytes of an `av1C` record: the descriptor's fourth byte holds hdr_wcg_idc +/// and a reserved bit where `av1C` has reserved zeros. +pub(crate) fn av1c(desc: &[u8]) -> Option<[u8; 4]> { + match descriptor(desc, 0x80, None)? { + &[0x81, b1, b2, b3, ..] => Some([0x81, b1, b2, b3 & 0x1F]), + _ => None, + } +} + fn language(desc: &[u8]) -> Option { let mut i = 0; while i + 2 <= desc.len() { @@ -369,10 +528,15 @@ fn add_pmt_streams(sec: &[u8], packet_size: usize, later: bool, es: &mut HashMap language: language(desc), units: Vec::new(), lpcm: None, + opus: if codec == Codec::Opus { opus_config(desc) } else { None }, + av1c: if codec == Codec::Av1 { av1c(desc) } else { None }, pes_packets: 0, skipped_bytes: 0, }; - es.insert(pid, EsState { stream, split: Splitter::new(&codec), asm: PesAsm::default(), cc: None, dup: DupGuard::default() }); + es.insert( + pid, + EsState { stream, split: Splitter::new(&codec), asm: PesAsm::default(), cc: None, dup: DupGuard::default(), random_access: false }, + ); order.push(pid); } changed || (later && es.keys().any(|p| !listed.contains(p))) @@ -595,14 +759,7 @@ pub(crate) fn scan(src: &S, packet_size: usize, sync_off } e.cc = Some(pk.cc); } - let (hdr, bytes) = e.asm.packet(pk.pusi, pk.payload); - if let Some(h) = hdr { - e.stream.pes_packets += 1; - let pts = h.pts.map(|t| unwrap.unwrap(t)); - let dts = h.dts.map(|t| unwrap.unwrap(t)); - e.split.pes_start(pts, dts); - } - e.split.feed(pos, bytes); + e.feed(&pk, pos, &mut unwrap); } // `p >= 1` here (the loop ran at least once or `resync` moved past the failed packet) off += p.max(1) as u64; @@ -640,6 +797,9 @@ pub(crate) fn scan(src: &S, packet_size: usize, sync_off e.split.finish(); e.stream.units = std::mem::take(&mut e.split.units); e.stream.skipped_bytes = e.split.skipped; + if let Some(o) = e.stream.opus.as_mut() { + o.trims = std::mem::take(&mut e.split.trims); + } if e.split.truncated { warnings.push(format!("PID {pid}: more than {} access units, the rest are not indexed", super::es::MAX_UNITS)); } @@ -729,7 +889,16 @@ mod dup_tests { #[test] fn a_discontinuity_packet_is_never_a_duplicate() { let payload = [7u8; 20]; - let pk = |discontinuity| Packet { pusi: true, pid: 0x100, cc: 3, has_payload: true, discontinuity, pcr: None, payload: &payload }; + let pk = |discontinuity| Packet { + pusi: true, + pid: 0x100, + cc: 3, + has_payload: true, + discontinuity, + random_access: false, + pcr: None, + payload: &payload, + }; let mut g = DupGuard::default(); assert!(!g.is_dup(&pk(false))); assert!(!g.is_dup(&pk(true)), "same counter and payload, but the stream restarts here"); @@ -745,6 +914,7 @@ mod dup_tests { cc: 3, has_payload, discontinuity, + random_access: false, pcr: None, payload: if has_payload { &payload } else { &[] }, }; diff --git a/crates/media/src/ogg/mod.rs b/crates/media/src/ogg/mod.rs index 850240f453..54ffc045eb 100644 --- a/crates/media/src/ogg/mod.rs +++ b/crates/media/src/ogg/mod.rs @@ -16,6 +16,10 @@ //! TOC-derived durations, the pre-skip, and end trimming of the final page, so a player can seek //! to any 48 kHz sample. //! +//! [`VorbisTiming`] does the same for Vorbis (Vorbis I §4.3.8 and §A.2): packet durations from the +//! block sizes of the modes in the setup header ([`VorbisModes`]), a nonzero starting position, +//! and end trimming of the final page. +//! //! [`PageWriter`] writes the pages of a logical bitstream, and [`opus_tags`] and //! [`vorbis_comment`] build the comment headers of Ogg Opus and Ogg Vorbis. //! @@ -32,8 +36,10 @@ use std::fmt; use std::io; pub use crate::source::{ByteSource, ReadSeekSource}; +pub use vorbis::{VorbisModes, VorbisTiming}; pub use write::{PAGE_TARGET_BYTES, PAGE_TARGET_PACKETS, PageWriter, opus_tags, vorbis_comment}; +mod vorbis; mod write; /// Errors from reading an Ogg file. @@ -1046,4 +1052,6 @@ pub use timing::{MAX_OPUS_GRANULE, OpusTiming, VorbisInfo, opus_packet_samples}; #[cfg(test)] mod tests; #[cfg(test)] +mod vorbis_tests; +#[cfg(test)] mod write_tests; diff --git a/crates/media/src/ogg/timing.rs b/crates/media/src/ogg/timing.rs index e01f39b4c3..e5485f507b 100644 --- a/crates/media/src/ogg/timing.rs +++ b/crates/media/src/ogg/timing.rs @@ -126,6 +126,10 @@ pub struct VorbisInfo { pub sample_rate: u32, /// Nominal bit rate in bits per second (0 or negative when not set). pub bitrate_nominal: i32, + /// The short block size in samples, as the header states it (Vorbis I allows 64 to 8192). + pub blocksize_0: u32, + /// The long block size in samples, as the header states it. + pub blocksize_1: u32, } impl VorbisInfo { @@ -138,6 +142,9 @@ impl VorbisInfo { channels: h[11], sample_rate: u32::from_le_bytes([h[12], h[13], h[14], h[15]]), bitrate_nominal: i32::from_le_bytes([h[20], h[21], h[22], h[23]]), + // two 4-bit exponents, the short block's in the low bits + blocksize_0: 1 << (h[28] & 0x0F), + blocksize_1: 1 << (h[28] >> 4), }) } } diff --git a/crates/media/src/ogg/vorbis.rs b/crates/media/src/ogg/vorbis.rs new file mode 100644 index 0000000000..c80d4ceb56 --- /dev/null +++ b/crates/media/src/ogg/vorbis.rs @@ -0,0 +1,447 @@ +//! Vorbis packet durations and stream timing, from the Vorbis I specification: the block sizes of +//! the identification header (§4.2.2), the modes at the end of the setup header (§4.2.4), the +//! samples a packet returns (§4.3.8) and the Ogg granule positions (§A.2). + +use super::{MAX_OPUS_GRANULE, Stream, VorbisInfo}; + +/// The most modes a setup header can declare (a 6-bit count plus one). +const MAX_MODES: usize = 64; + +/// What a Vorbis stream's packets need for their durations: the two block sizes and the block flag +/// of each mode. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VorbisModes { + /// The short and the long block size, in samples. + pub blocksizes: [u32; 2], + /// The block flag of each mode: `true` for the long block. + pub long: Vec, +} + +impl VorbisModes { + /// Reads the block sizes from the identification header and the modes from the setup header; + /// `None` when either is not a valid Vorbis I header. + /// + /// The setup header is walked from its start (codebooks, time-domain transforms, floors, + /// residues and mappings) to reach the modes, without building any decoder tables, so the cost + /// is one pass over the header's bits. + pub fn parse(identification: &[u8], setup: &[u8]) -> Option { + let info = VorbisInfo::parse(identification)?; + let [b0, b1] = [info.blocksize_0, info.blocksize_1]; + // Vorbis I is version 0, with channels and a sample rate (§4.2.2) + let version = u32::from_le_bytes([identification[7], identification[8], identification[9], identification[10]]); + if version != 0 + || info.channels == 0 + || info.sample_rate == 0 + || !(64..=8192).contains(&b0) + || !(64..=8192).contains(&b1) + || b0 > b1 + || identification[29] & 1 == 0 + { + return None; + } + let long = setup_modes(setup, info.channels)?; + Some(VorbisModes { blocksizes: [b0, b1], long }) + } + + /// The block size of an audio packet from its first byte (§4.3.1: a packet-type bit of 0, then + /// the mode number in `ilog(modes - 1)` bits); `None` for a packet that is not audio or names a + /// mode the setup header does not have. + pub fn blocksize(&self, first: u8) -> Option { + self.mode(first).map(|(_, long)| self.blocksizes[usize::from(long)]) + } + + /// The block size of an audio packet of `size` bytes starting with `prefix`; `None` also when + /// the packet ends inside its header, whose long blocks carry the previous and next window + /// flags after the mode number (§4.3.1), since a decoder drops such a packet. + fn packet_blocksize(&self, prefix: [u8; 2], size: u32) -> Option { + let (bits, long) = self.mode(prefix[0])?; + let header = 1 + bits + if long { 2 } else { 0 }; + (u64::from(size) * 8 >= u64::from(header)).then(|| self.blocksizes[usize::from(long)]) + } + + /// The width of the mode number and the block flag of the mode an audio packet's first byte + /// names. + fn mode(&self, first: u8) -> Option<(u32, bool)> { + if first & 1 != 0 { + return None; + } + let bits = ilog(self.long.len().saturating_sub(1) as u32); + let mode = usize::from(first >> 1) & ((1usize << bits) - 1); + self.long.get(mode).map(|&l| (bits, l)) + } +} + +/// Vorbis I §A.2 timing of a Vorbis stream, in samples at the stream's sample rate. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VorbisTiming { + /// Granule position of the first sample each packet returns. A packet's samples run from its + /// start for its duration; positions before 0 are samples to discard. + pub starts: Vec, + /// Samples each packet returns (§4.3.8): 0 for the first audio packet, which only primes the + /// decoder, and for packets that are not audio; otherwise a quarter of the previous audio + /// packet's block size plus a quarter of its own. + pub durations: Vec, + /// Samples to discard at the start: the first page's granule position states fewer samples + /// than its packets return (a negative starting position, at most the first two audio + /// packets' overlap). + pub skip: u32, + /// Granule position of the first sample to play: 0, or the positive start offset of a stream + /// that does not begin at time zero. + pub first: i64, + /// Playable samples from `first`, with the final page's end trimming applied. + pub total: i64, +} + +impl VorbisTiming { + /// Timing of the Vorbis stream `stream`, from its identification and setup headers and the + /// granule positions of its pages; `None` when the stream has no valid Vorbis headers. + /// + /// A granule position outside `0..=MAX_OPUS_GRANULE` is treated like a missing one, as + /// [`OpusTiming::of`](super::OpusTiming::of) does. + pub fn of(stream: &Stream) -> Option { + let modes = VorbisModes::parse(stream.headers.first()?, stream.headers.get(2)?)?; + Some(VorbisTiming::with_modes(stream, &modes)) + } + + /// Timing of `stream` with modes already read, for example from a stream whose headers came + /// from elsewhere. + pub fn with_modes(stream: &Stream, modes: &VorbisModes) -> VorbisTiming { + // Granule positions come straight from the file, so the arithmetic saturates. + let mut previous: Option = None; + // samples the first two audio packets return, the most a negative start can discard + let mut overlap = 0i64; + let mut audio = 0u8; + let durations: Vec = stream + .packets + .iter() + .map(|p| { + let Some(size) = modes.packet_blocksize(p.prefix, p.size) else { return 0 }; + let n = previous.map_or(0, |prev| prev / 4 + size / 4); + previous = Some(size); + if audio < 2 { + audio += 1; + overlap = overlap.saturating_add(i64::from(n)); + } + n + }) + .collect(); + let n = durations.len(); + let granule_of = |k: usize| stream.packets.get(k).and_then(|p| p.granule).filter(|g| (0..=MAX_OPUS_GRANULE).contains(g)); + let mut ends: Vec = vec![0; n]; + let mut cursor: Option = None; + let mut trimmed_end: Option = None; + let mut start: Option = None; + let mut i = 0; + while i < n { + // packets completing on the same page: i..=j, the last carries the page's granule + let mut j = i; + while j < n && granule_of(j).is_none() { + j += 1; + } + let sum = durations[i..j.min(n - 1) + 1].iter().fold(0i64, |a, &d| a.saturating_add(i64::from(d))); + let end = match (granule_of(j), cursor) { + // trailing packets without a granule (a truncated file): continue from the cursor + (None, c) => c.unwrap_or(0).saturating_add(sum), + // end trimming on the final page: keep the positions the packets would have + (Some(g), Some(c)) if stream.packets[j].eos && g < c.saturating_add(sum) => { + trimmed_end = Some(g); + c.saturating_add(sum) + } + // a page that returns no samples (only the priming packet) does not place the stream + (Some(g), None) if sum == 0 && !stream.packets[j].eos => { + ends[i..=j].fill(g); + i = j + 1; + continue; + } + // the first page with audio: its granule places the stream, which may start before + // or after 0 (§A.2) + (Some(g), None) => { + let s = g.saturating_sub(sum); + start = Some(s); + if stream.packets[j].eos && s < 0 { + // one page holds the whole stream: a granule below the samples it returns + // trims the end, not the start + trimmed_end = Some(g); + start = Some(0); + sum + } else { + g + } + } + // a discontinuity: trust the granule + (Some(g), Some(_)) => g, + }; + let mut e = end; + for k in (i..=j.min(n - 1)).rev() { + ends[k] = e; + e = e.saturating_sub(i64::from(durations[k])); + } + cursor = Some(end); + i = j + 1; + } + let starts: Vec = ends.iter().zip(&durations).map(|(e, &d)| e.saturating_sub(i64::from(d))).collect(); + let origin = start.unwrap_or(0); + // a negative start discards samples, never more than the first two audio packets overlap + let skip = origin.saturating_neg().clamp(0, overlap); + let first = origin.saturating_add(skip).max(0); + let end = trimmed_end.or(cursor).unwrap_or(0); + let total = end.saturating_sub(first).max(0); + VorbisTiming { starts, durations, skip: u32::try_from(skip).unwrap_or(u32::MAX), first, total } + } +} + +/// Number of bits needed to hold `x` (§9.2.1). +fn ilog(x: u32) -> u32 { + 32 - x.leading_zeros() +} + +/// Bits read least significant first (§2.1.4). +struct Bits<'a> { + data: &'a [u8], + pos: u64, +} + +impl Bits<'_> { + fn left(&self) -> u64 { + (self.data.len() as u64 * 8).saturating_sub(self.pos) + } + fn read(&mut self, n: u32) -> Option { + if u64::from(n) > self.left() { + return None; + } + let mut v = 0u32; + for k in 0..n { + let at = self.pos + u64::from(k); + let bit = (self.data[(at / 8) as usize] >> (at % 8)) & 1; + v |= u32::from(bit) << k; + } + self.pos += u64::from(n); + Some(v) + } + fn skip(&mut self, n: u64) -> Option<()> { + (n <= self.left()).then(|| self.pos += n) + } + fn zero(&mut self, n: u32) -> Option<()> { + (self.read(n)? == 0).then_some(()) + } +} + +/// The largest `r` with `r^dims <= entries` (§9.2.3). +pub(super) fn lookup1_values(entries: u32, dims: u32) -> u64 { + let fits = |r: u64| { + let mut p = 1u64; + for _ in 0..dims { + p = p.saturating_mul(r); + if p > u64::from(entries) { + return false; + } + } + true + }; + let (mut lo, mut hi) = (0u64, u64::from(entries)); + while lo < hi { + let mid = lo + (hi - lo).div_ceil(2); + if fits(mid) { lo = mid } else { hi = mid - 1 } + } + lo +} + +/// The block flag of each mode of a setup header (§4.2.4), passing over everything before them. +fn setup_modes(h: &[u8], channels: u8) -> Option> { + if !h.starts_with(b"\x05vorbis") { + return None; + } + let mut b = Bits { data: &h[7..], pos: 0 }; + let codebooks = b.read(8)? + 1; + for _ in 0..codebooks { + codebook(&mut b)?; + } + for _ in 0..b.read(6)? + 1 { + b.zero(16)?; + } + let floors = b.read(6)? + 1; + for _ in 0..floors { + floor(&mut b, codebooks)?; + } + let residues = b.read(6)? + 1; + for _ in 0..residues { + residue(&mut b, codebooks)?; + } + let mappings = b.read(6)? + 1; + for _ in 0..mappings { + mapping(&mut b, channels, floors, residues)?; + } + let count = b.read(6)? as usize + 1; + let mut long = Vec::with_capacity(count.min(MAX_MODES)); + for _ in 0..count { + let flag = b.read(1)? == 1; + b.zero(16)?; + b.zero(16)?; + if b.read(8)? >= mappings { + return None; + } + long.push(flag); + } + (b.read(1)? == 1).then_some(long) +} + +/// Passes over one codebook (§3.2.1). +fn codebook(b: &mut Bits<'_>) -> Option<()> { + if b.read(24)? != 0x56_4342 { + return None; + } + // a codebook of no dimensions is allowed and has no lookup values, as in the reference decoder + let dims = b.read(16)?; + let entries = b.read(24)?; + if b.read(1)? == 1 { + // ordered: runs of entries per length, each count in ilog(entries left) bits + let mut length = b.read(5)? + 1; + let mut entry = 0u32; + while entry < entries { + if length > 32 { + return None; + } + entry = entry.checked_add(b.read(ilog(entries - entry))?).filter(|&e| e <= entries)?; + length += 1; + } + } else { + let sparse = b.read(1)? == 1; + for _ in 0..entries { + if !sparse || b.read(1)? == 1 { + b.skip(5)?; + } + } + } + match b.read(4)? { + 0 => {} + kind @ (1 | 2) => { + // minimum value and delta, then the value width and the sequence flag + b.skip(32 + 32)?; + let width = u64::from(b.read(4)? + 1); + b.skip(1)?; + let values = match (kind, dims) { + (_, 0) => 0, + (1, _) => lookup1_values(entries, dims), + _ => u64::from(entries) * u64::from(dims), + }; + b.skip(values.checked_mul(width)?)?; + } + _ => return None, + } + Some(()) +} + +/// Passes over one floor configuration (§6.2.1, §7.2.2), whose books are among `codebooks`. +fn floor(b: &mut Bits<'_>, codebooks: u32) -> Option<()> { + match b.read(16)? { + 0 => { + // order, rate, bark map size, amplitude bits, amplitude offset, then the books + b.skip(8 + 16 + 16 + 6 + 8)?; + let books = b.read(4)? + 1; + for _ in 0..books { + if b.read(8)? >= codebooks { + return None; + } + } + Some(()) + } + 1 => floor1(b, codebooks), + _ => None, + } +} + +/// Passes over one residue configuration (§8.6.1), whose books are among `codebooks`. +fn residue(b: &mut Bits<'_>, codebooks: u32) -> Option<()> { + if b.read(16)? > 2 { + return None; + } + // begin, end, partition size, then the classifications and the classbook + b.skip(24 + 24 + 24)?; + let classifications = b.read(6)? + 1; + if b.read(8)? >= codebooks { + return None; + } + let mut books = 0u64; + for _ in 0..classifications { + let low = b.read(3)?; + let high = if b.read(1)? == 1 { b.read(5)? } else { 0 }; + books += u64::from((high << 3 | low).count_ones()); + } + for _ in 0..books { + if b.read(8)? >= codebooks { + return None; + } + } + Some(()) +} + +/// Passes over one mapping configuration (§4.2.4, mappings), whose submaps name one of `floors` +/// floors and one of `residues` residues. +fn mapping(b: &mut Bits<'_>, channels: u8, floors: u32, residues: u32) -> Option<()> { + b.zero(16)?; + let submaps = if b.read(1)? == 1 { b.read(4)? + 1 } else { 1 }; + if b.read(1)? == 1 { + let channel_bits = ilog(u32::from(channels) - 1); + for _ in 0..b.read(8)? + 1 { + let (magnitude, angle) = (b.read(channel_bits)?, b.read(channel_bits)?); + if magnitude == angle || magnitude >= u32::from(channels) || angle >= u32::from(channels) { + return None; + } + } + } + b.zero(2)?; + if submaps > 1 { + for _ in 0..channels { + if b.read(4)? >= submaps { + return None; + } + } + } + // per submap: an unused time configuration, the floor and the residue + for _ in 0..submaps { + b.skip(8)?; + if b.read(8)? >= floors || b.read(8)? >= residues { + return None; + } + } + Some(()) +} + +/// Passes over a floor 1 configuration (§7.2.2), whose books are among `codebooks`. The X list, +/// with its two implicit end points, holds at most 65 distinct values. +fn floor1(b: &mut Bits<'_>, codebooks: u32) -> Option<()> { + let partitions = b.read(5)?; + let mut classes = Vec::with_capacity(partitions as usize); + for _ in 0..partitions { + classes.push(b.read(4)? as usize); + } + let count = classes.iter().max().map_or(0, |&m| m + 1); + let mut dims = [0u32; 16]; + for d in dims.iter_mut().take(count) { + *d = b.read(3)? + 1; + let subclasses = b.read(2)?; + if subclasses != 0 && b.read(8)? >= codebooks { + return None; + } + // a subclass book is its number plus one, and 0 means none + for _ in 0..1u32 << subclasses { + if b.read(8)? > codebooks { + return None; + } + } + } + b.skip(2)?; + let range = b.read(4)?; + let points: u64 = classes.iter().map(|&c| u64::from(dims[c])).sum(); + if points + 2 > 65 { + return None; + } + let mut xs = vec![0u32, 1u32 << range]; + for _ in 0..points { + xs.push(b.read(range)?); + } + xs.sort_unstable(); + xs.windows(2).all(|w| w[0] != w[1]).then_some(()) +} diff --git a/crates/media/src/ogg/vorbis_tests.rs b/crates/media/src/ogg/vorbis_tests.rs new file mode 100644 index 0000000000..e84322099e --- /dev/null +++ b/crates/media/src/ogg/vorbis_tests.rs @@ -0,0 +1,359 @@ +//! Vorbis modes and timing on synthetic headers and packets. + +use super::vorbis::*; +use super::*; + +/// Bits written least significant first, as Vorbis reads them. +#[derive(Default)] +struct BitWriter { + bytes: Vec, + bits: u64, +} + +impl BitWriter { + fn put(&mut self, value: u32, n: u32) -> &mut Self { + for k in 0..n { + if self.bits.is_multiple_of(8) { + self.bytes.push(0); + } + let bit = ((value >> k) & 1) as u8; + let last = self.bytes.len() - 1; + self.bytes[last] |= bit << (self.bits % 8); + self.bits += 1; + } + self + } +} + +/// An identification header: one channel at 44.1 kHz, blocks of 256 and 2048 samples. +fn identification() -> Vec { + let mut h = b"\x01vorbis".to_vec(); + h.extend_from_slice(&0u32.to_le_bytes()); + h.push(1); + h.extend_from_slice(&44_100u32.to_le_bytes()); + h.extend_from_slice(&[0; 12]); + h.push(0xB8); + h.push(1); + h +} + +/// The smallest setup header: one codebook, floor 1, residue 0 and mapping, then `modes` with the +/// given block flags. +fn setup(modes: &[bool]) -> Vec { + setup_with(modes, Codebook { dims: 1, lookup: 0 }, 0, 0) +} + +/// The codebook of [`setup_with`]: 2 entries of length 1 with `dims` dimensions and lookup type +/// `lookup` (0, or 1 with 1-bit values). +#[derive(Clone, Copy)] +struct Codebook { + dims: u32, + lookup: u32, +} + +/// [`setup`] with the given codebook and the floor and residue its one mapping's submap names. +fn setup_with(modes: &[bool], book: Codebook, floor: u32, residue: u32) -> Vec { + let plain_floor = |w: &mut BitWriter| { + // one floor 1 with no partitions: multiplier and range bits + w.put(0, 6).put(1, 16).put(0, 5).put(0, 2).put(0, 4); + }; + let plain_residue = |w: &mut BitWriter| { + // one residue 0 with one classification, classbook 0 and no books + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(0, 8).put(0, 3).put(0, 1); + }; + setup_parts(modes, book, floor, residue, &plain_floor, &plain_residue) +} + +/// [`setup_with`] with the floor and residue configurations written by the given closures, each +/// starting with its count of 0 (one entry). +fn setup_parts( + modes: &[bool], + book: Codebook, + floor: u32, + residue: u32, + write_floor: &dyn Fn(&mut BitWriter), + write_residue: &dyn Fn(&mut BitWriter), +) -> Vec { + let mut w = BitWriter::default(); + // one codebook: 2 entries of length 1 + w.put(0, 8).put(0x56_4342, 24).put(book.dims, 16).put(2, 24).put(0, 1).put(0, 1).put(0, 5).put(0, 5).put(book.lookup, 4); + if book.lookup == 1 { + // minimum value, delta, 1-bit values, no sequence flag, then the values themselves + w.put(0, 32).put(0, 32).put(0, 4).put(0, 1); + let values = if book.dims == 0 { 0 } else { lookup1_values(2, book.dims) }; + for _ in 0..values { + w.put(0, 1); + } + } + // one time-domain transform + w.put(0, 6).put(0, 16); + write_floor(&mut w); + write_residue(&mut w); + // one mapping: one submap, no coupling, reserved bits, the submap's time, floor and residue + w.put(0, 6).put(0, 16).put(0, 1).put(0, 1).put(0, 2).put(0, 8).put(floor, 8).put(residue, 8); + w.put(modes.len() as u32 - 1, 6); + for &long in modes { + w.put(u32::from(long), 1).put(0, 16).put(0, 16).put(0, 8); + } + w.put(1, 1); + let mut h = b"\x05vorbis".to_vec(); + h.extend_from_slice(&w.bytes); + h +} + +const SHORT: u8 = 0b00; +const LONG: u8 = 0b10; + +/// A Vorbis stream whose packets are laid out in `pages`: each page is its packets' first bytes and +/// the page's granule position; the last page is the end of the stream. +fn stream(pages: &[(&[u8], i64)]) -> Stream { + let mut packets = Vec::new(); + for (k, &(firsts, granule)) in pages.iter().enumerate() { + for (i, &first) in firsts.iter().enumerate() { + let last = i + 1 == firsts.len(); + packets.push(Packet { + parts: Vec::new(), + size: 10, + granule: last.then_some(granule), + page: k as u32, + eos: k + 1 == pages.len(), + prefix: [first, 0], + }); + } + } + Stream { + serial: 1, + codec: Codec::Vorbis, + // three modes, so mode 3 is one the header does not have + headers: vec![identification(), b"\x03vorbis".to_vec(), setup(&[false, true, true])], + packets, + pages: pages.len() as u32, + last_granule: pages.last().map(|p| p.1), + saw_eos: true, + header_count: 3, + header_bytes: 0, + next_seq: None, + started: true, + } +} + +#[test] +fn modes_come_from_the_end_of_the_setup_header() { + let modes = VorbisModes::parse(&identification(), &setup(&[false, true, true])).unwrap(); + assert_eq!(modes.blocksizes, [256, 2048]); + assert_eq!(modes.long, [false, true, true]); + // two bits of mode number after the packet-type bit + assert_eq!(modes.blocksize(0b000), Some(256)); + assert_eq!(modes.blocksize(0b100), Some(2048)); + assert_eq!(modes.blocksize(0b110), None, "a mode the header does not have"); + assert_eq!(modes.blocksize(0b001), None, "not an audio packet"); +} + +#[test] +fn damaged_headers_give_no_modes() { + let id = identification(); + let full = setup(&[false, true]); + for cut in 7..full.len() { + assert_eq!(VorbisModes::parse(&id, &full[..cut]), None, "setup cut to {cut} bytes"); + } + let mut no_framing = full.clone(); + *no_framing.last_mut().unwrap() = 0; + assert_eq!(VorbisModes::parse(&id, &no_framing), None); + let mut long_first = id.clone(); + long_first[28] = 0x8B; + assert_eq!(VorbisModes::parse(&long_first, &full), None, "short block larger than the long one"); + let mut version_1 = id.clone(); + version_1[7] = 1; + assert_eq!(VorbisModes::parse(&version_1, &full), None, "not Vorbis I"); +} + +#[test] +fn a_zero_sample_rate_gives_no_modes() { + let full = setup(&[false, true]); + assert!(VorbisModes::parse(&identification(), &full).is_some()); + let mut no_rate = identification(); + no_rate[12..16].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(VorbisModes::parse(&no_rate, &full), None); +} + +#[test] +fn a_mapping_names_only_configured_floors_and_residues() { + let id = identification(); + let plain = Codebook { dims: 1, lookup: 0 }; + assert!(VorbisModes::parse(&id, &setup_with(&[false, true], plain, 0, 0)).is_some()); + assert_eq!(VorbisModes::parse(&id, &setup_with(&[false, true], plain, 1, 0)), None, "floor 1 of one floor"); + assert_eq!(VorbisModes::parse(&id, &setup_with(&[false, true], plain, 0, 1)), None, "residue 1 of one residue"); +} + +/// The setup of [`setup_with`] with one floor 1 (partition list, then classes) and one residue. +fn books_setup(floor: &dyn Fn(&mut BitWriter), residue: &dyn Fn(&mut BitWriter)) -> Option { + let plain = Codebook { dims: 1, lookup: 0 }; + VorbisModes::parse(&identification(), &setup_parts(&[false, true], plain, 0, 0, floor, residue)) +} + +#[test] +fn residue_books_name_configured_codebooks() { + let residue = |classbook: u32, book: u32| { + move |w: &mut BitWriter| { + // one classification with the first cascade bit set, which names one book + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(classbook, 8).put(1, 3).put(0, 1); + w.put(book, 8); + } + }; + let floor = |w: &mut BitWriter| { + w.put(0, 6).put(1, 16).put(0, 5).put(0, 2).put(0, 4); + }; + assert!(books_setup(&floor, &residue(0, 0)).is_some()); + assert_eq!(books_setup(&floor, &residue(1, 0)), None, "classbook 1 of one codebook"); + assert_eq!(books_setup(&floor, &residue(0, 1)), None, "book 1 of one codebook"); +} + +#[test] +fn floor_books_name_configured_codebooks() { + let residue = |w: &mut BitWriter| { + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(0, 8).put(0, 3).put(0, 1); + }; + // floor 0: order, rate, bark map size, amplitude bits and offset, one book + let floor0 = |book: u32| { + move |w: &mut BitWriter| { + w.put(0, 6).put(0, 16).put(0, 8).put(0, 16).put(0, 16).put(0, 6).put(0, 8).put(0, 4).put(book, 8); + } + }; + assert!(books_setup(&floor0(0), &residue).is_some()); + assert_eq!(books_setup(&floor0(1), &residue), None); + // floor 1: one partition of class 0 with one dimension and 1 subclass bit, a master book and + // two subclass books (number plus one), then 2 range bits and one X value + let floor1 = |master: u32, sub: u32, x: u32| { + move |w: &mut BitWriter| { + w.put(0, 6).put(1, 16).put(1, 5).put(0, 4).put(0, 3).put(1, 2).put(master, 8).put(sub, 8).put(0, 8); + w.put(0, 2).put(2, 4).put(x, 2); + } + }; + assert!(books_setup(&floor1(0, 1, 1), &residue).is_some()); + assert!(books_setup(&floor1(0, 0, 1), &residue).is_some(), "no subclass book"); + assert_eq!(books_setup(&floor1(1, 1, 1), &residue), None, "master book 1"); + assert_eq!(books_setup(&floor1(0, 2, 1), &residue), None, "subclass book 1"); + assert_eq!(books_setup(&floor1(0, 1, 0), &residue), None, "X value equal to the implicit 0"); + assert_eq!(books_setup(&floor1(0, 1, 1), &residue).map(|m| m.long), Some(vec![false, true])); +} + +#[test] +fn floor_one_x_values_are_distinct() { + let residue = |w: &mut BitWriter| { + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(0, 8).put(0, 3).put(0, 1); + }; + // one partition of class 0 with two dimensions and no subclasses, 3 range bits, two X values + let floor1 = |a: u32, b: u32| { + move |w: &mut BitWriter| { + w.put(0, 6).put(1, 16).put(1, 5).put(0, 4).put(1, 3).put(0, 2).put(0, 8); + w.put(0, 2).put(3, 4).put(a, 3).put(b, 3); + } + }; + assert!(books_setup(&floor1(3, 5), &residue).is_some()); + assert_eq!(books_setup(&floor1(3, 3), &residue), None, "repeated X value"); + assert_eq!(books_setup(&floor1(0, 5), &residue), None, "X value equal to the implicit 0"); +} + +#[test] +fn a_codebook_of_no_dimensions_has_no_lookup_values() { + let id = identification(); + for lookup in [0, 1] { + let modes = VorbisModes::parse(&id, &setup_with(&[false, true], Codebook { dims: 0, lookup }, 0, 0)); + assert_eq!(modes.map(|m| m.long), Some(vec![false, true]), "lookup type {lookup}"); + let one = VorbisModes::parse(&id, &setup_with(&[false, true], Codebook { dims: 1, lookup }, 0, 0)); + assert_eq!(one.map(|m| m.long), Some(vec![false, true]), "lookup type {lookup}, one dimension"); + } +} + +#[test] +fn the_first_packet_primes_and_the_rest_overlap_by_quarter_blocks() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 576), (&[LONG, LONG, SHORT], 3200)])).unwrap(); + assert_eq!(t.durations, [0, 64 + 512, 1024, 1024, 512 + 64]); + assert_eq!(t.starts, [0, 0, 576, 1600, 2624]); + assert_eq!((t.skip, t.first, t.total), (0, 0, 3200)); +} + +#[test] +fn a_negative_start_discards_leading_samples() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 476), (&[LONG, SHORT], 2076)])).unwrap(); + assert_eq!(t.starts[1], -100); + assert_eq!((t.skip, t.first), (100, 0)); + assert_eq!(t.total, 2076); +} + +#[test] +fn packets_that_are_not_audio_do_not_shrink_the_leading_discard() { + let t = VorbisTiming::of(&stream(&[(&[0xFF, SHORT, LONG], 476), (&[LONG, SHORT], 2076)])).unwrap(); + assert_eq!(&t.durations[..3], [0, 0, 576]); + assert_eq!(t.starts[2], -100); + assert_eq!((t.skip, t.first, t.total), (100, 0, 2076)); +} + +#[test] +fn a_packet_too_short_for_its_window_flags_returns_nothing() { + // 64 modes: six bits of mode number, so a long block's two window flags reach the second byte + let mut modes = vec![false; 64]; + modes[1] = true; + let mut s = stream(&[(&[SHORT, LONG, SHORT], 1000)]); + s.headers[2] = setup(&modes); + s.packets[1].size = 1; + let t = VorbisTiming::of(&s).unwrap(); + assert_eq!(t.durations, [0, 0, 128], "the cut long packet is skipped and the next one follows the first"); + s.packets[1].size = 2; + let t = VorbisTiming::of(&s).unwrap(); + assert_eq!(t.durations, [0, 64 + 512, 512 + 64]); +} + +#[test] +fn a_positive_start_is_a_time_offset() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 44_676), (&[LONG, SHORT], 46_276)])).unwrap(); + assert_eq!((t.skip, t.first), (0, 44_100)); + assert_eq!(t.starts[1], 44_100); + assert_eq!(t.total, 46_276 - 44_100); +} + +#[test] +fn a_page_with_only_the_priming_packet_does_not_place_the_stream() { + let negative = VorbisTiming::of(&stream(&[(&[SHORT], 0), (&[LONG], 476), (&[LONG, SHORT], 2076)])).unwrap(); + assert_eq!(negative.starts[1], -100); + assert_eq!((negative.skip, negative.first, negative.total), (100, 0, 2076)); + let offset = VorbisTiming::of(&stream(&[(&[SHORT], 0), (&[LONG], 44_676), (&[LONG, SHORT], 46_276)])).unwrap(); + assert_eq!(offset.starts[1], 44_100); + assert_eq!((offset.skip, offset.first, offset.total), (0, 44_100, 2176)); +} + +#[test] +fn the_final_page_trims_the_end() { + let full = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 576), (&[LONG, SHORT], 2176)])).unwrap(); + let trimmed = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 576), (&[LONG, SHORT], 2000)])).unwrap(); + assert_eq!(trimmed.starts, full.starts, "trimming moves no packet"); + assert_eq!(trimmed.total, full.total - 176); +} + +#[test] +fn one_page_shorter_than_its_packets_trims_the_end() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG, SHORT], 1000)])).unwrap(); + assert_eq!((t.skip, t.first, t.total), (0, 0, 1000)); + assert_eq!(t.starts[1], 0); +} + +#[test] +fn hostile_granules_and_packets_do_not_overflow() { + for g in [i64::MIN, -2, i64::MAX, MAX_OPUS_GRANULE] { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], g), (&[0xFF, 0b110, LONG], g)])).unwrap(); + assert_eq!(t.starts.len(), 5); + assert_eq!(&t.durations[2..4], [0, 0], "a non-audio packet and an unknown mode return nothing"); + assert!(t.total >= 0); + } + let mut no_setup = stream(&[(&[SHORT], 0)]); + no_setup.headers.truncate(2); + assert_eq!(VorbisTiming::of(&no_setup), None); +} + +#[test] +fn lookup_values_are_the_integer_root_of_the_entries() { + assert_eq!(lookup1_values(81, 4), 3); + assert_eq!(lookup1_values(80, 4), 2); + assert_eq!(lookup1_values(1 << 24, 1), 1 << 24); + assert_eq!(lookup1_values(1 << 24, 65_535), 1); +} diff --git a/crates/media/tests/mpegts_mux/mod.rs b/crates/media/tests/mpegts_mux/mod.rs index 4a3e6f2d11..0287a8ce9c 100644 --- a/crates/media/tests/mpegts_mux/mod.rs +++ b/crates/media/tests/mpegts_mux/mod.rs @@ -195,13 +195,24 @@ pub fn av1_unescape(es: &[u8]) -> Vec { out } -/// The Opus control header and packet the demuxer gives back for an Opus frame. -pub fn opus_unit(packet: &[u8]) -> Vec { - let mut v = vec![0x7F, 0xE0]; - v.extend(std::iter::repeat_n(0xFF, packet.len() / 255)); - v.push((packet.len() % 255) as u8); - v.extend_from_slice(packet); - v +/// The payload of every PES packet on `pid`, as the muxer wrote it (the PES header left out). +pub fn pes_payloads(ts: &[u8], pid: u16) -> Vec> { + let mut out: Vec> = Vec::new(); + for p in ts.chunks(PACKET_SIZE) { + if ((p[1] & 0x1F) as u16) << 8 | p[2] as u16 != pid || p[3] & 0x10 == 0 { + continue; + } + let start = if p[3] & 0x20 != 0 { 5 + p[4] as usize } else { 4 }; + let mut payload = &p[start..]; + if p[1] & 0x40 != 0 { + payload = &payload[9 + payload[8] as usize..]; + out.push(Vec::new()); + } + if let Some(last) = out.last_mut() { + last.extend_from_slice(payload); + } + } + out } /// What the demuxer gives back for a video frame: an access unit delimiter first. diff --git a/crates/media/tests/mpegts_mux_fuzz.rs b/crates/media/tests/mpegts_mux_fuzz.rs index 0067e5a17c..662105ae8e 100644 --- a/crates/media/tests/mpegts_mux_fuzz.rs +++ b/crates/media/tests/mpegts_mux_fuzz.rs @@ -66,8 +66,7 @@ fn frame(s: usize, size: usize, key: bool, n: usize) -> (Vec, Vec) { 1 => { let mut d = vec![0xFC]; fill(&mut d, size.min(1500), seed); - let e = opus_unit(&d); - (d, e) + (d.clone(), d) } 2 => { let mut d = Vec::new(); diff --git a/crates/media/tests/mpegts_mux_readback.rs b/crates/media/tests/mpegts_mux_readback.rs index 7d8471525c..733a6f2d75 100644 --- a/crates/media/tests/mpegts_mux_readback.rs +++ b/crates/media/tests/mpegts_mux_readback.rs @@ -90,7 +90,7 @@ fn every_codec_in_one_program() { for k in 0..150i64 { let mut p = vec![0xFC]; fill(&mut p, 1 + (k as usize * 41) % 700, k as u8); - items.push(Item { stream: 2, expect: opus_unit(&p), data: p, pts: t0 + k * 1800, dts: t0 + k * 1800, key: true }); + items.push(Item { stream: 2, expect: p.clone(), data: p, pts: t0 + k * 1800, dts: t0 + k * 1800, key: true }); } for k in 0..90i64 { let f = ac3(k as u8); @@ -100,7 +100,7 @@ fn every_codec_in_one_program() { let f = mp3(false, k as u8); items.push(Item { stream: 4, expect: f.clone(), data: f, pts: t0 + k * 2160, dts: t0 + k * 2160, key: true }); } - let want = [Demuxed::H264, Demuxed::AacAdts, Demuxed::Unknown(6), Demuxed::Ac3, Demuxed::MpegAudio]; + let want = [Demuxed::H264, Demuxed::AacAdts, Demuxed::Opus, Demuxed::Ac3, Demuxed::MpegAudio]; let (ts, pcrs) = round_trip(Config::default(), &streams, &mut items, &want); let file = mpegts::open(&ts).unwrap(); assert_eq!(file.pcr_range, Some((pcrs[0], *pcrs.last().unwrap()))); @@ -108,6 +108,10 @@ fn every_codec_in_one_program() { // the frames' own headers read back with the demuxer's frame parser let aac = file.read_unit(&ts, 1, 0).unwrap(); assert_eq!(mpegts::frame_info(&Demuxed::AacAdts, &aac).map(|i| (i.sample_rate, i.channels)), Some((48_000, 2))); + // a stereo Opus stream (channel_config_code 2): one coupled stream, no start trim + let opus = file.streams[2].codec_params(); + assert_eq!((opus.codec, opus.sample_rate, opus.channels), (craft_media::CodecId::Opus, Some(48_000), Some(2))); + assert_eq!(opus.extradata, [b"OpusHead".as_slice(), &[1, 2, 0, 0, 0x80, 0xBB, 0, 0, 0, 0, 0]].concat()); } #[test] @@ -162,9 +166,9 @@ fn timestamps_run_past_the_33_bit_wrap() { for k in 0..140i64 { let p = vec![0x08, k as u8 | 1, 0x55]; let t = start + k * 1800; - items.push(Item { stream: 1, expect: opus_unit(&p), data: p, pts: t, dts: t, key: true }); + items.push(Item { stream: 1, expect: p.clone(), data: p, pts: t, dts: t, key: true }); } - round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Unknown(6)]); + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Opus]); } #[test] @@ -185,7 +189,7 @@ fn eac3_mpeg1_video_and_mpeg4_part2() { let t = 100_000 + k * 2880; items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); } - round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg1Video, Demuxed::Eac3, Demuxed::Unknown(0x10)]); + round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg1Video, Demuxed::Eac3, Demuxed::Mpeg4Part2]); } #[test] @@ -200,20 +204,61 @@ fn av1_reads_back_as_its_obus() { let t = 90_000 + k * 3000; m.write_frame(0, &Frame { data: &tu, pts: t, dts: None, key }).unwrap(); m.write_frame(1, &Frame { data: &[0xFC, k as u8 | 1], pts: t, dts: None, key: true }).unwrap(); - tus.push((tu, t)); + tus.push((tu, t, key)); } let ts = m.finish().unwrap(); check_packets(&ts, 0x100, 3600 * 300); let file = mpegts::open(&ts).unwrap(); assert!(file.warnings.is_empty(), "{:?}", file.warnings); - assert_eq!(file.streams[0].codec, Demuxed::Unknown(6)); + assert_eq!(file.streams[0].codec, Demuxed::Av1); assert_eq!(file.streams[0].stream_type, 0x06); + assert_eq!(file.streams[1].codec, Demuxed::Opus); + // the descriptor's fields come back as the av1C record they were taken from + let params = file.streams[0].codec_params(); + assert_eq!(params.codec, craft_media::CodecId::Av1); + assert_eq!(Av1Config::from_av1c(¶ms.extradata).unwrap(), config); let units = &file.streams[0].units; assert_eq!(units.len(), tus.len()); - for (n, (u, (tu, t))) in units.iter().zip(&tus).enumerate() { + let written = pes_payloads(&ts, 0x100); + assert_eq!(written.len(), tus.len()); + for (n, (u, (tu, t, key))) in units.iter().zip(&tus).enumerate() { assert_eq!(u.pts, Some(*t)); - let es = file.read_unit(&ts, 0, n).unwrap(); - assert_eq!(av1_unescape(&es), av1_without_delimiters(tu), "unit {n}"); + assert_eq!(u.key, *key, "unit {n}"); + // the writer's start code form, and the demuxer's OBUs + assert_eq!(av1_unescape(&written[n]), av1_without_delimiters(tu), "unit {n}"); + assert_eq!(file.read_unit(&ts, 0, n).unwrap(), av1_without_delimiters(tu), "unit {n}"); + } +} + +#[test] +fn opus_channel_configurations_read_back() { + let opened = |codec: Codec| { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, codec)]).unwrap(); + for k in 0..10i64 { + m.write_frame(0, &Frame { data: &[0xFC, 1, 0x55], pts: 90_000 + k * 1800, dts: None, key: true }).unwrap(); + } + let ts = m.finish().unwrap(); + let s = mpegts::open(&ts).unwrap().streams.remove(0); + assert_eq!(s.codec, Demuxed::Opus); + let o = s.opus.unwrap(); + (o.channels, o.family, o.streams, o.coupled, o.mapping) + }; + // the fixed configurations: family 0 for one or two channels, the RFC 7845 surround orders + // for more + assert_eq!(opened(Codec::Opus { channels: 1 }), (1, 0, 1, 0, vec![0])); + assert_eq!(opened(Codec::Opus { channels: 2 }), (2, 0, 1, 1, vec![0, 1])); + assert_eq!(opened(Codec::Opus { channels: 6 }), (6, 1, 4, 2, vec![0, 4, 1, 2, 3, 5])); + assert_eq!(opened(Codec::Opus { channels: 8 }), (8, 1, 5, 3, vec![0, 6, 1, 2, 3, 4, 5, 7])); + // explicit configurations come back field for field, silent channels included + for m in [ + OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }, + OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [2, 255, 0, 0, 0, 0, 0, 0] }, + OpusMapping { channels: 8, family: 255, streams: 8, coupled: 0, mapping: [7, 6, 5, 4, 3, 2, 1, 0] }, + OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] }, + OpusMapping { channels: 1, family: 1, streams: 1, coupled: 0, mapping: [0, 0, 0, 0, 0, 0, 0, 0] }, + ] { + let ch = usize::from(m.channels); + assert_eq!(opened(Codec::OpusMapped(m)), (m.channels, m.family, m.streams, m.coupled, m.mapping[..ch].to_vec()), "{m:?}"); } } @@ -226,23 +271,32 @@ fn opus_with_an_explicit_mapping_and_trims() { for k in 0..20i64 { // three streams of 20 ms: two self-delimited packets, then the last one let au = [0xFC, 1, 0x55, 0xFC, 1, 0x66, 0xFC, 0x77]; - let trim = if k == 0 { craft_media::mpegts::mux::OpusTrim { start: 312, end: 0 } } else { Default::default() }; + let trim = match k { + 0 => craft_media::mpegts::mux::OpusTrim { start: 312, end: 0 }, + 19 => craft_media::mpegts::mux::OpusTrim { start: 0, end: 100 }, + _ => Default::default(), + }; let t = 90_000 + k * 1800; m.write_frame_with_trim(0, &Frame { data: &au, pts: t, dts: None, key: true }, trim).unwrap(); - let mut unit = if k == 0 { vec![0x7F, 0xF0, 8] } else { vec![0x7F, 0xE0, 8] }; - if k == 0 { - unit.extend_from_slice(&312u16.to_be_bytes()); - } - unit.extend_from_slice(&au); - want.push(unit); + want.push(au.to_vec()); } let ts = m.finish().unwrap(); let file = mpegts::open(&ts).unwrap(); assert!(file.warnings.is_empty(), "{:?}", file.warnings); - assert_eq!(file.streams[0].units.len(), want.len()); + let s = &file.streams[0]; + assert_eq!(s.codec, Demuxed::Opus); + assert_eq!(s.units.len(), want.len()); for (n, w) in want.iter().enumerate() { assert_eq!(&file.read_unit(&ts, 0, n).unwrap(), w); } + let opus = s.opus.as_ref().unwrap(); + assert_eq!((opus.channels, opus.family, opus.streams, opus.coupled, &opus.mapping[..]), (3, 255, 3, 0, &[0, 1, 2][..])); + assert_eq!(opus.trims, [mpegts::OpusTrim { unit: 0, start: 312, end: 0 }, mpegts::OpusTrim { unit: 19, start: 0, end: 100 }]); + // the OpusHead header (RFC 7845 §5.1) carries the start trim as its pre-skip + let head = s.codec_params().extradata; + assert_eq!(&head[..8], b"OpusHead"); + assert_eq!(u16::from_le_bytes([head[10], head[11]]), 312); + assert_eq!(&head[18..], &[255, 3, 0, 0, 1, 2]); } #[test] diff --git a/crates/media/tests/oracle_mpegts.rs b/crates/media/tests/oracle_mpegts.rs index d395c09ff1..28e5904fdb 100644 --- a/crates/media/tests/oracle_mpegts.rs +++ b/crates/media/tests/oracle_mpegts.rs @@ -22,6 +22,7 @@ const ALL: &[&str] = &[ "m2ts_h264_ac3.mts", "ts_hevc_latm.ts", "ts_h264_eac3.ts", + "ts_mpeg4_opus.ts", "ps_mpeg2_mp2.vob", "ps_mpeg2_lpcm.vob", "ps_mpeg2_ac3.vob", @@ -72,6 +73,10 @@ fn spec(name: &str) -> Vec<&'static str> { &["-c:a", "aac", "-b:a", "96k", "-f", "mpegts", "-mpegts_flags", "latm"], ]), "ts_h264_eac3.ts" => cat(&[PIC, NOISE, &["-t", "1"], x264, &["-c:a", "eac3", "-b:a", "192k", "-f", "mpegts"]]), + // stream type 0x10, and Opus with its registration and audio descriptors and control headers + "ts_mpeg4_opus.ts" => { + cat(&[PIC, NOISE, &["-t", "1.2", "-c:v", "mpeg4", "-bf", "2", "-g", "12", "-c:a", "libopus", "-b:a", "96k", "-f", "mpegts"]]) + } // DVD-style program streams "ps_mpeg2_mp2.vob" => cat(&[ &["-f", "lavfi", "-i", "testsrc2=size=720x480:rate=30000/1001"], @@ -112,7 +117,9 @@ fn expected_codec(name: &str, format: Format) -> Codec { "mpeg2video" => Codec::Mpeg2Video, "h264" => Codec::H264, "hevc" => Codec::Hevc, + "mpeg4" => Codec::Mpeg4Part2, "mp2" | "mp3" => Codec::MpegAudio, + "opus" => Codec::Opus, "aac" => Codec::AacAdts, "aac_latm" => Codec::AacLatm, "ac3" => Codec::Ac3, @@ -184,7 +191,7 @@ fn check(name: &str) -> Option { #[test] fn transport_streams_match_ffprobe() { - for name in ["ts_mpeg2_mp2.ts", "ts_h264_aac.ts", "ts_hevc_latm.ts", "ts_h264_eac3.ts"] { + for name in ["ts_mpeg2_mp2.ts", "ts_h264_aac.ts", "ts_hevc_latm.ts", "ts_h264_eac3.ts", "ts_mpeg4_opus.ts"] { let Some(f) = check(name) else { return }; assert_eq!(f.format, Format::Ts { packet_size: 188, sync_offset: 0 }, "{name}"); assert_eq!(f.program, Some(1), "{name}"); @@ -195,9 +202,17 @@ fn transport_streams_match_ffprobe() { "ts_mpeg2_mp2.ts" => [CodecId::Mpeg2Video, CodecId::Mp2], "ts_h264_aac.ts" => [CodecId::H264, CodecId::Aac], "ts_hevc_latm.ts" => [CodecId::Hevc, CodecId::Aac], + "ts_mpeg4_opus.ts" => [CodecId::Mpeg4Video, CodecId::Opus], _ => [CodecId::H264, CodecId::Eac3], }; assert_eq!(ids, want, "{name}"); + if name == "ts_mpeg4_opus.ts" { + // stereo from the Opus audio descriptor, and libopus's 312-sample start trim as the + // pre-skip + let p = f.streams[1].codec_params(); + assert_eq!((p.sample_rate, p.channels), (Some(48_000), Some(2))); + assert_eq!(&p.extradata[..12], &[b"OpusHead".as_slice(), &[1, 2], &312u16.to_le_bytes()].concat()[..]); + } } } diff --git a/crates/media/tests/oracle_ogg.rs b/crates/media/tests/oracle_ogg.rs index 4e14a651e0..d81dba1f35 100644 --- a/crates/media/tests/oracle_ogg.rs +++ b/crates/media/tests/oracle_ogg.rs @@ -1,9 +1,9 @@ -//! Oracle tests: compare the Ogg demuxer's streams, packet bytes and Opus timing with ffprobe on -//! ffmpeg-generated fixtures (skipped when ffmpeg/ffprobe are not installed). +//! Oracle tests: compare the Ogg demuxer's streams, packet bytes and Opus and Vorbis timing with +//! ffprobe on ffmpeg-generated fixtures (skipped when ffmpeg/ffprobe are not installed). use super::common; -use craft_media::ogg::{self, Codec, OggFile, OpusTiming}; +use craft_media::ogg::{self, Codec, OggFile, OpusTiming, VorbisTiming}; use serde_json::Value; use std::path::{Path, PathBuf}; use std::process::Command; @@ -184,6 +184,27 @@ fn assert_opus_timing_matches(name: &str, file: &OggFile, s: usize, json: &Value eprintln!("{context}: timing of {} packets matches, {} samples", theirs.len(), timing.total); } +/// `VorbisTiming` against ffmpeg: from the second packet on, the starts are its pts and the +/// durations its packet durations (the last one trimmed by the discard padding), and the total is +/// the sum of those durations. ffmpeg gives the first packet, which returns no samples, a pts and +/// duration of its own, so it is compared only for returning nothing. +fn assert_vorbis_timing_matches(name: &str, file: &OggFile, s: usize, json: &Value, ff: usize) { + let timing = VorbisTiming::of(&file.streams[s]).unwrap_or_else(|| panic!("{name}: Vorbis headers")); + let theirs = ff_packets(json, ff); + let context = format!("{name}: Vorbis stream {ff}"); + assert_eq!(timing.starts.len(), theirs.len(), "{context}: packet count"); + assert_eq!(timing.durations[0], 0, "{context}: the first packet returns nothing"); + let last = theirs.len() - 1; + for (k, p) in theirs.iter().enumerate().skip(1) { + assert_eq!(p.pts, Some(timing.starts[k]), "{context}: start of packet {k}"); + let duration = p.duration.unwrap() + if k == last { p.discard } else { 0 }; + assert_eq!(duration, i64::from(timing.durations[k]), "{context}: duration of packet {k}"); + } + let playable: i64 = theirs.iter().skip(1).map(|p| p.duration.unwrap()).sum(); + assert_eq!((timing.skip, timing.first, timing.total), (0, 0, playable), "{context}: skip, first, total"); + eprintln!("{context}: timing of {} packets matches, {} samples", theirs.len(), timing.total); +} + /// Multiplexed streams: each is read on its own, in ffmpeg's order. #[test] fn grouped_streams() { @@ -197,6 +218,7 @@ fn grouped_streams() { for s in 0..2 { assert_opus_timing_matches("grouped.ogg", &file, s, &json, s); } + assert_vorbis_timing_matches("grouped.ogg", &file, 2, &json, 2); } /// A chained file: two links, each its own stream with its own headers. ffmpeg joins the links of diff --git a/crates/menu/README.md b/crates/menu/README.md index a9de1bfded..69947e7bae 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -135,6 +135,14 @@ The module documentation lists every `Outcome`, `Options` and the words (`Shortc app translates. The dialog never opens a file dialog or touches the file system. Enable `screen-testing` for the stories and the `it` trials. +Automation can select a command and set `replace` to `{"old":"Text: Cmd+B","new":"Cmd+K"}` +through `ShortcutsDialog::set_json_field`. The old text must identify exactly one current binding; +the new trigger keeps its scope and regular or Hold column. An equivalent trigger changes nothing, +and a changed replacement has one Undo step. Ask mode leaves the original binding until the user +answers the conflict bar; Steal and Keep follow the host's configured policy. A stale confirmation +cannot replace bindings that changed after its prompt opened. Unavailable edits and replacements +that cannot be stored return a refusal. + ## Windows, Linux and web: the in-window bar `MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 3d1204ce5e..a852119d72 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -202,7 +202,7 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { .zip(&labels.menus) .map(|((menu, title), level)| { // The commands the title holds, for the palette's callout; a built-in has no command of the app. - let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect(); + let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect::>(); let row = MenuTitle::new(title.label.clone(), move |ui| shared.show(ui, &menu.children, level)).holds(held); match title.hidden { Some(letter) => row.mnemonic(letter), diff --git a/crates/menu/src/shortcuts/mod.rs b/crates/menu/src/shortcuts/mod.rs index 7a2bb5b536..2b2165d4f9 100644 --- a/crates/menu/src/shortcuts/mod.rs +++ b/crates/menu/src/shortcuts/mod.rs @@ -444,10 +444,14 @@ impl<'a> ShortcutsDialog<'a> { self } - /// Sets the value `field` names in `state`, as the user editing that control would - /// (`search`, `area`, `command`, `pressed`; `assign` true presses Assign; `remove` takes the text - /// of one of the command's keys, as [`DialogSnapshot::keys`] reports it), for automation. It builds the words `Env` that `DialogState::set_field` needs. `Err` says why - /// the field was refused. + /// Sets a dialog field for automation, as the user editing `search`, `area`, `command` or `pressed` would. + /// `assign` true presses Assign. + /// `remove` takes one of the selected command's keys as reported by [`DialogSnapshot::keys`]. `replace` takes + /// an object with `old` in the same form and `new` as [`Trigger`] text. It preserves the old scope and keeps + /// hold shortcuts in the Hold column. In [`ConflictMode::Ask`], a conflict leaves the old binding in place + /// until the user confirms. Hosts can use [`ConflictMode::Steal`] or [`ConflictMode::Keep`] for immediate + /// handling. Replacing a shortcut with an equivalent trigger leaves it alone. A replacement that changes + /// the shortcut can be undone in one step. `Err` says why the field was refused. pub fn set_json_field(self, ui: &Ui, state: &mut DialogState, field: &str, value: &serde_json::Value) -> Result<(), String> { use craft_ui::dialog::FieldRefusal; let rejects = || FieldRefusal::Rejects(value).message(field); @@ -490,6 +494,31 @@ impl<'a> ShortcutsDialog<'a> { state.remove(env, &command, &wanted); state.edit_result()?; } + "replace" => { + if !env.options.editable || !state.is_showing() || state.modal() || state.is_recording() || env.has_app_tab(state.tab) { + return Err(inactive()); + } + let command = state.selected.clone().ok_or_else(inactive)?; + let text = |key: &str| value.get(key).and_then(serde_json::Value::as_str).ok_or_else(rejects); + let old_text = text("old")?; + let bindings = env.keymap.bindings(&command); + let mut matches = bindings.iter().filter(|binding| binding.to_string() == old_text); + let old = matches.next().ok_or_else(rejects)?; + let trigger = Trigger::parse(text("new")?).map_err(|_| rejects())?; + if matches.next().is_some() || trigger.is_hold() != old.trigger.is_hold() { + return Err(rejects()); + } + let platform = env.keymap.platform(); + let effective = trigger.effective(platform); + if effective == old.trigger.effective(platform) { + return Ok(()); + } + if bindings.iter().any(|binding| binding.scope == old.scope && binding.trigger.effective(platform) == effective) { + return Err(rejects()); + } + let new = Binding { trigger, scope: old.scope.clone() }; + state.replace_for_automation(env, &command, old, new)?; + } _ => return Err(FieldRefusal::Unknown.message(field)), } Ok(()) diff --git a/crates/menu/src/shortcuts/pages.rs b/crates/menu/src/shortcuts/pages.rs index dee3c9589d..134cd86763 100644 --- a/crates/menu/src/shortcuts/pages.rs +++ b/crates/menu/src/shortcuts/pages.rs @@ -120,7 +120,7 @@ pub struct DialogSnapshot { pub selected: Option, /// Commands whose bindings differ from the defaults, with their binding texts. pub overrides: Vec<(CommandRef, Vec)>, - /// The conflict bar's chord and the commands holding it, while it shows. + /// The pending conflict's chord and the commands holding it. Another prompt or app tab can hide the conflict bar. pub conflict: Option<(String, Vec)>, /// Whether a chord is being recorded, and the command it is for. pub recording: Option, diff --git a/crates/menu/src/shortcuts/state.rs b/crates/menu/src/shortcuts/state.rs index eb9bc606c8..9f67d256b8 100644 --- a/crates/menu/src/shortcuts/state.rs +++ b/crates/menu/src/shortcuts/state.rs @@ -7,13 +7,15 @@ use craft_keymap::editor::{self, DOUBLE_PRESS, EditSession, Recorded, Recorder}; use craft_keymap::import::{self, ForeignEntry, ForeignSet, ImportOptions, ImportPlan, ImportReport, Start}; use craft_keymap::profiles::{Builtins, ProfileError, Profiles, set_name}; use craft_keymap::{ - AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Policy, Scope, Trigger, + AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Platform, Policy, + Scope, Trigger, }; +use craft_ui::primitives::ChordText; use super::keyboard::KeyboardState; use super::pages::TabSet; use super::rows::{self, AreaEntry, AreaId, Built, Filter, RowCache, View}; -use super::words::Say; +use super::words::{Say, around_chord}; use super::{ConflictMode, HoldSetting, JSON_FORMAT, Layout, Options, Outcome, summary}; /// What the dialog edits this frame. @@ -28,6 +30,10 @@ pub(crate) struct Env<'e> { } impl Env<'_> { + pub(crate) fn has_app_tab(&self, id: Option<&str>) -> bool { + id.is_some_and(|id| self.tabs.as_ref().is_some_and(|tabs| (0..tabs.len()).any(|i| tabs.describe(i).is_some_and(|(tab, _)| tab == id)))) + } + fn chord_text(&self, t: &Trigger) -> String { self.text.trigger(t, self.keymap.platform()) } @@ -129,14 +135,43 @@ pub(crate) struct FieldChord { /// The conflict bar, for one pending chord. #[derive(Clone, Debug, PartialEq)] pub(crate) struct ConflictBar { + pub revision: u64, pub command: CommandRef, pub old: Option, pub binding: Binding, pub holders: Vec, + pub can_steal: bool, + pub can_keep: bool, + before: Option, /// "{chord} is used by {label}". pub text: String, } +impl ConflictBar { + pub(crate) fn notice_text(&self, env: &Env) -> String { + if self.before.is_some() { self.text.clone() } else { around_chord(env.text.rtl(), &self.text, &env.chord_text(&self.binding.trigger)) } + } +} + +/// The existing bindings and home scopes that an automation conflict was opened against. +#[derive(Clone, Debug, PartialEq)] +struct ConflictBasis { + bindings: Vec>, + scopes: Vec>, + platform: Platform, +} + +impl ConflictBasis { + fn of(keymap: &Keymap, command: &CommandRef, holders: &[Holder]) -> Self { + let scopes = std::iter::once(command) + .chain(holders.iter().map(|holder| &holder.command)) + .map(|command| keymap.bindable(command).map(|entry| entry.scope.clone())) + .collect(); + let bindings = std::iter::once(command).chain(holders.iter().map(|holder| &holder.command)).map(|command| keymap.bindings(command)).collect(); + Self { bindings, scopes, platform: keymap.platform() } + } +} + /// A line under the table after an action. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Message { @@ -269,6 +304,7 @@ pub struct DialogState { pub(crate) recording: Option, pub(crate) field: Option, pub(crate) conflict: Option, + conflict_revision: u64, pub(crate) prompt: Option, pub(crate) message: Option, pub(crate) review: Option, @@ -320,6 +356,7 @@ impl DialogState { recording: None, field: None, conflict: None, + conflict_revision: 0, prompt: None, message: None, review: None, @@ -679,6 +716,49 @@ impl DialogState { self.commit_with(env, command, old, binding, mode); } + /// Checks that a replacement can be saved before offering conflict confirmation to an automation caller. + pub(crate) fn replace_for_automation(&mut self, env: &mut Env, command: &CommandRef, old: &Binding, binding: Binding) -> Result<(), String> { + let mut actions = None; + if env.options.conflicts == ConflictMode::Ask && !editor::holders(env.keymap, command, &binding).is_empty() { + let preview = |policy| editor::check_replace(env.keymap, command, old, &binding, policy); + let steal = preview(Policy::Steal); + let keep = preview(Policy::Keep).is_ok(); + if let Err(error) = &steal + && (!keep || !env.options.allow_keep) + { + let text = assign_error(env, error); + self.conflict = None; + self.refuse(text.clone()); + return Err(text); + } + actions = Some((steal.is_ok(), keep)); + } + self.commit(env, command, Some(old.clone()), binding); + if let (Some(conflict), Some((steal, keep))) = (&mut self.conflict, actions) { + conflict.can_steal = steal; + conflict.can_keep = keep; + conflict.before = Some(ConflictBasis::of(env.keymap, command, &conflict.holders)); + let chord = |trigger| { + let text = env.chord_text(trigger); + if env.text.rtl() { ChordText::new(text).isolated() } else { text } + }; + let label = env.label(command); + let target = match env.keymap.bindable(command) { + Some(entry) => fill!(env, label_scope, ("label", &label), ("scope", &env.text.scope_name(old.scope_or(&entry.scope)))), + None => label, + }; + conflict.text = fill!( + env, + replace_old_for_command_with_chord_used_by_label, + ("old", &chord(&old.trigger)), + ("command", &target), + ("chord", &chord(&conflict.binding.trigger)), + ("label", &env.holder_labels(&conflict.holders)) + ); + } + self.edit_result() + } + fn commit_with(&mut self, env: &mut Env, command: &CommandRef, old: Option, binding: Binding, mode: ConflictMode) { self.conflict = None; self.message = None; @@ -701,7 +781,18 @@ impl DialogState { match mode { ConflictMode::Ask => { let text = fill!(env, chord_is_used_by_label, ("chord", &chord), ("label", &env.holder_labels(&holders))); - self.conflict = Some(ConflictBar { command: command.clone(), old, binding, holders, text }); + self.conflict_revision = self.conflict_revision.wrapping_add(1); + self.conflict = Some(ConflictBar { + revision: self.conflict_revision, + command: command.clone(), + old, + binding, + holders, + can_steal: true, + can_keep: true, + before: None, + text, + }); } ConflictMode::Steal => { self.apply_and_say(env, command, old, binding, Policy::Steal); @@ -771,14 +862,14 @@ impl DialogState { /// Take It. pub(crate) fn take_it(&mut self, env: &mut Env) { - if let Some(c) = self.conflict.take() { + if let Some(c) = self.accept_conflict(env) { self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal); } } /// Accept and Go to Conflict. pub(crate) fn take_it_and_go(&mut self, env: &mut Env) { - if let Some(c) = self.conflict.take() { + if let Some(c) = self.accept_conflict(env) { let first = c.holders.first().map(|h| h.command.clone()); if self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal) && let Some(holder) = first @@ -793,11 +884,37 @@ impl DialogState { if !env.options.allow_keep { return; } - if let Some(c) = self.conflict.take() { + if let Some(c) = self.accept_conflict(env) { self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Keep); } } + /// The pending conflict the user can currently answer. + pub(crate) fn visible_conflict(&self, env: &Env) -> Option<&ConflictBar> { + self.conflict.as_ref().filter(|conflict| { + conflict.before.is_none() || (env.options.editable && !self.modal() && !self.is_recording() && !env.has_app_tab(self.tab)) + }) + } + + fn accept_conflict(&mut self, env: &Env) -> Option { + self.visible_conflict(env)?; + let conflict = self.conflict.take()?; + if let Some(before) = &conflict.before { + let holders = editor::holders(env.keymap, &conflict.command, &conflict.binding); + if holders != conflict.holders || ConflictBasis::of(env.keymap, &conflict.command, &holders) != *before { + self.refuse(word!(env, the_shortcuts_changed_try_replacing_again)); + return None; + } + if let (Some(accept), Some(command)) = (&env.options.accept, env.keymap.bindable(&conflict.command)) + && let Err(text) = accept(command, &conflict.binding) + { + self.refuse(text); + return None; + } + } + Some(conflict) + } + /// ✕ on the conflict bar: nothing was applied, so nothing changes. pub(crate) fn dismiss_conflict(&mut self) { self.conflict = None; @@ -982,7 +1099,7 @@ impl DialogState { pub(crate) fn escape(&mut self, env: &mut Env) { if self.recording.is_some() { self.stop_recording(); - } else if self.conflict.is_some() { + } else if self.visible_conflict(env).is_some() { self.conflict = None; } else if self.prompt.is_some() { self.prompt = None; diff --git a/crates/menu/src/shortcuts/view/bars.rs b/crates/menu/src/shortcuts/view/bars.rs index 22326b7f55..10c0ca6e75 100644 --- a/crates/menu/src/shortcuts/view/bars.rs +++ b/crates/menu/src/shortcuts/view/bars.rs @@ -49,30 +49,40 @@ fn prompt(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) { } fn conflict_bar(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) { - let Some(conflict) = state.conflict.clone() else { return }; + enum Action { + Take, + TakeAndGo, + Keep, + Dismiss, + } + + let Some(conflict) = state.visible_conflict(env).cloned() else { return }; let words = env.text.words(); - let chord = env.text.trigger(&conflict.binding.trigger, env.keymap.platform()); - let text = around_chord(env.text.rtl(), &conflict.text, &chord); + let text = conflict.notice_text(env); + let keep = conflict.can_keep && env.options.allow_keep; let mut notice = Notice::new(Tone::Warn, text) - .id_salt("shortcuts.conflict") + .id_salt(("shortcuts.conflict", conflict.revision, keep)) .layout(NoticeLayout::Inline) - .announce(Politeness::Polite) - .action(NoticeAction::new(words.take_it.clone())) - .action(NoticeAction::new(words.accept_and_go_to_conflict.clone())); - let keep = env.options.allow_keep; - if keep { - notice = notice.action(NoticeAction::new(words.keep_both.clone())); + .announce(Politeness::Polite); + let mut actions = Vec::new(); + for (available, label, action) in [ + (conflict.can_steal, &words.take_it, Action::Take), + (conflict.can_steal, &words.accept_and_go_to_conflict, Action::TakeAndGo), + (keep, &words.keep_both, Action::Keep), + (true, &words.undo_changes, Action::Dismiss), + ] { + if available { + notice = notice.action(NoticeAction::new(label.clone())); + actions.push(action); + } } - // Photoshop's wording for turning the new shortcut down is "Undo Changes", the notice's last action. - let undo_at = if keep { 3 } else { 2 }; - notice = notice.action(NoticeAction::new(words.undo_changes.clone())); let out = notice.show(ui); - match out.action { - Some(0) => state.take_it(env), - Some(1) => state.take_it_and_go(env), - Some(2) if keep => state.keep_both(env), - Some(at) if at == undo_at => state.dismiss_conflict(), - _ => {} + match out.action.and_then(|at| actions.get(at)) { + Some(Action::Take) => state.take_it(env), + Some(Action::TakeAndGo) => state.take_it_and_go(env), + Some(Action::Keep) => state.keep_both(env), + Some(Action::Dismiss) => state.dismiss_conflict(), + None => {} } } diff --git a/crates/menu/src/shortcuts/words.rs b/crates/menu/src/shortcuts/words.rs index 77c054e118..886b2a3df5 100644 --- a/crates/menu/src/shortcuts/words.rs +++ b/crates/menu/src/shortcuts/words.rs @@ -123,6 +123,8 @@ craft_ui::words! { keep_both: "keyboardShortcuts.keepBoth" = "Keep Both"; go_to_conflict: "keyboardShortcuts.goToConflict" = "Go to Conflict"; undo_changes: "keyboardShortcuts.undoChanges" = "Undo Changes"; + replace_old_for_command_with_chord_used_by_label: template "keyboardShortcuts.replaceOldForCommandWithChordUsedByLabel" = "Replace {old} for {command} with {chord}, which is used by {label}"; + the_shortcuts_changed_try_replacing_again: "keyboardShortcuts.theShortcutsChangedTryReplacingAgain" = "The shortcuts changed. Try the replacement again."; dismiss: "keyboardShortcuts.dismiss" = "Dismiss"; // Saved shortcuts that could not be used. key_no_command_has_this_name: template "keyboardShortcuts.keyNoCommandHasThisName" = "{key}: no command has this name"; diff --git a/crates/menu/tests/it/shortcuts/fixture.rs b/crates/menu/tests/it/shortcuts/fixture.rs index 1bc858139d..fbafc48bf1 100644 --- a/crates/menu/tests/it/shortcuts/fixture.rs +++ b/crates/menu/tests/it/shortcuts/fixture.rs @@ -258,6 +258,16 @@ impl Rig { self.shared.borrow().sets.as_ref().map(|(p, _)| p.active().to_string()) } + /// Sets an automation field in the next dialog pass. + pub(crate) fn set_json_field(&mut self, field: &'static str, value: serde_json::Value) -> Result<(), String> { + let result = Rc::new(RefCell::new(None)); + let out = result.clone(); + let job: Job = Box::new(move |dialog, ui, state| *out.borrow_mut() = Some(dialog.set_json_field(ui, state, field, &value))); + self.shared.borrow_mut().jobs.push(job); + self.fixture.idle(2); + result.take().expect("the automation job ran") + } + /// Runs `job` with the dialog in the next pass and returns what it returns. pub(crate) fn import_json(&mut self, json: &str) -> Result { let result = Rc::new(RefCell::new(None)); diff --git a/crates/menu/tests/it/shortcuts/mod.rs b/crates/menu/tests/it/shortcuts/mod.rs index fc1ff547c8..b59b5b7f59 100644 --- a/crates/menu/tests/it/shortcuts/mod.rs +++ b/crates/menu/tests/it/shortcuts/mod.rs @@ -9,11 +9,307 @@ pub(crate) mod rows; pub(crate) mod sets; pub(crate) mod tabs; -use craft_keymap::Platform; +use std::cell::Cell; +use std::rc::Rc; + +use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Policy, Scope, Scopes, Trigger}; +use craft_menu::shortcuts::HoldSetting; +use craft_ui::contract::Role; use craft_ui::testing::trial; +use egui::{Key, Modifiers}; +use serde_json::json; use fixture::Rig; +#[trial] +fn automation_replaces_a_shortcut_in_its_scope_as_one_undo_step() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("type.bold")).unwrap(); + let original = rig.bindings("type.bold"); + let old = &original[0]; + + assert!(rig.set_json_field("replace", json!({"old": old, "new": "not a trigger"})).is_err()); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+B", "new": "Cmd+K"})).is_err()); + assert!(rig.set_json_field("replace", json!({"old": old, "new": "Hold K"})).is_err()); + assert_eq!(rig.bindings("type.bold"), original); + + rig.set_json_field("replace", json!({"old": old, "new": "Cmd+K"})).unwrap(); + assert_eq!(rig.bindings("type.bold"), ["Text: Cmd+K"]); + rig.click("Undo"); + assert_eq!(rig.bindings("type.bold"), original); + let shared = rig.shared.borrow(); + assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo); +} + +#[trial] +fn an_automation_replacement_waits_for_conflict_confirmation() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + assert!([Role::STATUS, Role::ALERT].into_iter().any(|role| !rig.names_with(role, "for Save (Application) with").is_empty())); + + rig.click("Take It"); + assert_eq!(rig.bindings("file.save"), ["Cmd+E"]); + assert!(rig.bindings("file.export").is_empty()); + rig.click("Undo"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); +} + +#[trial] +fn confirming_an_automation_replacement_preserves_shortcuts_that_changed_after_the_prompt() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + let third = CommandRef::from("object.front"); + rig.shared.borrow_mut().km.assign(&third, Binding::parse("Cmd+E").unwrap(), Policy::Keep).unwrap(); + rig.pass(); + rig.answer("Take It"); + + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + assert_eq!(rig.bindings("object.front"), ["Cmd+E"]); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn confirming_an_automation_replacement_cannot_change_shortcuts_in_a_new_scope() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + let mut catalog = rig.shared.borrow().km.catalog().to_vec(); + for command in &mut catalog { + if matches!(command.command.key().as_str(), "file.save" | "file.export") { + command.scope = Scope::new("Text").unwrap(); + } + } + rig.shared.borrow_mut().km = Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Mac); + rig.pass(); + rig.answer("Take It"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn a_holder_binding_change_retires_its_pending_replacement_confirmation() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + rig.shared.borrow_mut().km.assign(&CommandRef::from("file.export"), Binding::parse("Cmd+K").unwrap(), Policy::Keep).unwrap(); + rig.pass(); + rig.answer("Take It"); + + assert_eq!(rig.bindings("file.save"), ["Cmd+S"], "a stale confirmation cannot replace the original shortcut"); + assert_eq!(rig.bindings("file.export"), ["Cmd+E", "Cmd+K"], "the changed holder keeps all its current shortcuts"); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn a_superseding_replacement_has_its_own_confirmation_actions() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + let old_action = rig.find("Take It").node; + rig.shared.borrow_mut().options.allow_keep = false; + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+Shift+S"})).unwrap(); + assert_ne!(rig.find("Take It").node, old_action); + assert!(!rig.has("Keep Both")); + let dismiss = rig.find("Undo Changes").node; + rig.shared.borrow_mut().options.allow_keep = true; + rig.pass(); + assert_ne!(rig.find("Keep Both").node, dismiss); +} + +#[trial] +fn escape_dismisses_a_visible_prompt_before_a_hidden_replacement() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+E"})).unwrap(); + assert!(rig.has("Take It")); + rig.click("Reset All…"); + assert!(rig.has("Reset All")); + assert!(!rig.has("Take It")); + + rig.press(Modifiers::NONE, Key::Escape); + assert!(!rig.has("Reset All")); + assert!(rig.has("Take It")); + assert_eq!(rig.bindings("file.save"), ["Cmd+K"]); +} + +#[trial] +fn automation_offers_only_keep_both_when_taking_the_shortcut_cannot_be_saved() { + let scope = "Text".repeat(16); + let trigger = Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap(); + let retained = Binding::in_scope(trigger, Scope::new(&scope).unwrap()); + let save = CommandDef::new("file.save", "Save", Scope::app()).with_default(Binding::parse("Cmd+S").unwrap()); + let export = CommandDef::new("file.export", "Export", Scope::app()).with_default(retained.clone()).with_default(Binding::parse("Cmd+E").unwrap()); + let keymap = Keymap::new(vec![save, export], Scopes::new().with_context(&scope), Platform::Mac); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + assert!(!rig.has("Take It")); + assert!(!rig.has("Accept and Go to Conflict")); + rig.click("Keep Both"); + assert_eq!(rig.bindings("file.save"), ["Cmd+E"]); + assert_eq!(rig.bindings("file.export"), [retained.to_string(), "Cmd+E".into()]); +} + +#[trial] +fn automation_replacement_preserves_the_shortcut_when_the_app_rejects_it() { + let mut rig = Rig::tuned(Platform::Mac, |options| options.accept = Some(Box::new(|_, _| Err("That shortcut is unavailable".into())))); + rig.set_json_field("command", json!("file.save")).unwrap(); + let result = rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})); + assert_eq!(result, Err("That shortcut is unavailable".into())); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); +} + +#[trial] +fn confirming_an_automation_replacement_checks_the_current_app_rule() { + let accepted = Rc::new(Cell::new(true)); + let rule = accepted.clone(); + let mut rig = Rig::tuned(Platform::Mac, |options| { + options.accept = Some(Box::new(move |_, _| if rule.get() { Ok(()) } else { Err("That shortcut is unavailable".into()) })); + }); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + accepted.set(false); + rig.answer("Take It"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn a_pending_automation_conflict_cannot_be_applied_from_a_read_only_dialog() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + assert!(rig.has("Take It")); + + rig.shared.borrow_mut().options.editable = false; + rig.pass(); + assert!(!rig.has("Take It")); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + rig.press(Modifiers::NONE, Key::Escape); + assert!(!rig.is_open()); +} + +#[trial] +fn automation_cannot_replace_a_shortcut_while_reset_confirmation_is_open() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap(); + rig.click("Reset All…"); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+B"})).is_err()); + assert_eq!(rig.bindings("file.save"), ["Cmd+K"]); +} + +#[trial] +fn an_automation_hold_replacement_is_dismissed_when_holds_are_disabled() { + let mut keymap = fixture::keymap(Platform::Mac); + keymap.set_holds(true); + for (command, binding) in [("file.save", "Hold K"), ("file.export", "Hold L")] { + keymap.assign(&CommandRef::from(command), Binding::parse(binding).unwrap(), Policy::Keep).unwrap(); + } + let mut rig = Rig::with_holds(keymap, fixture::options(), HoldSetting::new(true, 0.5, 0.2..=2.0)); + rig.set_json_field("command", json!("file.save")).unwrap(); + let original = rig.bindings("file.save"); + assert!(rig.set_json_field("replace", json!({"old": "Hold K", "new": "Cmd+E"})).is_err()); + rig.set_json_field("replace", json!({"old": "Hold K", "new": "Hold L"})).unwrap(); + assert!(rig.has("Take It")); + + rig.click("Hold Shortcuts"); + assert!(!rig.has("Take It")); + rig.click("Hold Shortcuts"); + assert_eq!(rig.bindings("file.save"), original); +} + +#[trial] +fn automation_does_not_replace_a_binding_while_the_recorder_owns_it() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.click("Save: ⌘S"); + assert!(rig.shared.borrow().state.is_recording()); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).is_err()); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + rig.press(Modifiers::COMMAND, Key::L); + assert_eq!(rig.bindings("file.save"), ["Cmd+L"]); + assert!(!rig.shared.borrow().state.is_recording()); +} + +#[trial] +fn automation_rejects_oversize_replacements_but_can_replace_an_oversize_default() { + let scope = "Text".repeat(16); + let original = Binding::in_scope(Trigger::parse("Cmd+S").unwrap(), Scope::new(&scope).unwrap()); + let trigger = "Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash"; + let oversize = Binding::in_scope(Trigger::parse(trigger).unwrap(), Scope::new(&scope).unwrap()); + let command = CommandDef::new("text.save", "Save Text", Scope::app()).with_default(original.clone()); + let repair = CommandDef::new("text.fix", "Fix Text", Scope::app()).with_default(oversize.clone()).with_default(Binding::parse("Cmd+K").unwrap()); + let export = CommandDef::new("text.export", "Export Text", Scope::app()).with_default(Binding::parse("Cmd+L").unwrap()); + let keymap = Keymap::new(vec![command, repair, export], Scopes::new().with_context(&scope), Platform::Mac); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("text.save")).unwrap(); + + assert!(rig.set_json_field("replace", json!({"old": original.to_string(), "new": trigger})).is_err()); + assert_eq!(rig.bindings("text.save"), [original.to_string()]); + rig.set_json_field("command", json!("text.fix")).unwrap(); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+L"})).is_err()); + assert!(!rig.has("Take It")); + assert_eq!(rig.bindings("text.fix"), [oversize.to_string(), "Cmd+K".into()]); + let adjusted = format!("{scope}: Cmd+J"); + rig.set_json_field("replace", json!({"old": oversize.to_string(), "new": "Cmd+J"})).unwrap(); + assert_eq!(rig.bindings("text.fix"), [adjusted.clone(), "Cmd+K".into()]); + rig.set_json_field("replace", json!({"old": adjusted, "new": trigger})).unwrap(); + assert_eq!(rig.bindings("text.fix"), [oversize.to_string(), "Cmd+K".into()]); + assert!(rig.shared.borrow().km.overrides().is_empty()); +} + +#[trial] +fn automation_rejects_a_shortcut_that_would_reload_in_a_different_scope() { + let scope = "Cmd+"; + let original = Binding::in_scope(Trigger::parse("K").unwrap(), Scope::new(scope).unwrap()); + let command = CommandDef::new("text.save", "Save Text", Scope::app()).with_default(original.clone()); + let keymap = Keymap::new(vec![command], Scopes::new().with_context(scope), Platform::Mac); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("text.save")).unwrap(); + assert!(rig.set_json_field("replace", json!({"old": original.to_string(), "new": "Cmd+:"})).is_err()); + assert_eq!(rig.bindings("text.save"), [original.to_string()]); +} + +#[trial] +fn an_automation_replacement_with_the_same_effective_shortcut_is_a_noop() { + let mut rig = Rig::tuned(Platform::Windows, |_| {}); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Ctrl+S"})).unwrap(); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + let shared = rig.shared.borrow(); + assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo); +} + +#[trial] +fn an_automation_replacement_does_not_offer_to_take_a_shortcut_the_command_already_has() { + let mut keymap = fixture::keymap(Platform::Mac); + let save = CommandRef::from("file.save"); + keymap.assign(&save, Binding::parse("Cmd+E").unwrap(), Policy::Keep).unwrap(); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("file.save")).unwrap(); + let original = rig.bindings("file.save"); + + assert!(rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).is_err()); + assert!(!rig.has("Take It")); + assert_eq!(rig.bindings("file.save"), original); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); +} + /// A read-only shortcuts reference does not stretch to the window's height: it opens at a moderate, fixed height and /// scrolls inside it. #[trial] diff --git a/crates/menu/tests/it/shortcuts/tabs.rs b/crates/menu/tests/it/shortcuts/tabs.rs index a1d8022351..2f3dcea838 100644 --- a/crates/menu/tests/it/shortcuts/tabs.rs +++ b/crates/menu/tests/it/shortcuts/tabs.rs @@ -1,5 +1,8 @@ //! The app's pages share the Keyboard Shortcuts dialog's width and navigation. +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + use craft_host::target::Os; use craft_keymap::{Platform, Profiles}; use craft_menu::shortcuts::{Area, DialogState, DialogTab, ShortcutsDialog}; @@ -8,9 +11,42 @@ use craft_ui::contract::Role; use craft_ui::runtime::egui::access::AccessTree; use craft_ui::runtime::env::RootEnv; use craft_ui::testing::{Fixture, Frames, pointer, trial}; +use serde_json::json; use super::fixture; +#[trial] +fn shortcut_replacement_is_unavailable_on_an_app_tab() { + for (tab, app_tab) in [("menus", true), ("unknown", false)] { + let result = Rc::new(RefCell::new(None)); + let observed = result.clone(); + let drawn = Rc::new(Cell::new(false)); + let app_page_drawn = drawn.clone(); + let mut keys = fixture::keymap(Platform::Mac); + let mut state = DialogState::new().with_tab(tab); + let mut fixture = Fixture::new(move |ui| { + let mut tabs = [DialogTab::new("menus", "Menus", |_| { + app_page_drawn.set(true); + false + })]; + if observed.borrow().is_none() { + ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(ui, &mut state, "command", &json!("file.save")).unwrap(); + let answer = ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field( + ui, + &mut state, + "replace", + &json!({"old": "Cmd+S", "new": "Cmd+E"}), + ); + *observed.borrow_mut() = Some(answer); + } + ShortcutsDialog::new(&mut keys).tabs(&mut tabs).show(ui, &mut state); + }); + fixture.settle(); + assert_eq!(drawn.get(), app_tab); + assert_eq!(result.borrow().as_ref().unwrap().is_err(), app_tab); + } +} + fn dialog_at_125_percent(toolbar_label: &str) -> (Frames, impl FnMut(&mut egui::Ui) + '_) { // Use the Windows test context and a 1600 × 1000 physical-pixel window at 125%. let mut os = Fixture::new(|_| {}); diff --git a/crates/menu/tests/it/title_bar.rs b/crates/menu/tests/it/title_bar.rs index 15543e8d97..8c1260f038 100644 --- a/crates/menu/tests/it/title_bar.rs +++ b/crates/menu/tests/it/title_bar.rs @@ -47,19 +47,22 @@ fn window(width: f32, pixels_per_point: f32) -> Fixture { let mut fixture = Fixture::new(move |ui| { let bar = Rc::clone(&bar); AppShell::new(WindowKey::main()) - .title_bar(move |ui, _, _: &mut ()| { - let bar = Rc::clone(&bar); - let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; - TitleBar::new().frame(Frame::Integrated(Captions { family: CaptionFamily::Windows, layout })).show_titled( - ui, - Title::new(DOCUMENT), - move |ui, _| { - Picture::new("", 7, &brand).show(ui); - MenuBarUi::new(&bar).target(Target::Windows).mnemonics(&PREFERRED).help_search(true).show(ui); - }, - |_, _| {}, - ); - }) + .title_bar( + |_| None, + move |ui, _, _: &mut ()| { + let bar = Rc::clone(&bar); + let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; + TitleBar::new().frame(Frame::Integrated(Captions { family: CaptionFamily::Windows, layout })).show_titled( + ui, + Title::new(DOCUMENT), + move |ui, _| { + Picture::new("", 7, &brand).show(ui); + MenuBarUi::new(&bar).target(Target::Windows).mnemonics(&PREFERRED).help_search(true).show(ui); + }, + |_, _| {}, + ); + }, + ) .body(|ui, _, _| { ui.label("Document"); }) diff --git a/crates/mesh-ops/ATTRIBUTION.md b/crates/mesh-ops/ATTRIBUTION.md new file mode 100644 index 0000000000..6e592bafa0 --- /dev/null +++ b/crates/mesh-ops/ATTRIBUTION.md @@ -0,0 +1,32 @@ +# Attribution + +`craft-mesh-ops` generates tangents with the `mikktspace` crate. + +| Package | Authors | Source | License | +|---|---|---|---| +| `mikktspace` 0.3.0 | Benjamin Wasty, David Harvey-Macaulay, Layl Bongers | [crates.io](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field) | + +The package's `src/generated.rs` is a translation of Morten S. Mikkelsen's C implementation of +the MikkTSpace algorithm and carries that implementation's notice, reproduced here unchanged: + +```text +Copyright (C) 2011 by Morten S. Mikkelsen + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. +``` diff --git a/crates/mesh-ops/Cargo.toml b/crates/mesh-ops/Cargo.toml new file mode 100644 index 0000000000..441abc88c1 --- /dev/null +++ b/crates/mesh-ops/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "craft-mesh-ops" +description = "Triangle mesh operations: smooth normals, MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs, a BVH and an orbit camera" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +glam = { version = "0.30", features = ["serde"] } +# MIT OR Apache-2.0; its src/generated.rs also carries the zlib-style notice of the C original, +# reproduced in ATTRIBUTION.md. +mikktspace = { version = "0.3", default-features = false, features = ["glam"] } +rayon = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md new file mode 100644 index 0000000000..6cce2e23df --- /dev/null +++ b/crates/mesh-ops/README.md @@ -0,0 +1,43 @@ +# craft-mesh-ops + +Operations on triangle meshes, for apps that paint, bake or preview materials on 3D models. The +crate has no UI, does no file or network I/O and has no `unsafe` code. File formats stay in +[`craft-mesh`](../mesh/README.md). + +- **`Mesh`.** Positions, normals, tangents, UVs, vertex colors, indices, per-material submeshes + and polygon-diagonal flags, with `validate`, `append`, `subdivided`, `normalize_to`, wireframe + and UV-seam edges, and UV-tile helpers. +- **Normals and tangents.** Smooth normals are area weighted. Tangents come from MikkTSpace, which + glTF 2.0 recommends for meshes without tangents + (): `w` holds the bitangent sign. +- **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting + vertices where charts meet. +- **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle + and barycentrics under the texel center; `surface_at` turns them into a position, normal and + tangent frame. `UvGBuffer::new` returns an error for a side of 0 or above `MAX_SIDE` (16,384), + for more than `MAX_TEXELS` texels (8,192 × 8,192), and when the memory cannot be reserved. +- **Primitives.** Sphere, rounded box, cube, cylinder, torus and plane with UVs and tangents, and + the built-in scenes in `primitives::BUILTINS`. +- **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a + leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box + queries. +- **Camera.** `OrbitCamera` and `Ray` give an orbit view and picking rays. + +`GeomError::Invalid` is the one error type. `rayon` parallelizes the UV G-buffer, and `serde` +serializes `OrbitCamera`; both are always on. + +## Origin + +| Part | Source | +|---|---| +| `mesh.rs`, `bvh.rs`, `primitives.rs`, `gbuffer.rs`, `unwrap.rs`, `camera.rs` and their tests | TextureCraft `crates/geom` at [386630e](https://github.com/storytold/texturecraft/commit/386630ee85cb22679295b24013575d1aecb39ad2) | +| `Mesh::subdivided` and `subdivision_shares_edge_midpoints` | MaterialCraft `crates/geom/src/mesh.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) | + +MikkTSpace comes from the `mikktspace` crate; its notice is in [ATTRIBUTION.md](ATTRIBUTION.md). + +## Migration + +| App | Status | +|---|---| +| TextureCraft | `texturecraft-geom` is the source. The app switches to this crate in its own pull request. | +| MaterialCraft | `materialcraft-geom` is the source of `subdivided`. The app switches in its own pull request. | diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs new file mode 100644 index 0000000000..9b01c84155 --- /dev/null +++ b/crates/mesh-ops/src/bvh.rs @@ -0,0 +1,678 @@ +//! Bounding volume hierarchy over a mesh's triangles: closest-hit and any-hit ray casts, and +//! box queries (used by picking, baking and brush stamps). + +use glam::{Vec3, Vec3A}; + +use crate::Mesh; + +#[derive(Clone, Copy, Debug)] +struct Node { + lo: Vec3A, + hi: Vec3A, + /// Leaf: first triangle in `order`; inner: index of the left child (right = left + 1). + first: u32, + /// Triangles in a leaf; 0 for inner nodes. + count: u32, +} + +/// A ray hit: distance, triangle and barycentrics (weights of vertices 1 and 2). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hit { + pub t: f32, + pub tri: u32, + pub u: f32, + pub v: f32, +} + +#[derive(Clone, Debug)] +pub struct Bvh { + nodes: Vec, + /// Triangle vertices in BVH order. + tris: Vec<[Vec3; 3]>, + /// Original triangle index of each entry in `tris`. + order: Vec, +} + +const LEAF: usize = 4; + +/// Traversal stack of (node, entry distance): inline for typical depths (no allocation per +/// ray), spilling to the heap for degenerate trees. +struct Stack { + inline: [(u32, f32); 64], + len: usize, + spill: Vec<(u32, f32)>, +} + +impl Default for Stack { + fn default() -> Self { + Stack { inline: [(0, 0.0); 64], len: 0, spill: Vec::new() } + } +} + +impl Stack { + fn push(&mut self, v: (u32, f32)) { + match self.inline.get_mut(self.len) { + Some(slot) if self.spill.is_empty() => { + *slot = v; + self.len += 1; + } + _ => self.spill.push(v), + } + } + + fn pop(&mut self) -> Option<(u32, f32)> { + self.spill.pop().or_else(|| { + self.len = self.len.checked_sub(1)?; + self.inline.get(self.len).copied() + }) + } +} +const BINS: usize = 12; + +fn grow(lo: &mut Vec3, hi: &mut Vec3, p: Vec3) { + *lo = lo.min(p); + *hi = hi.max(p); +} + +fn area(lo: Vec3, hi: Vec3) -> f32 { + let d = (hi - lo).max(Vec3::ZERO); + d.x * d.y + d.y * d.z + d.z * d.x +} + +impl Bvh { + pub fn new(mesh: &Mesh) -> Bvh { + let triangle_count = mesh.triangle_count(); + let mut tris = Vec::with_capacity(triangle_count); + + for triangle in 0..triangle_count { + let Some([a, b, c]) = mesh.tri(triangle) else { continue }; + let position = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); + tris.push([position(a), position(b), position(c)]); + } + + let mut order: Vec = (0..tris.len() as u32).collect(); + let centroids: Vec = tris.iter().map(|t| (t[0] + t[1] + t[2]) / 3.0).collect(); + + let mut nodes = vec![Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 }]; + let mut stack = vec![0usize]; + + while let Some(node_index) = stack.pop() { + let Node { first, count, .. } = nodes[node_index]; + let (start, count) = (first as usize, count as usize); + let (mut bounds_min, mut bounds_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + let (mut centroid_min, mut centroid_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + + for &triangle in &order[start..start + count] { + for position in tris[triangle as usize] { + grow(&mut bounds_min, &mut bounds_max, position); + } + grow(&mut centroid_min, &mut centroid_max, centroids[triangle as usize]); + } + + nodes[node_index].lo = bounds_min.into(); + nodes[node_index].hi = bounds_max.into(); + + if count <= LEAF { + continue; + } + + let centroid_extent = centroid_max - centroid_min; + let bin_of = |triangle: u32, axis: usize| { + let offset = centroids[triangle as usize][axis] - centroid_min[axis]; + ((offset / centroid_extent[axis] * BINS as f32) as usize).min(BINS - 1) + }; + + // Reuse each triangle's bounds across all three axes + let mut axis_bins = [[(0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); BINS]; 3]; + + for &triangle in &order[start..start + count] { + let [a, b, c] = tris[triangle as usize]; + let (triangle_min, triangle_max) = (a.min(b).min(c), a.max(b).max(c)); + + for axis in 0..3 { + if centroid_extent[axis] <= 1e-12 { + continue; + } + + let bin = &mut axis_bins[axis][bin_of(triangle, axis)]; + bin.0 += 1; + bin.1 = bin.1.min(triangle_min); + bin.2 = bin.2.max(triangle_max); + } + } + + let mut best_axis = 0; + let mut best_split = 0; + let mut best_cost = f32::MAX; + + for axis in 0..3 { + if centroid_extent[axis] <= 1e-12 { + continue; + } + + let bins = axis_bins[axis]; + + // Cache right bounds once and advance the left bounds per split + let mut suffix = bins; + for i in (0..BINS - 1).rev() { + suffix[i] = (suffix[i].0 + suffix[i + 1].0, suffix[i].1.min(suffix[i + 1].1), suffix[i].2.max(suffix[i + 1].2)); + } + + let (mut left_count, mut left_min, mut left_max) = (0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + + for split in 1..BINS { + let bin = bins[split - 1]; + left_count += bin.0; + left_min = left_min.min(bin.1); + left_max = left_max.max(bin.2); + + let (right_count, right_min, right_max) = suffix[split]; + if left_count == 0 || right_count == 0 { + continue; + } + + let cost = left_count as f32 * area(left_min, left_max) + right_count as f32 * area(right_min, right_max); + if cost < best_cost { + best_cost = cost; + best_axis = axis; + best_split = split; + } + } + } + + let node_order = &mut order[start..start + count]; + let left_count = if best_split == 0 || best_cost >= count as f32 * area(bounds_min, bounds_max) { + // Split by count when SAH cannot help, including tied centroids + let axis = if centroid_extent.x >= centroid_extent.y && centroid_extent.x >= centroid_extent.z { + 0 + } else if centroid_extent.y >= centroid_extent.z { + 1 + } else { + 2 + }; + + let mid = count / 2; + node_order.select_nth_unstable_by(mid, |&a, &b| centroids[a as usize][axis].total_cmp(¢roids[b as usize][axis])); + mid + } else { + let mut left_count = 0; + + for i in 0..node_order.len() { + if bin_of(node_order[i], best_axis) < best_split { + node_order.swap(left_count, i); + left_count += 1; + } + } + + left_count + }; + + if left_count == 0 || left_count == count { + continue; + } + + let left_child = nodes.len(); + nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first, count: left_count as u32 }); + nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: first + left_count as u32, count: (count - left_count) as u32 }); + + nodes[node_index].first = left_child as u32; + nodes[node_index].count = 0; + + stack.push(left_child); + stack.push(left_child + 1); + } + + let tris = order.iter().map(|t| tris[*t as usize]).collect(); + Bvh { nodes, tris, order } + } + + pub fn is_empty(&self) -> bool { + self.tris.is_empty() + } + + /// The flattened tree (for GPU traversal), root first: bounds, then for a leaf the range + /// `first..first + count` of [`Bvh::triangles`], for an inner node (`count` 0) the children + /// `first` and `first + 1`. + pub fn nodes(&self) -> impl ExactSizeIterator + '_ { + self.nodes.iter().map(|n| (n.lo.into(), n.hi.into(), n.first, n.count)) + } + + /// Triangle vertices in BVH order, and the original triangle index of each. + pub fn triangles(&self) -> (&[[Vec3; 3]], &[u32]) { + (&self.tris, &self.order) + } + + fn slab(lo: Vec3A, hi: Vec3A, o: Vec3A, inv: Vec3A, tmax: f32) -> Option { + let t0 = (lo - o) * inv; + let t1 = (hi - o) * inv; + // A ray lying in a slab plane gives 0·∞ = NaN: it is inside that slab, so the axis does + // not bound the hit. + let open = t0.is_nan_mask() | t1.is_nan_mask(); + let tn = Vec3A::select(open, Vec3A::NEG_INFINITY, t0.min(t1)).max_element().max(0.0); + let tf = Vec3A::select(open, Vec3A::INFINITY, t0.max(t1)).min_element().min(tmax); + (tn <= tf).then_some(tn) + } + + /// Möller–Trumbore, double sided. + fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { + let e1 = t[1] - t[0]; + let e2 = t[2] - t[0]; + let p = d.cross(e2); + let det = e1.dot(p); + if det.abs() < 1e-12 { + return None; + } + let inv = 1.0 / det; + let s = o - t[0]; + // A little slack on the edges: rays through a shared edge must not slip between its + // two triangles to a surface behind. + const EDGE: f32 = 1e-5; + let u = s.dot(p) * inv; + if !(-EDGE..=1.0 + EDGE).contains(&u) { + return None; + } + let q = s.cross(e1); + let v = d.dot(q) * inv; + if v < -EDGE || u + v > 1.0 + EDGE { + return None; + } + let tt = e2.dot(q) * inv; + (tt > 0.0).then_some((tt, u, v)) + } + + fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option { + let root = self.nodes.first().filter(|_| !self.tris.is_empty())?; + let (oa, inv) = (Vec3A::from(o), Vec3A::ONE / Vec3A::from(d)); + let mut best = None; + let mut stack = Stack::default(); + stack.push((0, Self::slab(root.lo, root.hi, oa, inv, tmax)?)); + // Entries carry their entry distance: nodes behind a closer hit are skipped unopened. + while let Some((ni, tn)) = stack.pop() { + let Some(n) = self.nodes.get(ni as usize).filter(|_| tn <= tmax) else { continue }; + if n.count > 0 { + let (f, c) = (n.first as usize, n.count as usize); + for i in f..(f + c).min(self.tris.len()) { + let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue }; + if let Some((t, u, v)) = Self::hit_tri(tri, o, d) + && t < tmax + && filter(orig) + { + tmax = t; + best = Some(Hit { t, tri: orig, u, v }); + if any { + return best; + } + } + } + } else { + // Visit the nearer child first. + let (l, r) = (n.first, n.first + 1); + let dl = self.nodes.get(l as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); + let dr = self.nodes.get(r as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); + match (dl, dr) { + (Some(a), Some(b)) if a <= b => { + stack.push((r, b)); + stack.push((l, a)); + } + (Some(a), Some(b)) => { + stack.push((l, a)); + stack.push((r, b)); + } + (Some(a), None) => stack.push((l, a)), + (None, Some(b)) => stack.push((r, b)), + (None, None) => {} + } + } + } + best + } + + /// Closest hit along `o + t·d` for `t` in (0, tmax). + pub fn closest(&self, o: Vec3, d: Vec3, tmax: f32) -> Option { + self.traverse(o, d, tmax, false, &|_| true) + } + + /// Closest hit on triangles accepted by `filter` (original triangle index). + pub fn closest_filtered(&self, o: Vec3, d: Vec3, tmax: f32, filter: &dyn Fn(u32) -> bool) -> Option { + self.traverse(o, d, tmax, false, filter) + } + + /// Whether anything is hit before `tmax` (occlusion rays). + pub fn occluded(&self, o: Vec3, d: Vec3, tmax: f32) -> bool { + self.traverse(o, d, tmax, true, &|_| true).is_some() + } + + /// The point nearest to `p` within `max_dist` on a triangle accepted by `filter` (original + /// index): a [`Hit`] with the distance in `t` and the barycentrics of vertices 1 and 2. + pub fn nearest(&self, p: Vec3, max_dist: f32, filter: &dyn Fn(u32) -> bool) -> Option { + let root = self.nodes.first().filter(|_| !self.tris.is_empty() && p.is_finite())?; + let pa = Vec3A::from(p); + let box_d2 = |n: &Node| (n.lo - pa).max(pa - n.hi).max(Vec3A::ZERO).length_squared(); + let (mut best_d2, mut best) = (max_dist * max_dist, None); + let mut stack = Stack::default(); + stack.push((0, box_d2(root))); + while let Some((ni, d2)) = stack.pop() { + let Some(n) = self.nodes.get(ni as usize).filter(|_| d2 <= best_d2) else { continue }; + if n.count > 0 { + for i in n.first as usize..(n.first as usize + n.count as usize).min(self.tris.len()) { + let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue }; + if !filter(orig) { + continue; + } + let (q, u, v) = closest_on_triangle(p, tri); + let dd = (q - p).length_squared(); + if dd < best_d2 { + best_d2 = dd; + best = Some(Hit { t: dd.sqrt(), tri: orig, u, v }); + } + } + } else { + // Push the farther child first so the nearer one is searched first. + let child = |c: u32| self.nodes.get(c as usize).map(|n| (c, box_d2(n))); + let (Some(l), Some(r)) = (child(n.first), child(n.first + 1)) else { continue }; + let (near, far) = if l.1 <= r.1 { (l, r) } else { (r, l) }; + stack.push(far); + stack.push(near); + } + } + best + } + + /// Call `f` with every triangle (original index) whose bounds overlap the box. + pub fn query_box(&self, lo: Vec3, hi: Vec3, mut f: impl FnMut(u32)) { + let mut stack = vec![0u32]; + while let Some(i) = stack.pop() { + let Some(n) = self.nodes.get(i as usize) else { continue }; + if self.tris.is_empty() || n.hi.cmplt(lo.into()).any() || n.lo.cmpgt(hi.into()).any() { + continue; + } + if n.count > 0 { + for k in n.first as usize..(n.first + n.count) as usize { + let (Some(t), Some(o)) = (self.tris.get(k), self.order.get(k)) else { continue }; + let tlo = t[0].min(t[1]).min(t[2]); + let thi = t[0].max(t[1]).max(t[2]); + if !(thi.cmplt(lo).any() || tlo.cmpgt(hi).any()) { + f(*o); + } + } + } else { + stack.push(n.first); + stack.push(n.first + 1); + } + } + } +} + +/// The point of triangle `t` nearest to `p` and its barycentrics (weights of vertices 1 and 2), +/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5). Degenerate triangles give +/// a non-finite distance and are never nearest. +fn closest_on_triangle(p: Vec3, t: &[Vec3; 3]) -> (Vec3, f32, f32) { + let [a, b, c] = *t; + let (ab, ac, ap) = (b - a, c - a, p - a); + let (d1, d2) = (ab.dot(ap), ac.dot(ap)); + if d1 <= 0.0 && d2 <= 0.0 { + return (a, 0.0, 0.0); + } + let bp = p - b; + let (d3, d4) = (ab.dot(bp), ac.dot(bp)); + if d3 >= 0.0 && d4 <= d3 { + return (b, 1.0, 0.0); + } + let vc = d1 * d4 - d3 * d2; + if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 { + let v = d1 / (d1 - d3); + return (a + ab * v, v, 0.0); + } + let cp = p - c; + let (d5, d6) = (ab.dot(cp), ac.dot(cp)); + if d6 >= 0.0 && d5 <= d6 { + return (c, 0.0, 1.0); + } + let vb = d5 * d2 - d1 * d6; + if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 { + let w = d2 / (d2 - d6); + return (a + ac * w, 0.0, w); + } + let va = d3 * d6 - d5 * d4; + if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 { + let w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return (b + (c - b) * w, 1.0 - w, w); + } + let denom = 1.0 / (va + vb + vc); + let (v, w) = (vb * denom, vc * denom); + (a + ab * v + ac * w, v, w) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::primitives; + + #[test] + fn nearest_point_matches_brute_force() { + let m = primitives::builtin("torus").unwrap(); + let bvh = Bvh::new(&m); + let mut seed = 7u32; + let mut rnd = move || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 * 4.0 - 2.0 + }; + for _ in 0..200 { + let p = Vec3::new(rnd(), rnd(), rnd()); + let hit = bvh.nearest(p, f32::MAX, &|_| true).unwrap(); + let brute = (0..m.triangle_count()) + .map(|t| { + let [a, b, c] = m.tri(t).unwrap().map(|i| m.positions[i]); + (closest_on_triangle(p, &[a, b, c]).0 - p).length() + }) + .fold(f32::MAX, f32::min); + assert!((hit.t - brute).abs() < 1e-5, "{} vs {brute}", hit.t); + let [a, b, c] = m.tri(hit.tri as usize).unwrap().map(|i| m.positions[i]); + let q = a * (1.0 - hit.u - hit.v) + b * hit.u + c * hit.v; + assert!(((q - p).length() - hit.t).abs() < 1e-4); + } + assert!(bvh.nearest(Vec3::splat(100.0), 1.0, &|_| true).is_none(), "out of range"); + assert!(bvh.nearest(Vec3::ZERO, f32::MAX, &|_| false).is_none(), "filtered out"); + } + + #[test] + fn traversal_stack_spills_in_lifo_order() { + let mut st = Stack::default(); + for v in 0..200 { + st.push((v, v as f32)); + } + assert!((0..200).rev().all(|v| st.pop() == Some((v, v as f32)))); + assert_eq!(st.pop(), None); + } + + #[test] + fn ray_hits_sphere_at_expected_distance() { + let m = primitives::sphere(1.0, 64, 32); + let bvh = Bvh::new(&m); + let h = bvh.closest(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!((h.t - 4.0).abs() < 0.01, "{}", h.t); + assert!(bvh.closest(Vec3::new(0.0, 3.0, 5.0), Vec3::NEG_Z, 100.0).is_none()); + // Rays lying exactly in a node's bounding plane (y = 0 is the equator) hit the front. + // Axis-aligned rays lying in a node's bounding plane (y = 0) still find the front. + for x in [-0.5f32, -0.4, 0.3] { + let h = bvh.closest(Vec3::new(x, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t); + } + // Rays through shared edges (the equator) hit the front, never slip through to the back. + let m = primitives::sphere(1.0, 48, 24); + let bvh = Bvh::new(&m); + for i in 0..200 { + let x = i as f32 / 100.0 - 1.0; + let o = Vec3::new(0.0, 0.0, 5.0); + let d = (Vec3::new(x * 0.9, 0.0, 0.0) - o).normalize(); + let h = bvh.closest(o, d, 100.0).unwrap(); + assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t); + } + assert!(bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 10.0)); + assert!(!bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 3.0)); + } + + #[test] + fn matches_brute_force() { + let m = primitives::material_ball(); + let bvh = Bvh::new(&m); + for i in 0..200 { + let a = i as f32 * 0.731; + let o = Vec3::new(a.cos() * 6.0, (i as f32 * 0.37).sin() * 3.0 + 1.0, a.sin() * 6.0); + let d = (Vec3::new(0.0, 1.0, 0.0) + Vec3::new((a * 3.1).sin(), (a * 1.7).cos(), (a * 2.3).sin()) * 0.6 - o).normalize(); + let fast = bvh.closest(o, d, 1e9).map(|h| h.t); + let mut slow: Option = None; + for t in 0..m.triangle_count() { + let [x, y, z] = m.tri(t).unwrap(); + if let Some((tt, _, _)) = Bvh::hit_tri(&[m.positions[x], m.positions[y], m.positions[z]], o, d) { + slow = Some(slow.map_or(tt, |s: f32| s.min(tt))); + } + } + match (fast, slow) { + (Some(a), Some(b)) => assert!((a - b).abs() < 1e-4, "{a} {b}"), + (None, None) => {} + other => panic!("mismatch {other:?}"), + } + } + } + + #[test] + fn box_query_finds_overlapping_triangles() { + let m = primitives::plane(2.0, 4); + let bvh = Bvh::new(&m); + let mut found = Vec::new(); + bvh.query_box(Vec3::new(-0.1, -0.1, -0.1), Vec3::new(0.1, 0.1, 0.1), |t| found.push(t)); + assert!(!found.is_empty() && found.len() <= 8, "{found:?}"); + let empty = Bvh::new(&Mesh::default()); + assert!(empty.closest(Vec3::ZERO, Vec3::X, 1.0).is_none()); + } + + #[test] + fn large_coplanar_plate_does_not_degrade_leaf_sizes() { + let mut positions = Vec::new(); + let mut indices = Vec::new(); + let w = 200.0f32; + let h = 100.0f32; + + // Large plate at z = 0 + let b = positions.len() as u32; + positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]); + indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]); + + // 500 small triangles sitting at z = 0.5 + for i in 0..500 { + let x = 20.0 + (i % 160) as f32; + let y = 10.0 + ((i / 160) % 80) as f32; + let idx = positions.len() as u32; + positions.push(Vec3::new(x, y, 0.5)); + positions.push(Vec3::new(x + 0.5, y, 0.5)); + positions.push(Vec3::new(x, y + 0.5, 0.6)); + indices.extend_from_slice(&[idx, idx + 1, idx + 2]); + } + + let mesh = Mesh { + positions, + normals: Vec::new(), + uvs: Vec::new(), + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: Vec::new(), + materials: Vec::new(), + diagonals: Vec::new(), + }; + + let bvh = Bvh::new(&mesh); + + for (_, _, _, count) in bvh.nodes() { + if count > 0 { + assert!(count <= LEAF as u32, "leaf has too many triangles: {count}"); + } + } + + // The foreground triangle is the closest hit + let hit = bvh.closest(Vec3::new(20.1, 10.1, 10.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!((hit.t - 9.5).abs() < 0.1, "hit t: {}", hit.t); + } + + #[test] + fn clustered_coplanar_fallback_partitions_nodes() { + let mut positions = Vec::new(); + let mut indices = Vec::new(); + let w = 200.0f32; + let h = 100.0f32; + + let b = positions.len() as u32; + positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]); + indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]); + + // Shared bins keep every SAH split as costly as an unsplit leaf + for i in 0..500 { + let x = 130.0 + (i % 10) as f32 * 0.1; + let y = 64.0 + (i / 10) as f32 * 0.02; + let idx = positions.len() as u32; + positions.push(Vec3::new(x, y, 0.0)); + positions.push(Vec3::new(x + 0.01, y, 0.0)); + positions.push(Vec3::new(x, y + 0.01, 0.0)); + indices.extend_from_slice(&[idx, idx + 1, idx + 2]); + } + + let mesh = Mesh { + positions, + normals: Vec::new(), + uvs: Vec::new(), + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: Vec::new(), + materials: Vec::new(), + diagonals: Vec::new(), + }; + + let bvh = Bvh::new(&mesh); + + for (_, _, _, count) in bvh.nodes() { + if count > 0 { + assert!(count <= LEAF as u32, "leaf has too many triangles: {count}"); + } + } + } + + #[test] + fn coincident_centroids_still_partition_large_and_small_triangles() { + let mut mesh = Mesh::default(); + + // Different triangle sizes share an exact centroid + for i in 0..=500 { + let size = if i == 0 { 100.0 } else { 0.01 + i as f32 * 0.0001 }; + let first = mesh.positions.len() as u32; + mesh.positions.extend([Vec3::new(-size, -size, 0.0), Vec3::new(size, -size, 0.0), Vec3::new(0.0, 2.0 * size, 0.0)]); + mesh.indices.extend([first, first + 1, first + 2]); + } + + mesh.normals.resize(mesh.positions.len(), Vec3::Z); + mesh.uvs.resize(mesh.positions.len(), glam::Vec2::ZERO); + mesh.tangents.resize(mesh.positions.len(), glam::Vec4::new(1.0, 0.0, 0.0, 1.0)); + mesh.validate().unwrap(); + + let bvh = Bvh::new(&mesh); + + for (_, _, _, count) in bvh.nodes() { + assert!(count <= LEAF as u32, "leaf has too many triangles: {count}"); + } + + // The outer ray only hits the large triangle + let origin = Vec3::new(50.0, 0.0, 10.0); + let hit = bvh.closest(origin, Vec3::NEG_Z, 100.0).unwrap(); + assert_eq!(hit.tri, 0); + assert_eq!(hit.t, 10.0); + + assert!(bvh.occluded(origin, Vec3::NEG_Z, 100.0)); + assert!(!bvh.occluded(origin, Vec3::NEG_Z, 5.0)); + + // Median partitions preserve original triangle IDs + let hit = bvh.closest_filtered(Vec3::new(0.0, 0.0, 10.0), Vec3::NEG_Z, 100.0, &|t| t == 500).unwrap(); + assert_eq!(hit.tri, 500); + assert_eq!(hit.t, 10.0); + } +} diff --git a/crates/mesh-ops/src/camera.rs b/crates/mesh-ops/src/camera.rs new file mode 100644 index 0000000000..1f4156c93e --- /dev/null +++ b/crates/mesh-ops/src/camera.rs @@ -0,0 +1,140 @@ +//! Orbit camera (texture painting navigation) and picking rays. + +use glam::{Mat4, Vec2, Vec3, Vec4}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct OrbitCamera { + pub target: Vec3, + /// Radians around Y. + pub yaw: f32, + /// Radians above the horizon, clamped to ±89°. + pub pitch: f32, + pub distance: f32, + /// Vertical field of view, degrees. + pub fov: f32, + /// Scene radius (sets the clip planes). + pub scene_radius: f32, + /// Orthographic projection instead of perspective. + #[serde(default)] + pub ortho: bool, +} + +impl Default for OrbitCamera { + fn default() -> Self { + OrbitCamera { target: Vec3::ZERO, yaw: 0.0, pitch: 0.12, distance: 5.0, fov: 40.0, scene_radius: 1.0, ortho: false } + } +} + +/// A ray in world space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ray { + pub origin: Vec3, + pub dir: Vec3, +} + +impl OrbitCamera { + pub fn eye(&self) -> Vec3 { + let (sy, cy) = self.yaw.sin_cos(); + let (sp, cp) = self.pitch.sin_cos(); + self.target + Vec3::new(cp * sy, sp, cp * cy) * self.distance + } + + pub fn forward(&self) -> Vec3 { + (self.target - self.eye()).try_normalize().unwrap_or(Vec3::NEG_Z) + } + + pub fn view(&self) -> Mat4 { + Mat4::look_at_rh(self.eye(), self.target, Vec3::Y) + } + + pub fn proj(&self, aspect: f32) -> Mat4 { + let r = self.scene_radius.max(1e-3); + let near = (self.distance - r * 4.0).max(r * 0.01).max(1e-4); + let far = self.distance + r * 50.0; + let aspect = if aspect.is_finite() && aspect > 1e-4 { aspect } else { 1.0 }; + if self.ortho { + let h = self.distance * (self.fov.to_radians() * 0.5).tan(); + Mat4::orthographic_rh(-h * aspect, h * aspect, -h, h, near.min(0.01), far) + } else { + Mat4::perspective_rh(self.fov.clamp(5.0, 150.0).to_radians(), aspect, near, far) + } + } + + pub fn view_proj(&self, aspect: f32) -> Mat4 { + self.proj(aspect) * self.view() + } + + /// Frame a bounding box, keeping the current angles. + pub fn frame(&mut self, lo: Vec3, hi: Vec3) { + self.target = (lo + hi) * 0.5; + let r = ((hi - lo).length() * 0.5).max(1e-3); + self.scene_radius = r; + self.distance = r / (self.fov.clamp(5.0, 150.0).to_radians() * 0.5).sin() * 1.1; + } + + pub fn orbit(&mut self, dx: f32, dy: f32) { + self.yaw -= dx; + self.pitch = (self.pitch + dy).clamp(-89f32.to_radians(), 89f32.to_radians()); + } + + /// Pan by a screen fraction (dx, dy in viewport heights). + pub fn pan(&mut self, dx: f32, dy: f32) { + let f = self.forward(); + let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let up = right.cross(f); + let scale = self.distance * (self.fov.to_radians() * 0.5).tan() * 2.0; + self.target += (-right * dx + up * dy) * scale; + } + + /// Dolly by a factor exponent (positive zooms in). + pub fn zoom(&mut self, amount: f32) { + let r = self.scene_radius.max(1e-3); + self.distance = (self.distance * (-amount).exp()).clamp(r * 0.05, r * 200.0); + } + + /// Ray through a viewport point given in normalized device coordinates (-1..1, y up). + pub fn ray(&self, ndc: Vec2, aspect: f32) -> Ray { + let inv = self.view_proj(aspect).inverse(); + let a = inv * Vec4::new(ndc.x, ndc.y, 0.0, 1.0); + let b = inv * Vec4::new(ndc.x, ndc.y, 1.0, 1.0); + let (a, b) = (a.truncate() / a.w, b.truncate() / b.w); + Ray { origin: a, dir: (b - a).try_normalize().unwrap_or(self.forward()) } + } + + /// Project a world point to NDC (x, y in -1..1, y up; z depth). None behind the camera. + pub fn project(&self, p: Vec3, aspect: f32) -> Option { + let c = self.view_proj(aspect) * p.extend(1.0); + (c.w > 1e-6).then(|| c.truncate() / c.w) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn center_ray_points_at_target_and_projection_inverts() { + let mut c = OrbitCamera::default(); + c.frame(Vec3::splat(-1.0), Vec3::splat(1.0)); + let r = c.ray(Vec2::ZERO, 1.5); + assert!((r.dir - c.forward()).length() < 1e-4); + let p = Vec3::new(0.3, -0.2, 0.1); + let ndc = c.project(p, 1.5).unwrap(); + let r = c.ray(ndc.truncate(), 1.5); + let to_p = (p - r.origin).normalize(); + assert!(to_p.dot(r.dir) > 0.9999); + } + + #[test] + fn pitch_is_clamped_and_zoom_bounded() { + let mut c = OrbitCamera::default(); + c.orbit(0.0, 10.0); + assert!(c.pitch <= 89f32.to_radians() + 1e-6); + for _ in 0..1000 { + c.zoom(1.0); + } + assert!(c.distance > 0.0 && c.distance.is_finite()); + let _ = c.proj(f32::NAN); + } +} diff --git a/crates/mesh-ops/src/gbuffer.rs b/crates/mesh-ops/src/gbuffer.rs new file mode 100644 index 0000000000..c40b6ea5cb --- /dev/null +++ b/crates/mesh-ops/src/gbuffer.rs @@ -0,0 +1,257 @@ +//! The UV-space G-buffer: which triangle (and where on it) each texel of a texture set maps +//! to. Painting, compositing, baking and padding all work from this one buffer, so they agree +//! on which texel is which surface point. + +use glam::{Vec2, Vec3, Vec4}; +use rayon::prelude::*; + +use crate::{GeomError, Mesh, Result}; + +/// Texel not covered by any triangle. +pub const NO_TRI: u32 = u32::MAX; + +const BAND: u32 = 32; + +/// Largest width or height of a G-buffer, in texels. +pub const MAX_SIDE: u32 = 16_384; + +/// Largest texel count of a G-buffer (8,192 × 8,192). Each texel takes 12 bytes, so a full +/// buffer takes 768 MiB and its largest vector (`bary`) 512 MiB, which fits a 32-bit address +/// space. +pub const MAX_TEXELS: usize = 1 << 26; + +#[derive(Clone, Debug, PartialEq)] +pub struct UvGBuffer { + pub width: u32, + pub height: u32, + /// Triangle under each texel center, [`NO_TRI`] when uncovered. + pub tri: Vec, + /// Barycentric weights of the triangle's second and third vertices. + pub bary: Vec<[f32; 2]>, + /// Texels written by more than one triangle (overlapping UVs). + pub overlaps: u32, +} + +/// Interpolated surface attributes at a texel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Surface { + pub pos: Vec3, + /// Interpolated shading normal (normalized). + pub nrm: Vec3, + /// Flat triangle normal (for ray offsets). + pub geo_nrm: Vec3, + pub tangent: Vec4, + pub uv: Vec2, + pub tri: u32, +} + +/// Checks a requested G-buffer size against [`MAX_SIDE`] and [`MAX_TEXELS`] and returns its +/// texel count. +fn checked_texels(width: u32, height: u32) -> Result { + for (name, side) in [("width", width), ("height", height)] { + if side == 0 || side > MAX_SIDE { + return Err(GeomError::Invalid(format!("G-buffer {name} {side} is outside 1..={MAX_SIDE}"))); + } + } + // Both sides are at most MAX_SIDE, so the product fits in usize on 32-bit targets too. + let n = width as usize * height as usize; + if n > MAX_TEXELS { + return Err(GeomError::Invalid(format!("G-buffer {width}×{height} has more than {MAX_TEXELS} texels"))); + } + Ok(n) +} + +/// A vector of `n` copies of `value`, or an error when the memory cannot be reserved. +fn filled(n: usize, value: T) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|e| GeomError::Invalid(format!("G-buffer of {n} texels: {e}")))?; + v.resize(n, value); + Ok(v) +} + +fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 { + (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) +} + +impl UvGBuffer { + /// Rasterize the triangles of material `material` at `width × height`. + /// + /// Returns an error when `width` or `height` is 0 or above [`MAX_SIDE`], when + /// `width × height` is above [`MAX_TEXELS`], or when the buffer's memory cannot be reserved. + pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> Result { + let n = checked_texels(width, height)?; + let (w, h) = (width, height); + let size = Vec2::new(w as f32, h as f32); + let bands = h.div_ceil(BAND) as usize; + let mut bins: Vec> = vec![Vec::new(); bands]; + for t in mesh.triangles_of(material) { + let Some([a, b, c]) = mesh.tri(t) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; + let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64; + let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64; + if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() { + continue; + } + let (b0, b1) = ((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize); + for bin in bins.iter_mut().take(b1 + 1).skip(b0) { + bin.push(t as u32); + } + } + let mut tri = filled(n, NO_TRI)?; + let mut bary = filled(n, [0.0f32; 2])?; + let band_len = BAND as usize * w as usize; + let overlaps: u32 = tri + .par_chunks_mut(band_len) + .zip(bary.par_chunks_mut(band_len)) + .enumerate() + .map(|(bi, (tri, bary))| { + let mut overlaps = 0u32; + let row0 = bi as u32 * BAND; + let rows = (tri.len() as u32) / w; + for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) { + let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; + let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; + let (pa, pb, pc) = (ua * size, ub * size, uc * size); + let area = edge(pa, pb, pc); + if area.abs() < 1e-12 { + continue; + } + let eps = -1e-6 * area.abs(); + let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32; + let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w); + let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0); + let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows); + for y in y0..y1 { + for x in x0..x1 { + let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum()); + if w0 < eps || w1 < eps || w2 < eps { + continue; + } + let i = (y - row0) as usize * w as usize + x as usize; + if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) { + if *slot != NO_TRI { + overlaps += 1; + } + *slot = t; + let inv = 1.0 / area.abs(); + *bw = [w1 * inv, w2 * inv]; + } + } + } + } + overlaps + }) + .sum(); + Ok(UvGBuffer { width: w, height: h, tri, bary, overlaps }) + } + + pub fn covered(&self, i: usize) -> bool { + self.tri.get(i).is_some_and(|t| *t != NO_TRI) + } + + pub fn coverage_mask(&self) -> Vec { + self.tri.iter().map(|t| *t != NO_TRI).collect() + } + + pub fn covered_count(&self) -> usize { + self.tri.iter().filter(|t| **t != NO_TRI).count() + } + + /// Surface attributes at texel index `i` (None when uncovered). + pub fn surface(&self, mesh: &Mesh, i: usize) -> Option { + let t = *self.tri.get(i)?; + if t == NO_TRI { + return None; + } + let [b1, b2] = *self.bary.get(i)?; + surface_at(mesh, t, b1, b2) + } +} + +/// Interpolate triangle `t` at barycentrics (weights of vertices 1 and 2). +pub fn surface_at(mesh: &Mesh, t: u32, b1: f32, b2: f32) -> Option { + let [a, b, c] = mesh.tri(t as usize)?; + let b0 = 1.0 - b1 - b2; + let p = |v: &[Vec3]| -> Option { Some(*v.get(a)? * b0 + *v.get(b)? * b1 + *v.get(c)? * b2) }; + let pos = p(&mesh.positions)?; + let nrm = p(&mesh.normals)?.try_normalize().unwrap_or(Vec3::Y); + let (pa, pb, pc) = (*mesh.positions.get(a)?, *mesh.positions.get(b)?, *mesh.positions.get(c)?); + let geo_nrm = (pb - pa).cross(pc - pa).try_normalize().unwrap_or(nrm); + let tan = *mesh.tangents.get(a)? * b0 + *mesh.tangents.get(b)? * b1 + *mesh.tangents.get(c)? * b2; + let uv = *mesh.uvs.get(a)? * b0 + *mesh.uvs.get(b)? * b1 + *mesh.uvs.get(c)? * b2; + let tdir = tan.truncate().try_normalize().unwrap_or_else(|| nrm.any_orthonormal_vector()); + let w = mesh.tangents.get(a).map(|t| if t.w < 0.0 { -1.0 } else { 1.0 }).unwrap_or(1.0); + Some(Surface { pos, nrm, geo_nrm, tangent: tdir.extend(w), uv, tri: t }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::primitives; + + #[test] + fn half_triangle_covers_texels_with_centers_inside() { + // One triangle covering the lower-left half of UV space (v down: y = v·H). + let m = Mesh::from_parts( + vec![Vec3::ZERO, Vec3::X, Vec3::Y], + None, + vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)], + vec![0, 1, 2], + "m", + ) + .unwrap(); + let g = UvGBuffer::new(&m, 0, 8, 8).unwrap(); + for y in 0..8u32 { + for x in 0..8u32 { + let inside = (x as f32 + 0.5) <= (y as f32 + 0.5); + assert_eq!(g.covered((y * 8 + x) as usize), inside, "({x},{y})"); + } + } + assert_eq!(g.overlaps, 0); + } + + #[test] + fn overlapping_and_degenerate_triangles() { + let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)]; + let m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z], None, uv, vec![0, 1, 2, 0, 1, 2, 0, 3, 3], "m").unwrap(); + let g = UvGBuffer::new(&m, 0, 16, 16).unwrap(); + assert!(g.overlaps > 0); + assert!(g.covered_count() > 0); + } + + #[test] + fn sizes_outside_the_limits_are_rejected() { + // 2^27 + 1 texels wide: 32 rows of it overflow u32. + assert!(checked_texels((1 << 27) + 1, 1).is_err()); + assert!(checked_texels(u32::MAX, u32::MAX).is_err()); + assert!(checked_texels(0, 8).is_err()); + assert!(checked_texels(8, 0).is_err()); + assert!(checked_texels(MAX_SIDE + 1, 1).is_err()); + assert!(checked_texels(1, MAX_SIDE + 1).is_err()); + // Both sides in range, but more than MAX_TEXELS texels. + assert!(checked_texels(MAX_SIDE, MAX_SIDE).is_err()); + assert!(checked_texels(MAX_SIDE, 4_097).is_err()); + assert_eq!(checked_texels(MAX_SIDE, 4_096), Ok(MAX_TEXELS)); + assert_eq!(checked_texels(MAX_SIDE, 1), Ok(MAX_SIDE as usize)); + + let m = primitives::sphere(1.0, 8, 4); + assert!(UvGBuffer::new(&m, 0, MAX_SIDE + 1, 1).is_err()); + assert!(UvGBuffer::new(&m, 0, 0, 1).is_err()); + let g = UvGBuffer::new(&m, 0, 64, 32).unwrap(); + assert_eq!((g.width, g.height, g.tri.len(), g.bary.len()), (64, 32, 2_048, 2_048)); + } + + #[test] + fn sphere_surface_lies_on_the_sphere() { + let m = primitives::sphere(2.0, 64, 32); + let g = UvGBuffer::new(&m, 0, 128, 128).unwrap(); + assert!(g.covered_count() > 128 * 128 * 9 / 10, "{}", g.covered_count()); + for i in (0..g.tri.len()).step_by(97) { + if let Some(s) = g.surface(&m, i) { + assert!((s.pos.length() - 2.0).abs() < 0.02); + assert!(s.nrm.dot(s.pos.normalize()) > 0.99); + } + } + } +} diff --git a/crates/mesh-ops/src/lib.rs b/crates/mesh-ops/src/lib.rs new file mode 100644 index 0000000000..51c528bd1e --- /dev/null +++ b/crates/mesh-ops/src/lib.rs @@ -0,0 +1,28 @@ +//! # craft-mesh-ops +//! +//! Triangle mesh operations: the [`Mesh`] type with normals and MikkTSpace tangents, built-in +//! [`primitives`] (material ball, sphere, cube, …), a [`Bvh`] for ray casts and box queries, +//! the UV-space [`UvGBuffer`] that maps texels to surface points, and the [`OrbitCamera`]. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod bvh; +pub mod camera; +pub mod gbuffer; +pub mod mesh; +pub mod primitives; +pub mod unwrap; + +pub use bvh::{Bvh, Hit}; +pub use camera::{OrbitCamera, Ray}; +pub use gbuffer::{MAX_SIDE, MAX_TEXELS, NO_TRI, Surface, UvGBuffer, surface_at}; +pub use glam; +pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; + +#[derive(Debug, thiserror::Error, Clone, PartialEq)] +pub enum GeomError { + #[error("invalid mesh: {0}")] + Invalid(String), +} + +pub type Result = std::result::Result; diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs new file mode 100644 index 0000000000..77c993d3c6 --- /dev/null +++ b/crates/mesh-ops/src/mesh.rs @@ -0,0 +1,647 @@ +//! The internal triangle mesh. + +use glam::{Vec2, Vec3, Vec4}; + +use crate::{GeomError, Result}; + +/// An edge by the bits of its two end positions, the lower one first +type EdgePositions = ([u32; 3], [u32; 3]); + +/// A contiguous index range drawn with one material. +#[derive(Clone, Debug, PartialEq)] +pub struct SubMesh { + pub name: String, + pub material: usize, + /// First index (into [`Mesh::indices`]) and index count. + pub start: u32, + pub count: u32, +} + +/// A material's base color (what a color-map bake transfers): `factor` (linear RGBA) times an +/// optional texture sampled at the mesh UVs. +#[derive(Clone, Debug, PartialEq)] +pub struct BaseColor { + pub factor: Vec4, + pub width: u32, + pub height: u32, + /// `width × height` RGBA8 texels (color sRGB-encoded, alpha linear), rows top → bottom like + /// the UVs' v; empty without a texture. + pub texels: Vec<[u8; 4]>, +} + +/// Triangle mesh in world space. UVs use the glTF convention (origin top-left, v down). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Mesh { + pub positions: Vec, + pub normals: Vec, + /// xyz tangent, w bitangent sign. + pub tangents: Vec, + pub uvs: Vec, + /// RGBA vertex colors in 0..1 (glTF: linear; OBJ, PLY: as stored): one per vertex, or empty. + pub colors: Vec, + pub indices: Vec, + /// Index ranges per material and part (node / object); `name` is the part name. + pub submeshes: Vec, + pub materials: Vec, + /// Per triangle, bit `i` set when edge `i` (corner `i` to corner `i + 1`) is a diagonal the + /// importer added to split a polygon, which wireframes leave out. Empty: every edge is real. + pub diagonals: Vec, +} + +/// Hard cap on mesh size accepted from files (triangles). +pub const MAX_TRIANGLES: usize = 20_000_000; + +impl Mesh { + pub fn triangle_count(&self) -> usize { + self.indices.len() / 3 + } + + pub fn vertex_count(&self) -> usize { + self.positions.len() + } + + /// Axis-aligned bounds (zero box for an empty mesh). + pub fn bounds(&self) -> (Vec3, Vec3) { + if self.positions.is_empty() { + return (Vec3::ZERO, Vec3::ZERO); + } + self.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))) + } + + /// Bounding-sphere radius around the bounds center (at least a small epsilon). + pub fn radius(&self) -> f32 { + let (lo, hi) = self.bounds(); + ((hi - lo).length() * 0.5).max(1e-4) + } + + /// Vertex indices of triangle `t`. + pub fn tri(&self, t: usize) -> Option<[usize; 3]> { + let i = self.indices.get(t * 3..t * 3 + 3)?; + Some([i[0] as usize, i[1] as usize, i[2] as usize]) + } + + /// The edges wireframes draw: each vertex pair once (smaller index first), leaving out + /// polygon diagonals ([`Mesh::diagonals`]) unless only one triangle has the edge (a UV seam + /// split it from its twin), per material in `0..materials.len().max(1)`. + pub fn wire_edges(&self) -> Vec> { + (0..self.materials.len().max(1)) + .map(|m| { + // Edge → (real in some triangle, triangles using it), in first-seen order. + let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new(); + let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); + for t in self.triangles_of(m) { + let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue }; + let hidden = self.diagonals.get(t).copied().unwrap_or(0); + for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() { + let key = (a.min(b), a.max(b)); + let real = hidden >> i & 1 == 0; + let e = *at.entry(key).or_insert_with(|| { + edges.push((key, false, 0)); + edges.len() - 1 + }); + if let Some((_, r, n)) = edges.get_mut(e) { + *r |= real; + *n = n.saturating_add(1); + } + } + } + edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect() + }) + .collect() + } + + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` + pub fn uv_seam_edges(&self) -> Vec> { + // Signed zero denotes the same position on either side of an imported seam + let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() }); + let mut seams = vec![Vec::new(); self.materials.len().max(1)]; + // Match across materials before grouping the lines for texture-set visibility + let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); + for material in 0..seams.len() { + for triangle in self.triangles_of(material) { + let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + + for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] { + let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { + continue; + }; + + let (from_bits, to_bits) = (bits(*from_position), bits(*to_position)); + let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }; + sides.entry(edge).or_default().push((pair.0, pair.1, material)); + } + } + } + + let uv = |index: u32| self.uvs.get(index as usize).copied(); + for pairs in sides.into_values() { + let Some(&(first_from, first_to, _)) = pairs.first() else { continue }; + + if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) { + for (from, to, material) in pairs { + if let Some(edges) = seams.get_mut(material) { + edges.push((from.min(to), from.max(to))); + } + } + } + } + for edges in &mut seams { + edges.sort_unstable(); + edges.dedup(); + } + + seams + } + + /// Material of triangle `t`. + pub fn material_of(&self, t: usize) -> Option { + let idx = (t * 3) as u32; + self.submeshes.iter().find(|s| idx >= s.start && idx < s.start.saturating_add(s.count)).map(|s| s.material) + } + + /// Triangle index range belonging to material `m` (all submeshes of that material). + pub fn triangles_of(&self, m: usize) -> impl Iterator + '_ { + self.submeshes.iter().filter(move |s| s.material == m).flat_map(|s| (s.start / 3) as usize..((s.start + s.count) / 3) as usize) + } + + /// Check that attribute arrays agree and every index is in range. + pub fn validate(&self) -> Result<()> { + let n = self.positions.len(); + if self.normals.len() != n || self.uvs.len() != n || self.tangents.len() != n { + return Err(GeomError::Invalid(format!( + "attribute counts differ: {} positions, {} normals, {} uvs, {} tangents", + n, + self.normals.len(), + self.uvs.len(), + self.tangents.len() + ))); + } + if !self.colors.is_empty() && self.colors.len() != n { + return Err(GeomError::Invalid(format!("{} vertex colors for {n} vertices", self.colors.len()))); + } + if !self.indices.len().is_multiple_of(3) { + return Err(GeomError::Invalid("index count is not a multiple of 3".into())); + } + if self.triangle_count() > MAX_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has more than {MAX_TRIANGLES} triangles"))); + } + if let Some(bad) = self.indices.iter().find(|i| **i as usize >= n) { + return Err(GeomError::Invalid(format!("index {bad} out of range ({n} vertices)"))); + } + if self.positions.iter().any(|p| !p.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite positions".into())); + } + for s in &self.submeshes { + if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) { + return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); + } + } + Ok(()) + } + + /// Area-weighted smooth normals over the index buffer. + pub fn compute_normals(&mut self) { + let mut normals = vec![Vec3::ZERO; self.positions.len()]; + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let face = (*pb - *pa).cross(*pc - *pa); + for v in [a, b, c] { + if let Some(x) = normals.get_mut(v) { + *x += face; + } + } + } + + self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + } + + /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). + pub fn compute_tangents(&mut self) { + self.tangents = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); self.positions.len()]; + if self.normals.len() != self.positions.len() { + self.compute_normals(); + } + if self.uvs.len() != self.positions.len() { + self.uvs = vec![Vec2::ZERO; self.positions.len()]; + } + // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. + let usable = !crate::unwrap::all_triangles_degenerate(self); + let mut g = Mikk { mesh: self }; + if !usable || !mikktspace::generate_tangents(&mut g) { + self.simple_tangents(); + } + for (t, n) in self.tangents.iter_mut().zip(&self.normals) { + // Orthonormalize against the normal; repair degenerate results. + let v = t.truncate(); + let o = (v - *n * n.dot(v)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); + *t = o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }); + } + } + + fn simple_tangents(&mut self) { + let mut tangents = vec![Vec3::ZERO; self.positions.len()]; + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; + let (e1, e2) = (*pb - *pa, *pc - *pa); + let (d1, d2) = (*ub - *ua, *uc - *ua); + let determinant = d1.x * d2.y - d2.x * d1.y; + if determinant.abs() < 1e-12 { + continue; + } + + let tangent = (e1 * d2.y - e2 * d1.y) / determinant; + for v in [a, b, c] { + if let Some(x) = tangents.get_mut(v) { + *x += tangent; + } + } + } + + self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); + } + + /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), + /// ascending. Non-finite UVs are skipped. + pub fn uv_tiles(&self, m: usize) -> std::collections::BTreeSet<(i32, i32)> { + self.triangles_of(m) + .filter_map(|t| { + let [a, b, c] = self.tri(t)?; + let uv = (*self.uvs.get(a)? + *self.uvs.get(b)? + *self.uvs.get(c)?) / 3.0; + uv.is_finite().then(|| (uv.x.floor() as i32, uv.y.floor() as i32)) + }) + .collect() + } + + /// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other + /// materials are duplicated first, so the other triangles keep their UVs. + pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) { + self.map_material_uvs_with(m, |_, uv| f(uv)); + } + + /// [`Mesh::map_material_uvs`] where `f` also gets the UV centroid of the first of the + /// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then + /// place a vertex on a tile border with its own triangle's tile. + pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) { + let material_triangles: Vec = self.triangles_of(m).collect(); + let mut in_material = vec![false; self.triangle_count()]; + for t in &material_triangles { + if let Some(x) = in_material.get_mut(*t) { + *x = true; + } + } + + let mut shared = vec![false; self.positions.len()]; + for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) { + for v in tri { + if let Some(s) = shared.get_mut(*v as usize) { + *s = true; + } + } + } + + let mut duplicates = std::collections::HashMap::new(); + for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) { + let Some(&v) = self.indices.get(k) else { continue }; + let v = if shared.get(v as usize).copied().unwrap_or(false) { + *duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) + } else { + v + }; + if let Some(i) = self.indices.get_mut(k) { + *i = v; + } + } + + // (vertex, centroid of its first triangle), each vertex once + let mut vertices = Vec::with_capacity(material_triangles.len() * 3); + for t in &material_triangles { + let Some(tri) = self.tri(*t) else { continue }; + let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::() / 3.0; + vertices.extend(tri.map(|v| (v, centroid))); + } + + vertices.sort_by_key(|(v, _)| *v); + vertices.dedup_by_key(|(v, _)| *v); + for (v, centroid) in vertices { + if let Some(uv) = self.uvs.get_mut(v) { + *uv = f(centroid, *uv); + } + } + } + + /// Append a copy of vertex `v`; returns its index. + fn duplicate_vertex(&mut self, v: usize) -> u32 { + let i = self.positions.len() as u32; + self.positions.push(self.positions.get(v).copied().unwrap_or_default()); + self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); + self.tangents.push(self.tangents.get(v).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0))); + self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); + if !self.colors.is_empty() { + self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE)); + } + i + } + + /// Append `other`, offsetting indices; its submeshes keep their material indices shifted by + /// this mesh's material count. + pub fn append(&mut self, other: &Mesh) { + let base = self.positions.len() as u32; + let ibase = self.indices.len() as u32; + let mbase = self.materials.len(); + self.positions.extend_from_slice(&other.positions); + self.normals.extend_from_slice(&other.normals); + self.tangents.extend_from_slice(&other.tangents); + self.uvs.extend_from_slice(&other.uvs); + if !(self.colors.is_empty() && other.colors.is_empty()) { + // Vertices of the side without colors become white. + self.colors.resize(base as usize, Vec4::ONE); + self.colors.extend(other.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(other.positions.len())); + } + if !(self.diagonals.is_empty() && other.diagonals.is_empty()) { + self.diagonals.resize(ibase as usize / 3, 0); + self.diagonals.extend(other.diagonals.iter().copied().chain(std::iter::repeat(0)).take(other.triangle_count())); + } + self.indices.extend(other.indices.iter().map(|i| i + base)); + self.materials.extend(other.materials.iter().cloned()); + self.submeshes.extend(other.submeshes.iter().map(|s| SubMesh { + name: s.name.clone(), + material: s.material + mbase, + start: s.start + ibase, + count: s.count, + })); + } + + /// Each triangle split into four at its edge midpoints (shared edges share their midpoint); + /// attributes are interpolated and submesh ranges keep their triangles. + pub fn subdivided(&self) -> Mesh { + let mut m = Mesh { indices: Vec::with_capacity(self.indices.len() * 4), ..self.clone() }; + let has = |len: usize| len == self.positions.len(); + let (has_n, has_t, has_uv, has_c) = (has(self.normals.len()), has(self.tangents.len()), has(self.uvs.len()), has(self.colors.len())); + let mut mids = std::collections::HashMap::new(); + let mut mid = |m: &mut Mesh, a: u32, b: u32| -> u32 { + *mids.entry((a.min(b), a.max(b))).or_insert_with(|| { + let (i, j) = (a as usize, b as usize); + m.positions.push((self.positions[i] + self.positions[j]) * 0.5); + if has_n { + m.normals.push((self.normals[i] + self.normals[j]).normalize_or_zero()); + } + if has_t { + let (ti, tj) = (self.tangents[i], self.tangents[j]); + m.tangents.push((ti.truncate() + tj.truncate()).normalize_or_zero().extend(ti.w)); + } + if has_uv { + m.uvs.push((self.uvs[i] + self.uvs[j]) * 0.5); + } + if has_c { + m.colors.push((self.colors[i] + self.colors[j]) * 0.5); + } + (m.positions.len() - 1) as u32 + }) + }; + for t in self.indices.as_chunks::<3>().0 { + if t.iter().any(|&i| i as usize >= self.positions.len()) { + continue; + } + let (a, b, c) = (t[0], t[1], t[2]); + let (ab, bc, ca) = (mid(&mut m, a, b), mid(&mut m, b, c), mid(&mut m, c, a)); + m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]); + } + for s in &mut m.submeshes { + s.start *= 4; + s.count *= 4; + } + m + } + + /// Uniformly scale and translate so the mesh is centered with the given bounding radius. + pub fn normalize_to(&mut self, radius: f32) { + let (lo, hi) = self.bounds(); + let c = (lo + hi) * 0.5; + let s = radius / self.radius(); + for p in &mut self.positions { + *p = (*p - c) * s; + } + } + + /// A single-material mesh from raw attributes; computes missing normals and tangents. + pub fn from_parts(positions: Vec, normals: Option>, uvs: Vec, indices: Vec, material: &str) -> Result { + let count = indices.len() as u32; + let mut m = Mesh { + normals: normals.unwrap_or_default(), + uvs, + positions, + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], + materials: vec![material.into()], + diagonals: Vec::new(), + }; + if m.normals.len() != m.positions.len() { + m.compute_normals(); + } + m.compute_tangents(); + m.validate()?; + Ok(m) + } +} + +struct Mikk<'a> { + mesh: &'a mut Mesh, +} + +impl Mikk<'_> { + fn vi(&self, face: usize, vert: usize) -> usize { + self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize + } +} + +impl mikktspace::Geometry for Mikk<'_> { + fn num_faces(&self) -> usize { + self.mesh.indices.len() / 3 + } + fn num_vertices_of_face(&self, _face: usize) -> usize { + 3 + } + fn position(&self, face: usize, vert: usize) -> [f32; 3] { + self.mesh.positions.get(self.vi(face, vert)).copied().unwrap_or_default().to_array() + } + fn normal(&self, face: usize, vert: usize) -> [f32; 3] { + self.mesh.normals.get(self.vi(face, vert)).copied().unwrap_or(Vec3::Y).to_array() + } + fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] { + // MikkTSpace expects OpenGL texture coordinates (v up); our UVs are glTF (v down). With + // v flipped, the bitangent `cross(N, T) * w` points up the image, as glTF requires. + let uv = self.mesh.uvs.get(self.vi(face, vert)).copied().unwrap_or_default(); + [uv.x, 1.0 - uv.y] + } + fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) { + let i = self.vi(face, vert); + if let Some(t) = self.mesh.tangents.get_mut(i) { + *t = Vec4::from_array(tangent); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn quad() -> Mesh { + Mesh::from_parts( + vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)], + None, + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)], + vec![0, 1, 2, 0, 2, 3], + "Default", + ) + .unwrap() + } + + #[test] + fn normals_and_tangents_of_a_quad() { + let m = quad(); + for n in &m.normals { + assert!((*n - Vec3::Z).length() < 1e-5); + } + for t in &m.tangents { + assert!((t.truncate() - Vec3::X).length() < 1e-4, "{t:?}"); + } + assert_eq!(m.material_of(1), Some(0)); + assert_eq!(m.triangles_of(0).collect::>(), vec![0, 1]); + } + + #[test] + fn wire_edges_leave_out_polygon_diagonals() { + let mut m = quad(); + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge"); + // Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad. + m.diagonals = vec![0b100, 0b001]; + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]); + // A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays. + let mut seam = m.clone(); + seam.indices[3] = 4; + assert_eq!(seam.wire_edges()[0].len(), 6); + // Appending keeps each side's diagonals on its own triangles. + let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap(); + a.append(&m); + assert_eq!(a.diagonals, vec![0, 0b100, 0b001]); + assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); + } + + #[test] + fn uv_seams_are_where_the_uv_layout_splits() { + let mesh = quad(); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); + + // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut + let mut seam = mesh.clone(); + seam.positions.push(seam.positions[0]); + seam.normals.push(seam.normals[0]); + seam.tangents.push(seam.tangents[0]); + seam.uvs.push(Vec2::new(0.9, 0.9)); + seam.indices[3] = 4; + assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + + // The same split with the same UV is a hard edge, not a seam + let mut hard = seam.clone(); + hard.uvs[4] = hard.uvs[0]; + assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); + } + + #[test] + fn uv_seams_join_positions_with_opposite_signed_zero() { + let mut mesh = quad(); + mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0)); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + assert_eq!(mesh.positions[0], mesh.positions[4]); + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + } + + #[test] + fn uv_seams_between_materials_belong_to_both_materials() { + let mut mesh = quad(); + mesh.positions.push(mesh.positions[0]); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + mesh.materials.push("second".into()); + mesh.submeshes[0].count = 3; + mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 }); + + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); + mesh.uvs[4] = mesh.uvs[0]; + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam"); + } + + #[test] + fn subdivision_shares_edge_midpoints() { + let m = quad().subdivided(); + // 4 corners + 5 edge midpoints (the diagonal is shared), 8 triangles. + assert_eq!((m.positions.len(), m.triangle_count()), (9, 8)); + assert_eq!(m.uvs.len(), 9); + assert_eq!((m.submeshes[0].start, m.submeshes[0].count), (0, 24)); + m.validate().unwrap(); + } + + #[test] + fn validate_catches_bad_indices() { + let mut m = quad(); + m.indices[0] = 99; + assert!(m.validate().is_err()); + let mut m = quad(); + m.uvs.pop(); + assert!(m.validate().is_err()); + } + + #[test] + fn append_offsets_indices_and_materials() { + let mut a = quad(); + let b = quad(); + a.append(&b); + assert_eq!(a.indices[6], 4); + assert_eq!(a.submeshes[1].material, 1); + assert_eq!(a.submeshes[1].start, 6); + a.validate().unwrap(); + // Colors on one side only: the other side's vertices become white. + let mut red = quad(); + red.colors = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); 4]; + a.append(&red); + assert_eq!(a.colors.len(), 12); + assert_eq!((a.colors[0], a.colors[8]), (Vec4::ONE, Vec4::new(1.0, 0.0, 0.0, 1.0))); + a.append(&quad()); + assert_eq!(a.colors[15], Vec4::ONE); + a.validate().unwrap(); + a.colors.pop(); + assert!(a.validate().is_err()); + } + + #[test] + fn material_uvs_remap_and_split_shared_vertices() { + // quad(): two triangles sharing an edge; put the second in its own material. + let mut m = quad(); + m.materials = vec!["a".into(), "b".into()]; + m.submeshes = + vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }]; + let before = m.clone(); + m.map_material_uvs(1, |uv| uv + Vec2::X); + m.validate().unwrap(); + assert_eq!(m.vertex_count(), 6, "the two shared vertices are split"); + assert_eq!(&m.indices[..3], &before.indices[..3]); + for k in 0..3 { + let (old, new) = (before.indices[k] as usize, m.indices[k] as usize); + assert_eq!(m.uvs[new], before.uvs[old], "material a keeps its UVs"); + let (old, new) = (before.indices[3 + k] as usize, m.indices[3 + k] as usize); + assert_eq!((m.uvs[new], m.positions[new]), (before.uvs[old] + Vec2::X, before.positions[old])); + } + assert_eq!(m.uv_tiles(1).into_iter().collect::>(), vec![(1, 0)]); + assert_eq!(m.uv_tiles(0).into_iter().collect::>(), vec![(0, 0)]); + } +} diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs new file mode 100644 index 0000000000..43a9f29684 --- /dev/null +++ b/crates/mesh-ops/src/primitives.rs @@ -0,0 +1,556 @@ +//! Built-in meshes with clean, non-overlapping UVs: material ball, sphere, (rounded) cube, +//! cylinder, torus and plane. Y is up; triangles are counter-clockwise seen from outside. + +use std::f32::consts::{PI, TAU}; + +use glam::{Vec2, Vec3}; + +use crate::mesh::{Mesh, SubMesh}; + +/// A UV-space rectangle: origin and size. +#[derive(Clone, Copy, Debug)] +struct UvRect { + o: Vec2, + s: Vec2, +} + +impl UvRect { + const FULL: UvRect = UvRect { o: Vec2::ZERO, s: Vec2::ONE }; + fn map(&self, u: f32, v: f32) -> Vec2 { + self.o + self.s * Vec2::new(u, v) + } + fn inset(&self, m: f32) -> UvRect { + UvRect { o: self.o + Vec2::splat(m), s: self.s - Vec2::splat(2.0 * m) } + } +} + +#[derive(Default)] +struct Builder { + p: Vec, + n: Vec, + uv: Vec, + idx: Vec, + /// Per triangle: its [`Mesh::diagonals`] bits. + diag: Vec, +} + +impl Builder { + fn vert(&mut self, p: Vec3, n: Vec3, uv: Vec2) -> u32 { + self.p.push(p); + self.n.push(n.try_normalize().unwrap_or(Vec3::Y)); + self.uv.push(uv); + (self.p.len() - 1) as u32 + } + + /// A grid of (rows+1)×(cols+1) vertices from `f(row, col)`, rows going "down" the texture. + fn grid(&mut self, rows: usize, cols: usize, mut f: impl FnMut(usize, usize) -> (Vec3, Vec3, Vec2)) { + let base = self.p.len() as u32; + for i in 0..=rows { + for j in 0..=cols { + let (p, n, uv) = f(i, j); + self.vert(p, n, uv); + } + } + let w = (cols + 1) as u32; + for i in 0..rows as u32 { + for j in 0..cols as u32 { + let a = base + i * w + j; + let (b, c, d) = (a + 1, a + w, a + w + 1); + self.idx.extend_from_slice(&[a, c, d, a, d, b]); + // Edge d-a of the first triangle and a-d of the second split the quad. + self.diag.extend_from_slice(&[0b100, 0b001]); + } + } + } + + /// The mesh of one material, with tangents. + fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m + } + + /// The mesh of one material, without tangents. + fn into_mesh(self, material: &str) -> Mesh { + let count = self.idx.len() as u32; + Mesh { + positions: self.p, + normals: self.n, + uvs: self.uv, + indices: self.idx, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], + materials: vec![material.into()], + diagonals: self.diag, + } + } +} + +/// UV sphere of `radius` centred at `center`. +pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh { + let mut b = Builder::default(); + sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL); + b.finish("Sphere") +} + +fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: usize, r: UvRect) { + b.grid(rings, segs, |i, j| { + let (u, v) = (j as f32 / segs as f32, i as f32 / rings as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let n = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (center + n * radius, n, r.map(u, v)) + }); +} + +/// A box with rounded edges (`bevel` = edge radius; 0 gives a plain cube). Faces are laid out +/// in a 3×2 UV atlas. +pub fn rounded_box(half: Vec3, bevel: f32) -> Mesh { + let mut b = Builder::default(); + rounded_box_into(&mut b, Vec3::ZERO, half, bevel, UvRect::FULL); + b.finish("Box") +} + +/// The cube primitive (sharp edges). +pub fn cube(size: f32) -> Mesh { + let mut m = rounded_box(Vec3::splat(size * 0.5), 0.0); + m.materials = vec!["Cube".into()]; + if let Some(s) = m.submeshes.first_mut() { + s.name = "Cube".into(); + } + m +} + +fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: UvRect) { + let bevel = bevel.clamp(0.0, half.min_element() * 0.95); + // (normal, U = right, V = down) per face, seen from outside. + let faces = [ + (Vec3::Z, Vec3::X, -Vec3::Y), + (Vec3::X, -Vec3::Z, -Vec3::Y), + (-Vec3::Z, -Vec3::X, -Vec3::Y), + (-Vec3::X, Vec3::Z, -Vec3::Y), + (Vec3::Y, Vec3::X, Vec3::Z), + (-Vec3::Y, Vec3::X, -Vec3::Z), + ]; + let (kb, kc) = if bevel > 0.0 { (6usize, 10usize) } else { (0, 12) }; + // Coordinates along one face axis from -h to h, dense in the bevels. + let coords = |h: f32| -> Vec { + let inner = h - bevel; + let mut v = Vec::new(); + for i in 0..kb { + v.push(-h + bevel * i as f32 / kb as f32); + } + for i in 0..=kc { + v.push(-inner + 2.0 * inner * i as f32 / kc as f32); + } + for i in 1..=kb { + v.push(inner + bevel * i as f32 / kb as f32); + } + v + }; + let inner = half - Vec3::splat(bevel); + for (f, (n, u, v)) in faces.iter().enumerate() { + let cell = UvRect { o: r.map((f % 3) as f32 / 3.0, (f / 3) as f32 / 2.0), s: r.s * Vec2::new(1.0 / 3.0, 0.5) }.inset(0.01 * r.s.x); + let (hu, hv, hn) = ((*u * half).abs().max_element(), (*v * half).abs().max_element(), (*n * half).abs().max_element()); + let (cu, cv) = (coords(hu), coords(hv)); + let (cols, rows) = (cu.len() - 1, cv.len() - 1); + b.grid(rows, cols, |i, j| { + let (a, c) = (cu[j], cv[i]); + let q = *n * hn + *u * a + *v * c; + let clamped = q.clamp(-inner, inner); + let dir = (q - clamped).try_normalize().unwrap_or(*n); + let p = if bevel > 0.0 { clamped + dir * bevel } else { q }; + let nn = if bevel > 0.0 { dir } else { *n }; + (center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv))) + }); + } +} + +/// Surface of revolution of a profile `(radius, y)` listed top → bottom, mapped into `r` +/// (u around, v down the profile by arc length). +fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize, r: UvRect) { + if profile.len() < 2 { + return; + } + let mut len = vec![0.0f32]; + for w in profile.windows(2) { + let d = Vec2::new(w[1].0 - w[0].0, w[1].1 - w[0].1).length(); + len.push(len.last().copied().unwrap_or(0.0) + d); + } + let total = len.last().copied().unwrap_or(1.0).max(1e-6); + let rows = profile.len() - 1; + b.grid(rows, segs, |i, j| { + let (rad, y) = profile[i]; + // Profile tangent (downwards) → outward normal in the (r, y) plane. + let prev = profile[i.saturating_sub(1)]; + let next = profile[(i + 1).min(rows)]; + let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y); + let n2 = Vec2::new(-t.y, t.x); + let u = j as f32 / segs as f32; + let phi = u * TAU + PI * 1.5; + let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); + let p = center + dir * rad + Vec3::Y * y; + let n = dir * n2.x + Vec3::Y * n2.y; + (p, n, r.map(u, len[i] / total)) + }); +} + +/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the +/// circle where they meet). +const ORB_CUT: f32 = 0.8; +/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. +const ORB_PANEL_VALLEY: f32 = 0.88; + +/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base +/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly +/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys +/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it +/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top) +/// carry the panels, so the shape is made to be seen from the front left, slightly from above. +/// The body takes the top 79 % of the UV square, the base the bottom 19 %. +pub fn preview_orb() -> Mesh { + // Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time + const ROWS: usize = 300; + const BODY_UV_HEIGHT: f32 = 0.79; + const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) }; + const BASE_RADIUS: f32 = 0.95; + const BASE_HALF_HEIGHT: f32 = 0.025; + const BASE_Y: f32 = -0.6; + const BASE_RIM_STEPS: usize = 12; + const BASE_SEGMENTS: usize = 256; + + let mut b = Builder::default(); + b.grid(ROWS, ROWS * 2, |i, j| { + let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT)) + }); + + // Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face) + let mut profile = vec![(0.0, BASE_HALF_HEIGHT)]; + for k in 0..=BASE_RIM_STEPS { + let a = k as f32 / BASE_RIM_STEPS as f32 * PI; + profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos())); + } + profile.push((0.0, -BASE_HALF_HEIGHT)); + lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); + + let mut m = b.into_mesh("Preview"); + // Normals from the triangles: the panel walls are too steep for the sphere's directions + m.compute_normals(); + // Body and base both run U around the vertical axis, so the tangent is that direction (a + // fraction of the cost of the general tangent pass on this many triangles) + m.tangents = m + .positions + .iter() + .zip(&m.normals) + .map(|(p, n)| { + let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X); + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) + }) + .collect(); + m +} + +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. +fn preview_orb_radius(d: Vec3) -> f32 { + // Rim blends: the sharp faces, and the softly blended left face + const SHARP_BLEND: f32 = 0.035; + const SOFT_BLEND: f32 = 0.18; + // Domed panels: valley depth below the face, dome rise past it; the left panel is smaller + const PANEL_DEPTH: f32 = 0.11; + const PANEL_BULGE: f32 = 0.04; + const LEFT_PANEL_SCALE: f32 = 0.9; + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over + // this fraction of the left panel's rim + const SLOT_Y: f32 = -0.03; + const SLOT_HALF_WIDTH: f32 = 0.05; + const SLOT_ROUNDING: f32 = 0.015; + const SLOT_DEPTH: f32 = 0.12; + const SLOT_FADE: f32 = 0.04; + + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let smooth = |a: f32, b: f32, x: f32| { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; + // Polynomial smooth minimum with blend radius k + let smin = |a: f32, b: f32, k: f32| { + let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0); + b + (a - b) * h - k * h * (1.0 - h) + }; + // Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from + // the rim into a valley, then a dome rising slightly past the face over the middle + let panel = |rho: f32, rim: f32| { + let valley = rim * ORB_PANEL_VALLEY; + if rho < valley { + PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3) + } else { + -PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0)) + } + }; + let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3); + + // The cut: sharp rims except the softly blended left face + let mut radius = 1.0f32; + for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] { + // Directions facing away from a face stay on the sphere (9 = far past it) + let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 }; + radius = smin(radius, to_face, blend); + } + + let a = d.abs(); + let left_rim = rim * LEFT_PANEL_SCALE; + let mut relief = 0.0; + if d.z > 0.0 && a.z >= a.x && a.z >= a.y { + relief += panel(face_rho(d.z, d.x, d.y), rim); + } + if d.x < 0.0 && a.x >= a.y && a.x >= a.z { + relief += panel(face_rho(-d.x, d.y, d.z), left_rim); + } + if d.y > 0.0 && a.y >= a.x && a.y >= a.z { + relief += panel(face_rho(d.y, d.x, d.z), rim); + } + + // Slot around the middle, stopping at the left panel + let in_left_panel = + if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 }; + let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs()); + relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel); + + radius + relief +} + +/// A flat disk facing up (+Y) or down, with planar UVs inside `r`. +fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { + let n = if up { Vec3::Y } else { Vec3::NEG_Y }; + let c = b.vert(center, n, r.map(0.5, 0.5)); + let first = b.p.len() as u32; + for j in 0..segs { + let a = j as f32 / segs as f32 * TAU; + let (x, z) = (a.cos(), a.sin()); + // Top view: +X right, +Z down the texture; bottom view mirrors X. + let uv = if up { r.map(0.5 + x * 0.5, 0.5 + z * 0.5) } else { r.map(0.5 + x * 0.5, 0.5 - z * 0.5) }; + b.vert(center + Vec3::new(x, 0.0, z) * radius, n, uv); + } + for j in 0..segs as u32 { + let (a, bb) = (first + j, first + (j + 1) % segs as u32); + if up { + b.idx.extend_from_slice(&[c, bb, a]); + } else { + b.idx.extend_from_slice(&[c, a, bb]); + } + b.diag.push(0); + } +} + +/// A capped cylinder along Y. +pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh { + let mut b = Builder::default(); + let h = height * 0.5; + lathe_into(&mut b, Vec3::ZERO, &[(radius, h), (radius, -h)], segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); + disk_into(&mut b, Vec3::Y * h, radius, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + disk_into(&mut b, -Vec3::Y * h, radius, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + b.finish("Cylinder") +} + +/// A torus around Y. +pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh { + let mut b = Builder::default(); + let (segs, sides) = (segs.max(3), sides.max(3)); + b.grid(sides, segs, |i, j| { + let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32); + let phi = u * TAU + PI * 1.5; + let theta = v * TAU; + let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); + let n = dir * theta.cos() - Vec3::Y * theta.sin(); + (dir * major + n * minor, n, Vec2::new(u, v)) + }); + b.finish("Torus") +} + +/// A subdivided plane facing +Y. +pub fn plane(size: f32, subdivisions: usize) -> Mesh { + let mut b = Builder::default(); + let s = subdivisions.max(1); + b.grid(s, s, |i, j| { + let (u, v) = (j as f32 / s as f32, i as f32 / s as f32); + (Vec3::new((u - 0.5) * size, 0.0, (v - 0.5) * size), Vec3::Y, Vec2::new(u, v)) + }); + b.finish("Plane") +} + +/// Two planes side by side on UV tiles 1001 and 1002 (UDIM): one material, 4 × 2 units. +pub fn udim_plane() -> Mesh { + let mut m = plane(2.0, 16); + let mut right = m.clone(); + for p in &mut m.positions { + p.x -= 1.0; + } + for p in &mut right.positions { + p.x += 1.0; + } + for uv in &mut right.uvs { + uv.x += 1.0; + } + right.materials.clear(); + right.submeshes.clear(); + m.append(&right); + let count = m.indices.len() as u32; + if let Some(s) = m.submeshes.first_mut() { + s.count = count; + } + m +} + +/// The default project mesh: a ball on a beveled pedestal, two materials ("Ball", "Base"). +pub fn material_ball() -> Mesh { + let mut ball = Builder::default(); + sphere_into(&mut ball, Vec3::new(0.0, 1.32, 0.0), 1.0, 128, 64, UvRect::FULL); + let mut ball = ball.finish("Ball"); + + let mut base = Builder::default(); + let (r, top, bot, bev) = (1.05f32, 0.32f32, 0.0f32, 0.07f32); + let mut profile = vec![(0.42, top + 0.06), (0.62, top + 0.06)]; + // Collar bevel and the ring the ball sits on, then the beveled drum. + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((0.62 + 0.06 * a.sin(), top + 0.06 * a.cos())); + } + profile.push((r - bev, top)); + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((r - bev + bev * a.sin(), top - bev + bev * a.cos())); + } + profile.push((r, bot + bev)); + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((r - bev + bev * a.cos(), bot + bev - bev * a.sin())); + } + lathe_into(&mut base, Vec3::ZERO, &profile, 128, UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); + disk_into(&mut base, Vec3::new(0.0, top + 0.06, 0.0), 0.42, true, 128, UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + disk_into(&mut base, Vec3::new(0.0, bot, 0.0), r - bev, false, 128, UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + let base = base.finish("Base"); + ball.append(&base); + ball +} + +/// A small showcase scene: a beveled crate with a rounded lid and a cylinder handle, in three +/// materials (used for demo projects and tests of multiple texture sets). +pub fn crate_scene() -> Mesh { + let mut body = Builder::default(); + rounded_box_into(&mut body, Vec3::new(0.0, 0.8, 0.0), Vec3::new(1.2, 0.8, 0.8), 0.12, UvRect::FULL); + let mut m = body.finish("Crate"); + let mut lid = Builder::default(); + rounded_box_into(&mut lid, Vec3::new(0.0, 1.72, 0.0), Vec3::new(1.28, 0.12, 0.88), 0.08, UvRect::FULL); + m.append(&lid.finish("Lid")); + let mut handle = torus(0.32, 0.07, 64, 24); + for p in &mut handle.positions { + *p = Vec3::new(p.x, p.z, -p.y) + Vec3::new(0.0, 1.84, 0.0); + } + for n in &mut handle.normals { + *n = Vec3::new(n.x, n.z, -n.y); + } + handle.materials = vec!["Handle".into()]; + if let Some(s) = handle.submeshes.first_mut() { + s.name = "Handle".into(); + } + handle.compute_tangents(); + m.append(&handle); + m +} + +/// Built-in mesh by id (`builtin:` in project files). +pub fn builtin(id: &str) -> Option { + Some(match id { + "material_ball" | "materialball" | "ball" => material_ball(), + "sphere" => sphere(1.0, 128, 64), + "cube" => cube(2.0), + "rounded_cube" | "roundedcube" | "box" => rounded_box(Vec3::ONE, 0.15), + "cylinder" => cylinder(1.0, 2.0, 96), + "torus" => torus(1.0, 0.35, 128, 48), + "plane" => plane(2.0, 16), + "crate" => crate_scene(), + "udim_plane" | "udimplane" => udim_plane(), + // Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh + "preview_orb" => preview_orb(), + _ => return None, + }) +} + +/// Ids accepted by [`builtin`], in menu order. +pub const BUILTINS: [(&str, &str); 9] = [ + ("material_ball", "Material ball"), + ("sphere", "Sphere"), + ("cube", "Cube"), + ("rounded_cube", "Rounded cube"), + ("cylinder", "Cylinder"), + ("torus", "Torus"), + ("plane", "Plane"), + ("crate", "Crate"), + ("udim_plane", "UDIM plane"), +]; + +#[cfg(test)] +mod tests { + use super::*; + + /// Every triangle's winding agrees with its vertex normals, UVs stay in 0..1 (u in 0..max_u), + /// and the UV mapping is not mirrored (tangent handedness +1). + fn check(m: &Mesh, max_u: f32) { + m.validate().unwrap(); + let mut bad = 0; + for t in 0..m.triangle_count() { + let [a, b, c] = m.tri(t).unwrap(); + let face = (m.positions[b] - m.positions[a]).cross(m.positions[c] - m.positions[a]); + if face.length() < 1e-9 { + continue; + } + let n = m.normals[a] + m.normals[b] + m.normals[c]; + if face.dot(n) <= 0.0 { + bad += 1; + } + } + assert_eq!(bad, 0, "{} triangles wound against their normals", bad); + for uv in &m.uvs { + assert!((0.0..=max_u).contains(&uv.x) && (0.0..=1.0).contains(&uv.y), "{uv:?}"); + } + let mirrored = m.tangents.iter().filter(|t| t.w < 0.0).count(); + assert!(mirrored * 50 < m.tangents.len().max(1), "{mirrored} mirrored tangents"); + } + + #[test] + fn primitives_are_well_formed() { + for (id, _) in BUILTINS { + let m = builtin(id).unwrap(); + assert!(m.triangle_count() > 0, "{id}"); + check(&m, if id == "udim_plane" { 2.0 } else { 1.0 }); + } + assert!(builtin("nope").is_none()); + assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); + } + + #[test] + fn preview_orb_is_well_formed_with_domed_panels() { + let m = preview_orb(); + check(&m, 1.0); + + // Above the middle slot, the front panel's dome rises past the cut face and its valley + // sits below it + let front_depth = |rho: f32| { + let d = Vec3::new(0.0, rho, 1.0).normalize(); + preview_orb_radius(d) * d.z + }; + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY)); + assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}"); + } + + #[test] + fn material_ball_has_two_materials() { + let m = material_ball(); + assert_eq!(m.materials, vec!["Ball".to_string(), "Base".to_string()]); + assert!(m.triangles_of(0).count() > 0 && m.triangles_of(1).count() > 0); + } +} diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs new file mode 100644 index 0000000000..01a9744d33 --- /dev/null +++ b/crates/mesh-ops/src/unwrap.rs @@ -0,0 +1,384 @@ +//! Automatic UV unwrapping for meshes imported without texture coordinates. +//! +//! Triangles are grouped into charts by flood fill across shared (welded) edges while each face +//! normal stays within 60° of the chart's seed face, so every chart is a height field over its +//! seed plane and projects onto it without flipping. Charts are rotated to their principal axes +//! and shelf-packed per material into 0..1 with one uniform scale, so texel density is the same +//! everywhere within a material. + +use std::collections::{HashMap, VecDeque}; + +use glam::{Vec2, Vec3}; + +use crate::{GeomError, Mesh, Result}; + +/// Faces of a chart stay within this angle of the seed face normal (cos 60°). +const CHART_COS: f32 = 0.5; +/// Packing never goes beyond this virtual resolution (texels per side). +const MAX_PACK_RES: f32 = 65_536.0; + +/// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of +/// the bounding diagonal) share an id. Ids are dense, in order of first appearance. +pub fn weld_ids(positions: &[Vec3]) -> Vec { + let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); + let cell = ((hi - lo).length() * 1e-6).max(1e-12); + let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len()); + positions + .iter() + .map(|p| { + let q = ((*p - lo) / cell).round(); + let next = map.len() as u32; + *map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next) + }) + .collect() +} + +/// True when the mesh has triangles and every one of them has two corners at the same position. +/// MikkTSpace (and so [`Mesh::compute_tangents`]) crashes on such meshes, so callers reject them. +pub fn all_triangles_degenerate(mesh: &Mesh) -> bool { + let p = |i: &u32| mesh.positions.get(*i as usize); + !mesh.indices.is_empty() + && mesh.indices.chunks(3).all(|t| match t { + [a, b, c] => p(a) == p(b) || p(a) == p(c) || p(b) == p(c), + _ => true, + }) +} + +struct Chart { + material: usize, + /// Projection basis (right-handed with the seed normal). + t: Vec3, + b: Vec3, + /// Rotation to the chart's principal axes (cos, sin). + rot: Vec2, + lo: Vec2, + hi: Vec2, + /// Texel offset of the chart's packed rectangle and the material's scale and resolution. + offset: Vec2, +} + +impl Chart { + fn local(&self, p: Vec3) -> Vec2 { + let q = Vec2::new(p.dot(self.t), p.dot(self.b)); + Vec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x) + } + fn size(&self) -> Vec2 { + (self.hi - self.lo).max(Vec2::ZERO) + } +} + +/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its +/// own 0..1 space with charts at least `padding_texels` (minimum 1) away from each other and +/// the borders at `resolution`. Vertices are split at chart borders; tangents are recomputed. +/// Returns the number of charts. +pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result { + mesh.validate_indices()?; + if all_triangles_degenerate(mesh) { + return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into())); + } + if mesh.normals.len() != mesh.positions.len() { + mesh.compute_normals(); + } + let n = mesh.triangle_count(); + let weld = weld_ids(&mesh.positions); + let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default(); + let wid = |v: usize| weld.get(v).copied().unwrap_or(u32::MAX); + + // Face normals (None for degenerate faces) and materials. + let mut normal: Vec> = Vec::with_capacity(n); + let mut area = Vec::with_capacity(n); + for t in 0..n { + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); + let cr = (pos(b) - pos(a)).cross(pos(c) - pos(a)); + area.push(cr.length() * 0.5); + normal.push(cr.try_normalize()); + } + let mut material = vec![0usize; n]; + for s in &mesh.submeshes { + for t in (s.start / 3) as usize..((s.start as usize + s.count as usize) / 3) { + if let Some(m) = material.get_mut(t) { + *m = s.material; + } + } + } + + // Manifold edge adjacency over welded vertices: edge → (face, face, count). + let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2); + let tri_edges = |t: usize| -> [(u32, u32); 3] { + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); + let key = |x: usize, y: usize| { + let (p, q) = (wid(x), wid(y)); + (p.min(q), p.max(q)) + }; + [key(a, b), key(b, c), key(c, a)] + }; + for t in 0..n { + for e in tri_edges(t) { + if e.0 == e.1 { + continue; + } + let slot = edges.entry(e).or_insert((t as u32, u32::MAX, 0)); + if slot.2 == 1 { + slot.1 = t as u32; + } + slot.2 = slot.2.saturating_add(1); + } + } + + // Grow charts from the largest unassigned faces. + let mut order: Vec = (0..n).collect(); + order.sort_by(|a, b| area[*b].total_cmp(&area[*a])); + let mut chart_of = vec![u32::MAX; n]; + let mut charts: Vec = Vec::new(); + let mut queue = VecDeque::new(); + for &seed in &order { + if chart_of[seed] != u32::MAX { + continue; + } + let id = charts.len() as u32; + let sn = normal[seed].unwrap_or(Vec3::Z); + let t = sn.any_orthonormal_vector(); + charts.push(Chart { material: material[seed], t, b: sn.cross(t), rot: Vec2::X, lo: Vec2::ZERO, hi: Vec2::ZERO, offset: Vec2::ZERO }); + chart_of[seed] = id; + queue.push_back(seed); + while let Some(f) = queue.pop_front() { + for e in tri_edges(f) { + let Some(&(f0, f1, 2)) = edges.get(&e) else { continue }; + let g = if f0 as usize == f { f1 } else { f0 } as usize; + let ok = normal.get(g).is_some_and(|nn| nn.is_none_or(|nn| nn.dot(sn) >= CHART_COS)); + if ok && chart_of.get(g) == Some(&u32::MAX) && material.get(g) == Some(&material[seed]) { + chart_of[g] = id; + queue.push_back(g); + } + } + } + } + + // Principal axes and bounds of every chart. + let mut cov = vec![(Vec2::ZERO, [0.0f64; 3], 0usize); charts.len()]; + for (t, &c) in chart_of.iter().enumerate() { + let c = c as usize; + for v in mesh.tri(t).unwrap_or([0; 3]) { + if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) { + let q = ch.local(pos(v)); + acc.0 += q; + acc.1[0] += (q.x * q.x) as f64; + acc.1[1] += (q.y * q.y) as f64; + acc.1[2] += (q.x * q.y) as f64; + acc.2 += 1; + } + } + } + for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) { + let k = (*k).max(1) as f64; + let (mx, my) = (sum.x as f64 / k, sum.y as f64 / k); + let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my); + let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy); + // Rotate so the principal axis lies along x. + ch.rot = Vec2::new((-angle).cos() as f32, (-angle).sin() as f32); + ch.lo = Vec2::splat(f32::MAX); + ch.hi = Vec2::splat(f32::MIN); + } + for (t, &c) in chart_of.iter().enumerate() { + let c = c as usize; + for v in mesh.tri(t).unwrap_or([0; 3]) { + if let Some(ch) = charts.get_mut(c) { + let q = ch.local(pos(v)); + ch.lo = ch.lo.min(q); + ch.hi = ch.hi.max(q); + } + } + } + for ch in &mut charts { + if ch.size().y > ch.size().x { + // Quarter turn (x, y) → (y, −x) so shelves stay low. + ch.rot = Vec2::new(ch.rot.y, -ch.rot.x); + let (lo, hi) = (ch.lo, ch.hi); + ch.lo = Vec2::new(lo.y, -hi.x); + ch.hi = Vec2::new(hi.y, -lo.x); + } + } + + // Pack each material's charts into its own 0..1 square. + let pad = padding_texels.max(1.0); + let mut scale = HashMap::new(); + let mats: std::collections::BTreeSet = charts.iter().map(|c| c.material).collect(); + for m in mats { + let ids: Vec = (0..charts.len()).filter(|i| charts[*i].material == m).collect(); + let sizes: Vec = ids.iter().map(|i| charts[*i].size()).collect(); + let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?; + for (i, o) in ids.iter().zip(offsets) { + charts[*i].offset = o; + } + scale.insert(m, (s, res)); + } + + // Rebuild vertices: one per (vertex, chart). + let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len() * 2); + let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut indices = Vec::with_capacity(mesh.indices.len()); + for (t, &c) in chart_of.iter().enumerate() { + let Some(ch) = charts.get(c as usize) else { continue }; + let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0)); + for v in mesh.tri(t).unwrap_or([0; 3]) { + let idx = *remap.entry((v as u32, c)).or_insert_with(|| { + let q = ch.local(pos(v)); + // Chart y points up; UV v points down the image. + let texel = ch.offset + Vec2::splat(pad) + Vec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s; + positions.push(pos(v)); + normals.push(mesh.normals.get(v).copied().unwrap_or(Vec3::Y)); + if let Some(c) = mesh.colors.get(v) { + colors.push(*c); + } + uvs.push((texel / res).clamp(Vec2::ZERO, Vec2::ONE)); + (positions.len() - 1) as u32 + }); + indices.push(idx); + } + } + mesh.positions = positions; + mesh.normals = normals; + mesh.uvs = uvs; + mesh.colors = colors; + mesh.indices = indices; + mesh.compute_tangents(); + mesh.validate()?; + Ok(charts.len()) +} + +/// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of +/// `res` texels with the largest uniform scale that fits. Returns (texels per world unit, +/// resolution used, texel offset per rectangle). The resolution doubles when the padding alone +/// cannot fit (very many charts), so the result always fits in 0..1. +fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec)> { + let mut order: Vec = (0..sizes.len()).collect(); + order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y)); + let place = |s: f32, res: f32| -> Option> { + let mut out = vec![Vec2::ZERO; sizes.len()]; + let (mut x, mut y, mut shelf) = (0.0f32, 0.0f32, 0.0f32); + for &i in &order { + let r = sizes[i] * s + Vec2::splat(2.0 * pad); + if r.x > res { + return None; + } + if x + r.x > res { + y += shelf; + x = 0.0; + shelf = 0.0; + } + if y + r.y > res { + return None; + } + out[i] = Vec2::new(x, y); + x += r.x; + shelf = shelf.max(r.y); + } + Some(out) + }; + while place(0.0, res).is_none() { + res *= 2.0; + if res > MAX_PACK_RES { + return Err(GeomError::Invalid("too many UV charts to pack".into())); + } + } + let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f32, f32::max); + if largest <= 0.0 { + return Ok((0.0, res, place(0.0, res).unwrap_or_default())); + } + let (mut lo, mut hi) = (0.0f32, (res - 2.0 * pad).max(0.0) / largest); + if place(hi, res).is_some() { + lo = hi; + } + for _ in 0..40 { + if hi - lo <= lo * 1e-4 { + break; + } + let mid = 0.5 * (lo + hi); + if place(mid, res).is_some() { lo = mid } else { hi = mid } + } + Ok((lo, res, place(lo, res).unwrap_or_default())) +} + +impl Mesh { + /// Index-range checks only (attribute arrays may be incomplete before unwrapping). + fn validate_indices(&self) -> Result<()> { + let n = self.positions.len(); + if !self.indices.len().is_multiple_of(3) || self.indices.iter().any(|i| *i as usize >= n) { + return Err(GeomError::Invalid("mesh indices are out of range".into())); + } + if self.triangle_count() > crate::MAX_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has more than {} triangles", crate::MAX_TRIANGLES))); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{UvGBuffer, primitives}; + + fn check(mut m: Mesh, min_coverage: f32) { + m.uvs.clear(); + let charts = auto_unwrap(&mut m, 4.0, 512).unwrap(); + assert!(charts >= 1); + m.validate().unwrap(); + assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); + let g = UvGBuffer::new(&m, 0, 512, 512).unwrap(); + let covered = g.covered_count() as f32; + let coverage = covered / (512.0 * 512.0); + assert!(coverage > min_coverage, "coverage {coverage} with {charts} charts"); + assert!((g.overlaps as f32) < covered * 0.005, "overlaps {} of {covered}", g.overlaps); + } + + #[test] + fn sphere_unwraps_without_overlaps() { + check(primitives::sphere(1.0, 48, 24), 0.3); + } + + #[test] + fn cube_unwraps_without_overlaps() { + check(primitives::cube(2.0), 0.3); + } + + #[test] + fn torus_and_material_ball_unwrap() { + check(primitives::torus(1.0, 0.3, 48, 24), 0.2); + let mut ball = primitives::material_ball(); + ball.uvs.clear(); + auto_unwrap(&mut ball, 2.0, 1024).unwrap(); + for m in 0..ball.materials.len() { + let g = UvGBuffer::new(&ball, m, 512, 512).unwrap(); + assert!((g.overlaps as f32) < g.covered_count() as f32 * 0.005 + 1.0, "material {m}: {} overlaps", g.overlaps); + } + } + + #[test] + fn many_tiny_charts_still_fit() { + // 2000 disconnected triangles: the packer grows its virtual resolution. + let mut p = Vec::new(); + let mut idx = Vec::new(); + for i in 0..2000u32 { + let o = Vec3::new(i as f32 * 3.0, 0.0, 0.0); + p.extend([o, o + Vec3::X, o + Vec3::Y]); + idx.extend([i * 3, i * 3 + 1, i * 3 + 2]); + } + let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap(); + auto_unwrap(&mut m, 4.0, 128).unwrap(); + assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); + } + + #[test] + fn degenerate_and_empty_meshes_do_not_fail() { + let mut empty = Mesh::default(); + assert_eq!(auto_unwrap(&mut empty, 4.0, 256).unwrap(), 0); + // A sliver (zero-area) triangle next to a real one. + let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 2.0]; + let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 1, 3], "m").unwrap(); + auto_unwrap(&mut m, 4.0, 256).unwrap(); + m.validate().unwrap(); + let mut point = Mesh { positions: vec![Vec3::ONE; 3], indices: vec![0, 1, 2], ..Mesh::default() }; + assert!(all_triangles_degenerate(&point)); + assert!(auto_unwrap(&mut point, 4.0, 256).is_err()); + } +} diff --git a/crates/odf/src/text/body/drawing.rs b/crates/odf/src/text/body/drawing.rs index eeb466f59c..96d1ba3881 100644 --- a/crates/odf/src/text/body/drawing.rs +++ b/crates/odf/src/text/body/drawing.rs @@ -137,7 +137,7 @@ impl Body<'_> { let path = self.shape_path.take().filter(|_| kind == craft_wordmodel::para::ShapeKind::Freeform); let (w, h) = (w.unwrap_or(72.0), h.unwrap_or(1.0)); self.note_place(kind, (w, h), &look, float.as_ref()); - Some(Inline::Shape { kind, w, h, float: float.map(Box::new), blocks, look, path }) + Some(Inline::Shape { kind, w, h, float: float.map(Box::new), blocks, look, path, link: None }) } (None, Some((linear, display))) => Some(Inline::Equation { linear, display }), (None, None) if let Some(spec) = chart => Some(Inline::Chart(model::Chart { @@ -177,7 +177,7 @@ impl Body<'_> { // A group's member goes into the group, at its place in it. if let Some(((x, y), g)) = self.member_at.take().zip(self.group.as_mut().filter(|_| self.note.is_none())) { if g.members.len() < craft_wordmodel::para::MAX_GROUP_CHILDREN { - g.members.push(model::Member { x, y, inline }); + g.members.push(model::Member { x, y, inline, link: None }); } } else { self.push_inline(inline); @@ -358,7 +358,7 @@ impl Body<'_> { float.z = g.z; let float = (float.wrap != craft_wordmodel::para::Wrap::Inline || float.z != 0).then(|| Box::new(float)); let fit = |v: f32| if v.is_finite() { v.clamp(1.0, MAX_LEN) } else { 1.0 }; - self.push_inline(Inline::Group { w: fit(x1 - x0), h: fit(y1 - y0), float, members }); + self.push_inline(Inline::Group { w: fit(x1 - x0), h: fit(y1 - y0), float, members, link: None }); } /// Begin a drawing shape (ODF 1.3 §10.3): its size, placement and look, and its text read diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index adf62a3ed5..1695725359 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -546,7 +546,7 @@ impl Writer { self.image(img, Place::Text(img.float.as_deref()), out); prev_space = false; } - Inline::Group { w, h, float, members } => { + Inline::Group { w, h, float, members, .. } => { self.group((*w, *h), float.as_deref(), members, out); prev_space = false; } @@ -571,7 +571,7 @@ impl Writer { self.comment(*id, comment, out); prev_space = false; } - Inline::Shape { kind, w, h, float, blocks, look, path } => { + Inline::Shape { kind, w, h, float, blocks, look, path, .. } => { self.drawing_shape(*kind, (*w, *h), Place::Text(float.as_deref()), (look, path.as_deref()), blocks, out); prev_space = false; } diff --git a/crates/odf/src/text/writer/drawing.rs b/crates/odf/src/text/writer/drawing.rs index 8d7576accb..6d6b2a4deb 100644 --- a/crates/odf/src/text/writer/drawing.rs +++ b/crates/odf/src/text/writer/drawing.rs @@ -383,7 +383,7 @@ impl Writer { for m in members { let (x, y) = (at.0 + m.x, at.1 + m.y); match &m.inline { - Inline::Shape { kind, w, h, float, blocks, look, path } => { + Inline::Shape { kind, w, h, float, blocks, look, path, .. } => { self.drawing_shape(*kind, (*w, *h), Place::Member(x, y, float.as_deref()), (look, path.as_deref()), blocks, out) } Inline::Image(img) => self.image(img, Place::Member(x, y, img.float.as_deref()), out), @@ -673,6 +673,7 @@ mod tests { let mut w = Writer::with_prefix("wc"); w.reserved = std::sync::Arc::new(std::iter::once("Pictures/wcimage1.png".to_string()).collect()); let img = model::Img { + link: None, data: std::sync::Arc::new(vec![1, 2, 3]), ext: "png".into(), w: 10.0, diff --git a/crates/pages/src/ui/table/size_picker.rs b/crates/pages/src/ui/table/size_picker.rs index edd1d67b6d..35e9304f07 100644 --- a/crates/pages/src/ui/table/size_picker.rs +++ b/crates/pages/src/ui/table/size_picker.rs @@ -186,7 +186,7 @@ impl Component for TableSizePicker { } fn update(&mut self, cx: &mut Cx<'_, Self>) { - let pointer = (0..ROWS * COLUMNS).find(|&index| cx.hover_pos(Self::part(index)).is_some()); + let pointer = (0..ROWS * COLUMNS).find(|&index| cx.part_if_declared(Self::part(index)).is_some_and(|result| result.hovered)); let focused = cx.active_part().and_then(|part| (0..ROWS * COLUMNS).find(|&index| Self::part(index) == part)).filter(|_| cx.focus_visible()); self.lead = pointer.or(focused).or_else(|| self.preset_index()); self.picked = (0..ROWS * COLUMNS).find(|&index| cx.part_activated(Self::part(index)).is_some()); diff --git a/crates/palette/Cargo.toml b/crates/palette/Cargo.toml index d39a80b677..b139e44f1f 100644 --- a/crates/palette/Cargo.toml +++ b/crates/palette/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-palette" -description = "Bounded, application-independent GIMP palette reading" +description = "Bounded, application-independent GIMP and RIFF palette reading" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/palette/src/lib.rs b/crates/palette/src/lib.rs index c49b0666d6..e9da784ef0 100644 --- a/crates/palette/src/lib.rs +++ b/crates/palette/src/lib.rs @@ -1,9 +1,13 @@ -//! GIMP palette (.gpl) reading with neutral RGB8 colours and names. +//! GIMP palette (.gpl) reading with neutral RGB8 colours and names, and RIFF palette (.pal) +//! reading with neutral RGB8 colours. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -/// Largest accepted palette, bounding all parsing allocations. +mod riff; +pub use riff::parse_riff_pal; + +/// Largest accepted GIMP palette, bounding all parsing allocations. pub const MAX_BYTES: usize = 1 << 20; -/// Maximum colours returned; later rows are ignored. +/// Maximum colours a GIMP palette gives; later rows are ignored. pub const MAX_COLORS: usize = 1024; /// A named RGB colour. Display-name sanitization belongs to the caller. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/palette/src/riff.rs b/crates/palette/src/riff.rs new file mode 100644 index 0000000000..30fe28d637 --- /dev/null +++ b/crates/palette/src/riff.rs @@ -0,0 +1,164 @@ +//! RIFF palette (.pal) reading. +//! +//! A RIFF palette is a `RIFF` file of form `PAL `. Its `data` chunk holds a version word, an +//! entry count and four bytes per entry (red, green, blue, flags), all little-endian. Other +//! chunks may come before `data`; each chunk is padded to an even length. + +/// The `PALETTEENTRY` flag that makes an entry an index into the display's hardware palette +/// instead of a colour. +const PC_EXPLICIT: u8 = 0x02; + +/// Reads a RIFF palette's colours in file order, flags dropped. +/// +/// Chunks other than `data` are skipped, and only chunks inside the form's declared size count, +/// so bytes after the form are ignored. A file that isn't a RIFF palette, a form or chunk that +/// runs past the end (before or after `data`), a `data` chunk with fewer entries than its count, a +/// form without a `data` chunk and a palette without colours are errors. An entry flagged +/// `PC_EXPLICIT` holds a hardware palette index, which an RGB colour can't stand for, so it is an +/// error too. Never panics. The count is a 16-bit word, so at most 65 535 colours are returned. +pub fn parse_riff_pal(bytes: &[u8]) -> Result, String> { + if bytes.get(..4) != Some(b"RIFF".as_slice()) || bytes.get(8..12) != Some(b"PAL ".as_slice()) { + return Err("this isn't a RIFF palette (.pal) file".into()); + } + let le32 = |b: &[u8]| b.first_chunk::<4>().and_then(|w| usize::try_from(u32::from_le_bytes(*w)).ok()); + // The form's size counts its `PAL ` type and its chunks. + let size = bytes.get(4..8).and_then(le32).ok_or_else(cut_short)?; + let mut rest = 8usize.checked_add(size).and_then(|end| bytes.get(12..end)).ok_or_else(cut_short)?; + let mut colors = None; + while let (Some(id), Some(len)) = (rest.get(..4), rest.get(4..8).and_then(le32)) { + let end = 8usize.checked_add(len).ok_or_else(cut_short)?; + let body = rest.get(8..end).ok_or_else(cut_short)?; + // The first `data` chunk gives the colours; the chunks after it are still checked. + if id == b"data" && colors.is_none() { + colors = Some(data_colors(body)?); + } + // Chunks are padded to an even length; a pad byte the form leaves out ends it. + rest = end.checked_add(len & 1).and_then(|next| rest.get(next..)).unwrap_or_default(); + } + colors.ok_or_else(|| "the palette has no colour data".into()) +} + +fn cut_short() -> String { + "the palette is cut short".into() +} + +/// The colours of a `data` chunk's body: a version word, an entry count and the entries. +fn data_colors(body: &[u8]) -> Result, String> { + let [_, _, lo, hi, entries @ ..] = body else { return Err(cut_short()) }; + let count = usize::from(u16::from_le_bytes([*lo, *hi])); + let colors = entries.as_chunks::<4>().0.iter().take(count).enumerate().map(|(i, &[r, g, b, flags])| { + if flags & PC_EXPLICIT == 0 { + Ok([r, g, b]) + } else { + Err(format!("colour {} of the palette is a hardware palette index, not a colour", i + 1)) + } + }); + let colors = colors.collect::, String>>()?; + if colors.len() < count { + return Err(cut_short()); + } + if colors.is_empty() { + return Err("the palette has no colours in it".into()); + } + Ok(colors) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + + /// `n` distinct colours. + fn colors(n: usize) -> Vec<[u8; 3]> { + (0..n).map(|i| [(i % 256) as u8, (i / 256) as u8 * 100 + 7, 255 - (i % 256) as u8]).collect() + } + + /// A RIFF palette declaring `count` entries and holding `colors`, with an unrelated chunk of + /// odd length (so padded) before `data`. + fn pal(colors: &[[u8; 3]], count: u16) -> Vec { + let mut data = vec![0x00, 0x03]; + data.extend_from_slice(&count.to_le_bytes()); + for c in colors { + data.extend_from_slice(&[c[0], c[1], c[2], 0x55]); + } + let mut body = b"PAL ".to_vec(); + body.extend_from_slice(b"note"); + body.extend_from_slice(&3u32.to_le_bytes()); + body.extend_from_slice(b"abc\0"); + body.extend_from_slice(b"data"); + body.extend_from_slice(&(data.len() as u32).to_le_bytes()); + body.extend_from_slice(&data); + let mut b = b"RIFF".to_vec(); + b.extend_from_slice(&(body.len() as u32).to_le_bytes()); + b.extend_from_slice(&body); + b + } + + #[test] + fn colours_come_in_file_order_past_other_chunks() { + let want = colors(300); + assert_eq!(parse_riff_pal(&pal(&want, 300)).unwrap(), want); + // Entries past the count and bytes after the form don't count. + let mut extra = pal(&want, 3); + extra.extend_from_slice(b"junk after the form"); + assert_eq!(parse_riff_pal(&extra).unwrap(), want[..3]); + } + + #[test] + fn an_entry_that_indexes_the_hardware_palette_is_refused() { + let want = colors(3); + let mut bytes = pal(&want, 3); + assert_eq!(parse_riff_pal(&bytes).unwrap(), want); + // Past the chunk header, the version and count words and the first entry: the second + // entry's flags byte. The other flags `pal` sets (reserved, no-collapse) still read. + let at = bytes.windows(4).position(|w| w == b"data").unwrap() + 8 + 4 + 4 + 3; + bytes[at] |= PC_EXPLICIT; + assert!(parse_riff_pal(&bytes).is_err()); + } + + #[test] + fn damaged_or_empty_palettes_are_refused() { + let three = colors(3); + let mut no_data = pal(&three, 3); + let at = no_data.windows(4).position(|w| w == b"data").unwrap(); + no_data[at..at + 4].copy_from_slice(b"junk"); + // A form declared as only its `PAL ` type, with the colour data after it, outside the form. + let mut empty_form = pal(&three, 3); + empty_form[4..8].copy_from_slice(&4u32.to_le_bytes()); + // A form declared one byte longer than the file. + let mut past_end = pal(&three, 3); + let size = past_end.len() as u32 - 7; + past_end[4..8].copy_from_slice(&size.to_le_bytes()); + // A chunk whose length runs to the top of the address range. + let mut huge_chunk = pal(&three, 3); + huge_chunk[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + let mut not_pal = pal(&three, 3); + not_pal[8..12].copy_from_slice(b"WAVE"); + // A chunk after `data`, inside the form, whose body runs past the end. + let mut after_data = pal(&three, 3); + after_data.extend_from_slice(b"JUNK"); + after_data.extend_from_slice(&100u32.to_le_bytes()); + let size = after_data.len() as u32 - 8; + after_data[4..8].copy_from_slice(&size.to_le_bytes()); + let cases = [ + ("empty", Vec::new()), + ("text", b"JASC-PAL\r\n0100\r\n1\r\n255 0 0\r\n".to_vec()), + ("not PAL", not_pal), + ("no colours", pal(&[], 0)), + ("short", pal(&three[..2], 3)), + ("no data", no_data), + ("empty form", empty_form), + ("past end", past_end), + ("huge chunk", huge_chunk), + ("chunk past end after data", after_data), + ]; + for (name, bytes) in cases { + assert!(parse_riff_pal(&bytes).is_err(), "{name} should be refused"); + } + // Every truncation of a valid palette is refused. + let whole = pal(&three, 3); + for n in 0..whole.len() { + assert!(parse_riff_pal(&whole[..n]).is_err(), "cut to {n} bytes"); + } + } +} diff --git a/crates/pbr/Cargo.toml b/crates/pbr/Cargo.toml index 654a7c93b8..3d44054c35 100644 --- a/crates/pbr/Cargo.toml +++ b/crates/pbr/Cargo.toml @@ -10,17 +10,25 @@ repository.workspace = true [features] default = [] parallel = ["dep:rayon"] +# The conversion from craft-mesh's glTF metallic-roughness material. +mesh = ["dep:craft-mesh"] +# The conversion from craft-materialx's resolved shader inputs. +materialx = ["dep:craft-materialx"] [lints] workspace = true [dependencies] +craft-materialx = { workspace = true, optional = true } +craft-mesh = { path = "../mesh", default-features = false, optional = true } craft-texture = { workspace = true } rayon = { workspace = true, optional = true } thiserror = { workspace = true } [dev-dependencies] -craft-pbr = { path = ".", features = ["parallel"] } +craft-materialx = { workspace = true } +craft-mesh = { path = "../mesh", default-features = false } +craft-pbr = { path = ".", features = ["parallel", "mesh", "materialx"] } # The differential tests run verbatim copies of the apps' previous code, which uses glam and rayon. glam = "0.30" # Parses and validates the WGSL text of `SHADE_WGSL`. diff --git a/crates/pbr/README.md b/crates/pbr/README.md index 6a531206d0..fd46864090 100644 --- a/crates/pbr/README.md +++ b/crates/pbr/README.md @@ -107,8 +107,49 @@ It has no UI, does no file or network I/O and has no `unsafe` code. (`PbrError::OutOfMemory`). Options out of range give `PbrError::BadOption`, and directions that are not finite or have zero length give `PbrError::BadDirection`. -- **Features.** `parallel` computes rows on several threads with rayon. The default build is - serial and builds for `wasm32-unknown-unknown`. Results are the same either way. + After size and byte checks pass, a filtering work count above `u64::MAX` returns + `PbrError::BadOption`, including when `max_work` is `u64::MAX`. `hammersley` returns coordinates in `0..1`. +- **Surfaces.** A `Surface` holds a `Material` and the state a renderer applies around it: alpha + and `AlphaMode`, linear emission, the double-sided and unlit flags, optional `Clearcoat` and + `Sheen` layers, `TextureBinding`s (the image or file, UV set, wrap modes, UV transform, encoding + and a scale) and `other_inputs`. Textures are not loaded. `try_direct` shades only the + `Material`; the layers, textures and other inputs are kept for a renderer that shades them, and + an unlit surface shows its base color without lighting. +- **Conversions.** `try_from_mesh` (feature `mesh`) converts a `craft_mesh::Material` and + `try_from_materialx` (feature `materialx`) converts the `craft_materialx::StrictMaterial` that + `Document::read_material_strict` reads. Each returns + a `Conversion`: the `Surface` and a `ConversionReport` that lists what was kept without being + shaded, what was approximated and how, what was dropped and why, and the MaterialX reader's + warnings. No value is clamped: one that is not finite, is out of its range or has the wrong + number of components gives a `ConvertError` naming the source field. + - From craft-mesh, the glTF 2.0 metallic-roughness material + (): base color, alpha, + metallic, roughness, emissive, alpha mode and cutoff, double-sided and unlit map as they are. + Every texture is kept with its UV state; base color, emissive and sheen color textures are + sRGB and the others linear. Clearcoat (`KHR_materials_clearcoat`) and sheen + (`KHR_materials_sheen`) are kept when on; a clearcoat factor of 0 or a black sheen color turns + the layer off, and its textures are dropped. + - From MaterialX, OpenPBR Surface, Standard Surface and glTF PBR inputs take the defaults of + their node definitions when absent + (). The base + color is multiplied by the base weight, the specular weight becomes the weight times + `((ior − 1) / (ior + 1))² / 0.04` (at most `MAX_SPECULAR`), emission is the color times its + strength, and the coat, fuzz or sheen become the layers. Color constants are decoded to linear + Rec.709 from the color space in effect (`srgb_texture`, `srgb_rec709_scene`, the Rec.709 + gamma spaces, `lin_rec709`, `lin_rec709_scene`, `data`); another color space is an error. An + image becomes a texture binding and the core holds 1 times any weight in its place. A coat or + sheen roughness image binds as `ClearcoatRoughnessFirst` or `SheenRoughnessFirst`, which read + the first channel; the glTF bindings `ClearcoatRoughness` and `SheenRoughness` read G and A. + Tangent-space normal textures require an image connected through a `normalmap` node. + Direct world-space normal images are dropped with a report entry. Literal normal-map + inputs and authored normal-map frames are unsupported and reported. Authored `constant`, + `clamp`, and `mirror` image addressing modes are also reported. Other inputs of the shader's + table are kept in `other_inputs`. +- **Features.** `parallel` computes rows on several threads with rayon. `mesh` and `materialx` + add the conversions and depend on craft-mesh and craft-materialx. The default build has none of + them, is serial and builds for `wasm32-unknown-unknown`, as do `mesh` and `materialx`. Results + are the same either way. + The `craft` facade forwards the conversion features as `pbr-mesh` and `pbr-materialx`. On a 256 × 128 source, the default `try_prefilter` evaluates 1,396,736 samples (10,912 output pixels in levels 1 to 5, 128 samples each). @@ -190,9 +231,12 @@ text with naga, alone and with app bindings and `vs` and `fs` entry points, and ## Origin The algorithms come from the `crates/render/src/ibl.rs` files of TextureCraft and MaterialCraft, -which held the same filtering code. With a firefly cap of 64, which both apps applied, the -prefiltered levels match theirs for sources with even sides that are at least twice as wide as -they are tall. Changes from those files: +which held the same filtering code. With a firefly cap of 64, 128 samples and a level bias of 1, +the differential tests measure differences in prefiltered levels at most `1e-5` relative to +`max(1, |a|, |b|)` for procedural sources of 64 × 32, 128 × 64 and 256 × 128 and synthetic sources +of 128 × 64. An odd intermediate side +retains its last column or row when halved, so initially even sources can also differ. +Changes from those files: - Halving an odd side keeps its last column or row instead of dropping it. - The firefly cap is an option, off by default, and the source level bias is an option. @@ -201,7 +245,7 @@ they are tall. Changes from those files: - Level sizes never grow past the level before, so a source smaller than 4 × 2 is accepted. - The source pyramid halves a source while it is wider than 8 or taller than 4, so a source 8 or fewer pixels wide and more than 4 tall also gets coarser levels. A source at least twice as wide - as it is tall gets the same pyramid as in those files. + as it is tall stops at the same pyramid dimensions as in those files. - The SH projection reads every pixel of the source instead of a source halved to 128 wide by plain averaging, which gave rows near the poles too much weight (a lit top row of a 256 × 128 source counted twice). It integrates each basis function over the area of each pixel instead of diff --git a/crates/pbr/src/convert_materialx.rs b/crates/pbr/src/convert_materialx.rs new file mode 100644 index 0000000000..339b165ee9 --- /dev/null +++ b/crates/pbr/src/convert_materialx.rs @@ -0,0 +1,600 @@ +//! The conversion from a `craft_materialx::StrictMaterial`: an OpenPBR Surface, Standard Surface +//! or glTF PBR shader with its resolved inputs. + +use craft_materialx::{Resolved, Shader, StrictMaterial}; +use craft_texture::srgb_to_linear; +use std::collections::HashSet; + +use crate::surface::{ + AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, FINITE, NON_NEGATIVE, ReportItem, Sheen, Surface, TextureBinding, + TextureEncoding, TextureInput, TextureSource, UNIT, UvTransform, Wrap, +}; +use crate::{MAX_SPECULAR, Material}; + +/// What a shader input holds and the range its values must be in. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Kind { + /// One number from `lo` to `hi`. + Scalar(f32, f32), + /// Three color components from 0 to the bound, in the color space in effect. + Color(f32), + /// Three finite numbers, such as a normal. + Vector, + /// glTF PBR's alpha mode: 0, 1 or 2. + Mode, +} + +const UNIT_KIND: Kind = Kind::Scalar(0.0, 1.0); +const NON_NEGATIVE_KIND: Kind = Kind::Scalar(0.0, f32::MAX); +const COLOR: Kind = Kind::Color(1.0); + +const COAT_OFF: &str = "the coat weight is 0, which turns the layer off"; +const SHEEN_OFF: &str = "the sheen color is black or its weight is 0, which turns the layer off"; + +/// What an input maps to on the [`Surface`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Role { + BaseColor, + BaseWeight, + Metallic, + Roughness, + SpecularWeight, + Ior, + CoatWeight, + CoatRoughness, + SheenWeight, + SheenColor, + SheenRoughness, + EmissionStrength, + EmissionColor, + Opacity, + AlphaMode, + AlphaCutoff, + Normal, + Occlusion, + /// Kept as an other input or a texture, and not shaded. + Kept, + /// Kept like [`Role::Kept`] while the coat is on, and dropped when it is off. + CoatKept, +} + +/// A shader input the conversion reads, with its default from the shader's node definition. +struct Field { + name: &'static str, + kind: Kind, + role: Role, + default: [f32; 3], +} + +const fn field(name: &'static str, kind: Kind, role: Role, default: f32) -> Field { + Field { name, kind, role, default: [default; 3] } +} + +/// OpenPBR Surface inputs and defaults, from its node definition +/// (). +const OPEN_PBR: &[Field] = &[ + field("base_color", COLOR, Role::BaseColor, 0.8), + field("base_weight", UNIT_KIND, Role::BaseWeight, 1.0), + field("base_metalness", UNIT_KIND, Role::Metallic, 0.0), + field("specular_roughness", UNIT_KIND, Role::Roughness, 0.3), + field("specular_weight", NON_NEGATIVE_KIND, Role::SpecularWeight, 1.0), + field("specular_ior", NON_NEGATIVE_KIND, Role::Ior, 1.5), + field("coat_weight", UNIT_KIND, Role::CoatWeight, 0.0), + field("coat_roughness", UNIT_KIND, Role::CoatRoughness, 0.0), + field("fuzz_weight", UNIT_KIND, Role::SheenWeight, 0.0), + field("fuzz_color", COLOR, Role::SheenColor, 1.0), + field("fuzz_roughness", UNIT_KIND, Role::SheenRoughness, 0.5), + field("emission_luminance", NON_NEGATIVE_KIND, Role::EmissionStrength, 0.0), + field("emission_color", COLOR, Role::EmissionColor, 1.0), + field("geometry_opacity", UNIT_KIND, Role::Opacity, 1.0), + field("geometry_normal", Kind::Vector, Role::Normal, 0.0), + field("geometry_coat_normal", Kind::Vector, Role::CoatKept, 0.0), + field("specular_color", COLOR, Role::Kept, 1.0), + field("specular_roughness_anisotropy", UNIT_KIND, Role::Kept, 0.0), + field("transmission_weight", UNIT_KIND, Role::Kept, 0.0), + field("subsurface_weight", UNIT_KIND, Role::Kept, 0.0), + field("coat_color", COLOR, Role::CoatKept, 1.0), + field("coat_ior", NON_NEGATIVE_KIND, Role::CoatKept, 1.6), +]; + +/// Standard Surface 1.0.1 inputs and defaults, from its node definition +/// (). +const STANDARD_SURFACE: &[Field] = &[ + field("base_color", COLOR, Role::BaseColor, 0.8), + field("base", UNIT_KIND, Role::BaseWeight, 1.0), + field("metalness", UNIT_KIND, Role::Metallic, 0.0), + field("specular_roughness", UNIT_KIND, Role::Roughness, 0.2), + field("specular", UNIT_KIND, Role::SpecularWeight, 1.0), + field("specular_IOR", NON_NEGATIVE_KIND, Role::Ior, 1.5), + field("coat", UNIT_KIND, Role::CoatWeight, 0.0), + field("coat_roughness", UNIT_KIND, Role::CoatRoughness, 0.1), + field("sheen", UNIT_KIND, Role::SheenWeight, 0.0), + field("sheen_color", COLOR, Role::SheenColor, 1.0), + field("sheen_roughness", UNIT_KIND, Role::SheenRoughness, 0.3), + field("emission", NON_NEGATIVE_KIND, Role::EmissionStrength, 0.0), + field("emission_color", COLOR, Role::EmissionColor, 1.0), + field("opacity", COLOR, Role::Opacity, 1.0), + field("normal", Kind::Vector, Role::Normal, 0.0), + field("coat_normal", Kind::Vector, Role::CoatKept, 0.0), + field("specular_color", COLOR, Role::Kept, 1.0), + field("specular_anisotropy", UNIT_KIND, Role::Kept, 0.0), + field("transmission", UNIT_KIND, Role::Kept, 0.0), + field("subsurface", UNIT_KIND, Role::Kept, 0.0), + field("coat_color", COLOR, Role::CoatKept, 1.0), + field("coat_IOR", NON_NEGATIVE_KIND, Role::CoatKept, 1.5), +]; + +/// glTF PBR inputs and defaults, from its node definition +/// (). +const GLTF_PBR: &[Field] = &[ + field("base_color", COLOR, Role::BaseColor, 1.0), + field("metallic", UNIT_KIND, Role::Metallic, 1.0), + field("roughness", UNIT_KIND, Role::Roughness, 1.0), + field("specular", UNIT_KIND, Role::SpecularWeight, 1.0), + field("ior", Kind::Scalar(1.0, f32::MAX), Role::Ior, 1.5), + field("clearcoat", UNIT_KIND, Role::CoatWeight, 0.0), + field("clearcoat_roughness", UNIT_KIND, Role::CoatRoughness, 0.0), + field("sheen_color", COLOR, Role::SheenColor, 0.0), + field("sheen_roughness", UNIT_KIND, Role::SheenRoughness, 0.0), + field("emissive_strength", NON_NEGATIVE_KIND, Role::EmissionStrength, 1.0), + field("emissive", COLOR, Role::EmissionColor, 0.0), + field("alpha", UNIT_KIND, Role::Opacity, 1.0), + field("alpha_mode", Kind::Mode, Role::AlphaMode, 0.0), + field("alpha_cutoff", UNIT_KIND, Role::AlphaCutoff, 0.5), + field("normal", Kind::Vector, Role::Normal, 0.0), + field("occlusion", UNIT_KIND, Role::Occlusion, 1.0), + field("clearcoat_normal", Kind::Vector, Role::CoatKept, 0.0), + field("transmission", UNIT_KIND, Role::Kept, 0.0), + field("specular_color", Kind::Color(f32::MAX), Role::Kept, 1.0), +]; + +/// What a conversion found for one field of the table. +#[derive(Clone, Debug, PartialEq)] +enum Got { + Missing, + /// Checked values, linear for a color. + Constant(Vec), + Texture, +} + +/// The table of the material's shader and what each field holds. +struct Inputs { + table: &'static [Field], + got: Vec, +} + +impl Inputs { + fn find(&self, role: Role) -> Option<(&Field, &Got)> { + self.table.iter().zip(&self.got).find(|(f, _)| f.role == role) + } + + /// The field's value: the authored one, 1 for a texture (the factor its samples multiply), + /// or the default when the input is absent. `None` when the shader has no such field. + fn value(&self, role: Role) -> Option<[f32; 3]> { + let (f, got) = self.find(role)?; + Some(match got { + Got::Missing => f.default, + Got::Texture => [1.0; 3], + Got::Constant(v) if v.len() == 1 => [v[0]; 3], + Got::Constant(v) => [v.first().copied().unwrap_or(0.0), v.get(1).copied().unwrap_or(0.0), v.get(2).copied().unwrap_or(0.0)], + }) + } + + fn scalar(&self, role: Role, absent: f32) -> f32 { + self.value(role).map_or(absent, |v| v[0]) + } + + fn textured(&self, role: Role) -> bool { + self.find(role).is_some_and(|(_, g)| *g == Got::Texture) + } + + fn name(&self, role: Role) -> &'static str { + self.table.iter().find(|f| f.role == role).map_or("", |f| f.name) + } +} + +/// Converts a `craft_materialx::StrictMaterial`, as `Document::read_material_strict` reads it, by +/// the input tables of its shader's node definition +/// (). An input +/// that is absent takes the definition's default, so an empty input list gives the shader's +/// default material. +/// +/// - The core's base color is the base color times the base weight (`base_weight`, or `base` in +/// Standard Surface), which both shaders apply to the diffuse and the metal color. Metallic +/// and roughness map as they are. The core's specular weight is the specular weight times +/// Schlick's reflectance at normal incidence for the index of refraction, +/// `((ior − 1) / (ior + 1))²`, divided by 0.04; it is reported as approximated when it is not 1, +/// and a value over [`MAX_SPECULAR`] is an error. +/// - The coat (`coat_*`, or `clearcoat*` in glTF PBR) becomes [`Surface::clearcoat`] when its +/// weight is above 0 or a texture sets it. The fuzz of OpenPBR and the sheen of Standard +/// Surface become [`Surface::sheen`] with the weight times the color as its color, reported as +/// approximated; glTF PBR's sheen maps as it is. A layer is kept only when it is on. +/// - Emission is the emission color times its strength: `emission_luminance` (reported as +/// approximated, since it is in nits), `emission`, or `emissive_strength`. A color whose +/// strength is 0 gives no emission. +/// An authored color at strength 0 is validated and reported as dropped. +/// - Alpha is the opacity. Standard Surface's opacity is a color: equal channels give that value, +/// and different channels give their luminance by the Rec.709 luma coefficients, reported as +/// approximated, as the shader's own node graph reduces it with a `luminance` node. OpenPBR's +/// `geometry_opacity` and glTF PBR's `alpha` are floats in their node definitions, so a color +/// there is [`ConvertError::Components`]. glTF PBR's `alpha_mode` 0, 1 and 2 give opaque, +/// masked at `alpha_cutoff`, and blended; the other shaders blend when the opacity is below 1 +/// or a texture sets it. +/// - Every other input of the table (normals, specular color, anisotropy, transmission, +/// subsurface, coat color and IOR, occlusion) is kept in [`Surface::other_inputs`], or as a +/// texture, and reported as unshaded. The displacement is kept the same way. +/// - An image becomes a [`TextureBinding`] with the file path, the UV tiling as its transform's +/// scale, and an encoding from its color space for a color input (linear for data); the core +/// holds 1 times any weight in its place; Standard Surface's color `opacity` binds as +/// [`TextureInput::OpacityRgb`] and the float opacities as [`TextureInput::Opacity`]; an IOR +/// texture leaves the default IOR, reported +/// as approximated. The inputs and textures of a layer that is off (the coat's roughness, +/// color, IOR and normal among them) are dropped and reported. +/// - Color constants are decoded to linear Rec.709 from the color space in effect, as the +/// MaterialX specification asks +/// (): +/// `srgb_texture` and `srgb_rec709_scene` by the sRGB transfer function, the Rec.709 gamma +/// spaces by their power, and `lin_rec709`, `lin_rec709_scene`, `data`, `none` or no color +/// space as they are. Another color space is [`ConvertError::ColorSpace`]. +/// - The reader's warnings are carried into the report. Inputs outside the table are dropped and +/// reported. +/// +/// Every value is checked and none is clamped: a value that is not finite (a color also after it +/// is decoded to linear), is outside the definition's range (`0..=1` for weights, colors and +/// roughness, at least 0 for strengths and IOR, at least 1 for glTF PBR's `ior`), has the wrong +/// number of components, or is an +/// `alpha_mode` other than 0, 1 or 2 is an error, and so is a texture on `alpha_mode` or +/// `alpha_cutoff`, a UV tiling that is not two positive numbers, or an input named twice. +pub fn try_from_materialx(m: &StrictMaterial) -> Result { + let table = match m.shader { + Shader::OpenPbr => OPEN_PBR, + Shader::StandardSurface => STANDARD_SURFACE, + Shader::GltfPbr => GLTF_PBR, + }; + let mut report = ConversionReport::default(); + let mut inputs = Inputs { table, got: table.iter().map(|_| Got::Missing).collect() }; + let mut textures: Vec<(Role, TextureBinding)> = Vec::new(); + let mut others: Vec<(Role, String, Vec)> = Vec::new(); + let mut seen = HashSet::new(); + for (name, value) in &m.inputs { + if !seen.insert(name.as_str()) { + return Err(ConvertError::Duplicate(name.clone())); + } + let Some(idx) = table.iter().position(|f| f.name == name) else { + report.items.push(ReportItem::Dropped { input: name.clone(), why: "is not an input of the shader that the conversion reads" }); + continue; + }; + let f = &table[idx]; + match value { + Resolved::Constant { values, colorspace } => { + let v = checked_values(f, values, colorspace.as_deref())?; + if matches!(f.role, Role::Kept | Role::CoatKept | Role::Normal | Role::Occlusion) { + others.push((f.role, name.clone(), v)); + } else { + inputs.got[idx] = Got::Constant(v); + } + } + Resolved::Image { file, colorspace, uv_tiling } | Resolved::NormalMap { file, colorspace, uv_tiling } => { + if matches!(f.role, Role::AlphaMode | Role::AlphaCutoff) { + return Err(ConvertError::BadValue { input: name.clone(), reason: "cannot be a texture" }); + } + let binding = image_binding(f, file, colorspace.as_deref(), *uv_tiling)?; + let tangent = matches!(value, Resolved::NormalMap { .. }); + let normal = matches!(f.role, Role::Normal) || (matches!(f.role, Role::CoatKept) && matches!(f.kind, Kind::Vector)); + if normal && !tangent { + report.items.push(ReportItem::Dropped { input: name.clone(), why: "world-space normal images are not supported" }); + continue; + } + if tangent && !normal { + report.items.push(ReportItem::Dropped { input: name.clone(), why: "a normalmap image is not supported on this input" }); + continue; + } + textures.push((f.role, binding)); + inputs.got[idx] = Got::Texture; + } + } + } + let material = core(&inputs, &mut report)?; + let clearcoat = clearcoat(&inputs); + let sheen = sheen(&inputs, m.shader, &mut report); + let emissive = emission(&inputs, m.shader, &mut report); + let (alpha, alpha_mode) = alpha(&inputs, m.shader, &mut report)?; + let off = |role: Role| match role { + Role::CoatWeight | Role::CoatRoughness | Role::CoatKept if clearcoat.is_none() => Some(COAT_OFF), + Role::SheenWeight | Role::SheenColor | Role::SheenRoughness if sheen.is_none() => Some(SHEEN_OFF), + Role::EmissionColor if inputs.scalar(Role::EmissionStrength, 1.0) == 0.0 => Some("the emission strength is 0"), + _ => None, + }; + // Authored constants of a layer that is off, except the weight or color that turns it off. + for (f, got) in table.iter().zip(&inputs.got) { + let Got::Constant(v) = got else { continue }; + let turns_it_off = match f.role { + Role::CoatWeight => true, + Role::SheenWeight | Role::SheenColor => v.iter().all(|c| *c == 0.0), + _ => false, + }; + if let Some(why) = off(f.role).filter(|_| !turns_it_off) { + report.items.push(ReportItem::Dropped { input: f.name.to_owned(), why }); + } + } + let mut other_inputs = Vec::new(); + for (role, input, values) in others { + match off(role) { + Some(why) => report.items.push(ReportItem::Dropped { input, why }), + None => { + report.items.push(ReportItem::Unshaded { input: input.clone() }); + other_inputs.push((input, values)); + } + } + } + let mut kept = Vec::new(); + for (role, binding) in textures { + let off = off(role); + let input = texture_name(&inputs, role, &binding); + match off { + Some(why) => report.items.push(ReportItem::Dropped { input, why }), + None => { + report.items.push(ReportItem::Unshaded { input }); + kept.push(binding); + } + } + } + for (layer, on) in [("clearcoat", clearcoat.is_some()), ("sheen", sheen.is_some())] { + if on { + report.items.push(ReportItem::Unshaded { input: layer.into() }); + } + } + displacement(m.displacement.as_ref(), &mut kept, &mut other_inputs, &mut report)?; + report.items.extend(m.warnings.iter().cloned().map(ReportItem::Warning)); + let surface = Surface { + name: m.name.clone(), + material, + alpha, + alpha_mode, + emissive, + double_sided: false, + unlit: false, + clearcoat, + sheen, + textures: kept, + other_inputs, + }; + Ok(Conversion { surface, report }) +} + +/// The source name of a texture for the report. +fn texture_name(inputs: &Inputs, role: Role, binding: &TextureBinding) -> String { + match &binding.input { + TextureInput::Other(name) => name.clone(), + _ => inputs.name(role).to_owned(), + } +} + +/// The reason text for a value outside `lo..=hi`. +fn reason(lo: f32, hi: f32) -> &'static str { + match (lo, hi) { + (0.0, 1.0) => UNIT, + (0.0, _) => NON_NEGATIVE, + (1.0, _) => "is not a finite number of at least 1", + _ => FINITE, + } +} + +/// The values of a constant for field `f`, checked against its kind and, for a color, decoded +/// to linear from `space`. +fn checked_values(f: &Field, values: &[f32], space: Option<&str>) -> Result, ConvertError> { + let expected = match f.kind { + Kind::Scalar(..) | Kind::Mode => 1, + Kind::Color(_) | Kind::Vector => 3, + }; + if values.len() != expected { + return Err(ConvertError::Components { input: f.name.to_owned(), expected, found: values.len() }); + } + let bad = |reason| ConvertError::BadValue { input: f.name.to_owned(), reason }; + let (lo, hi) = match f.kind { + Kind::Scalar(lo, hi) => (lo, hi), + Kind::Color(hi) => (0.0, hi), + Kind::Vector => (f32::MIN, f32::MAX), + Kind::Mode => (0.0, 2.0), + }; + let in_range = |v: f32| v.is_finite() && (lo..=hi).contains(&v); + for &v in values { + if !in_range(v) { + return Err(bad(reason(lo, hi))); + } + if f.kind == Kind::Mode && v.fract() != 0.0 { + return Err(bad("is not 0, 1 or 2")); + } + } + match f.kind { + Kind::Color(_) => { + let linear = decode(values, space, f.name)?; + if linear.iter().all(|&v| in_range(v)) { Ok(linear) } else { Err(bad("is not a finite color once decoded to linear")) } + } + _ => Ok(values.to_vec()), + } +} + +/// `values` decoded to linear Rec.709 from the color space `space`. +fn decode(values: &[f32], space: Option<&str>, input: &str) -> Result, ConvertError> { + let power = |p: f32| values.iter().map(|v| v.powf(p)).collect(); + Ok(match space { + None | Some("data" | "none" | "lin_rec709" | "lin_rec709_scene") => values.to_vec(), + Some("srgb_texture" | "srgb_rec709_scene") => values.iter().map(|v| srgb_to_linear(*v)).collect(), + Some("g22_rec709" | "g22_rec709_scene") => power(2.2), + Some("g18_rec709" | "g18_rec709_scene") => power(1.8), + Some("g24_rec709_scene") => power(2.4), + Some(other) => return Err(ConvertError::ColorSpace { input: input.to_owned(), colorspace: other.to_owned() }), + }) +} + +/// The binding of an image on field `f`. +fn image_binding(f: &Field, file: &str, space: Option<&str>, tiling: Option<[f32; 2]>) -> Result { + let input = match f.role { + Role::BaseColor => TextureInput::BaseColor, + Role::Metallic => TextureInput::Metallic, + Role::Roughness => TextureInput::Roughness, + Role::Normal => TextureInput::Normal, + Role::Occlusion => TextureInput::Occlusion, + Role::EmissionColor => TextureInput::Emissive, + Role::Opacity if matches!(f.kind, Kind::Color(_)) => TextureInput::OpacityRgb, + Role::Opacity => TextureInput::Opacity, + Role::CoatWeight => TextureInput::Clearcoat, + Role::CoatRoughness => TextureInput::ClearcoatRoughnessFirst, + Role::SheenColor => TextureInput::SheenColor, + Role::SheenRoughness => TextureInput::SheenRoughnessFirst, + _ => TextureInput::Other(f.name.to_owned()), + }; + let encoding = if matches!(f.kind, Kind::Color(_)) { encoding(space) } else { TextureEncoding::Linear }; + let transform = match tiling { + Some(scale) if scale.iter().all(|v| v.is_finite() && *v > 0.0) => Some(UvTransform { offset: [0.0; 2], rotation: 0.0, scale }), + Some(_) => return Err(ConvertError::BadValue { input: f.name.to_owned(), reason: "has a UV tiling that is not two positive numbers" }), + None => None, + }; + Ok(TextureBinding { input, source: TextureSource::File(file.to_owned()), encoding, uv_set: 0, wrap: [Wrap::Repeat; 2], transform, scale: 1.0 }) +} + +/// The encoding of a color image in the color space `space`. +fn encoding(space: Option<&str>) -> TextureEncoding { + match space { + None | Some("data" | "none" | "lin_rec709" | "lin_rec709_scene") => TextureEncoding::Linear, + Some("srgb_texture" | "srgb_rec709_scene") => TextureEncoding::Srgb, + Some(other) => TextureEncoding::Named(other.to_owned()), + } +} + +/// The BRDF core. +fn core(inputs: &Inputs, report: &mut ConversionReport) -> Result { + let color = inputs.value(Role::BaseColor).unwrap_or([1.0; 3]); + let weight = inputs.scalar(Role::BaseWeight, 1.0); + let base = color.map(|c| c * weight); + let metallic = inputs.scalar(Role::Metallic, 0.0); + let roughness = inputs.scalar(Role::Roughness, 0.0); + if inputs.textured(Role::Ior) { + report + .items + .push(ReportItem::Approximated { input: inputs.name(Role::Ior).into(), how: "is a texture; the default index of refraction was used" }); + } + let ior = match inputs.find(Role::Ior) { + Some((f, Got::Texture)) => f64::from(f.default[0]), + _ => f64::from(inputs.scalar(Role::Ior, 1.5)), + }; + // The reflectance relative to 0.04, which is 1 within rounding at the default IOR of 1.5. + let mut ratio = ((ior - 1.0) / (ior + 1.0)).powi(2) / 0.04; + if (ratio - 1.0).abs() < 1e-9 { + ratio = 1.0; + } + let specular = f64::from(inputs.scalar(Role::SpecularWeight, 1.0)) * ratio; + let name = inputs.name(Role::SpecularWeight); + if specular > f64::from(MAX_SPECULAR) { + return Err(ConvertError::BadValue { + input: name.into(), + reason: "times the reflectance of the index of refraction is over the 25 the BRDF supports", + }); + } + if specular != 1.0 { + report.items.push(ReportItem::Approximated { + input: name.into(), + how: "times Schlick's reflectance at normal incidence for the index of refraction, over 0.04, is the core's specular weight", + }); + } + Ok(Material::try_new(base, metallic, roughness)?.try_with_weights(specular as f32, 1.0)?) +} + +/// The coat, when its weight is above 0 or a texture sets it. +fn clearcoat(inputs: &Inputs) -> Option { + let weight = inputs.scalar(Role::CoatWeight, 0.0); + (weight > 0.0).then(|| Clearcoat { weight, roughness: inputs.scalar(Role::CoatRoughness, 0.0) }) +} + +/// The sheen, when its color times its weight is not black. +fn sheen(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> Option { + let weight = inputs.scalar(Role::SheenWeight, 1.0); + let color = inputs.value(Role::SheenColor)?.map(|c| c * weight); + if color == [0.0; 3] { + return None; + } + if shader != Shader::GltfPbr { + report.items.push(ReportItem::Approximated { input: inputs.name(Role::SheenWeight).into(), how: "times the color is the sheen color" }); + } + Some(Sheen { color, roughness: inputs.scalar(Role::SheenRoughness, 0.0) }) +} + +/// The emission color times its strength. +fn emission(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> [f32; 3] { + let strength = inputs.scalar(Role::EmissionStrength, 1.0); + let color = inputs.value(Role::EmissionColor).unwrap_or([0.0; 3]); + let emissive = color.map(|c| c * strength); + if shader == Shader::OpenPbr && emissive != [0.0; 3] { + report.items.push(ReportItem::Approximated { + input: inputs.name(Role::EmissionStrength).into(), + how: "is in nits and multiplies the emission color", + }); + } + emissive +} + +/// Alpha and its mode. +fn alpha(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> Result<(f32, AlphaMode), ConvertError> { + let opacity = inputs.value(Role::Opacity).unwrap_or([1.0; 3]); + let alpha = if shader == Shader::StandardSurface && (opacity[0] != opacity[1] || opacity[1] != opacity[2]) { + report + .items + .push(ReportItem::Approximated { input: inputs.name(Role::Opacity).into(), how: "is a color; its Rec.709 luminance is the alpha" }); + luminance(opacity) + } else { + opacity[0] + }; + let mode = if shader == Shader::GltfPbr { + match inputs.scalar(Role::AlphaMode, 0.0) { + 0.0 => AlphaMode::Opaque, + 1.0 => AlphaMode::Mask(inputs.scalar(Role::AlphaCutoff, 0.5)), + 2.0 => AlphaMode::Blend, + _ => return Err(ConvertError::BadValue { input: "alpha_mode".into(), reason: "is not 0, 1 or 2" }), + } + } else if alpha < 1.0 || inputs.textured(Role::Opacity) { + AlphaMode::Blend + } else { + AlphaMode::Opaque + }; + if shader == Shader::GltfPbr + && !matches!(mode, AlphaMode::Mask(_)) + && inputs.find(Role::AlphaCutoff).is_some_and(|(_, value)| matches!(value, Got::Constant(_))) + { + report.items.push(ReportItem::Dropped { input: inputs.name(Role::AlphaCutoff).into(), why: "the alpha mode does not use a cutoff" }); + } + Ok((alpha, mode)) +} + +/// The luminance of a linear Rec.709 color, by the `rec709` luma coefficients of the MaterialX +/// `luminance` node +/// (), +/// kept between the smallest and largest channel so that rounding cannot leave `0..=1`. +fn luminance(c: [f32; 3]) -> f32 { + let y = 0.2126 * f64::from(c[0]) + 0.7152 * f64::from(c[1]) + 0.0722 * f64::from(c[2]); + (y as f32).clamp(c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2])) +} + +/// Keeps the displacement as a texture or an other input. +fn displacement( + value: Option<&Resolved>, + textures: &mut Vec, + other_inputs: &mut Vec<(String, Vec)>, + report: &mut ConversionReport, +) -> Result<(), ConvertError> { + const DISPLACEMENT: Field = field("displacement", Kind::Scalar(f32::MIN, f32::MAX), Role::Kept, 0.0); + match value { + None => return Ok(()), + Some(Resolved::Constant { values, .. }) => other_inputs.push(("displacement".into(), checked_values(&DISPLACEMENT, values, None)?)), + Some(Resolved::Image { file, colorspace, uv_tiling }) => { + let mut binding = image_binding(&DISPLACEMENT, file, colorspace.as_deref(), *uv_tiling)?; + binding.input = TextureInput::Displacement; + textures.push(binding); + } + Some(Resolved::NormalMap { .. }) => { + return Err(ConvertError::BadValue { input: "displacement".into(), reason: "cannot be a normalmap image" }); + } + } + report.items.push(ReportItem::Unshaded { input: "displacement".into() }); + Ok(()) +} diff --git a/crates/pbr/src/convert_mesh.rs b/crates/pbr/src/convert_mesh.rs new file mode 100644 index 0000000000..a98e0539b9 --- /dev/null +++ b/crates/pbr/src/convert_mesh.rs @@ -0,0 +1,177 @@ +//! The conversion from a `craft_mesh::Material`, which holds a glTF 2.0 metallic-roughness +//! material. + +use craft_mesh::{AlphaMode as MeshAlpha, Material as MeshMaterial, TextureRef, Wrap as MeshWrap}; + +use crate::Material; +use crate::surface::{ + AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, FINITE, NON_NEGATIVE, ReportItem, Sheen, Surface, TextureBinding, + TextureEncoding, TextureInput, TextureSource, UNIT, UvTransform, Wrap, checked, +}; + +/// The material extensions whose values `craft_mesh` reads into `craft_mesh::Material`'s fields. +/// It reads only part of `KHR_materials_pbrSpecularGlossiness` and of `KHR_materials_clearcoat`. +const CONVERTED_EXTENSIONS: &[&str] = &[ + "KHR_materials_unlit", + "KHR_materials_emissive_strength", + "KHR_materials_pbrSpecularGlossiness", + "KHR_materials_clearcoat", + "KHR_materials_sheen", +]; +const SPECULAR_GLOSSINESS: &str = "KHR_materials_pbrSpecularGlossiness"; + +/// Converts a `craft_mesh::Material` as glTF 2.0 defines its metallic-roughness material +/// (). +/// +/// - Mapped as they are: the linear base color RGB, metallic and roughness into the core with +/// specular and diffuse weights of 1, base color alpha into [`Surface::alpha`], the alpha mode +/// and cutoff, the linear emissive color, the double-sided flag, the unlit flag of +/// `KHR_materials_unlit` and the name. Nothing is converted between color spaces: the source +/// values are linear. +/// - Kept and reported as [`ReportItem::Unshaded`]: every texture, with its image index, UV set, +/// wrap modes and `KHR_texture_transform`, and the normal scale and occlusion strength as the +/// binding's scale; the clearcoat layer of `KHR_materials_clearcoat`; the sheen layer of +/// `KHR_materials_sheen`; and the unlit flag. Base color, emissive and sheen color textures +/// are sRGB-encoded and the others are linear, as glTF and its extensions define them. +/// - Dropped and reported: the clearcoat textures when the clearcoat factor is 0, and the sheen +/// textures when the sheen color factor is black. Each extension turns its layer off then. +/// Every other material extension in `craft_mesh::Material::extensions`, such as +/// `KHR_materials_transmission`, is dropped and reported by its name, and so is the +/// `clearcoatNormalTexture` of `KHR_materials_clearcoat`, which `craft_mesh` does not read. +/// - Reported as [`ReportItem::Approximated`]: `KHR_materials_pbrSpecularGlossiness`, which +/// `craft_mesh` reads as its diffuse color and texture with roughness from the glossiness, +/// without its specular color or specular-glossiness texture. +/// +/// Every value is checked and none is clamped. Base color channels, alpha, metallic, +/// roughness, occlusion strength and the clearcoat and sheen values must be numbers from 0 to 1; +/// emissive channels and the alpha cutoff must be finite and at least 0; the normal scale and +/// every UV transform value must be finite. Otherwise the result is +/// [`ConvertError::BadValue`] naming the `craft_mesh::Material` field. +pub fn try_from_mesh(m: &MeshMaterial) -> Result { + let [r, g, b, a] = m.base_color; + let base = [checked(r, 0.0, 1.0, "base_color", UNIT)?, checked(g, 0.0, 1.0, "base_color", UNIT)?, checked(b, 0.0, 1.0, "base_color", UNIT)?]; + let alpha = checked(a, 0.0, 1.0, "base_color alpha", UNIT)?; + let metallic = checked(m.metallic, 0.0, 1.0, "metallic", UNIT)?; + let roughness = checked(m.roughness, 0.0, 1.0, "roughness", UNIT)?; + let material = Material::try_new(base, metallic, roughness)?; + let mut emissive = [0.0; 3]; + for (out, v) in emissive.iter_mut().zip(m.emissive) { + *out = checked(v, 0.0, f32::MAX, "emissive", NON_NEGATIVE)?; + } + let alpha_mode = match m.alpha_mode { + MeshAlpha::Opaque => AlphaMode::Opaque, + MeshAlpha::Mask(cutoff) => AlphaMode::Mask(checked(cutoff, 0.0, f32::MAX, "alpha cutoff", NON_NEGATIVE)?), + MeshAlpha::Blend => AlphaMode::Blend, + }; + let normal_scale = checked(m.normal_scale, f32::MIN, f32::MAX, "normal_scale", FINITE)?; + let occlusion_strength = checked(m.occlusion_strength, 0.0, 1.0, "occlusion_strength", UNIT)?; + let clearcoat_weight = checked(m.clearcoat, 0.0, 1.0, "clearcoat", UNIT)?; + let clearcoat_roughness = checked(m.clearcoat_roughness, 0.0, 1.0, "clearcoat_roughness", UNIT)?; + let mut sheen_color = [0.0; 3]; + for (out, v) in sheen_color.iter_mut().zip(m.sheen_color) { + *out = checked(v, 0.0, 1.0, "sheen_color", UNIT)?; + } + let sheen_roughness = checked(m.sheen_roughness, 0.0, 1.0, "sheen_roughness", UNIT)?; + + let mut report = ConversionReport::default(); + let mut textures = Vec::new(); + let mut bind = + |name: &str, slot: &Option, input: TextureInput, encoding: TextureEncoding, scale: f32, dropped: Option<&'static str>| { + let Some(t) = slot else { + if scale != 1.0 { + let factor = match input { + TextureInput::Normal => "normal_scale", + TextureInput::Occlusion => "occlusion_strength", + _ => name, + }; + report.items.push(ReportItem::Dropped { input: factor.to_owned(), why: "the corresponding texture is absent" }); + } + return Ok(()); + }; + // The texture is checked before a layer that is off drops it. + let b = binding(name, t, input, encoding, scale)?; + if let Some(why) = dropped { + report.items.push(ReportItem::Dropped { input: name.to_owned(), why }); + return Ok(()); + } + textures.push(b); + report.items.push(ReportItem::Unshaded { input: name.to_owned() }); + Ok::<(), ConvertError>(()) + }; + use TextureEncoding::{Linear, Srgb}; + bind("base_color_texture", &m.base_color_texture, TextureInput::BaseColor, Srgb, 1.0, None)?; + bind("metallic_roughness_texture", &m.metallic_roughness_texture, TextureInput::MetallicRoughness, Linear, 1.0, None)?; + bind("normal_texture", &m.normal_texture, TextureInput::Normal, Linear, normal_scale, None)?; + bind("occlusion_texture", &m.occlusion_texture, TextureInput::Occlusion, Linear, occlusion_strength, None)?; + bind("emissive_texture", &m.emissive_texture, TextureInput::Emissive, Srgb, 1.0, None)?; + let coat_off = (clearcoat_weight == 0.0).then_some("the clearcoat factor is 0, which turns the layer off"); + bind("clearcoat_texture", &m.clearcoat_texture, TextureInput::Clearcoat, Linear, 1.0, coat_off)?; + bind("clearcoat_roughness_texture", &m.clearcoat_roughness_texture, TextureInput::ClearcoatRoughness, Linear, 1.0, coat_off)?; + let sheen_off = (sheen_color == [0.0; 3]).then_some("the sheen color factor is black, which turns the layer off"); + bind("sheen_color_texture", &m.sheen_color_texture, TextureInput::SheenColor, Srgb, 1.0, sheen_off)?; + bind("sheen_roughness_texture", &m.sheen_roughness_texture, TextureInput::SheenRoughness, Linear, 1.0, sheen_off)?; + + let clearcoat = coat_off.is_none().then_some(Clearcoat { weight: clearcoat_weight, roughness: clearcoat_roughness }); + if clearcoat.is_some() { + report.items.push(ReportItem::Unshaded { input: "clearcoat".into() }); + } + let sheen = sheen_off.is_none().then_some(Sheen { color: sheen_color, roughness: sheen_roughness }); + if sheen.is_some() { + report.items.push(ReportItem::Unshaded { input: "sheen".into() }); + } + for (inactive, roughness, input) in + [(clearcoat.is_none(), clearcoat_roughness, "clearcoat_roughness"), (sheen.is_none(), sheen_roughness, "sheen_roughness")] + { + if inactive && roughness != 0.0 { + report.items.push(ReportItem::Dropped { input: input.into(), why: "the layer is off" }); + } + } + if m.unlit { + report.items.push(ReportItem::Unshaded { input: "unlit".into() }); + } + for name in m.extensions.keys().filter(|k| !CONVERTED_EXTENSIONS.contains(&k.as_str())) { + report.items.push(ReportItem::Dropped { input: name.clone(), why: "the extension is not converted" }); + } + if m.extensions.get("KHR_materials_clearcoat").is_some_and(|c| c.get("clearcoatNormalTexture").is_some()) { + report.items.push(ReportItem::Dropped { input: "clearcoatNormalTexture".into(), why: "craft-mesh does not read it" }); + } + if m.extensions.contains_key(SPECULAR_GLOSSINESS) { + report.items.push(ReportItem::Approximated { + input: SPECULAR_GLOSSINESS.into(), + how: "read as its diffuse color and texture with roughness from the glossiness; its specular color and texture are not converted", + }); + } + let surface = Surface { + name: m.name.clone(), + material, + alpha, + alpha_mode, + emissive, + double_sided: m.double_sided, + unlit: m.unlit, + clearcoat, + sheen, + textures, + other_inputs: Vec::new(), + }; + Ok(Conversion { surface, report }) +} + +/// The binding of the texture `t` in the field `name`. +fn binding(name: &str, t: &TextureRef, input: TextureInput, encoding: TextureEncoding, scale: f32) -> Result { + let transform = match t.transform { + Some(x) => { + for v in [x.offset[0], x.offset[1], x.rotation, x.scale[0], x.scale[1]] { + checked(v, f32::MIN, f32::MAX, &format!("{name} transform"), FINITE)?; + } + Some(UvTransform { offset: x.offset, rotation: x.rotation, scale: x.scale }) + } + None => None, + }; + let wrap = t.wrap.map(|w| match w { + MeshWrap::Repeat => Wrap::Repeat, + MeshWrap::Clamp => Wrap::Clamp, + MeshWrap::Mirror => Wrap::Mirror, + }); + Ok(TextureBinding { input, source: TextureSource::Image(t.image), encoding, uv_set: t.uv_set, wrap, transform, scale }) +} diff --git a/crates/pbr/src/lib.rs b/crates/pbr/src/lib.rs index 9413f9c0b2..45c0a28f06 100644 --- a/crates/pbr/src/lib.rs +++ b/crates/pbr/src/lib.rs @@ -36,6 +36,14 @@ //! [`SHADE_WGSL`] is the WGSL text of the same shading functions for an app's own shaders, and //! [`GpuMaterial`] and [`GpuSh9`] lay out the values it reads. //! +//! A [`Surface`] is a [`Material`] with the state a renderer applies around it: alpha and its +//! mode, emission, sidedness, the unlit flag, clearcoat and sheen layers, and texture bindings +//! that are kept but not loaded. With the `mesh` feature, `try_from_mesh` converts a +//! `craft_mesh::Material`, and with the `materialx` feature, `try_from_materialx` converts a +//! `craft_materialx::StrictMaterial`. Each returns the surface and a [`ConversionReport`] of what it +//! kept without shading, approximated or dropped, and a [`ConvertError`] for a value that is not +//! finite or is out of its range. Neither feature is on by default. +//! //! The diffuse coefficients are the nine real SH coefficients of the radiance, convolved with the //! clamped cosine lobe (band factors `π`, `2π/3` and `π/4`, Ramamoorthi and Hanrahan 2001, //! ) and divided by `π`. [`irradiance`] @@ -51,9 +59,14 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod brdf; +#[cfg(feature = "materialx")] +mod convert_materialx; +#[cfg(feature = "mesh")] +mod convert_mesh; mod environment; mod prefilter; mod sh; +mod surface; mod vec3; mod wgsl; @@ -61,9 +74,17 @@ mod wgsl; use rayon::prelude::*; pub use brdf::{MAX_SPECULAR, MIN_DIRECT_ROUGHNESS, Material, Visibility, try_environment_brdf}; +#[cfg(feature = "materialx")] +pub use convert_materialx::try_from_materialx; +#[cfg(feature = "mesh")] +pub use convert_mesh::try_from_mesh; pub use environment::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, MAX_RADIANCE, default_environment, dir_of, uv_of}; pub use prefilter::{PrefilterOptions, ggx_distribution, ggx_distribution_between, hammersley, try_prefilter}; pub use sh::{irradiance, sh_basis, try_sh9}; +pub use surface::{ + AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, ReportItem, Sheen, Surface, TextureBinding, TextureEncoding, TextureInput, + TextureSource, UvTransform, Wrap, +}; pub use wgsl::{GpuMaterial, GpuSh9, SHADE_WGSL}; /// Why an environment could not be made, filtered or read, or a material could not be shaded. diff --git a/crates/pbr/src/prefilter.rs b/crates/pbr/src/prefilter.rs index 31122f80b4..66d76dfe27 100644 --- a/crates/pbr/src/prefilter.rs +++ b/crates/pbr/src/prefilter.rs @@ -49,9 +49,12 @@ impl PrefilterOptions { } /// Point `i` of `n` of the Hammersley set: `(i / n, radical inverse of i in base 2)`. Returns -/// `None` when `i` is not below `n`. +/// coordinates in `0..1`, or `None` when `i` is not below `n`. pub fn hammersley(i: u32, n: u32) -> Option<[f32; 2]> { - (i < n).then(|| [i as f32 / n as f32, i.reverse_bits() as f32 * 2.328_306_4e-10]) + (i < n).then(|| { + let upper = f32::from_bits(1.0_f32.to_bits() - 1); + [i as f32 / n as f32, i.reverse_bits() as f32 * 2.328_306_4e-10].map(|v| v.min(upper)) + }) } /// The GGX normal distribution `D` at `n_dot_h` for perceptual `roughness`, with @@ -180,7 +183,8 @@ fn check_budget(env: &EnvImage, options: &PrefilterOptions, pyramid: &[(u32, u32 let lists = u64::from(options.levels) * (size_of::<(u32, u32)>() + size_of::()) as u64 + pyramid_lists; let bytes = pixels.and_then(|p| p.checked_mul(PIXEL_BYTES)?.checked_add(table)?.checked_add(lists)); limits.check_total_bytes(bytes, w, h)?; - let needed = levels.and_then(|l| l.checked_mul(u64::from(options.samples))).unwrap_or(u64::MAX); + let needed = + levels.and_then(|l| l.checked_mul(u64::from(options.samples))).ok_or(PbrError::BadOption("the filtering work count exceeds u64::MAX"))?; if needed > limits.max_work { return Err(PbrError::TooMuchWork { needed, limit: limits.max_work }); } @@ -258,7 +262,8 @@ fn filter_level(w: u32, h: u32, table: &[Sample<'_>]) -> Result Result, PbrError> { options.validate(limits)?; let (w, h) = (env.width(), env.height()); @@ -300,3 +305,18 @@ pub fn try_prefilter(env: &EnvImage, options: &PrefilterOptions, limits: &Limits } Ok(out) } + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + + #[test] + fn overflowing_sample_work_is_refused_with_unlimited_work() { + let limits = Limits { max_levels: u32::MAX, max_samples: u32::MAX, max_bytes: u64::MAX, max_work: u64::MAX, ..Limits::default() }; + let env = EnvImage::try_from_linear(4, 2, vec![[1.0; 3]; 8], &limits).unwrap(); + let options = PrefilterOptions { levels: 536_870_914, samples: u32::MAX, ..PrefilterOptions::default() }; + assert!(check_budget(&env, &options, &[], &limits).is_err()); + } +} diff --git a/crates/pbr/src/surface.rs b/crates/pbr/src/surface.rs new file mode 100644 index 0000000000..c418a8f17c --- /dev/null +++ b/crates/pbr/src/surface.rs @@ -0,0 +1,237 @@ +//! A surface material: the BRDF core with the surface state around it, and the report and errors +//! of the conversions into it. + +use crate::{Material, PbrError}; + +/// A material as a renderer needs it: the metallic-roughness [`Material`] that +/// [`Material::try_direct`] shades, and the state a renderer applies around it. Alpha, emission +/// and sidedness are applied by the renderer, not by the BRDF. The clearcoat and sheen layers, +/// the textures and [`Surface::other_inputs`] are kept but not shaded by +/// [`Material::try_direct`]. When [`Surface::unlit`] is set, the surface shows its base color +/// without lighting, and [`Material::try_direct`] does not give its appearance. +/// +/// Made by `try_from_mesh` (the `mesh` feature) and `try_from_materialx` (the `materialx` +/// feature), which check every value. +/// `#[non_exhaustive]`: read and change the fields, but get a value from a conversion. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Surface { + /// The source material's name. + pub name: String, + /// The BRDF core. Where a texture is bound to one of its values, the core holds the factor the + /// texture's samples are multiplied by. + pub material: Material, + /// Coverage from 0 (transparent) to 1 (opaque). + pub alpha: f32, + /// How [`Surface::alpha`] is used. + pub alpha_mode: AlphaMode, + /// Linear RGB emission, each channel at least 0. + pub emissive: [f32; 3], + /// Both faces are drawn and lit. + pub double_sided: bool, + /// The surface is shown as its base color and alpha, without lighting. + pub unlit: bool, + /// A clear layer over the base, when its weight is above 0 or a texture sets it. + pub clearcoat: Option, + /// A sheen layer, when its color is not black or a texture sets it. + pub sheen: Option, + /// Textures bound to the material's values, not loaded or sampled. + pub textures: Vec, + /// Source inputs with no field here, by their source name, as authored. Color values are + /// linear. + pub other_inputs: Vec<(String, Vec)>, +} + +/// How a surface's alpha is used. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum AlphaMode { + /// Alpha is ignored and the surface is opaque. + #[default] + Opaque, + /// The surface is drawn where alpha is at least the cutoff, which is at least 0. + Mask(f32), + /// The surface is blended by alpha. + Blend, +} + +/// A clear layer over the base: weight and perceptual roughness, each from 0 to 1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Clearcoat { + pub weight: f32, + pub roughness: f32, +} + +/// A sheen layer: linear RGB color and perceptual roughness, each from 0 to 1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Sheen { + pub color: [f32; 3], + pub roughness: f32, +} + +/// The value a texture sets, and which of its channels it reads. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum TextureInput { + /// Base color in RGB; from glTF, alpha in A. + BaseColor, + /// glTF's packed texture: roughness in G and metallic in B. + MetallicRoughness, + /// Metallic in the first channel. + Metallic, + /// Roughness in the first channel. + Roughness, + /// A tangent-space normal map; [`TextureBinding::scale`] scales its X and Y. + Normal, + /// Ambient occlusion in R; [`TextureBinding::scale`] is its strength. + Occlusion, + /// Emission color in RGB. + Emissive, + /// Opacity: alpha in the first channel. + Opacity, + /// A colored opacity in RGB, such as Standard Surface's `opacity`; the alpha is its Rec.709 + /// luminance. + OpacityRgb, + /// Clearcoat weight in R. + Clearcoat, + /// glTF's clearcoat roughness texture: roughness in G. + ClearcoatRoughness, + /// Clearcoat roughness in the first channel. + ClearcoatRoughnessFirst, + /// Sheen color in RGB. + SheenColor, + /// glTF's sheen roughness texture: roughness in A. + SheenRoughness, + /// Sheen roughness in the first channel. + SheenRoughnessFirst, + /// Displacement height in the first channel. + Displacement, + /// A source input with no slot above, by its source name. + Other(String), +} + +/// Where a texture's image is. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum TextureSource { + /// An index into the source scene's images (`craft_mesh::Scene::images`). + Image(usize), + /// A file path, as the source document wrote it with any file prefix applied. + File(String), +} + +/// How a texture's samples are encoded. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum TextureEncoding { + /// Linear values, or data that is not a color. + Linear, + /// sRGB-encoded color. + Srgb, + /// A color space by the name the source gives it, which the caller converts. + Named(String), +} + +/// How a texture continues outside 0..1. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Wrap { + #[default] + Repeat, + Clamp, + Mirror, +} + +/// A UV transform: scale, then rotate by `rotation` radians, then add `offset`, in the order and +/// with the signs of glTF's `KHR_texture_transform`. Every value is finite. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvTransform { + pub offset: [f32; 2], + pub rotation: f32, + pub scale: [f32; 2], +} + +/// A texture bound to a value of a [`Surface`]. +#[derive(Clone, Debug, PartialEq)] +pub struct TextureBinding { + pub input: TextureInput, + pub source: TextureSource, + pub encoding: TextureEncoding, + /// The UV set the texture reads. + pub uv_set: u32, + /// How the texture continues outside 0..1 along u and v. + pub wrap: [Wrap; 2], + pub transform: Option, + /// A finite scale on the samples: the normal scale of a normal map, the strength of an + /// occlusion map, and 1 otherwise. + pub scale: f32, +} + +/// A converted surface and what the conversion did not carry over exactly. +#[derive(Clone, Debug, PartialEq)] +pub struct Conversion { + pub surface: Surface, + pub report: ConversionReport, +} + +/// What a conversion kept without shading, approximated or dropped, in the order it found them. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ConversionReport { + pub items: Vec, +} + +impl ConversionReport { + /// Whether every source value went into a field that [`Material::try_direct`] shades or that + /// a renderer applies (alpha, emission, sidedness), with nothing approximated or dropped. + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } +} + +/// One entry of a [`ConversionReport`]. `input` is the source's name for the value. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum ReportItem { + /// Kept on the [`Surface`] (a layer, a texture, an unlit flag or an other input), and not + /// shaded by [`Material::try_direct`]. + Unshaded { input: String }, + /// Mapped with a change of meaning; `how` says what was done. + Approximated { input: String, how: &'static str }, + /// Not kept; `why` says why. + Dropped { input: String, why: &'static str }, + /// A warning the source reader gave. + Warning(String), +} + +/// Why a material could not be converted. Nothing is clamped or replaced: a value out of its +/// range is an error. +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[non_exhaustive] +pub enum ConvertError { + /// A value is not a finite number, or is out of its range; `reason` says which. + #[error("{input} {reason}")] + BadValue { input: String, reason: &'static str }, + /// A value has the wrong number of components. + #[error("{input} has {found} values where {expected} are needed")] + Components { input: String, expected: usize, found: usize }, + /// A color value is in a color space the conversion does not decode. + #[error("{input} is in the color space {colorspace}, which is not converted")] + ColorSpace { input: String, colorspace: String }, + /// The source names an input more than once. + #[error("the material has more than one {0} input")] + Duplicate(String), + /// The BRDF core rejected the converted values. + #[error(transparent)] + Material(#[from] PbrError), +} + +/// `v` when it is finite and in `lo..=hi`, else [`ConvertError::BadValue`] naming `input`. +#[cfg(feature = "mesh")] +pub(crate) fn checked(v: f32, lo: f32, hi: f32, input: &str, reason: &'static str) -> Result { + if v.is_finite() && (lo..=hi).contains(&v) { Ok(v) } else { Err(ConvertError::BadValue { input: input.to_owned(), reason }) } +} + +/// The reason text for a value that must be from 0 to 1. +#[cfg(any(feature = "mesh", feature = "materialx"))] +pub(crate) const UNIT: &str = "is not a number from 0 to 1"; +/// The reason text for a value that must be finite and at least 0. +#[cfg(any(feature = "mesh", feature = "materialx"))] +pub(crate) const NON_NEGATIVE: &str = "is not a finite number of at least 0"; +/// The reason text for a value that must be finite. +#[cfg(any(feature = "mesh", feature = "materialx"))] +pub(crate) const FINITE: &str = "is not a finite number"; diff --git a/crates/pbr/tests/it/bench.rs b/crates/pbr/tests/it/bench.rs index 3abfbe9265..caecedfb18 100644 --- a/crates/pbr/tests/it/bench.rs +++ b/crates/pbr/tests/it/bench.rs @@ -1,7 +1,6 @@ //! Elapsed (wall-clock) time of the default filtering: -//! `cargo test -p craft-pbr --release --test it -- --ignored --nocapture bench`. -//! The `parallel` feature is on in this test target even without `--features parallel`, since -//! the crate's dev-dependency on itself enables it, so the times are not a serial baseline. +//! `cargo test -p craft-pbr --release --features parallel --test it -- --ignored --nocapture bench`. +//! The command measures the parallel build. Omitting `--features parallel` measures the serial build. use std::time::Instant; diff --git a/crates/pbr/tests/it/bounds.rs b/crates/pbr/tests/it/bounds.rs index ee5ea4fd20..0b7f5e7be5 100644 --- a/crates/pbr/tests/it/bounds.rs +++ b/crates/pbr/tests/it/bounds.rs @@ -28,6 +28,15 @@ fn zero_sizes_are_refused() { assert_eq!(Environment::Night.try_render(0, &limits), Err(PbrError::BadSize(0, 0))); } +#[test] +fn hammersley_points_stay_below_one_after_rounding() { + for (i, n) in [(0x03ff_ffff, 0x0400_0000), (u32::MAX - 1, u32::MAX)] { + let point = hammersley(i, n).unwrap(); + assert!(point.into_iter().all(|v| (0.0..1.0).contains(&v)), "{i}/{n}: {point:?}"); + } + assert_eq!(hammersley(u32::MAX, u32::MAX), None); +} + #[test] fn huge_sizes_are_refused_before_allocating() { let default = Limits::default(); diff --git a/crates/pbr/tests/it/brdf.rs b/crates/pbr/tests/it/brdf.rs index d150803e79..79f4dc98f6 100644 --- a/crates/pbr/tests/it/brdf.rs +++ b/crates/pbr/tests/it/brdf.rs @@ -5,8 +5,7 @@ use std::f32::consts::PI; use craft_pbr::{ - EnvImage, MIN_DIRECT_ROUGHNESS, Material, PbrError, Visibility, default_environment, ggx_distribution, ggx_distribution_between, hammersley, - try_environment_brdf, + EnvImage, MIN_DIRECT_ROUGHNESS, Material, PbrError, Visibility, default_environment, ggx_distribution, hammersley, try_environment_brdf, }; const VISIBILITIES: [Visibility; 3] = [Visibility::SmithSchlick, Visibility::SmithSeparable, Visibility::SmithHeightCorrelated]; @@ -338,15 +337,6 @@ fn the_default_visibility_is_effectcrafts_smith_schlick() { assert!(at(Visibility::SmithHeightCorrelated) > at(Visibility::SmithSeparable)); } -/// A unit vector along `d`, computed in the same steps and order as the crate normalizes -/// directions: divided by its largest component, then multiplied by the reciprocal length. -fn crate_unit(d: [f32; 3]) -> [f32; 3] { - let big = d[0].abs().max(d[1].abs()).max(d[2].abs()); - let s = [d[0] / big, d[1] / big, d[2] / big]; - let r = 1.0 / ((s[0] * s[0]) + (s[1] * s[1]) + (s[2] * s[2])).sqrt(); - [s[0] * r, s[1] * r, s[2] * r] -} - /// The light a material reflects from a uniform white sky onto a surface seen at `theta`: the /// specular lobe by GGX importance sampling of the half vector, and the diffuse lobe by cosine /// sampling of the light. @@ -354,34 +344,36 @@ fn albedo(m: &Material, theta: f32, steps: u32) -> f64 { let n = [0.0, 0.0, 1.0]; let v = [theta.sin(), 0.0, theta.cos()]; let spec_only = m.try_with_weights(m.specular(), 0.0).unwrap(); - let a = m.roughness().max(MIN_DIRECT_ROUGHNESS).powi(2); + let a = f64::from(m.roughness().max(MIN_DIRECT_ROUGHNESS).powi(2)); + let view = v.map(f64::from); + let view_length = view.into_iter().map(|c| c * c).sum::().sqrt(); + let view = view.map(|c| c / view_length); let (mut spec, mut diff) = (0.0f64, 0.0f64); for i in 0..steps { - let xi = (i as f32 + 0.5) / steps as f32; + let xi = (f64::from(i) + 0.5) / f64::from(steps); for j in 0..steps { - let phi = 2.0 * PI * (j as f32 + 0.5) / steps as f32; + let phi = 2.0 * std::f64::consts::PI * (f64::from(j) + 0.5) / f64::from(steps); // Specular: a half vector drawn from D (n·h), a light reflected about it. let ct = ((1.0 - xi) / (1.0 + (a * a - 1.0) * xi)).sqrt(); let st = (1.0 - ct * ct).max(0.0).sqrt(); let hv = [st * phi.cos(), st * phi.sin(), ct]; - let vh = dot(v, hv); + let vh = view.into_iter().zip(hv).map(|(v, h)| v * h).sum::(); if vh > 0.0 { - let l = [2.0 * vh * hv[0] - v[0], 2.0 * vh * hv[1] - v[1], 2.0 * vh * hv[2] - v[2]]; + let l = [2.0 * vh * hv[0] - view[0], 2.0 * vh * hv[1] - view[1], 2.0 * vh * hv[2] - view[2]]; if l[2] > 0.0 { - // The density at the half vector `try_direct` finds again from `v` and `l`, - // rounded the same way and with `D` taken from the same vectors. - let (uv, ul) = (crate_unit(v), crate_unit(l)); - let h = crate_unit([uv[0] + ul[0], uv[1] + ul[1], uv[2] + ul[2]]); - let d = ggx_distribution_between(n, h, m.roughness().max(MIN_DIRECT_ROUGHNESS)).unwrap(); - let pdf = d * h[2] / (4.0 * dot(uv, h)); - spec += f64::from(spec_only.try_direct(n, v, l).unwrap()[0] / PI / pdf); + // The sampled half vector has density D(h) * h.z, and reflection divides it by 4(v.h). + let a2 = a * a; + let denominator = hv[0] * hv[0] + hv[1] * hv[1] + a2 * hv[2] * hv[2]; + let d = a2 / (std::f64::consts::PI * denominator.powi(2)); + let pdf = d * hv[2] / (4.0 * vh); + spec += f64::from(spec_only.try_direct(n, v, l.map(|c| c as f32)).unwrap()[0]) / std::f64::consts::PI / pdf; } } // Diffuse: a light drawn from n·l / π. let (cl, sl) = ((1.0 - xi).sqrt(), xi.sqrt()); - let l = [sl * phi.cos(), sl * phi.sin(), cl]; + let l = [sl * phi.cos(), sl * phi.sin(), cl].map(|c| c as f32); let d = m.try_direct(n, v, l).unwrap()[0] - spec_only.try_direct(n, v, l).unwrap()[0]; - diff += f64::from(d / cl); + diff += f64::from(d) / cl; } } (spec + diff) / f64::from(steps * steps) diff --git a/crates/pbr/tests/it/conversion_edges.rs b/crates/pbr/tests/it/conversion_edges.rs new file mode 100644 index 0000000000..a34969fed0 --- /dev/null +++ b/crates/pbr/tests/it/conversion_edges.rs @@ -0,0 +1,252 @@ +use craft_materialx::{Document, Resolved}; +use craft_mesh::Material as Mesh; +use craft_pbr::{ConvertError, ReportItem, TextureInput, TextureSource, try_from_materialx, try_from_mesh}; + +fn document(shader: &str, inputs: &str, nodes: &str, material_inputs: &str) -> Document { + let text = format!( + r#"<{shader} name="S">{inputs}{nodes}{material_inputs}"# + ); + Document::parse(text.as_bytes()).unwrap() +} + +#[test] +fn inactive_emission_still_validates_the_color_field() { + let doc = document("standard_surface", r#""#, "", ""); + let material = doc.read_material_strict(None).unwrap(); + assert!(matches!(try_from_materialx(&material), Err(ConvertError::BadValue { input, .. }) if input == "emission_color")); + let legacy = doc.read_material(None).unwrap(); + assert!(!legacy.inputs.iter().any(|(name, _)| name == "emission_color")); + let valid = document("standard_surface", r#""#, "", ""); + let converted = try_from_materialx(&valid.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.emissive, [0.0; 3]); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "emission_color"))); +} + +#[test] +fn displacement_scale_is_reported_when_it_is_not_applied() { + for scale in ["", r#""#, r#""#] { + let node = format!(r#"{scale}"#); + let doc = document("standard_surface", "", &node, r#""#); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.other_inputs, vec![("displacement".into(), vec![0.25])]); + assert_eq!( + converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("scale"))), + scale.contains('2') + ); + } + for scale in ["1,2", "NaN", ""] { + let node = format!(r#""#); + assert!(document("standard_surface", "", &node, r#""#).read_material_strict(None).is_err()); + } +} + +#[test] +fn graph_surface_connections_preserve_the_shader_scope() { + let doc = Document::parse( + br#" + + + + "#, + ) + .unwrap(); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.textures[0].source, TextureSource::File("graph.png".into())); + assert!(doc.read_material(None).is_err()); +} + +#[test] +fn broken_authored_connections_do_not_become_shader_defaults() { + for reference in [r#"nodename="missing""#, r#"nodegraph="missing" output="out""#] { + let doc = document("open_pbr_surface", &format!(r#""#), "", ""); + assert!(doc.read_material_strict(None).is_err(), "{reference}"); + } +} + +#[test] +fn a_nonzero_tiled_image_offset_is_reported() { + for offset in ["0,0", "0.25,0"] { + let nodes = format!( + r#""# + ); + let doc = document("open_pbr_surface", r#""#, &nodes, ""); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.textures[0].transform.unwrap().scale, [2.0, 2.0]); + assert_eq!( + converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("uvoffset"))), + offset != "0,0" + ); + } +} + +#[test] +fn an_omitted_color_constant_value_is_black() { + let doc = document("open_pbr_surface", r#""#, r#""#, ""); + let material = doc.read_material_strict(None).unwrap(); + assert!( + matches!(material.inputs.iter().find(|(name, _)| name == "base_color"), Some((_, Resolved::Constant { values, .. })) if values == &[0.0; 3]) + ); + assert_eq!(try_from_materialx(&material).unwrap().surface.material.base_color(), [0.0; 3]); +} + +#[test] +fn an_authored_cutoff_is_reported_when_the_alpha_mode_does_not_use_it() { + for mode in [0, 1, 2] { + let doc = document("gltf_pbr", &format!(r#""#), "", ""); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "alpha_cutoff")), mode != 1); + if mode == 1 { + assert_eq!(converted.surface.alpha_mode, craft_pbr::AlphaMode::Mask(0.25)); + } + let absent = document("gltf_pbr", &format!(r#""#), "", ""); + let converted = try_from_materialx(&absent.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "alpha_cutoff"))); + } +} + +#[test] +fn vector_displacement_is_reported_without_a_scalar_height_binding() { + for source in [r#"type="vector3" value="0.1,0.2,0.3""#, r#"type="vector3" nodename="T""#, r#"value="0.1,0.2,0.3""#] { + let nodes = format!( + r#""# + ); + let doc = document("standard_surface", "", &nodes, r#""#); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.surface.textures.iter().any(|texture| texture.input == TextureInput::Displacement)); + assert!(!converted.surface.other_inputs.iter().any(|(name, _)| name == "displacement")); + assert!( + converted + .report + .items + .iter() + .any(|item| matches!(item, ReportItem::Warning(message) if message.contains("vector") && message.contains("displacement"))) + ); + } +} + +#[test] +fn inactive_mesh_layers_report_nondefault_roughness() { + assert!(try_from_mesh(&Mesh::default()).unwrap().report.is_empty()); + let converted = try_from_mesh(&Mesh { clearcoat_roughness: 0.5, sheen_roughness: 0.5, ..Mesh::default() }).unwrap(); + for field in ["clearcoat_roughness", "sheen_roughness"] { + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == field)), "{field}"); + } + let active = + try_from_mesh(&Mesh { clearcoat: 1.0, clearcoat_roughness: 0.5, sheen_color: [0.2; 3], sheen_roughness: 0.5, ..Mesh::default() }).unwrap(); + assert_eq!(active.surface.clearcoat.unwrap().roughness, 0.5); + assert_eq!(active.surface.sheen.unwrap().roughness, 0.5); +} + +#[test] +fn omitted_numeric_constants_use_their_typed_zero_values() { + for (kind, count) in [("float", 1), ("integer", 1), ("boolean", 1), ("vector2", 2), ("vector3", 3), ("vector4", 4), ("color3", 3), ("color4", 4)] + { + let doc = document("open_pbr_surface", r#""#, &format!(r#""#), ""); + let material = doc.read_material_strict(None).unwrap(); + assert!( + matches!(material.inputs.iter().find(|(name, _)| name == "base_color"), Some((_, Resolved::Constant { values, .. })) if values == &vec![0.0; count]), + "{kind}" + ); + } + let unsupported = document("open_pbr_surface", r#""#, r#""#, ""); + let material = unsupported.read_material_strict(None).unwrap(); + assert!(material.inputs.is_empty() && !material.warnings.is_empty()); +} + +#[test] +fn strict_graph_output_selection_rejects_ambiguity() { + let read = |outputs: &str, selection: &str| { + Document::parse( + format!( + r#" + + {outputs} + "# + ) + .as_bytes(), + ) + .unwrap() + .read_material_strict(None) + }; + let both = r#""#; + assert!(read(both, "").is_err()); + assert!(read(both, r#"output="missing""#).is_err()); + assert_eq!(try_from_materialx(&read(both, r#"output="b""#).unwrap()).unwrap().surface.material.base_color(), [0.8; 3]); + let sole = read(r#""#, r#"output="unused""#).unwrap(); + assert_eq!(try_from_materialx(&sole).unwrap().surface.material.base_color(), [0.2; 3]); +} + +#[test] +fn omitted_node_parameters_keep_their_identity_defaults() { + let displaced = document( + "standard_surface", + "", + r#""#, + r#""#, + ); + assert!(displaced.read_material_strict(None).unwrap().warnings.is_empty()); + let image = document( + "open_pbr_surface", + r#""#, + r#""#, + "", + ); + assert!(image.read_material_strict(None).unwrap().warnings.is_empty()); + let normal = document( + "open_pbr_surface", + r#""#, + r#""#, + "", + ); + assert!(normal.read_material_strict(None).unwrap().warnings.is_empty()); +} + +#[test] +fn interface_connections_report_the_unsupported_value() { + let doc = Document::parse( + br#" + + + "#, + ) + .unwrap(); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!( + converted + .report + .items + .iter() + .any(|item| matches!(item, ReportItem::Warning(message) if message.contains("interface") && message.contains("tint"))) + ); +} + +#[test] +fn connected_image_tiling_keeps_the_resolved_scale() { + for connection in [r#"nodename="K""#, r#"nodegraph="g""#] { + let nodes = format!( + r#" + + "# + ); + let doc = document("standard_surface", r#""#, &nodes, ""); + let material = doc.read_material_strict(None).unwrap(); + assert!(material.warnings.is_empty(), "{:?}", material.warnings); + assert_eq!(material.uv_tiling, [2.0, 3.0]); + let converted = try_from_materialx(&material).unwrap(); + let binding = converted.surface.textures.iter().find(|binding| binding.input == TextureInput::BaseColor).unwrap(); + assert_eq!(binding.transform.as_ref().map(|transform| transform.scale), Some([2.0, 3.0])); + } +} + +#[test] +fn images_without_literal_file_values_report_the_skipped_texture() { + for kind in ["image", "tiledimage"] { + for file in ["", r#""#, r#""#, r#""#] { + let nodes = format!(r#"<{kind} name="T" type="color3">{file}"#); + let doc = document("standard_surface", r#""#, &nodes, ""); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(converted.surface.textures.is_empty()); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("file")))); + } + } +} diff --git a/crates/pbr/tests/it/conversion_followups.rs b/crates/pbr/tests/it/conversion_followups.rs new file mode 100644 index 0000000000..5c085e800a --- /dev/null +++ b/crates/pbr/tests/it/conversion_followups.rs @@ -0,0 +1,162 @@ +use craft_materialx::Document; +use craft_mesh::Material; +use craft_pbr::{ReportItem, TextureInput, try_from_materialx, try_from_mesh}; + +fn document(input: &str, nodes: &str) -> Document { + Document::parse( + format!( + r#"{input}{nodes}"# + ) + .as_bytes(), + ) + .unwrap() +} + +#[test] +fn a_selected_output_without_a_target_does_not_select_another_output() { + let doc = Document::parse( + br#" + + "#, + ) + .unwrap(); + assert!(doc.read_material_strict(None).is_err()); +} + +#[test] +fn nondefault_image_addressing_modes_are_reported() { + for name in ["uaddressmode", "vaddressmode"] { + for mode in ["constant", "clamp", "mirror"] { + let node = + format!(r#""#); + let doc = document(r#""#, &node); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains(name)))); + } + } +} + +#[test] +fn an_identified_convert_node_uses_its_omitted_input_default() { + let doc = document(r#""#, r#""#); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.material.base_color(), [0.0; 3]); + assert!(converted.report.is_empty(), "{:?}", converted.report); +} + +#[test] +fn constant_literals_use_the_nodes_type_when_the_input_omits_it() { + for (ty, value) in [("integer", "0.5"), ("float", "1,2"), ("color3", "1,2")] { + let node = format!(r#""#); + let doc = document(r#""#, &node); + assert!(doc.read_material_strict(None).is_err(), "{ty} {value}"); + } +} + +#[test] +fn a_missing_graph_local_node_does_not_bind_a_root_node() { + let doc = Document::parse( + br#" + + + "#, + ) + .unwrap(); + assert!(doc.read_material_strict(None).is_err()); +} + +#[test] +fn direct_normal_vectors_are_not_bound_as_tangent_space_maps() { + let image = r#""#; + let direct = document(r#""#, image); + let converted = try_from_materialx(&direct.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal)); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "geometry_normal"))); + let nodes = format!(r#"{image}"#); + let wrapped = document(r#""#, &nodes); + let converted = try_from_materialx(&wrapped.read_material_strict(None).unwrap()).unwrap(); + assert!(converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal)); +} + +#[test] +fn nondefault_factors_without_textures_are_reported() { + let material = Material { normal_scale: 0.5, occlusion_strength: 0.25, ..Material::default() }; + let converted = try_from_mesh(&material).unwrap(); + for name in ["normal_scale", "occlusion_strength"] { + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == name))); + } + assert!(try_from_mesh(&Material::default()).unwrap().report.is_empty()); +} + +#[test] +fn nested_normalmaps_are_reported_and_skipped() { + let nodes = r#" + + "#; + let doc = document(r#""#, nodes); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal)); + assert!( + converted + .report + .items + .iter() + .any(|item| matches!(item, ReportItem::Warning(message) if message.contains("nested") && message.contains("Outer"))) + ); +} + +#[test] +fn normalmap_literals_do_not_become_untransformed_world_normals() { + for value in ["1,0.5,1", "0.5,0.5,1"] { + let doc = document( + r#""#, + &format!(r#""#), + ); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.surface.other_inputs.iter().any(|(name, _)| name == "geometry_normal")); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("normalmap")))); + } +} + +#[test] +fn authored_normalmap_frames_are_reported() { + for name in ["normal", "tangent", "bitangent"] { + let nodes = format!( + r#" + "# + ); + let doc = document(r#""#, &nodes); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains(name)))); + } +} + +#[test] +fn coat_normals_keep_tangent_maps_and_report_direct_world_images() { + for (shader, weight, normal) in [ + ("open_pbr_surface", "coat_weight", "geometry_coat_normal"), + ("standard_surface", "coat", "coat_normal"), + ("gltf_pbr", "clearcoat", "clearcoat_normal"), + ] { + for (node, wrapped) in [("T", false), ("N", true)] { + let xml = format!( + r#"<{shader} name="S"> + + + "# + ); + let doc = Document::parse(xml.as_bytes()).unwrap(); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!( + converted.surface.textures.iter().any(|binding| matches!(&binding.input, TextureInput::Other(name) if name == normal)), + wrapped, + "{shader} {node}" + ); + assert_eq!( + converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == normal)), + !wrapped, + "{shader} {node}" + ); + } + } +} diff --git a/crates/pbr/tests/it/convert.rs b/crates/pbr/tests/it/convert.rs new file mode 100644 index 0000000000..8ec3d5d70b --- /dev/null +++ b/crates/pbr/tests/it/convert.rs @@ -0,0 +1,724 @@ +//! Conversions into a `Surface`: glTF 2.0 materials from craft-mesh and MaterialX shaders from +//! craft-materialx, checked against the defaults and ranges the public definitions give. + +use craft_materialx::{Document, Resolved as Value, Shader, StrictMaterial as Mx, Texture, write_open_pbr}; +use craft_mesh::{AlphaMode as MeshAlpha, Material as Mesh, TextureRef, UvTransform as MeshUv, Wrap as MeshWrap}; +use craft_pbr::{ + AlphaMode, Clearcoat, Conversion, ConvertError, ReportItem, Sheen, TextureEncoding, TextureInput, TextureSource, UvTransform, Wrap, + try_from_materialx, try_from_mesh, +}; + +fn close(a: f32, b: f32) -> bool { + a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0) +} + +#[test] +fn close_is_false_for_values_that_are_not_finite() { + assert!(close(1.0, 1.0 + 1e-7)); + assert!(!close(f32::INFINITY, 1.0) && !close(f32::INFINITY, f32::INFINITY) && !close(f32::NAN, 1.0)); +} + +#[track_caller] +fn assert_close3(a: [f32; 3], b: [f32; 3]) { + assert!(a.iter().zip(b).all(|(x, y)| close(*x, y)), "{a:?} against {b:?}"); +} + +fn unshaded(c: &Conversion, input: &str) -> bool { + c.report.items.iter().any(|i| matches!(i, ReportItem::Unshaded { input: n } if n == input)) +} + +fn approximated(c: &Conversion, input: &str) -> bool { + c.report.items.iter().any(|i| matches!(i, ReportItem::Approximated { input: n, .. } if n == input)) +} + +fn dropped(c: &Conversion, input: &str) -> bool { + c.report.items.iter().any(|i| matches!(i, ReportItem::Dropped { input: n, .. } if n == input)) +} + +#[track_caller] +fn bad_value(r: Result, input: &str) { + match r { + Err(ConvertError::BadValue { input: n, .. }) => assert!(n.contains(input), "{n} is not {input}"), + other => panic!("{input}: expected a bad value, got {other:?}"), + } +} + +fn tex(image: usize) -> Option { + Some(TextureRef { image, ..TextureRef::default() }) +} + +// ------------------------------------------------------------------ craft-mesh (glTF 2.0) + +#[test] +fn mesh_factors_map_as_they_are() { + let m = Mesh { + name: "Paint".into(), + base_color: [0.25, 0.5, 0.75, 0.6], + metallic: 0.3, + roughness: 0.7, + emissive: [2.0, 0.5, 0.0], + alpha_mode: MeshAlpha::Mask(0.4), + double_sided: true, + ..Mesh::default() + }; + let c = try_from_mesh(&m).unwrap(); + let s = &c.surface; + assert_eq!(s.name, "Paint"); + assert_eq!(s.material.base_color(), [0.25, 0.5, 0.75]); + assert_eq!((s.material.metallic(), s.material.roughness()), (0.3, 0.7)); + assert_eq!((s.material.specular(), s.material.diffuse()), (1.0, 1.0)); + assert_eq!(s.alpha, 0.6); + assert_eq!(s.alpha_mode, AlphaMode::Mask(0.4)); + assert_eq!(s.emissive, [2.0, 0.5, 0.0]); + assert!(s.double_sided && !s.unlit); + assert_eq!((s.clearcoat, s.sheen), (None, None)); + assert!(s.textures.is_empty() && s.other_inputs.is_empty()); + assert!(c.report.is_empty(), "{:?}", c.report); +} + +#[test] +fn mesh_defaults_are_the_gltf_defaults() { + // glTF 2.0 gives baseColorFactor [1, 1, 1, 1], metallicFactor 1, roughnessFactor 1, + // emissiveFactor [0, 0, 0] and alphaMode OPAQUE + // (https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-material). + let c = try_from_mesh(&Mesh::default()).unwrap(); + let s = &c.surface; + assert_eq!(s.material.base_color(), [1.0; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.alpha), (1.0, 1.0, 1.0)); + assert_eq!((s.emissive, s.alpha_mode), ([0.0; 3], AlphaMode::Opaque)); + assert!(!s.double_sided); + assert!(c.report.is_empty()); +} + +#[test] +fn mesh_extensions_that_are_not_converted_are_reported_as_dropped() { + let mut m = Mesh::default(); + for name in ["KHR_materials_transmission", "KHR_materials_clearcoat", "KHR_materials_unlit", "KHR_materials_emissive_strength"] { + m.extensions.insert(name.into(), craft_mesh::serde_json::json!({})); + } + let c = try_from_mesh(&m).unwrap(); + assert!(dropped(&c, "KHR_materials_transmission"), "{:?}", c.report); + assert_eq!(c.report.items.len(), 1, "{:?}", c.report); + // craft-mesh reads part of these two. + m.extensions.insert("KHR_materials_clearcoat".into(), craft_mesh::serde_json::json!({ "clearcoatNormalTexture": { "index": 0 } })); + m.extensions.insert("KHR_materials_pbrSpecularGlossiness".into(), craft_mesh::serde_json::json!({ "specularFactor": [1, 0, 0] })); + let c = try_from_mesh(&m).unwrap(); + assert!(dropped(&c, "clearcoatNormalTexture"), "{:?}", c.report); + assert!(approximated(&c, "KHR_materials_pbrSpecularGlossiness"), "{:?}", c.report); + assert_eq!(c.report.items.len(), 3, "{:?}", c.report); +} + +#[test] +fn mesh_textures_keep_their_uv_state_scale_and_encoding() { + let mr = TextureRef { + image: 2, + uv_set: 1, + wrap: [MeshWrap::Clamp, MeshWrap::Mirror], + transform: Some(MeshUv { offset: [0.25, 0.5], rotation: 0.5, scale: [2.0, 3.0] }), + }; + let m = Mesh { + base_color_texture: tex(1), + metallic_roughness_texture: Some(mr), + normal_texture: tex(3), + normal_scale: 0.5, + occlusion_texture: tex(4), + occlusion_strength: 0.25, + emissive_texture: tex(5), + clearcoat: 0.5, + clearcoat_texture: tex(6), + clearcoat_roughness_texture: tex(7), + sheen_color: [0.1, 0.0, 0.0], + sheen_color_texture: tex(8), + sheen_roughness_texture: tex(9), + ..Mesh::default() + }; + let c = try_from_mesh(&m).unwrap(); + // Base color, emissive and sheen color textures are sRGB, the rest linear (glTF 2.0 and + // KHR_materials_sheen); the packed texture holds roughness in G and metallic in B. + let expected = [ + ("base_color_texture", TextureInput::BaseColor, TextureEncoding::Srgb), + ("metallic_roughness_texture", TextureInput::MetallicRoughness, TextureEncoding::Linear), + ("normal_texture", TextureInput::Normal, TextureEncoding::Linear), + ("occlusion_texture", TextureInput::Occlusion, TextureEncoding::Linear), + ("emissive_texture", TextureInput::Emissive, TextureEncoding::Srgb), + ("clearcoat_texture", TextureInput::Clearcoat, TextureEncoding::Linear), + ("clearcoat_roughness_texture", TextureInput::ClearcoatRoughness, TextureEncoding::Linear), + ("sheen_color_texture", TextureInput::SheenColor, TextureEncoding::Srgb), + ("sheen_roughness_texture", TextureInput::SheenRoughness, TextureEncoding::Linear), + ]; + assert_eq!(c.surface.textures.len(), expected.len()); + for (i, ((name, input, encoding), b)) in expected.into_iter().zip(&c.surface.textures).enumerate() { + assert_eq!((&b.input, &b.encoding, &b.source), (&input, &encoding, &TextureSource::Image(i + 1)), "{name}"); + assert!(unshaded(&c, name), "{name}"); + } + let mr = &c.surface.textures[1]; + assert_eq!((mr.uv_set, mr.wrap), (1, [Wrap::Clamp, Wrap::Mirror])); + assert_eq!(mr.transform, Some(UvTransform { offset: [0.25, 0.5], rotation: 0.5, scale: [2.0, 3.0] })); + assert_eq!((c.surface.textures[2].scale, c.surface.textures[3].scale, c.surface.textures[0].scale), (0.5, 0.25, 1.0)); + assert_eq!(c.surface.textures[0].transform, None); + // The core holds the factors the textures multiply: glTF's defaults here. + assert_eq!((c.surface.material.metallic(), c.surface.material.roughness()), (1.0, 1.0)); + assert!(unshaded(&c, "clearcoat") && unshaded(&c, "sheen")); +} + +#[test] +fn mesh_clearcoat_and_sheen_are_kept_and_layers_that_are_off_drop_their_textures() { + let on = Mesh { clearcoat: 0.75, clearcoat_roughness: 0.25, sheen_color: [0.5, 0.25, 0.0], sheen_roughness: 0.6, ..Mesh::default() }; + let c = try_from_mesh(&on).unwrap(); + assert_eq!(c.surface.clearcoat, Some(Clearcoat { weight: 0.75, roughness: 0.25 })); + assert_eq!(c.surface.sheen, Some(Sheen { color: [0.5, 0.25, 0.0], roughness: 0.6 })); + // A clearcoat factor of 0 and a black sheen color each turn their layer off + // (KHR_materials_clearcoat, KHR_materials_sheen). + let off = Mesh { + clearcoat_roughness: 0.5, + clearcoat_texture: tex(1), + clearcoat_roughness_texture: tex(2), + sheen_roughness: 0.5, + sheen_color_texture: tex(3), + sheen_roughness_texture: tex(4), + ..Mesh::default() + }; + let c = try_from_mesh(&off).unwrap(); + assert_eq!((c.surface.clearcoat, c.surface.sheen), (None, None)); + assert!(c.surface.textures.is_empty()); + for name in ["clearcoat_texture", "clearcoat_roughness_texture", "sheen_color_texture", "sheen_roughness_texture"] { + assert!(dropped(&c, name), "{name}"); + } + assert!(!unshaded(&c, "clearcoat") && !unshaded(&c, "sheen")); +} + +#[test] +fn mesh_textures_of_a_layer_that_is_off_are_checked_before_they_are_dropped() { + let t = TextureRef { transform: Some(MeshUv { rotation: f32::NAN, ..MeshUv::default() }), ..TextureRef::default() }; + bad_value(try_from_mesh(&Mesh { clearcoat_roughness_texture: Some(t), ..Mesh::default() }), "clearcoat_roughness_texture transform"); + bad_value(try_from_mesh(&Mesh { sheen_color_texture: Some(t), ..Mesh::default() }), "sheen_color_texture transform"); + let fine = TextureRef { transform: Some(MeshUv { rotation: 0.5, ..MeshUv::default() }), ..TextureRef::default() }; + let c = try_from_mesh(&Mesh { clearcoat_texture: Some(fine), ..Mesh::default() }).unwrap(); + assert!(c.surface.textures.is_empty() && dropped(&c, "clearcoat_texture")); +} + +#[test] +fn mesh_unlit_is_kept_and_reported() { + let c = try_from_mesh(&Mesh { unlit: true, base_color: [0.2, 0.4, 0.6, 1.0], ..Mesh::default() }).unwrap(); + assert!(c.surface.unlit); + assert_eq!(c.surface.material.base_color(), [0.2, 0.4, 0.6]); + assert!(unshaded(&c, "unlit")); +} + +#[test] +fn mesh_values_that_are_not_finite_or_out_of_range_are_errors() { + type Set = fn(&mut Mesh, f32); + let unit: [(&str, Set); 8] = [ + ("base_color", |m, v| m.base_color[1] = v), + ("base_color alpha", |m, v| m.base_color[3] = v), + ("metallic", |m, v| m.metallic = v), + ("roughness", |m, v| m.roughness = v), + ("occlusion_strength", |m, v| m.occlusion_strength = v), + ("clearcoat", |m, v| m.clearcoat = v), + ("clearcoat_roughness", |m, v| m.clearcoat_roughness = v), + ("sheen_color", |m, v| m.sheen_color[2] = v), + ]; + for (name, set) in unit.iter().chain([("sheen_roughness", (|m: &mut Mesh, v| m.sheen_roughness = v) as Set)].iter()) { + for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01] { + let mut m = Mesh::default(); + set(&mut m, v); + bad_value(try_from_mesh(&m), name); + } + for v in [0.0, 1.0] { + let mut m = Mesh::default(); + set(&mut m, v); + assert!(try_from_mesh(&m).is_ok(), "{name} {v}"); + } + } + for v in [f32::NAN, f32::INFINITY, -1.0] { + bad_value(try_from_mesh(&Mesh { emissive: [0.0, v, 0.0], ..Mesh::default() }), "emissive"); + bad_value(try_from_mesh(&Mesh { alpha_mode: MeshAlpha::Mask(v), ..Mesh::default() }), "alpha cutoff"); + } + for v in [f32::NAN, f32::INFINITY] { + bad_value(try_from_mesh(&Mesh { normal_scale: v, ..Mesh::default() }), "normal_scale"); + let t = TextureRef { transform: Some(MeshUv { rotation: v, ..MeshUv::default() }), ..TextureRef::default() }; + bad_value(try_from_mesh(&Mesh { emissive_texture: Some(t), ..Mesh::default() }), "emissive_texture transform"); + } + // Emission above 1, a cutoff above 1 and a negative normal scale are in range. + let wide = Mesh { emissive: [40.0; 3], alpha_mode: MeshAlpha::Mask(2.0), normal_scale: -1.0, ..Mesh::default() }; + let c = try_from_mesh(&wide).unwrap(); + assert_eq!((c.surface.emissive, c.surface.alpha_mode), ([40.0; 3], AlphaMode::Mask(2.0))); +} + +// ------------------------------------------------------------------ craft-materialx + +fn mx(shader: Shader, inputs: &[(&str, Value)]) -> Mx { + Mx { + name: "M".into(), + shader, + inputs: inputs.iter().map(|(n, v)| ((*n).to_owned(), v.clone())).collect(), + displacement: None, + uv_tiling: [1.0, 1.0], + warnings: Vec::new(), + } +} + +fn k(values: &[f32]) -> Value { + Value::Constant { values: values.to_vec(), colorspace: None } +} + +fn ks(values: &[f32], space: &str) -> Value { + Value::Constant { values: values.to_vec(), colorspace: Some(space.into()) } +} + +fn img(file: &str, space: Option<&str>, tiling: Option<[f32; 2]>) -> Value { + Value::Image { file: file.into(), colorspace: space.map(str::to_owned), uv_tiling: tiling } +} + +/// Schlick's reflectance at normal incidence for an index of refraction, as the specular weight +/// of the core: `((n − 1) / (n + 1))² / 0.04`. +fn specular_for_ior(n: f64) -> f32 { + (((n - 1.0) / (n + 1.0)).powi(2) / 0.04) as f32 +} + +#[test] +fn materialx_empty_inputs_give_each_shaders_defaults() { + // The defaults of the node definitions in MaterialX's libraries/bxdf: open_pbr_surface.mtlx, + // standard_surface.mtlx (version 1.0.1) and gltf_pbr.mtlx + // (https://github.com/AcademySoftwareFoundation/MaterialX/tree/main/libraries/bxdf). + let open = try_from_materialx(&mx(Shader::OpenPbr, &[])).unwrap(); + let s = &open.surface; + assert_close3(s.material.base_color(), [0.8; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (0.0, 0.3, 1.0)); + assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3])); + assert_eq!((s.clearcoat, s.sheen), (None, None)); + assert!(open.report.is_empty(), "{:?}", open.report); + + let standard = try_from_materialx(&mx(Shader::StandardSurface, &[])).unwrap(); + let s = &standard.surface; + assert_close3(s.material.base_color(), [0.8; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (0.0, 0.2, 1.0)); + assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3])); + assert_eq!((s.clearcoat, s.sheen), (None, None)); + assert!(standard.report.is_empty(), "{:?}", standard.report); + + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[])).unwrap(); + let s = &gltf.surface; + assert_eq!(s.material.base_color(), [1.0; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (1.0, 1.0, 1.0)); + assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3])); + assert_eq!((s.clearcoat, s.sheen), (None, None)); + assert!(gltf.report.is_empty(), "{:?}", gltf.report); +} + +#[test] +fn materialx_base_weight_scales_the_base_color_and_specular_follows_weight_and_ior() { + let c = + try_from_materialx(&mx(Shader::OpenPbr, &[("base_color", k(&[0.5, 0.4, 0.2])), ("base_weight", k(&[0.5])), ("base_metalness", k(&[0.25]))])) + .unwrap(); + assert_close3(c.surface.material.base_color(), [0.25, 0.2, 0.1]); + assert_eq!(c.surface.material.metallic(), 0.25); + assert!(c.report.is_empty(), "{:?}", c.report); + let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("base", k(&[0.5])), ("specular", k(&[0.5]))])).unwrap(); + assert_close3(standard.surface.material.base_color(), [0.4; 3]); + assert!(close(standard.surface.material.specular(), 0.5)); + assert!(approximated(&standard, "specular")); + + let weight = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[2.0]))])).unwrap(); + assert!(close(weight.surface.material.specular(), 2.0)); + assert!(approximated(&weight, "specular_weight")); + let water = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_ior", k(&[1.33]))])).unwrap(); + assert!(close(water.surface.material.specular(), specular_for_ior(1.33)), "{}", water.surface.material.specular()); + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("ior", k(&[2.0])), ("specular", k(&[0.5]))])).unwrap(); + assert!(close(gltf.surface.material.specular(), 0.5 * specular_for_ior(2.0))); + // 25 is the largest weight the core takes: at IOR 1.5 a weight of 25 fits, 25.5 does not. + let max = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[25.0]))])).unwrap(); + assert!(close(max.surface.material.specular(), 25.0)); + bad_value(try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[25.5]))])), "specular_weight"); + bad_value(try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[2.0])), ("specular_ior", k(&[30.0]))])), "specular_weight"); +} + +#[test] +fn materialx_color_constants_are_decoded_from_the_color_space_in_effect() { + let base = |v: Value| try_from_materialx(&mx(Shader::GltfPbr, &[("base_color", v)])).map(|c| c.surface.material.base_color()); + let c = [0.5, 0.2, 0.02]; + // The sRGB transfer function of IEC 61966-2-1, written out here independently. + let srgb = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; + for space in ["srgb_texture", "srgb_rec709_scene"] { + let got = base(ks(&c, space)).unwrap(); + assert_close3(got, c.map(srgb)); + assert_close3(got, c.map(craft_texture::srgb_to_linear)); + } + for space in ["lin_rec709", "lin_rec709_scene", "data", "none"] { + assert_eq!(base(ks(&c, space)).unwrap(), c, "{space}"); + } + assert_eq!(base(k(&c)).unwrap(), c); + assert_close3(base(ks(&c, "g22_rec709")).unwrap(), c.map(|v| v.powf(2.2))); + assert_close3(base(ks(&c, "g18_rec709_scene")).unwrap(), c.map(|v| v.powf(1.8))); + assert_close3(base(ks(&c, "g24_rec709_scene")).unwrap(), c.map(|v| v.powf(2.4))); + for space in ["acescg", "lin_ap1_scene", "srgb_p3d65_scene", "bogus"] { + match base(ks(&c, space)) { + Err(ConvertError::ColorSpace { input, colorspace }) => assert_eq!((input.as_str(), colorspace.as_str()), ("base_color", space)), + other => panic!("{space}: {other:?}"), + } + } + // Scalars are never decoded, whatever the color space. + let rough = try_from_materialx(&mx(Shader::GltfPbr, &[("roughness", ks(&[0.5], "srgb_texture"))])).unwrap(); + assert_eq!(rough.surface.material.roughness(), 0.5); +} + +#[test] +fn materialx_images_become_bindings_and_the_core_holds_the_factor() { + let m = mx( + Shader::OpenPbr, + &[ + ("base_color", img("tex/albedo.png", Some("srgb_texture"), Some([2.0, 3.0]))), + ("base_weight", k(&[0.5])), + ("base_metalness", img("metal.png", Some("srgb_texture"), None)), + ("specular_roughness", img("rough.png", None, None)), + ("geometry_opacity", img("cut.png", None, None)), + ("geometry_normal", Value::NormalMap { file: "n.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }), + ("emission_color", img("glow.png", Some("acescg"), None)), + ("emission_luminance", k(&[4.0])), + ("specular_ior", img("ior.png", None, None)), + ], + ); + let c = try_from_materialx(&m).unwrap(); + let s = &c.surface; + assert_close3(s.material.base_color(), [0.5; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (1.0, 1.0, 1.0)); + assert_eq!((s.alpha, s.alpha_mode), (1.0, AlphaMode::Blend)); + assert_eq!(s.emissive, [4.0; 3]); + let find = |input: TextureInput| s.textures.iter().find(|b| b.input == input).unwrap(); + let albedo = find(TextureInput::BaseColor); + assert_eq!((&albedo.source, &albedo.encoding), (&TextureSource::File("tex/albedo.png".into()), &TextureEncoding::Srgb)); + assert_eq!(albedo.transform, Some(UvTransform { offset: [0.0; 2], rotation: 0.0, scale: [2.0, 3.0] })); + assert_eq!((albedo.uv_set, albedo.wrap, albedo.scale), (0, [Wrap::Repeat; 2], 1.0)); + // Data inputs are linear whatever color space the file carries; color inputs keep theirs. + assert_eq!(find(TextureInput::Metallic).encoding, TextureEncoding::Linear); + assert_eq!(find(TextureInput::Roughness).encoding, TextureEncoding::Linear); + assert_eq!(find(TextureInput::Normal).encoding, TextureEncoding::Linear); + assert_eq!(find(TextureInput::Opacity).source, TextureSource::File("cut.png".into())); + assert_eq!(find(TextureInput::Emissive).encoding, TextureEncoding::Named("acescg".into())); + assert_eq!(find(TextureInput::Other("specular_ior".into())).source, TextureSource::File("ior.png".into())); + for name in ["base_color", "base_metalness", "specular_roughness", "geometry_opacity", "geometry_normal", "emission_color", "specular_ior"] { + assert!(unshaded(&c, name), "{name}"); + } + assert!(approximated(&c, "specular_ior")); +} + +#[test] +fn materialx_coat_and_sheen_are_kept_only_when_they_are_on() { + let c = try_from_materialx(&mx( + Shader::OpenPbr, + &[("coat_weight", k(&[0.5])), ("coat_roughness", k(&[0.2])), ("fuzz_weight", k(&[0.5])), ("fuzz_color", k(&[1.0, 0.5, 0.0]))], + )) + .unwrap(); + assert_eq!(c.surface.clearcoat, Some(Clearcoat { weight: 0.5, roughness: 0.2 })); + // fuzz_roughness defaults to 0.5. + assert_eq!(c.surface.sheen, Some(Sheen { color: [0.5, 0.25, 0.0], roughness: 0.5 })); + assert!(approximated(&c, "fuzz_weight") && unshaded(&c, "clearcoat") && unshaded(&c, "sheen")); + + let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("coat", k(&[1.0])), ("sheen", k(&[0.5]))])).unwrap(); + // coat_roughness 0.1, sheen_color white and sheen_roughness 0.3 by default. + assert_eq!(standard.surface.clearcoat, Some(Clearcoat { weight: 1.0, roughness: 0.1 })); + assert_eq!(standard.surface.sheen, Some(Sheen { color: [0.5; 3], roughness: 0.3 })); + + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("sheen_color", k(&[0.2, 0.1, 0.0])), ("sheen_roughness", k(&[0.4]))])).unwrap(); + assert_eq!(gltf.surface.sheen, Some(Sheen { color: [0.2, 0.1, 0.0], roughness: 0.4 })); + assert!(!approximated(&gltf, "sheen_color")); + + let off = try_from_materialx(&mx( + Shader::OpenPbr, + &[("coat_roughness", img("coat_r.png", None, None)), ("fuzz_color", img("fuzz.png", None, None)), ("coat_weight", k(&[0.0]))], + )) + .unwrap(); + assert_eq!((off.surface.clearcoat, off.surface.sheen), (None, None)); + assert!(off.surface.textures.is_empty()); + assert!(dropped(&off, "coat_roughness") && dropped(&off, "fuzz_color")); + let textured = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", img("coat.png", None, None))])).unwrap(); + assert_eq!(textured.surface.clearcoat, Some(Clearcoat { weight: 1.0, roughness: 0.0 })); + assert_eq!(textured.surface.textures[0].input, TextureInput::Clearcoat); +} + +#[test] +fn materialx_coat_and_sheen_roughness_images_read_their_first_channel() { + let cases = [ + (Shader::OpenPbr, [("coat_weight", k(&[1.0])), ("fuzz_weight", k(&[1.0]))], ["coat_roughness", "fuzz_roughness"]), + (Shader::StandardSurface, [("coat", k(&[1.0])), ("sheen", k(&[1.0]))], ["coat_roughness", "sheen_roughness"]), + (Shader::GltfPbr, [("clearcoat", k(&[1.0])), ("sheen_color", k(&[1.0, 1.0, 1.0]))], ["clearcoat_roughness", "sheen_roughness"]), + ]; + for (shader, [coat, sheen], [coat_roughness, sheen_roughness]) in cases { + let c = try_from_materialx(&mx( + shader, + &[coat, sheen, (coat_roughness, img("coat_r.png", None, None)), (sheen_roughness, img("sheen_r.png", None, None))], + )) + .unwrap(); + let inputs: Vec<_> = c.surface.textures.iter().map(|t| (t.input.clone(), t.source.clone())).collect(); + assert_eq!( + inputs, + [ + (TextureInput::ClearcoatRoughnessFirst, TextureSource::File("coat_r.png".into())), + (TextureInput::SheenRoughnessFirst, TextureSource::File("sheen_r.png".into())), + ], + "{shader:?}" + ); + } +} + +#[test] +fn materialx_coat_only_inputs_are_dropped_while_the_coat_is_off() { + let coat_only = [ + (Shader::OpenPbr, "coat_weight", ["geometry_coat_normal", "coat_color", "coat_ior"]), + (Shader::StandardSurface, "coat", ["coat_normal", "coat_color", "coat_IOR"]), + ]; + for (shader, weight, [normal, color, ior]) in coat_only { + let inputs = [ + (normal, Value::NormalMap { file: "coat_n.png".into(), colorspace: None, uv_tiling: None }), + (color, img("coat_c.png", None, None)), + (ior, k(&[1.4])), + ]; + // The coat weight is left at its default of 0. + let off = try_from_materialx(&mx(shader, &inputs)).unwrap(); + assert_eq!(off.surface.clearcoat, None); + assert!(off.surface.textures.is_empty(), "{:?}", off.surface.textures); + assert!(off.surface.other_inputs.is_empty(), "{:?}", off.surface.other_inputs); + for name in [normal, color, ior] { + assert!(dropped(&off, name) && !unshaded(&off, name), "{name}: {:?}", off.report); + } + // With the coat on, the same inputs are kept and reported as unshaded. + let mut with_coat = inputs.to_vec(); + with_coat.push((weight, k(&[0.5]))); + let on = try_from_materialx(&mx(shader, &with_coat)).unwrap(); + assert!(on.surface.clearcoat.is_some()); + assert_eq!(on.surface.textures.len(), 2); + assert_eq!(on.surface.other_inputs, vec![(ior.to_owned(), vec![1.4])]); + for name in [normal, color, ior] { + assert!(unshaded(&on, name) && !dropped(&on, name), "{name}"); + } + } + let gltf = try_from_materialx(&mx( + Shader::GltfPbr, + &[("clearcoat_normal", Value::NormalMap { file: "cc_n.png".into(), colorspace: None, uv_tiling: None })], + )) + .unwrap(); + assert!(gltf.surface.textures.is_empty() && dropped(&gltf, "clearcoat_normal")); +} + +#[test] +fn materialx_constants_of_a_layer_that_is_off_are_dropped() { + // The coat weight defaults to 0, so the coat is off and its roughness is dropped. + let coat = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_roughness", k(&[0.4]))])).unwrap(); + assert_eq!(coat.surface.clearcoat, None); + assert!(dropped(&coat, "coat_roughness"), "{:?}", coat.report); + // The weight that turns the layer off is not reported as dropped. + let zero = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", k(&[0.0])), ("coat_roughness", k(&[0.4]))])).unwrap(); + assert!(dropped(&zero, "coat_roughness") && !dropped(&zero, "coat_weight"), "{:?}", zero.report); + let on = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", k(&[0.5])), ("coat_roughness", k(&[0.4]))])).unwrap(); + assert!(!dropped(&on, "coat_roughness")); + // fuzz_weight defaults to 0: the fuzz color and roughness are dropped. + let fuzz = try_from_materialx(&mx(Shader::OpenPbr, &[("fuzz_color", k(&[1.0, 0.5, 0.0])), ("fuzz_roughness", k(&[0.2]))])).unwrap(); + assert!(dropped(&fuzz, "fuzz_color") && dropped(&fuzz, "fuzz_roughness"), "{:?}", fuzz.report); + // A black color turns the sheen off, so its weight is dropped and the color is not. + let black = try_from_materialx(&mx(Shader::StandardSurface, &[("sheen", k(&[0.5])), ("sheen_color", k(&[0.0; 3]))])).unwrap(); + assert!(dropped(&black, "sheen") && !dropped(&black, "sheen_color"), "{:?}", black.report); + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("sheen_roughness", k(&[0.3]))])).unwrap(); + assert!(dropped(&gltf, "sheen_roughness"), "{:?}", gltf.report); +} + +#[test] +fn materialx_emission_is_the_color_times_its_strength() { + let dark = try_from_materialx(&mx(Shader::OpenPbr, &[("emission_color", k(&[1.0, 0.5, 0.0]))])).unwrap(); + assert_eq!(dark.surface.emissive, [0.0; 3]); + assert!(dropped(&dark, "emission_color"), "{:?}", dark.report); + let lit = try_from_materialx(&mx(Shader::OpenPbr, &[("emission_color", k(&[1.0, 0.5, 0.0])), ("emission_luminance", k(&[10.0]))])).unwrap(); + assert_eq!(lit.surface.emissive, [10.0, 5.0, 0.0]); + assert!(approximated(&lit, "emission_luminance")); + let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("emission", k(&[2.0])), ("emission_color", k(&[0.5, 0.25, 1.0]))])).unwrap(); + assert_eq!(standard.surface.emissive, [1.0, 0.5, 2.0]); + assert!(standard.report.is_empty()); + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("emissive", k(&[0.5, 0.25, 0.0])), ("emissive_strength", k(&[2.0]))])).unwrap(); + assert_eq!(gltf.surface.emissive, [1.0, 0.5, 0.0]); +} + +#[test] +fn materialx_standard_surface_opacity_color_gives_its_luminance() { + let standard = |opacity: &[f32]| try_from_materialx(&mx(Shader::StandardSurface, &[("opacity", k(opacity))])); + let gray = standard(&[0.5; 3]).unwrap(); + assert_eq!(gray.surface.alpha, 0.5); + assert!(gray.report.is_empty(), "{:?}", gray.report); + // 0.2126 * 0.2 + 0.7152 * 0.4 + 0.0722 * 0.6, the Rec.709 luminance; the mean would be 0.4. + let colored = standard(&[0.2, 0.4, 0.6]).unwrap(); + assert!(close(colored.surface.alpha, 0.37192), "{}", colored.surface.alpha); + assert_eq!(colored.surface.alpha_mode, AlphaMode::Blend); + assert!(approximated(&colored, "opacity")); + let green = standard(&[0.0, 1.0, 0.0]).unwrap(); + assert!(close(green.surface.alpha, 0.7152), "{}", green.surface.alpha); + let near_white = standard(&[1.0, 1.0, 0.999_999_9]).unwrap(); + assert!(near_white.surface.alpha <= 1.0 && near_white.surface.alpha >= 0.999_999_9); + for v in [f32::NAN, f32::INFINITY, -0.01, 1.01] { + bad_value(standard(&[0.5, v, 0.5]), "opacity"); + } + // An image on the color opacity binds as RGB; the float opacities bind their first channel. + let textured = try_from_materialx(&mx(Shader::StandardSurface, &[("opacity", img("o.png", None, None))])).unwrap(); + assert_eq!(textured.surface.textures[0].input, TextureInput::OpacityRgb); + for (shader, name) in [(Shader::OpenPbr, "geometry_opacity"), (Shader::GltfPbr, "alpha")] { + let c = try_from_materialx(&mx(shader, &[(name, img("o.png", None, None))])).unwrap(); + assert_eq!(c.surface.textures[0].input, TextureInput::Opacity, "{name}"); + } + // OpenPBR's geometry_opacity is a float in its node definition. + assert_eq!( + try_from_materialx(&mx(Shader::OpenPbr, &[("geometry_opacity", k(&[0.5; 3]))])).unwrap_err(), + ConvertError::Components { input: "geometry_opacity".into(), expected: 1, found: 3 } + ); +} + +#[test] +fn materialx_alpha_and_its_mode() { + let open = try_from_materialx(&mx(Shader::OpenPbr, &[("geometry_opacity", k(&[0.5]))])).unwrap(); + assert_eq!((open.surface.alpha, open.surface.alpha_mode), (0.5, AlphaMode::Blend)); + + let gltf = |inputs: &[(&str, Value)]| try_from_materialx(&mx(Shader::GltfPbr, inputs)); + assert_eq!(gltf(&[("alpha_mode", k(&[1.0])), ("alpha_cutoff", k(&[0.25]))]).unwrap().surface.alpha_mode, AlphaMode::Mask(0.25)); + assert_eq!(gltf(&[("alpha_mode", k(&[1.0]))]).unwrap().surface.alpha_mode, AlphaMode::Mask(0.5)); + assert_eq!(gltf(&[("alpha_mode", k(&[2.0]))]).unwrap().surface.alpha_mode, AlphaMode::Blend); + let opaque = gltf(&[("alpha", k(&[0.5]))]).unwrap(); + assert_eq!((opaque.surface.alpha, opaque.surface.alpha_mode), (0.5, AlphaMode::Opaque)); + for bad in [3.0, 1.5, -1.0] { + bad_value(gltf(&[("alpha_mode", k(&[bad]))]), "alpha_mode"); + } + bad_value(gltf(&[("alpha_mode", img("m.png", None, None))]), "alpha_mode"); + bad_value(gltf(&[("alpha_cutoff", img("c.png", None, None))]), "alpha_cutoff"); +} + +#[test] +fn materialx_bad_inputs_are_errors_and_unknown_ones_are_dropped() { + let open = |inputs: &[(&str, Value)]| try_from_materialx(&mx(Shader::OpenPbr, inputs)); + assert_eq!(open(&[("base_metalness", k(&[0.0])), ("base_metalness", k(&[1.0]))]).unwrap_err(), ConvertError::Duplicate("base_metalness".into())); + assert_eq!(open(&[("base_color", k(&[0.5]))]).unwrap_err(), ConvertError::Components { input: "base_color".into(), expected: 3, found: 1 }); + assert_eq!( + open(&[("base_metalness", k(&[0.5; 3]))]).unwrap_err(), + ConvertError::Components { input: "base_metalness".into(), expected: 1, found: 3 } + ); + for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01] { + for name in + ["base_weight", "base_metalness", "specular_roughness", "coat_weight", "fuzz_roughness", "geometry_opacity", "transmission_weight"] + { + bad_value(open(&[(name, k(&[v]))]), name); + } + bad_value(open(&[("base_color", k(&[0.5, v, 0.5]))]), "base_color"); + } + for v in [f32::NAN, f32::INFINITY, -1.0] { + bad_value(open(&[("emission_luminance", k(&[v]))]), "emission_luminance"); + bad_value(open(&[("specular_ior", k(&[v]))]), "specular_ior"); + bad_value(open(&[("geometry_normal", k(&[0.0, 0.0, if v < 0.0 { f32::NAN } else { v }]))]), "geometry_normal"); + } + bad_value(try_from_materialx(&mx(Shader::GltfPbr, &[("ior", k(&[0.9]))])), "ior"); + // glTF PBR's specular_color has no upper bound, so a large encoded value overflows to + // infinity when it is decoded to linear; that is an error, not an infinite input. + for space in ["g22_rec709", "srgb_texture", "srgb_rec709_scene", "g24_rec709_scene"] { + bad_value(try_from_materialx(&mx(Shader::GltfPbr, &[("specular_color", ks(&[1e20, 1.0, 1.0], space))])), "specular_color"); + } + let wide = try_from_materialx(&mx(Shader::GltfPbr, &[("specular_color", ks(&[4.0, 1.0, 1.0], "g22_rec709"))])).unwrap(); + assert_eq!(wide.surface.other_inputs.len(), 1); + assert!(close(wide.surface.other_inputs[0].1[0], 4f32.powf(2.2))); + bad_value(open(&[("base_color", img("a.png", None, Some([0.0, 1.0])))]), "base_color"); + bad_value(open(&[("base_color", img("a.png", None, Some([f32::NAN, 1.0])))]), "base_color"); + let unknown = open(&[("thin_film_weight", k(&[0.5])), ("not_an_input", img("x.png", None, None))]).unwrap(); + assert!(dropped(&unknown, "thin_film_weight") && dropped(&unknown, "not_an_input")); + assert!(unknown.surface.textures.is_empty() && unknown.surface.other_inputs.is_empty()); +} + +#[test] +fn materialx_other_inputs_and_the_displacement_are_kept() { + let mut m = mx( + Shader::OpenPbr, + &[ + ("specular_color", ks(&[1.0, 0.5, 0.5], "srgb_texture")), + ("transmission_weight", k(&[0.5])), + ("subsurface_weight", img("sss.png", None, None)), + ], + ); + m.displacement = Some(k(&[0.25])); + let c = try_from_materialx(&m).unwrap(); + let srgb_half = craft_texture::srgb_to_linear(0.5); + assert_eq!( + c.surface.other_inputs, + vec![ + ("specular_color".into(), vec![1.0, srgb_half, srgb_half]), + ("transmission_weight".into(), vec![0.5]), + ("displacement".into(), vec![0.25]) + ] + ); + assert_eq!(c.surface.textures[0].input, TextureInput::Other("subsurface_weight".into())); + for name in ["specular_color", "transmission_weight", "subsurface_weight", "displacement"] { + assert!(unshaded(&c, name), "{name}"); + } + m.displacement = Some(img("h.png", Some("srgb_texture"), Some([4.0, 4.0]))); + let c = try_from_materialx(&m).unwrap(); + let h = c.surface.textures.iter().find(|b| b.input == TextureInput::Displacement).unwrap(); + assert_eq!((&h.source, &h.encoding), (&TextureSource::File("h.png".into()), &TextureEncoding::Linear)); + assert_eq!(h.transform.map(|t| t.scale), Some([4.0, 4.0])); + m.displacement = Some(k(&[f32::NAN])); + bad_value(try_from_materialx(&m), "displacement"); +} + +#[test] +fn materialx_reader_warnings_reach_the_report() { + let mut m = mx(Shader::OpenPbr, &[]); + m.warnings = vec!["input thin_film_weight is not read".into()]; + let c = try_from_materialx(&m).unwrap(); + assert_eq!(c.report.items, vec![ReportItem::Warning("input thin_film_weight is not read".into())]); +} + +#[test] +fn materialx_float_converted_to_a_color_is_not_decoded_from_the_nodes_color_space() { + // The float is not a color value, so the node's srgb_texture does not apply to it. + let doc = Document::parse( + br#" + + + + "#, + ) + .unwrap(); + let c = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_close3(c.surface.material.base_color(), [0.5; 3]); +} + +#[test] +fn materialx_documents_convert_from_xml() { + let doc = Document::parse( + br#" + + + + + + + + "#, + ) + .unwrap(); + let c = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(c.surface.name, "Red"); + assert_close3(c.surface.material.base_color(), [craft_texture::srgb_to_linear(0.5); 3]); + assert_eq!(c.surface.emissive, [3.0, 0.0, 0.0]); + assert_eq!(c.report.items, vec![ReportItem::Warning("input iridescence is not read".into())]); + + // craft-materialx's OpenPBR writer and this conversion agree on every texture it writes. + let textures = [ + Texture { input: "base_color".into(), file: "albedo.png".into(), colorspace: "srgb_texture".into() }, + Texture { input: "specular_roughness".into(), file: "rough.png".into(), colorspace: "srgb_texture".into() }, + Texture { input: "geometry_normal".into(), file: "normal.png".into(), colorspace: "lin_rec709".into() }, + Texture { input: "emission_color".into(), file: "glow.png".into(), colorspace: "lin_rec709".into() }, + Texture { input: "height".into(), file: "height.png".into(), colorspace: "lin_rec709".into() }, + ]; + let written = Document::parse(write_open_pbr("Stone", &textures, None).as_bytes()).unwrap(); + let c = try_from_materialx(&written.read_material_strict(None).unwrap()).unwrap(); + let s = &c.surface; + let by = |input: TextureInput| s.textures.iter().find(|b| b.input == input).map(|b| (b.source.clone(), b.encoding.clone())); + assert_eq!(by(TextureInput::BaseColor), Some((TextureSource::File("albedo.png".into()), TextureEncoding::Srgb))); + assert_eq!(by(TextureInput::Roughness), Some((TextureSource::File("rough.png".into()), TextureEncoding::Linear))); + assert_eq!(by(TextureInput::Normal), Some((TextureSource::File("normal.png".into()), TextureEncoding::Linear))); + assert_eq!(by(TextureInput::Emissive), Some((TextureSource::File("glow.png".into()), TextureEncoding::Linear))); + assert_eq!(by(TextureInput::Displacement), Some((TextureSource::File("height.png".into()), TextureEncoding::Linear))); + // The writer sets emission_luminance to 1 with an emission texture, so the texture shows. + assert_eq!(s.emissive, [1.0; 3]); + assert_eq!(s.name, "Stone"); +} diff --git a/crates/pbr/tests/it/differential.rs b/crates/pbr/tests/it/differential.rs index 787544f329..fa912eac8d 100644 --- a/crates/pbr/tests/it/differential.rs +++ b/crates/pbr/tests/it/differential.rs @@ -1,10 +1,10 @@ -//! This crate against the apps' previous code (`crate::reference`), on the same generated -//! environments. With the apps' settings (a firefly cap of 64, 128 samples, a level bias of 1), -//! every level matches within `TOLERANCE` for sources with even sides. The intended differences: -//! halving an odd side keeps the last column or row, which the previous code dropped, so levels -//! read from the pyramid of an odd-sized source differ; and the SH projection integrates the -//! basis over each pixel of the full source and sums in `f64`, so the irradiance differs within -//! `SH_TOLERANCE`. +//! These tests compare this crate with `crate::reference` on generated environments. +//! With a firefly cap of 64, 128 samples and a level bias of 1, +//! every level matches within `TOLERANCE` for the 64 × 32, 128 × 64 and 256 × 128 procedural +//! sources and the 128 × 64 synthetic sources tested here. Halving an odd side keeps its last +//! column or row, so its source pyramid can differ from the reference. The SH projection +//! integrates the basis over each pixel of the full source and sums in `f64`. +//! The irradiance comparison uses `SH_TOLERANCE`. use craft_pbr::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, Limits, PrefilterOptions, irradiance, try_prefilter, try_sh9}; diff --git a/crates/pbr/tests/it/main.rs b/crates/pbr/tests/it/main.rs index af2668dee1..3752e6e2b2 100644 --- a/crates/pbr/tests/it/main.rs +++ b/crates/pbr/tests/it/main.rs @@ -5,6 +5,9 @@ mod bench; mod bounds; mod brdf; +mod conversion_edges; +mod conversion_followups; +mod convert; mod differential; mod moved; mod numeric; diff --git a/crates/pdf/read-only-contract/Cargo.lock b/crates/pdf/read-only-contract/Cargo.lock index cfeccf816f..e999c63e13 100644 --- a/crates/pdf/read-only-contract/Cargo.lock +++ b/crates/pdf/read-only-contract/Cargo.lock @@ -103,8 +103,6 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d" dependencies = [ "hayro-ccitt", ] diff --git a/crates/pdf/src/cos/content/tests.rs b/crates/pdf/src/cos/content/tests.rs index 4076370cd5..cdedd45aeb 100644 --- a/crates/pdf/src/cos/content/tests.rs +++ b/crates/pdf/src/cos/content/tests.rs @@ -611,7 +611,8 @@ fn renderer_operators(data: &[u8]) -> Vec> { let mut iter = hayro_syntax::content::UntypedIter::new(data); let mut out = Vec::new(); while let Some(instruction) = iter.next() { - out.push(instruction.operator.as_ref().to_vec()); + let operator: &[u8] = instruction.operator.as_ref(); + out.push(operator.to_vec()); } out } diff --git a/crates/pdf/src/cos/object.rs b/crates/pdf/src/cos/object.rs index 3a82f82299..f0678f23b5 100644 --- a/crates/pdf/src/cos/object.rs +++ b/crates/pdf/src/cos/object.rs @@ -859,6 +859,23 @@ mod tests { } let small = zero_stream(1000); assert_eq!(&small.decoded().unwrap()[..], &[0u8; 1000][..], "the hand-written stream is a valid one"); + assert_eq!(crate::cos::MAX_PAGE_DECODED, 256 << 20); + let max = 4096; + let mut data = vec![0u8; max]; + let stream = Stream::flate(Dict::new(), &data); + assert_eq!(stream.decoded_within(max).ok().as_deref(), Some(data.as_slice())); + data.push(0); + let stream = Stream::flate(Dict::new(), &data); + assert!(matches!(stream.decoded_within(max), Err(CosError::Filter(_)))); + // Keep the default-cap wiring at full size in the existing native nightly convention. + // wasm32 has no divisor and always runs the small controls above. + #[cfg(not(target_arch = "wasm32"))] + let full = craft_testkit::hostile::divisor() == 1; + #[cfg(target_arch = "wasm32")] + let full = false; + if !full { + return; + } let stream = zero_stream((256 << 20) + 1); assert!(matches!(stream.decoded(), Err(CosError::Filter(_)))); } diff --git a/crates/pdf/src/cos/parser.rs b/crates/pdf/src/cos/parser.rs index 2e19d0c7ba..b050800577 100644 --- a/crates/pdf/src/cos/parser.rs +++ b/crates/pdf/src/cos/parser.rs @@ -33,13 +33,15 @@ pub struct Lexer<'a> { pub pos: usize, /// Objects built by the current top-level [`Lexer::object`] call. nodes: usize, + /// Maximum objects one top-level [`Lexer::object`] call may build. + max_nodes: usize, /// Whether the current top-level [`Lexer::object`] call reached [`MAX_DEPTH`]. too_deep: bool, } impl<'a> Lexer<'a> { pub fn new(data: &'a [u8], pos: usize) -> Self { - Self { data, pos: pos.min(data.len()), nodes: 0, too_deep: false } + Self { data, pos: pos.min(data.len()), nodes: 0, max_nodes: MAX_NODES, too_deep: false } } fn peek(&self) -> Option { @@ -97,7 +99,7 @@ impl<'a> Lexer<'a> { } fn over_budget(&self) -> bool { - self.nodes > MAX_NODES + self.nodes > self.max_nodes } /// Whether the last [`Lexer::object`] call failed because the object nests deeper than the @@ -972,27 +974,36 @@ mod tests { #[test] fn one_object_has_a_node_budget() { - // A wide array (from a tiny compressed object stream) must not grow without bound. - let wide = |n: usize| format!("[{}]", "0 ".repeat(n)); - let at_cap = Lexer::new(wide(MAX_NODES - 1).as_bytes(), 0).object(); - assert!(matches!(at_cap, Ok(Object::Array(ref items)) if items.len() == MAX_NODES - 1)); - assert!(Lexer::new(wide(MAX_NODES).as_bytes(), 0).object().is_err()); - // The gate stops at the plain array (each case parses millions of operands); nightly adds the same budget inside a - // dictionary value, behind tolerated junk, and per top-level object. + fn capped(data: &[u8], max: usize) -> Lexer<'_> { + let mut lx = Lexer::new(data, 0); + if max != MAX_NODES { + lx.max_nodes = max; + } + lx + } + + assert_eq!(MAX_NODES, 1 << 22); + // Exercise every budget path with small inputs in the gate; nightly also keeps the real cap. // wasm32 has no divisor and always runs the gate's part. #[cfg(not(target_arch = "wasm32"))] let full = craft_testkit::hostile::divisor() == 1; #[cfg(target_arch = "wasm32")] let full = false; - if !full { - return; + let caps = [1000].into_iter().chain(full.then_some(MAX_NODES)); + for max in caps { + // A wide array (from a tiny compressed object stream) must not grow without bound. + let wide = |n: usize| format!("[{}]", "0 ".repeat(n)); + let at_cap = capped(wide(max - 1).as_bytes(), max).object(); + assert!(matches!(at_cap, Ok(Object::Array(ref items)) if items.len() == max - 1)); + assert!(capped(wide(max).as_bytes(), max).object().is_err()); + // The same inside a dictionary value and a nested array. + assert!(capped(format!("<< /A {} >>", wide(max)).as_bytes(), max).object().is_err()); + assert!(capped(format!("[[{}] ]", "0 ".repeat(max)).as_bytes(), max).object().is_err()); + // The budget is per top-level object: a lexer reused for many operands keeps working. + let two = wide(max - 1).repeat(2); + let mut lx = capped(two.as_bytes(), max); + assert!(lx.object().is_ok() && lx.object().is_ok()); } - assert!(Lexer::new(format!("<< /A {} >>", wide(MAX_NODES)).as_bytes(), 0).object().is_err()); - assert!(Lexer::new(format!("[[{}] ]", "0 ".repeat(MAX_NODES)).as_bytes(), 0).object().is_err()); - // The budget is per top-level object: a lexer reused for many operands keeps working. - let two = wide(MAX_NODES - 1).repeat(2); - let mut lx = Lexer::new(two.as_bytes(), 0); - assert!(lx.object().is_ok() && lx.object().is_ok()); } /// A plain real is read without a cleaned copy of its token; the forms that need one read diff --git a/crates/pdf/tests/writing.rs b/crates/pdf/tests/writing.rs index 976c87a55a..63e6583ce5 100644 --- a/crates/pdf/tests/writing.rs +++ b/crates/pdf/tests/writing.rs @@ -82,3 +82,420 @@ fn retaining_a_writer_after_page_unwind_cannot_serialize_missing_pages() { ); } } + +// Original pixel recipes from issue #561 (OPUZZLES); no app, font or image assets. +#[cfg(feature = "filters")] +mod row_prediction { + use super::*; + use std::io::{Read, Write}; + use std::sync::Arc; + + use backend::color::device_n::{Colorant, DeviceNSpace, Process}; + use backend::image::{BitsPerComponent, CustomImage, Image, ImageColorspace}; + use flate2::{Compression, read::ZlibDecoder, write::ZlibEncoder}; + use hayro_syntax::object::{Array, Dict, Name, Object, Stream}; + + // Original spec-built64x32 RGBA16 PNG: the custom RGB16/alpha recipe below, + // big-endian samples; PNG color type6, no interlace, Up rows (tag2). + // Generated only with Python stdlib struct/zlib (including chunk CRCs); no image codec/assets. + const PNG16: &[u8] = b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x40\x00\x00\x00\x20\ + \x10\x06\x00\x00\x00\xf2\x0d\xa2\xc7\x00\x00\x01\x7d\x49\x44\x41\x54\x78\xda\xed\xd2\x21\x48\x43\ + \x51\x00\x85\xe1\xbb\x87\xc2\x34\xe8\x40\xc3\x0c\xca\xd0\xe0\x82\xc2\x34\xe8\x40\xc3\x2c\x32\xb0\ + \xac\x08\xc3\xe2\x82\x61\x16\x19\x58\x5e\x11\x86\xc5\x05\xc3\x2c\x32\xb0\xcc\x30\x50\x8b\x0a\x06\ + \x57\x44\xb1\xcc\x20\xa8\x45\x05\x83\x2b\xa2\x58\x66\x10\xd4\xf2\xe4\xf1\x07\x45\xb3\x96\x7b\x4e\ + \xb8\x61\xef\x83\xc1\xbd\xbf\x63\xbc\x80\xf1\x8c\x31\xfe\xe9\x79\xc1\x66\xff\x34\x26\xd4\xea\x9f\ + \xc6\x0b\xb7\xfb\x67\xc0\x44\x3a\x71\xd1\x2e\x5c\xac\x07\x17\xef\xc3\x25\xa2\xb8\xe4\x20\x2e\x35\ + \x8c\x4b\x8f\xe2\x32\xe3\xb8\xec\x04\x2e\x37\x89\x73\xa7\x70\xf9\x14\xae\x30\x8d\x2b\xce\xe0\x4a\ + \xb3\xb8\xf2\x1c\x6e\x6b\x1e\xb7\xb7\x80\x3b\x5c\xc4\x1d\xbb\xb8\xda\x12\xee\x62\x19\x77\xb3\x82\ + \xbb\x5f\xc5\x3d\xae\xe1\x1a\xeb\xb8\xb7\x0d\x9c\x29\xe3\x82\x15\x5c\x68\x07\x17\xde\xc5\x45\x0e\ + \x70\xd1\x2a\x2e\x76\x84\x8b\x9f\xe2\x12\x35\x5c\xf2\x1c\x97\xba\xc2\xa5\xaf\x71\x99\x3b\x5c\xb6\ + \x8e\xcb\x3d\xe0\xdc\x67\x5c\xbe\x81\x2b\xbc\xe2\x8a\x1f\xb8\x92\x87\xdb\x6c\xc2\x6d\xb7\xe0\xf6\ + \xdb\x70\xd5\x0e\xdc\x49\x18\x77\xd6\x8d\xbb\xec\xc5\xdd\xf6\xe3\xea\x03\xb8\xa7\x21\xdc\xcb\x08\ + \xee\x7d\xcc\x71\x02\x5f\x73\x7e\x9c\xce\xaf\x5f\xe5\xfe\xd7\x39\x7f\xfe\xbf\xdf\xbf\x6b\x16\x4e\ + \x01\x28\x00\x4d\x01\x68\x0a\x40\xb3\xf3\x59\x14\x80\x52\xd3\x14\x80\xa6\x00\x34\x05\xa0\x59\xf8\ + \x1c\x0a\x40\xc9\x69\x0a\x40\x53\x00\x9a\x02\xd0\x2c\x7c\x06\x05\xa0\xf4\x34\x05\xa0\x29\x00\x4d\ + \x01\x68\x16\x5e\xbf\x02\x50\x82\x9a\x02\xd0\x14\x80\xa6\x00\x34\x0b\xaf\x5d\x01\x28\x45\x4d\x01\ + \x68\x0a\x40\x53\x00\x9a\x85\xd7\xfd\x09\x61\x07\x13\x9b\x10\xb0\x38\x81\x00\x00\x00\x00\x49\x45\ + \x4e\x44\xae\x42\x60\x82"; + + #[derive(Clone, Hash)] + struct Samples { + color: Vec, + alpha: Option>, + size: (u32, u32), + bits: BitsPerComponent, + space: ImageColorspace, + } + + impl CustomImage for Samples { + fn color_channel(&self) -> &[u8] { + &self.color + } + fn alpha_channel(&self) -> Option<&[u8]> { + self.alpha.as_deref() + } + fn bits_per_component(&self) -> BitsPerComponent { + self.bits + } + fn size(&self) -> (u32, u32) { + self.size + } + fn icc_profile(&self) -> Option<&[u8]> { + None + } + fn color_space(&self) -> ImageColorspace { + self.space + } + fn device_n_space(&self) -> Option { + (self.space == ImageColorspace::DeviceN) + .then(|| DeviceNSpace::new([Colorant::Process(Process::Magenta), Colorant::Process(Process::Cyan)]).unwrap()) + } + } + + struct Row { + name: &'static str, + samples: Samples, + rgba: bool, + png: bool, + must_predict: bool, + must_keep_raw: bool, + } + + struct Benefit { + name: &'static str, + ascii: bool, + predictor: Option, + selected: usize, + unpredicted: usize, + } + + fn components(space: ImageColorspace) -> usize { + match space { + ImageColorspace::Luma => 1, + ImageColorspace::Rgb => 3, + ImageColorspace::Cmyk => 4, + ImageColorspace::DeviceN => 2, + } + } + + fn bpc(bits: BitsPerComponent) -> i32 { + match bits { + BitsPerComponent::Eight => 8, + BitsPerComponent::Sixteen => 16, + } + } + + fn raw_deflate(data: &[u8]) -> Vec { + // The existing writer's raw control: the same zlib level, with no row transform. + let mut encoder = ZlibEncoder::new(Vec::new(), Compression::new(6)); + encoder.write_all(data).unwrap(); + encoder.finish().unwrap() + } + + /// Serialize complete candidate filter-stream objects, including Length and DecodeParms. + /// The common image dictionary entries cancel; this control uses the shared framing writer. + fn complete_stream_size(data: &[u8], samples: &Samples, predicted: bool, ascii: bool) -> usize { + let mut encoded = Vec::new(); + if ascii { + for (i, byte) in data.iter().enumerate() { + write!(&mut encoded, "{byte:02X}").unwrap(); + if (i + 1) % 35 == 0 { + encoded.push(b'\n'); + } + } + } else { + encoded.extend_from_slice(data); + } + let filter = if ascii { "[/ASCIIHexDecode /FlateDecode]" } else { "/FlateDecode" }; + let parms = if predicted { + let dict = format!( + "<< /Predictor 12 /Columns {} /Colors {} /BitsPerComponent {} >>", + samples.size.0, + components(samples.space), + bpc(samples.bits) + ); + if ascii { format!(" /DecodeParms [null {dict}]") } else { format!(" /DecodeParms {dict}") } + } else { + String::new() + }; + let mut writer = craft_pdf::classic::Writer::with_capacity(0).unwrap(); + writer.object(1, "<< /Type /Catalog /Pages 2 0 R >>").unwrap(); + writer.object(2, "<< /Type /Pages /Kids [] /Count 0 >>").unwrap(); + writer.stream(3, &format!("/Filter {filter}{parms}"), &encoded).unwrap(); + let pdf = writer.finish(1, None).unwrap(); + // The one control stream is the last object, immediately before the classic xref table. + let start = pdf.windows(b"3 0 obj\n".len()).position(|bytes| bytes == b"3 0 obj\n").unwrap(); + let end = pdf.windows(b"\nxref\n".len()).rposition(|bytes| bytes == b"\nxref\n").unwrap(); + end - start + } + + fn image(row: &Row) -> Image { + if row.png { + Image::from_png(PNG16.to_vec().into(), false).unwrap() + } else if row.rgba { + let rgba = row.samples.color.as_chunks::<3>().0.iter().flat_map(|rgb| [rgb[0], rgb[1], rgb[2], 255]).collect(); + Image::from_rgba8(rgba, row.samples.size.0, row.samples.size.1) + } else { + Image::from_custom(row.samples.clone(), false).unwrap() + } + } + + fn export(row: &Row, ascii: bool) -> Vec { + let settings = backend::SerializeSettings { + ascii_compatible: ascii, + no_device_cs: false, + configuration: write::configuration(PdfVersion::Pdf17, None).unwrap(), + ..Default::default() + }; + let mut writer = Writer::new(settings, Metadata::default()); + let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(100.0, 80.0).unwrap()); + let mut surface = page.surface(); + surface.draw_image(image(row), Size::from_wh(100.0, 80.0).unwrap()); + surface.finish(); + page.finish(); + writer.finish().unwrap() + } + + fn check_plane(stream: &Stream<'_>, expected: &[u8], samples: &Samples, colors: usize, ascii: bool) -> Option { + let dict = stream.dict(); + assert_eq!(dict.get::>(b"Subtype").unwrap().as_str(), "Image"); + assert_eq!(dict.get::(b"Width"), Some(samples.size.0 as i32)); + assert_eq!(dict.get::(b"Height"), Some(samples.size.1 as i32)); + assert_eq!(dict.get::(b"BitsPerComponent"), Some(bpc(samples.bits))); + assert_eq!(stream.decoded().unwrap().as_ref(), expected, "all samples, including 16-bit byte rollover"); + + let has_params = dict.contains_key(b"DecodeParms"); + let params = if ascii { + let filters: Vec<_> = dict.get::>(b"Filter").unwrap().iter::>().map(|n| n.as_str().to_owned()).collect(); + assert_eq!(filters, ["ASCIIHexDecode", "FlateDecode"]); + has_params.then(|| { + let array = dict.get::>(b"DecodeParms").unwrap(); + let slots: Vec<_> = array.iter::>().collect(); + assert_eq!(slots.len(), 2, "one DecodeParms slot per filter"); + assert!(matches!(slots[0], Object::Null(_)), "ASCIIHex has no parameters"); + slots[1].clone().into_dict().unwrap() + }) + } else { + assert_eq!(dict.get::>(b"Filter").unwrap().as_str(), "FlateDecode"); + has_params.then(|| dict.get::>(b"DecodeParms").unwrap()) + }; + params.map(|params| { + let predictor = params.get::(b"Predictor").unwrap(); + assert_eq!(predictor, 12); + assert_eq!(params.get::(b"Colors"), Some(colors as i32)); + assert_eq!(params.get::(b"Columns"), Some(samples.size.0 as i32)); + assert_eq!(params.get::(b"BitsPerComponent"), Some(bpc(samples.bits))); + if !ascii { + let encoded = stream.raw_data(); + let mut tagged_rows = Vec::new(); + ZlibDecoder::new(encoded.as_ref()).read_to_end(&mut tagged_rows).unwrap(); + let stride = samples.size.0 as usize * colors * (bpc(samples.bits) as usize / 8) + 1; + assert_eq!(tagged_rows.len(), stride * samples.size.1 as usize); + assert!(tagged_rows.chunks_exact(stride).all(|row| row[0] == 2), "PNG Up tag on every row"); + } + predictor + }) + } + + fn check_row(row: &Row, ascii: bool) -> Option { + let pdf = hayro_syntax::Pdf::new(Arc::new(export(row, ascii))).unwrap(); + let page = &pdf.pages()[0]; + assert_eq!(page.render_dimensions(), (100.0, 80.0)); + let resources = &page.resources().x_objects; + let keys: Vec<_> = resources.keys().collect(); + assert_eq!(keys.len(), 1, "{}: one drawn image", row.name); + let stream = resources.get::>(keys[0].as_ref()).unwrap(); + let predictor = check_plane(&stream, &row.samples.color, &row.samples, components(row.samples.space), ascii); + let dict = stream.dict(); + if row.samples.space == ImageColorspace::DeviceN { + let cs: Vec<_> = dict.get::>(b"ColorSpace").unwrap().iter::>().collect(); + assert_eq!(cs[0].clone().into_name().unwrap().as_str(), "DeviceN"); + let names: Vec<_> = cs[1].clone().into_array().unwrap().iter::>().map(|n| n.as_str().to_owned()).collect(); + assert_eq!(names, ["Magenta", "Cyan"], "preserve colorant/sample order"); + } else { + let name = match row.samples.space { + ImageColorspace::Luma => Some("DeviceGray"), + ImageColorspace::Rgb => Some("DeviceRGB"), + ImageColorspace::Cmyk => Some("DeviceCMYK"), + ImageColorspace::DeviceN => None, + }; + assert!(name.is_some(), "{}: DeviceN fixture needs the colorant ColorSpace check", row.name); + assert_eq!(dict.get::>(b"ColorSpace").unwrap().as_str(), name.unwrap()); + } + if let Some(alpha) = &row.samples.alpha { + let mask = dict.get::>(b"SMask").unwrap(); + assert_eq!(mask.dict().get::>(b"ColorSpace").unwrap().as_str(), "DeviceGray"); + let mask_predictor = check_plane(&mask, alpha, &row.samples, 1, ascii); + if row.samples.space == ImageColorspace::Luma && row.samples.bits == BitsPerComponent::Sixteen { + // This multi-row rollover mask is compressible; other masks may legitimately keep raw Flate. + assert_eq!(mask_predictor, Some(12), "{} (ASCII={ascii}): predict the compressible soft mask", row.name); + } + } else { + assert!(dict.get::>(b"SMask").is_none(), "{}: no extra alpha plane", row.name); + } + if row.must_keep_raw { + assert_eq!(predictor, None, "{}: prediction must not enlarge tiny/noisy images", row.name); + let raw = raw_deflate(&row.samples.color); + let expected_length = if ascii { raw.len() * 2 + raw.len() / 35 } else { raw.len() }; + assert_eq!(stream.raw_data().len(), expected_length, "{}: retain raw deflation", row.name); + } + row.must_predict.then(|| { + let raw = raw_deflate(&row.samples.color); + Benefit { + name: row.name, + ascii, + predictor, + // Compare like encoded payloads. The separate overhead control below compares + // complete streams; tiny/noisy rows also retain their raw fallback checks. + selected: stream.raw_data().len(), + unpredicted: if ascii { raw.len() * 2 + raw.len() / 35 } else { raw.len() }, + } + }) + } + + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] + #[cfg_attr(not(target_arch = "wasm32"), test)] + fn preserves_samples_and_compresses_redundant_rows() { + let mut rows = Vec::new(); + for pattern in [false, true] { + let mut color = Vec::with_capacity(1000 * 800 * 3); + for y in 0..800u32 { + for x in 0..1000u32 { + let rgb = if pattern { + [((x * 31 + y * 17) % 256) as u8, ((x * 7 + y * 53) % 256) as u8, ((x * 11 + y * 23) % 256) as u8] + } else { + [(x * 255 / 999) as u8, (y * 255 / 799) as u8, ((x + y) * 127 / 899) as u8] + }; + color.extend_from_slice(&rgb); + } + } + rows.push(Row { + name: if pattern { "repeating RGB" } else { "gradient RGB" }, + samples: Samples { color, alpha: None, size: (1000, 800), bits: BitsPerComponent::Eight, space: ImageColorspace::Rgb }, + rgba: true, + png: false, + must_predict: true, + must_keep_raw: false, + }); + } + for space in [ImageColorspace::Luma, ImageColorspace::Rgb, ImageColorspace::Cmyk, ImageColorspace::DeviceN] { + for bits in [BitsPerComponent::Eight, BitsPerComponent::Sixteen] { + let mut color = Vec::new(); + let mut alpha = Vec::new(); + for y in 0..32u16 { + for x in 0..64u16 { + for c in 0..components(space) { + // Carries cross both low- and high-byte boundaries between rows. + let sample = [0x00ffu16, 0x0100, 0xff00, 0xffff, 0][(x as usize + c) % 5].wrapping_add(y * 257); + if bits == BitsPerComponent::Sixteen { + color.extend_from_slice(&sample.to_be_bytes()); + } else { + color.push(sample as u8); + } + } + let sample = x.wrapping_mul(2053).wrapping_add(y * 257); + if bits == BitsPerComponent::Sixteen { + alpha.extend_from_slice(&sample.to_be_bytes()); + } else { + alpha.push(sample as u8); + } + } + } + rows.push(Row { + name: if bits == BitsPerComponent::Sixteen && space == ImageColorspace::Luma { + "16-bit gray rollover" + } else { + "custom color and alpha" + }, + samples: Samples { color, alpha: Some(alpha), size: (64, 32), bits, space }, + rgba: false, + png: false, + must_predict: bits == BitsPerComponent::Sixteen && space == ImageColorspace::Luma, + must_keep_raw: false, + }); + } + } + let mut random = 0x561u32; + let noisy = (0..37 * 29 * 3) + .map(|_| { + random ^= random << 13; + random ^= random >> 17; + random ^= random << 5; + random as u8 + }) + .collect(); + for (name, color, size) in [("tiny RGB", vec![7, 129, 253], (1, 1)), ("noisy RGB", noisy, (37, 29))] { + rows.push(Row { + name, + samples: Samples { color, alpha: None, size, bits: BitsPerComponent::Eight, space: ImageColorspace::Rgb }, + rgba: true, + png: false, + must_predict: false, + must_keep_raw: true, + }); + } + + // Prediction saves payload bytes here, but cannot pay for its serialized parameters in + // either output mode. A payload-only selection would wrongly predict this multi-row image. + let overhead = Samples { + color: (0..3u8).flat_map(|y| (0..4u8).flat_map(move |x| (0..3u8).map(move |c| x * 19 + y * 7 + c * 31))).collect(), + alpha: None, + size: (4, 3), + bits: BitsPerComponent::Eight, + space: ImageColorspace::Rgb, + }; + let mut up = Vec::new(); + for (y, row) in overhead.color.as_chunks::<12>().0.iter().enumerate() { + up.push(2); + for (x, byte) in row.iter().enumerate() { + let previous = if y == 0 { 0 } else { overhead.color[(y - 1) * 12 + x] }; + up.push(byte.wrapping_sub(previous)); + } + } + let raw = raw_deflate(&overhead.color); + let predicted = raw_deflate(&up); + assert!(predicted.len() < raw.len(), "the overhead control must save compressed payload bytes"); + for ascii in [false, true] { + assert!( + complete_stream_size(&predicted, &overhead, true, ascii) > complete_stream_size(&raw, &overhead, false, ascii), + "ASCII={ascii}: serialized parameters must outweigh the payload saving" + ); + } + rows.push(Row { name: "serialized overhead RGB", samples: overhead, rgba: true, png: false, must_predict: false, must_keep_raw: true }); + + let png_samples = rows + .iter() + .find(|row| row.samples.space == ImageColorspace::Rgb && row.samples.bits == BitsPerComponent::Sixteen) + .unwrap() + .samples + .clone(); + rows.push(Row { + name: "PNG16 RGB and alpha rollover", + samples: png_samples, + rgba: false, + png: true, + must_predict: true, + must_keep_raw: false, + }); + + let mut benefits = Vec::new(); + for row in &rows { + for ascii in [false, true] { + if let Some(benefit) = check_row(row, ascii) { + benefits.push(benefit); + } + } + } + // All rows' decoded samples, metadata, masks, ASCII chains and fallback checks run + // before main's expected failure: it has no row predictor on the gradient. + for benefit in benefits { + assert_eq!(benefit.predictor, Some(12), "{} (ASCII={}): sampled rows need PNG Up prediction", benefit.name, benefit.ascii); + assert!( + benefit.selected < benefit.unpredicted, + "{} (ASCII={}): predicted payload must beat raw-deflated payload", + benefit.name, + benefit.ascii + ); + } + } +} diff --git a/crates/prepress/src/flatten/compose.rs b/crates/prepress/src/flatten/compose.rs index b17c302895..c3bebda6b7 100644 --- a/crates/prepress/src/flatten/compose.rs +++ b/crates/prepress/src/flatten/compose.rs @@ -30,6 +30,13 @@ use super::{BlendMode, DisplayList, FillItem, FillRule, GroupItem, Item, Paint}; use crate::ink::{InkColor, InkId, InkSet, Overprint, Process}; /// How [`flatten`] cuts transparent art. +/// +/// `FlattenOptions` can be initialized with its three fields: +/// +/// ``` +/// use craft_prepress::flatten::FlattenOptions; +/// let options = FlattenOptions { sliver: 0.01, max_regions: 5000, raster_dpi: 300.0 }; +/// ``` #[derive(Clone, Copy, Debug, PartialEq)] pub struct FlattenOptions { /// Regions narrower than this (in points) are dropped ([`geom::regions_with`]). @@ -48,6 +55,27 @@ impl Default for FlattenOptions { } } +/// These limits bound each region sweep used by [`flatten_with_limits`]. The PDF entry points +/// with explicit limits also apply them to each even-odd path rebuild during page reading. +/// A stopped rebuild retains the original path and fill rule. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FlattenSweepLimits { + /// The region sweep of one group stops after this many work units. The group then goes to + /// [`Flattened::complex`] whole as [`ComplexReason::Degenerate`]. The default is + /// [`geom::DEFAULT_MAX_SWEEP_WORK`]. + pub max_sweep_work: u64, + /// The region sweep of one group stops before holding more than this many output units. + /// The group then goes to [`Flattened::complex`] whole as [`ComplexReason::Degenerate`]. + /// The default is [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]. + pub max_sweep_units: usize, +} + +impl Default for FlattenSweepLimits { + fn default() -> Self { + Self { max_sweep_work: geom::DEFAULT_MAX_SWEEP_WORK, max_sweep_units: geom::DEFAULT_MAX_TOPOLOGY_UNITS } + } +} + /// A page with no transparency left. #[derive(Clone, Debug, PartialEq)] pub struct Flattened { @@ -132,6 +160,11 @@ pub enum FlattenError { /// an item that does come back unchanged, and so do opaque items with no transparency painted /// above them where they paint. pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result { + flatten_with_limits(list, opts, &FlattenSweepLimits::default()) +} + +/// `flatten_with_limits` flattens `list` using `opts` and the region sweep `limits`. +pub fn flatten_with_limits(list: &DisplayList, opts: &FlattenOptions, limits: &FlattenSweepLimits) -> Result { let nan = Rect::new(f64::NAN, f64::NAN, f64::NAN, f64::NAN); let bounds: Vec = list.items.iter().map(|i| bounds(i).unwrap_or(nan)).collect(); let transparent: Vec = list.items.iter().map(is_transparent).collect(); @@ -165,7 +198,7 @@ pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result {} - Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, &mut out)?, + Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, limits, &mut out)?, } } out.report.complex_regions = out.complex.len(); @@ -178,6 +211,7 @@ fn flatten_group( bounds: &[Rect], transparent: &[bool], opts: &FlattenOptions, + limits: &FlattenSweepLimits, out: &mut Flattened, ) -> Result<(), FlattenError> { let mut b = Builder::new(&list.inks); @@ -206,7 +240,7 @@ fn flatten_group( out.report.flattened += members.len(); return Ok(()); } - let regions = match geom::regions_with(&b.shapes, &b.clips, opts.sliver) { + let regions = match geom::regions_with_limits(&b.shapes, &b.clips, opts.sliver, limits.max_sweep_work, limits.max_sweep_units) { Ok(r) => r, Err(GeomError::Degenerate) => { // Each member's box is clear of every other group's items. @@ -1046,4 +1080,24 @@ mod tests { let l = list(InkSet::new(), vec![Item::Group(group(0.5, BlendMode::Normal, vec![crowded]))]); assert!(flatten(&l, &FlattenOptions::default()).is_err()); } + + #[test] + fn sweep_limits_send_the_group_to_complex() { + let l = list( + InkSet::new(), + vec![ + solid(Rect::new(0.0, 0.0, 100.0, 100.0), &[(M, 1.0)]), + Item::Group(group(0.5, BlendMode::Normal, vec![solid(Rect::new(50.0, 0.0, 150.0, 100.0), &[(C, 1.0)])])), + ], + ); + assert!(flat(&l).report.complex_groups.is_empty()); + + for limits in [ + FlattenSweepLimits { max_sweep_work: 1, ..FlattenSweepLimits::default() }, + FlattenSweepLimits { max_sweep_units: 1, ..FlattenSweepLimits::default() }, + ] { + let f = flatten_with_limits(&l, &FlattenOptions::default(), &limits).unwrap(); + assert_eq!(f.report.complex_groups, [ComplexGroup { items: vec![0, 1], reason: ComplexReason::Degenerate }], "{limits:?}"); + } + } } diff --git a/crates/prepress/src/flatten/document.rs b/crates/prepress/src/flatten/document.rs index 95ef200604..82c32df9b5 100644 --- a/crates/prepress/src/flatten/document.rs +++ b/crates/prepress/src/flatten/document.rs @@ -42,7 +42,7 @@ use kurbo::Rect; use super::pdf::{ReadColor, ReadError, ReadOptions, read_color, read_page_in}; use super::raster::{FlattenPageReport, Rasterizer}; use super::write::{FontMap, WriteError, write_flattened_with_fonts}; -use super::{DisplayList, FlattenError, FlattenOptions, flatten}; +use super::{DisplayList, FlattenError, FlattenOptions, FlattenSweepLimits, flatten_with_limits}; use crate::cms::CmsConversion; use crate::plates::{self, Fallback, pdf_text}; @@ -175,7 +175,16 @@ pub enum FlattenDocumentError { /// `pdf` with the transparency of every page in [`FlattenDocumentOptions::pages`] flattened, as /// one PDF. See the module docs for what carries over. pub fn flatten_document(pdf: &[u8], opts: &FlattenDocumentOptions) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { - flatten_document_with_progress(pdf, opts, &mut |_, _| {}) + flatten_document_with_limits(pdf, opts, &FlattenSweepLimits::default()) +} + +/// [`flatten_document`] with explicit sweep work and output limits. +pub fn flatten_document_with_limits( + pdf: &[u8], + opts: &FlattenDocumentOptions, + limits: &FlattenSweepLimits, +) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { + flatten_document_with_limits_and_progress(pdf, opts, limits, &mut |_, _| {}) } /// [`flatten_document`], calling `progress(done, total)` after each page. @@ -183,6 +192,16 @@ pub fn flatten_document_with_progress( pdf: &[u8], opts: &FlattenDocumentOptions, progress: &mut dyn FnMut(usize, usize), +) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { + flatten_document_with_limits_and_progress(pdf, opts, &FlattenSweepLimits::default(), progress) +} + +/// [`flatten_document_with_limits`], calling `progress(done, total)` after each page. +pub fn flatten_document_with_limits_and_progress( + pdf: &[u8], + opts: &FlattenDocumentOptions, + limits: &FlattenSweepLimits, + progress: &mut dyn FnMut(usize, usize), ) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { let doc = Arc::new(open_slice(pdf, None)?); let count = doc.pages().len(); @@ -213,9 +232,9 @@ pub fn flatten_document_with_progress( report.other_intents.push(page); } let p = doc.pages().get(page).ok_or(FlattenDocumentError::Read { page, source: ReadError::NoPage(page) })?; - match read_page_in(&doc, page, &opts.read, color.read.clone()) { + match read_page_in(&doc, page, &opts.read, color.read.clone(), limits) { Ok((list, read)) => { - let flat = flatten(&list, &opts.flatten).map_err(|source| FlattenDocumentError::Flatten { page, source })?; + let flat = flatten_with_limits(&list, &opts.flatten, limits).map_err(|source| FlattenDocumentError::Flatten { page, source })?; let mut raster = Rasterizer::new(&list, color.settings.clone(), color.condition.clone(), &color.cms, opts.flatten.raster_dpi); let at = |source| FlattenDocumentError::Write { page, source }; let settings = page_settings(p, list.page).ok_or(at(WriteError::Page))?; diff --git a/crates/prepress/src/flatten/geom.rs b/crates/prepress/src/flatten/geom.rs index 433484be4f..d613c4f365 100644 --- a/crates/prepress/src/flatten/geom.rs +++ b/crates/prepress/src/flatten/geom.rs @@ -12,6 +12,7 @@ //! a boolean per clipped shape, and a clip edge is then the same edge in every region it bounds. use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape as _, Vec2}; use linesweeper::topology::{ContourIdx, Contours, Topology, WindingNumber}; @@ -20,6 +21,19 @@ use linesweeper::topology::{ContourIdx, Contours, Topology, WindingNumber}; /// numerical debris, such as the lens between two nearly coincident curves. pub const DEFAULT_SLIVER: f64 = 0.01; +/// The default for the most work the sweep may do, counted as segment comparisons plus segment +/// position checks plus one unit for every 16 segments a search of the sweep line passes or probes +/// plus the horizontal segments each step of a sweep line visits, +/// before the shapes count as too degenerate to sweep. Stacked copies of a shape can need billions +/// of comparisons; a release build makes about 17 million a second. +pub const DEFAULT_MAX_SWEEP_WORK: u64 = 100_000_000; + +/// The default for the most output the sweep's topology may hold before the shapes count as too +/// degenerate to sweep, in units: each output segment takes one unit plus one for each entry of its +/// two winding numbers (at least one each), so 2,000,000 segments with single-entry windings fill +/// it. Each segment's windings can hold an entry for every shape that covers it. +pub const DEFAULT_MAX_TOPOLOGY_UNITS: usize = 6_000_000; + /// How a path's winding number decides what is inside it. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum FillRule { @@ -124,10 +138,17 @@ pub fn regions(shapes: &[Shape], clips: &[ClipPath]) -> Result, Geom /// [`regions`] with contours narrower than `sliver` dropped. pub fn regions_with(shapes: &[Shape], clips: &[ClipPath], sliver: f64) -> Result, GeomError> { + regions_with_limits(shapes, clips, sliver, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS) +} + +/// [`regions_with`] with the sweep stopped, as [`GeomError::Degenerate`], once it passes +/// `max_work` units of work or its topology passes `max_units` units of output (see +/// [`DEFAULT_MAX_SWEEP_WORK`] and [`DEFAULT_MAX_TOPOLOGY_UNITS`] for the units). +pub fn regions_with_limits(shapes: &[Shape], clips: &[ClipPath], sliver: f64, max_work: u64, max_units: usize) -> Result, GeomError> { if shapes.is_empty() { return Ok(Vec::new()); } - Ok(Arrangement::new(shapes, clips, sliver)?.regions()) + Arrangement::new(shapes, clips, sliver, max_work, max_units)?.regions() } /// The finiteness check [`regions_with`] makes: every point of every shape path and of every clip @@ -212,8 +233,12 @@ pub fn transparent_groups(bounds: &[Rect], transparent: &[bool]) -> Vec); +struct Multi(Arc>); impl Multi { fn get(&self, tag: usize) -> i32 { @@ -233,17 +258,21 @@ impl std::ops::AddAssign for Multi { fn add_assign(&mut self, rhs: Self) { // The sweep mostly adds one input's ±1 to a short list: add in place, insert in tag order, // drop a winding that reaches zero. - for (t, k) in rhs.0 { - match self.0.binary_search_by_key(&t, |e| e.0) { + if rhs.0.iter().all(|e| e.1 == 0) { + return; + } + let list = Arc::make_mut(&mut self.0); + for &(t, k) in rhs.0.iter() { + match list.binary_search_by_key(&t, |e| e.0) { Ok(i) => { - if let Some(e) = self.0.get_mut(i) { + if let Some(e) = list.get_mut(i) { e.1 += k; if e.1 == 0 { - self.0.remove(i); + list.remove(i); } } } - Err(i) if k != 0 => self.0.insert(i, (t, k)), + Err(i) if k != 0 => list.insert(i, (t, k)), Err(_) => {} } } @@ -253,11 +282,14 @@ impl std::ops::AddAssign for Multi { impl WindingNumber for Multi { type Tag = usize; fn single(tag: usize, positive: bool) -> Self { - Multi(vec![(tag, if positive { 1 } else { -1 })]) + Multi(Arc::new(vec![(tag, if positive { 1 } else { -1 })])) } fn of_tag(&self, tag: usize) -> Self { let w = self.get(tag); - Multi(if w == 0 { vec![] } else { vec![(tag, w)] }) + Multi(Arc::new(if w == 0 { vec![] } else { vec![(tag, w)] })) + } + fn storage_units(&self) -> usize { + self.0.len().max(1) } } @@ -272,7 +304,7 @@ struct Arrangement { } impl Arrangement { - fn new(shapes: &[Shape], clips: &[ClipPath], sliver: f64) -> Result { + fn new(shapes: &[Shape], clips: &[ClipPath], sliver: f64, work_limit: u64, output_limit: usize) -> Result { let n = shapes.len(); let mut used = vec![false; clips.len()]; let mut shape_clips = Vec::with_capacity(n); @@ -295,8 +327,11 @@ impl Arrangement { let eps = eps_for(paths.iter().map(|p| &p.0))?; snap_horizontals(&mut paths.iter_mut().map(|p| &mut p.0).collect::>(), eps); // The sweep can panic on rare near-degenerate input; the flattener then rasterizes. - let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::::from_paths(paths.iter().map(|(p, t)| (p, *t)), eps))); - // Every subpath is closed, so a path error is a degenerate input too. + let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + Topology::::from_paths_with_limits(paths.iter().map(|(p, t)| (p, *t)), eps, work_limit, output_limit) + })); + // Every subpath is closed, so a path error or a sweep past its work or output limit is a + // degenerate input too. let top = sweep.map_err(|_| GeomError::Degenerate)?.map_err(|_| GeomError::Degenerate)?; let rules = shapes.iter().map(|s| s.rule).chain(clips.iter().map(|c| c.rule)).collect(); let tidy = Tidy::keeping(sliver, paths.iter().map(|p| &p.0)); @@ -315,7 +350,7 @@ impl Arrangement { /// sets × edges. Instead the sets go into batches whose faces share no vertex (so no edge /// either): one pass per batch walks each face's contours as its own set's pass would, and the /// set a contour bounds is the one of its batch at its first point. - fn regions(&self) -> Vec { + fn regions(&self) -> Result, GeomError> { let top = &self.top; // The distinct non-empty coverage sets, numbered in the order met, and the set of each // side of each segment. Faces have many sides, so a set is worked out once per winding. @@ -382,7 +417,7 @@ impl Arrangement { } let mut faces: Vec> = vec![Vec::new(); sets.len()]; for b in 0..batches { - let c = top.contours(|w| id(w).is_some_and(|m| batch[m] == b)); + let c = contours(top, |w| id(w).is_some_and(|m| batch[m] == b))?; let owner: Option> = c .contours() .map(|ct| { @@ -394,7 +429,7 @@ impl Arrangement { // Not expected: every contour starts at a vertex of the arrangement. Fall back to // a pass per set for this batch. for m in (0..sets.len()).filter(|&m| batch[m] == b) { - let c = top.contours(|w| id(w) == Some(m)); + let c = contours(top, |w| id(w) == Some(m))?; faces[m].extend(c.grouped().into_iter().map(|g| self.outline(&c, g))); } continue; @@ -430,7 +465,7 @@ impl Arrangement { out.push(Region { path, area, sources: sources.clone() }); } } - out + Ok(out) } /// The contours `idx` of `c` as one path, repaired, without slivers, and with the pieces the @@ -458,6 +493,18 @@ impl Arrangement { } } +/// The contours of `top`'s faces for which `inside` holds. The contour walk returns an error when the +/// sweep left winding numbers that disagree around a point, and can still panic on other degenerate +/// input; either way that input is degenerate. +fn contours(top: &Topology, inside: impl Fn(&Multi) -> bool) -> Result { + walk_result(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| top.try_contours(inside)))) +} + +/// Maps a contour walk that panicked or returned an error to [`GeomError::Degenerate`]. +fn walk_result(walk: std::thread::Result>) -> Result { + walk.map_err(|_| GeomError::Degenerate)?.map_err(|_| GeomError::Degenerate) +} + /// A point as a map key (the arrangement's vertices are exact). fn vertex_key(p: Point) -> (u64, u64) { (p.x.to_bits(), p.y.to_bits()) @@ -954,6 +1001,20 @@ mod tests { Shape::new(path, FillRule::NonZero) } + #[test] + fn inconsistent_windings_are_degenerate() { + // A walk that returns an error or panics gives `Degenerate`; one that finishes gives its contours. + assert_eq!(walk_result::(Ok(Err(linesweeper::Error::InconsistentWindingNumbers))), Err(GeomError::Degenerate)); + assert_eq!(walk_result::(Err(Box::new("walk panicked"))), Err(GeomError::Degenerate)); + assert_eq!(walk_result(Ok(Ok(7_u8))), Ok(7)); + let shapes = [fill(rect(0.0, 0.0, 10.0, 10.0))]; + let arrangement = Arrangement::new(&shapes, &[], DEFAULT_SLIVER, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap(); + assert_eq!(contours(&arrangement.top, |w: &Multi| w.get(0) != 0).map(|c| c.contours().count()), Ok(1)); + // A walk that panics, in debug and release builds alike, gives `Degenerate`. + let panicking = |_: &Multi| -> bool { panic!("degenerate walk") }; + assert_eq!(contours(&arrangement.top, panicking).err(), Some(GeomError::Degenerate)); + } + /// The regions with their sources and areas rounded to 1e-6, sorted. fn summary(regions: &[Region]) -> Vec<(Vec, f64)> { let mut v: Vec<(Vec, f64)> = regions.iter().map(|r| (r.sources.clone(), (r.area * 1e6).round() / 1e6)).collect(); @@ -1026,6 +1087,58 @@ mod tests { top.contours(|w| *w != 0).contours().map(|c| c.path.area()).sum::().abs() } + #[test] + fn sweep_past_its_work_limit_is_degenerate() { + let shapes = vec![fill(Circle::new((50.0, 50.0), 40.0).to_path(0.01)); 20]; + assert_eq!(Arrangement::new(&shapes, &[], DEFAULT_SLIVER, 1_000, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate)); + assert_eq!(regions(&shapes, &[]).unwrap().len(), 1); + } + + #[test] + fn regions_with_limits_takes_the_callers_limits() { + let shapes = vec![fill(Circle::new((50.0, 50.0), 40.0).to_path(0.01)); 20]; + let limited = |work, units| regions_with_limits(&shapes, &[], DEFAULT_SLIVER, work, units); + assert_eq!(limited(1_000, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate)); + assert_eq!(limited(DEFAULT_MAX_SWEEP_WORK, 10).err(), Some(GeomError::Degenerate)); + assert_eq!(limited(DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap().len(), 1); + } + + // 1,100 overlapping shapes made only of horizontal edges at one height. The sweep makes one + // output segment for each run of coincident horizontal pieces and none for a run whose winding + // numbers cancel, as every run does here, so the topology stays under + // DEFAULT_MAX_TOPOLOGY_UNITS. + #[test] + fn coincident_horizontal_edges_stay_under_the_output_limit() { + let n = 1_100; + let shapes: Vec = (0..n) + .map(|i| { + let i = f64::from(i); + let mut path = BezPath::new(); + path.move_to((i, 0.0)); + path.line_to((2.0 * f64::from(n) + i, 0.0)); + path.close_path(); + fill(path) + }) + .collect(); + assert_eq!(regions(&shapes, &[]), Ok(vec![])); + } + + // 200 squares, each one unit down and right of the one before, cross each other's edges and + // make fewer than 2,000,000 output segments, but the winding numbers of those segments hold an + // entry for each square that covers them, which passes DEFAULT_MAX_TOPOLOGY_UNITS. The sweep + // has no work limit here, so the output limit stops it. + #[test] + fn winding_entries_count_toward_the_output_limit() { + let k = 200; + let shapes: Vec = (0..k) + .map(|i| { + let i = f64::from(i); + fill(rect(i, i, f64::from(k) + i, f64::from(k) + i)) + }) + .collect(); + assert_eq!(Arrangement::new(&shapes, &[], DEFAULT_SLIVER, u64::MAX, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate)); + } + #[test] fn stacked_boxes_fold_into_one_group_past_the_comparison_budget() { // Boxes one above the other, all sharing x 0–10: each stays open for every later one. @@ -1034,6 +1147,33 @@ mod tests { assert_eq!(overlap_groups(&stack(4_000)).len(), 1, "8 million comparisons: folded"); } + /// A segment's clockwise side holds the same winding as the previous segment's + /// counter-clockwise side, and the two sides share one stored list instead of two copies. + #[test] + fn neighboring_sides_share_one_winding_list() { + // Eight squares that all cross each other. + let shapes: Vec = (0..8) + .map(|i| { + let i = i as f64; + fill(rect(i, i + 0.25, i + 8.0, i + 8.25)) + }) + .collect(); + let a = Arrangement::new(&shapes, &[], DEFAULT_SLIVER, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap(); + let mut sides = 0; + let mut lists = std::collections::HashSet::new(); + for s in a.top.segment_indices() { + let h = s.first_half(); + for w in [a.top.winding_clockwise(h), a.top.winding_counter_clockwise(h)] { + if !w.0.is_empty() { + sides += 1; + lists.insert(w.0.as_ptr().addr()); + } + } + } + assert!(sides > 100, "{sides} sides"); + assert!(lists.len() * 3 <= sides * 2, "{} lists for {sides} sides", lists.len()); + } + /// One open cubic per path, from `p0` to `p3` through the two handles. fn cubic(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64), p3: (f64, f64)) -> BezPath { let mut bp = BezPath::new(); diff --git a/crates/prepress/src/flatten/mod.rs b/crates/prepress/src/flatten/mod.rs index 2a657a6701..7755eb0fe9 100644 --- a/crates/prepress/src/flatten/mod.rs +++ b/crates/prepress/src/flatten/mod.rs @@ -14,12 +14,16 @@ use kurbo::{Affine, BezPath, Point, Rect}; use crate::ink::{InkColor, InkId, InkSet, Overprint}; -pub use compose::{ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, Flattened, flatten}; +pub use compose::{ + ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, FlattenSweepLimits, Flattened, flatten, + flatten_with_limits, +}; pub use document::{ - FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_progress, + FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_limits, + flatten_document_with_limits_and_progress, flatten_document_with_progress, }; pub use geom::FillRule; -pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page}; +pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page, flatten_page_with_limits}; mod compose; mod document; diff --git a/crates/prepress/src/flatten/pdf.rs b/crates/prepress/src/flatten/pdf.rs index 229c7c955f..f908478bb9 100644 --- a/crates/prepress/src/flatten/pdf.rs +++ b/crates/prepress/src/flatten/pdf.rs @@ -43,6 +43,8 @@ use craft_pdf::{OpenError, open_slice}; use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke, StrokeOpts}; use super::font::FontCache; +#[cfg(test)] +use super::geom; use super::shade::{self, Canvas, StopInks}; use super::{ BlendMode, DisplayList, FillItem, FillRule, GradientGeometry, GroupItem, ImageItem, ImageSpace, Item, Mask, MaskKind, Paint, PlacedGlyph, @@ -170,7 +172,7 @@ pub enum ReadError { pub fn read_page(pdf: &[u8], page: usize, opts: &ReadOptions) -> Result<(DisplayList, ReadReport), ReadError> { let doc = open_slice(pdf, None)?; let color = read_color(&doc, page, &opts.fallback)?; - read_page_in(&doc, page, opts, color) + read_page_in(&doc, page, opts, color, &super::FlattenSweepLimits::default()) } /// How a page's process color converts: its output intent's simulation, else `fallback`'s. @@ -189,7 +191,13 @@ pub(crate) fn read_color(doc: &Pdf, page: usize, fallback: &Fallback) -> Result< } /// [`read_page`] of an open document, with the page's color already read. -pub(crate) fn read_page_in(doc: &Pdf, page: usize, opts: &ReadOptions, color: ReadColor) -> Result<(DisplayList, ReadReport), ReadError> { +pub(crate) fn read_page_in( + doc: &Pdf, + page: usize, + opts: &ReadOptions, + color: ReadColor, + limits: &super::FlattenSweepLimits, +) -> Result<(DisplayList, ReadReport), ReadError> { let (simulation, conversion) = color; let pages = doc.pages(); let p = pages.get(page).ok_or(ReadError::NoPage(page))?; @@ -220,6 +228,7 @@ pub(crate) fn read_page_in(doc: &Pdf, page: usize, opts: &ReadOptions, color: Re masks: HashMap::new(), fonts: FontCache::new(), scale: f64::from(dpi) / 72.0, + sweep_limits: *limits, }; let items = catch_unwind(AssertUnwindSafe(|| { @@ -260,6 +269,7 @@ struct Shared { fonts: FontCache, /// Raster pixels per point. scale: f64, + sweep_limits: super::FlattenSweepLimits, } /// How a paint composites: what wraps it in a group of its own. @@ -344,6 +354,11 @@ fn clip_group((clip, rule): (BezPath, FillRule)) -> GroupItem { } impl<'s, 'a> Reader<'s, 'a> { + fn nonzero(&self, path: &BezPath, rule: FillRule) -> (BezPath, FillRule) { + let limits = self.shared.sweep_limits; + nonzero_within(path, rule, limits.max_sweep_work, limits.max_sweep_units) + } + fn new(shared: &'s mut Shared, glyph: bool, bounds: Rect) -> Self { Self { shared, @@ -621,7 +636,7 @@ impl<'s, 'a> Reader<'s, 'a> { fn area_fill(&mut self, path: BezPath, rule: FillRule, paint: &PdfPaint<'a>, stroke: bool) { let PdfPaint::Pattern(pattern) = paint else { return }; self.flush(); - let (clip, rule) = nonzero(&path, rule); + let (clip, rule) = self.nonzero(&path, rule); let (op, big_op, _) = self.overprint; let flag = if stroke { big_op } else { op }; match pattern.as_ref() { @@ -975,7 +990,7 @@ impl<'s, 'a> Reader<'s, 'a> { let mut outline = BezPath::new(); for item in &items { if let Item::Fill(f) = item { - let (path, rule) = nonzero(&f.path, f.rule); + let (path, rule) = self.nonzero(&f.path, f.rule); if rule != FillRule::NonZero { return None; } @@ -1016,7 +1031,7 @@ impl<'a> Device<'a> for Reader<'_, 'a> { fn push_clip_path(&mut self, clip_path: &ClipPath) { self.flush(); - let clip = nonzero(&clip_path.path, fill_rule(clip_path.fill)); + let clip = self.nonzero(&clip_path.path, fill_rule(clip_path.fill)); self.frames.push(Frame { kind: FrameKind::Clip, group: clip_group(clip) }); } @@ -1317,22 +1332,35 @@ fn dash_pattern(path: &BezPath, dashes: &[f32]) -> Option> { } /// `path` filled by `rule`, as a path and the rule it is filled by. An even-odd path is -/// rebuilt from its boundary as a path filled nonzero; if that fails it is kept closed and -/// filled even-odd. +/// rebuilt from its boundary as a path filled nonzero; if that fails, panics, or passes the +/// flattener's default sweep work or output limit ([`geom::DEFAULT_MAX_SWEEP_WORK`], +/// [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]), it is kept closed and filled even-odd. The same fallback +/// applies when an input subpath fails [`linesweeper::binary_op`]'s automatic-accuracy check. +#[cfg(test)] fn nonzero(path: &BezPath, rule: FillRule) -> (BezPath, FillRule) { + nonzero_within(path, rule, geom::DEFAULT_MAX_SWEEP_WORK, geom::DEFAULT_MAX_TOPOLOGY_UNITS) +} + +/// Rebuilds an even-odd path with the sweep stopped after `work_limit` units of work or before +/// its topology holds more than `output_limit` units. A stopped rebuild keeps the original rule. +fn nonzero_within(path: &BezPath, rule: FillRule, work_limit: u64, output_limit: usize) -> (BezPath, FillRule) { if rule == FillRule::NonZero { return (path.clone(), FillRule::NonZero); } let closed = closed(path); - match linesweeper::binary_op(&closed, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union) { - Ok(contours) => { + let op = catch_unwind(AssertUnwindSafe(|| { + let top = linesweeper::topology::Topology::::from_paths_with_automatic_limits([(&closed, ())], work_limit, output_limit)?; + top.try_contours(|winding| winding % 2 != 0) + })); + match op { + Ok(Ok(contours)) => { let mut out = BezPath::new(); for contour in contours.contours() { out.extend(contour.path.iter()); } (out, FillRule::NonZero) } - Err(_) => (closed, FillRule::EvenOdd), + Ok(Err(_)) | Err(_) => (closed, FillRule::EvenOdd), } } @@ -1363,6 +1391,119 @@ fn closed(path: &BezPath) -> BezPath { mod tests { use super::*; + #[test] + fn page_reader_uses_explicit_sweep_limits_for_even_odd_clips() { + use craft_pdf::write::backend::geom::{PathBuilder, Rect as KRect}; + use craft_pdf::write::backend::page::PageSettings; + use craft_pdf::write::backend::paint::{Fill, FillRule as KFillRule}; + use craft_pdf::write::{Metadata, Writer}; + let mut writer = Writer::new(Default::default(), Metadata::default()); + let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(100.0, 100.0).unwrap()); + let mut surface = page.surface(); + let mut clip = PathBuilder::new(); + clip.push_rect(KRect::from_ltrb(0.0, 0.0, 90.0, 90.0).unwrap()); + clip.push_rect(KRect::from_ltrb(20.0, 20.0, 70.0, 70.0).unwrap()); + surface.push_clip_path(&clip.finish().unwrap(), &KFillRule::EvenOdd); + let mut paint = PathBuilder::new(); + paint.push_rect(KRect::from_ltrb(0.0, 0.0, 100.0, 100.0).unwrap()); + surface.set_fill(Some(Fill::default())); + surface.draw_path(&paint.finish().unwrap()); + surface.pop(); + surface.finish(); + page.finish(); + let bytes = writer.finish().unwrap(); + let doc = open_slice(&bytes, None).unwrap(); + let opts = ReadOptions::default(); + for limits in [ + super::super::FlattenSweepLimits::default(), + super::super::FlattenSweepLimits { max_sweep_work: 1, ..Default::default() }, + super::super::FlattenSweepLimits { max_sweep_units: 1, ..Default::default() }, + ] { + let color = read_color(&doc, 0, &opts.fallback).unwrap(); + let (list, _) = read_page_in(&doc, 0, &opts, color, &limits).unwrap(); + let group = list + .items + .iter() + .find_map(|item| match item { + Item::Group(group) if group.clip.is_some() => Some(group), + _ => None, + }) + .unwrap(); + let expected = if limits == super::super::FlattenSweepLimits::default() { FillRule::NonZero } else { FillRule::EvenOdd }; + assert_eq!(group.clip_rule, expected, "{limits:?}"); + let path = group.clip.as_ref().unwrap(); + let filled = |point| match group.clip_rule { + FillRule::NonZero => path.winding(point) != 0, + FillRule::EvenOdd => path.winding(point) % 2 != 0, + }; + assert!(filled((10.0, 10.0).into())); + assert!(!filled((50.0, 50.0).into())); + } + } + + #[test] + fn even_odd_path_with_inconsistent_windings_is_kept() { + // `nonzero` returns a path for this input whether the sweep succeeds or reports + // winding numbers that disagree around a point. + let path = BezPath::from_svg("M4,-1 C8,1 -7,-2 5,8 L-4,-8 L2,1 L1,1 Z").unwrap(); + assert!(!nonzero(&path, FillRule::EvenOdd).0.elements().is_empty()); + } + + #[test] + fn even_odd_holes_stay_open_beside_a_far_point() { + // A square with a hole drawn in the same direction, a 0.3 wide sliver and a triangle at + // 3e13, which makes the sweep tolerance about 0.43. + let mut path = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.0); + path.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.0).iter()); + path.extend(Rect::new(200.0, 0.0, 200.3, 10.0).to_path(0.0).iter()); + path.move_to((3.0e13, 3.0e13)); + path.line_to((3.0e13 + 1.0e3, 3.0e13)); + path.line_to((3.0e13, 3.0e13 + 1.0e3)); + path.close_path(); + // The automatic-accuracy check rejects rebuilding the narrow subpath. + let swept = linesweeper::binary_op(&path, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union); + assert!(matches!(swept, Err(linesweeper::Error::FeatureBelowTolerance { .. }))); + let (out, rule) = nonzero(&path, FillRule::EvenOdd); + let contains = |point| { + let winding = out.winding(point); + match rule { + FillRule::EvenOdd => winding % 2 != 0, + FillRule::NonZero => winding != 0, + } + }; + assert!(contains((200.15, 5.0).into()), "the narrow subpath remains filled"); + assert!(contains((10.0, 10.0).into())); + assert!(!contains((50.0, 50.0).into())); + assert_eq!(rule, FillRule::EvenOdd); + assert_eq!(out, path); + } + + #[test] + fn even_odd_path_past_the_sweep_work_limit_is_kept() { + // 21 stacked copies of one circle: the sweep compares their segments many times over. + let circle = kurbo::Circle::new((50.0, 50.0), 40.0).to_path(0.01); + let mut path = BezPath::new(); + for _ in 0..21 { + path.extend(circle.iter()); + } + let (kept, rule) = nonzero_within(&path, FillRule::EvenOdd, 1_000, geom::DEFAULT_MAX_TOPOLOGY_UNITS); + assert_eq!(kept.elements(), closed(&path).elements()); + assert_eq!(rule, FillRule::EvenOdd); + assert_ne!(nonzero(&path, FillRule::EvenOdd).0.elements(), closed(&path).elements()); + } + + #[test] + fn even_odd_path_past_the_sweep_output_limit_is_kept() { + // A square with a hole drawn in the same direction makes 8 output segments. + let mut path = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.0); + path.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.0).iter()); + let (kept, rule) = nonzero_within(&path, FillRule::EvenOdd, geom::DEFAULT_MAX_SWEEP_WORK, 4); + assert_eq!(kept.elements(), closed(&path).elements()); + assert_eq!(rule, FillRule::EvenOdd); + assert_ne!(kept.winding((50.0, 50.0).into()), 0); + assert_eq!(nonzero(&path, FillRule::EvenOdd).0.winding((50.0, 50.0).into()), 0); + } + #[test] fn even_odd_paths_keep_their_rule_when_the_rebuild_fails() { // Two nested squares drawn in the same direction: even-odd leaves a hole, nonzero fills it. diff --git a/crates/prepress/src/flatten/raster.rs b/crates/prepress/src/flatten/raster.rs index 6ca926d81c..72e9d2075e 100644 --- a/crates/prepress/src/flatten/raster.rs +++ b/crates/prepress/src/flatten/raster.rs @@ -41,7 +41,7 @@ use craft_pdf::interpret::color::CmykConversion; use craft_pdf::write::backend::SerializeSettings; use kurbo::{Affine, Rect, Shape as _}; -use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document}; +use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document_with_limits}; use super::pdf::{ReadError, ReadOptions, ReadReport}; use super::write::{WriteError, page_pdf}; use super::{ @@ -409,11 +409,21 @@ pub enum FlattenPageError { } /// Page `page` (from 0) of `pdf` with its transparency flattened, as a one-page PDF: the -/// one-page case of [`flatten_document`]. +/// one-page case of [`super::flatten_document`]. pub fn flatten_page(pdf: &[u8], page: usize, opts: &FlattenPageOptions) -> Result<(Vec, FlattenPageReport), FlattenPageError> { + flatten_page_with_limits(pdf, page, opts, &super::FlattenSweepLimits::default()) +} + +/// [`flatten_page`] with explicit sweep work and output limits. +pub fn flatten_page_with_limits( + pdf: &[u8], + page: usize, + opts: &FlattenPageOptions, + limits: &super::FlattenSweepLimits, +) -> Result<(Vec, FlattenPageReport), FlattenPageError> { let doc = FlattenDocumentOptions { read: opts.read.clone(), flatten: opts.flatten, pages: Some(page..page.saturating_add(1)), ..Default::default() }; - let (bytes, mut report) = flatten_document(pdf, &doc).map_err(|e| match e { + let (bytes, mut report) = flatten_document_with_limits(pdf, &doc, limits).map_err(|e| match e { FlattenDocumentError::Open(e) => FlattenPageError::Open(e), FlattenDocumentError::PageRange { .. } => FlattenPageError::Read(ReadError::NoPage(page)), FlattenDocumentError::Read { source, .. } => FlattenPageError::Read(source), diff --git a/crates/prepress/src/plates.rs b/crates/prepress/src/plates.rs index 0a5d1ed8f5..330bf3bd12 100644 --- a/crates/prepress/src/plates.rs +++ b/crates/prepress/src/plates.rs @@ -171,7 +171,7 @@ pub enum Error { pub fn plates(pdf: &[u8], page: usize, dpi: f32, opts: &Options) -> Result { let mut whole = None; // One band of the whole page: `plate_scale` keeps it within `MAX_PLATE_PIXELS`. - separate(pdf, page, dpi, opts, plate_scale, Some(u32::MAX), &mut |band: Band| { + separate(pdf, page, dpi, opts, plate_scale, BandLimit { pixels: MAX_PLATE_PIXELS, rows: Some(u32::MAX) }, &mut |band: Band| { whole = Some(band.plates); ControlFlow::Break(()) })?; @@ -198,7 +198,7 @@ pub struct Band { /// `each` gets the bands in order and returns [`ControlFlow::Break`] to stop. Each band renders /// the page again, clipped to its rows. Never panics. pub fn plates_in_bands(pdf: &[u8], page: usize, dpi: f32, opts: &Options, mut each: impl FnMut(Band) -> ControlFlow<()>) -> Result<(), Error> { - separate(pdf, page, dpi, opts, banded_scale, None, &mut each) + separate(pdf, page, dpi, opts, banded_scale, BandLimit { pixels: MAX_PLATE_PIXELS, rows: None }, &mut each) } /// The printing condition page `page` (from 0) of `pdf` separates through with `opts`: the CMYK @@ -221,15 +221,19 @@ pub fn press_profile(pdf: &[u8], page: usize, opts: &Options) -> Result, +} + +/// Separates at `scale_of`'s scale, in the requested rows or as many as fit the plate limit. fn separate( pdf: &[u8], page: usize, dpi: f32, opts: &Options, - scale_of: fn(f32, f32, f32) -> f32, - rows: Option, + scale_of: impl Fn(f32, f32, f32) -> f32, + limit: BandLimit, each: &mut dyn FnMut(Band) -> ControlFlow<()>, ) -> Result<(), Error> { if !dpi.is_finite() || dpi <= 0.0 { @@ -249,16 +253,16 @@ fn separate( let scale = scale_of(w, h, dpi / 72.0); let cache = RenderCache::new(); // Inks are found on a small render of the whole page, within the renderer's limits. - let (inks, separated, unseparated) = discover(p, &cache, plate_scale(w, h, DISCOVERY_SCALE.min(scale)))?; + let (inks, separated, unseparated) = discover(p, &cache, plate_scale_within(w, h, DISCOVERY_SCALE.min(scale), limit.pixels))?; // The page's size in pixels, as the renderer floors it. Only each band's viewport goes to // the renderer, so the page itself may pass the renderer's own size limits. let [width, page_height] = [w, h].map(|side| (side * scale).floor().max(1.0) as u32); // A band is within the plate cap and, like any render, the renderer's side limit. - let fit = (MAX_PLATE_PIXELS / width as f32).floor().clamp(1.0, MAX_SIDE as f32) as u32; + let fit = (limit.pixels / width as f32).floor().clamp(1.0, MAX_SIDE as f32) as u32; if u64::from(width) * u64::from(page_height) > MAX_BANDED_PIXELS as u64 { return Err(Error::Render(raster::Error::OutputLimit)); } - let rows = rows.unwrap_or(fit).clamp(1, page_height); + let rows = limit.rows.unwrap_or(fit).clamp(1, page_height); let mut top = 0; while top < page_height { let height = rows.min(page_height - top); @@ -337,8 +341,12 @@ fn banded_scale(w: f32, h: f32, scale: f32) -> f32 { /// The scale a `w` × `h` pt page separates at: `scale`, within [`MAX_PLATE_PIXELS`] and /// [`MAX_SIDE`]. fn plate_scale(w: f32, h: f32, scale: f32) -> f32 { + plate_scale_within(w, h, scale, MAX_PLATE_PIXELS) +} + +fn plate_scale_within(w: f32, h: f32, scale: f32, max_pixels: f32) -> f32 { let (w, h) = (w.max(1.0), h.max(1.0)); - let by_area = (MAX_PLATE_PIXELS / (w * h)).sqrt(); + let by_area = (max_pixels / (w * h)).sqrt(); let by_side = MAX_SIDE as f32 / w.max(h); let s = scale.min(by_area).min(by_side); if s.is_finite() && s > 0.0 { s } else { f32::MIN_POSITIVE } @@ -513,7 +521,7 @@ endstream endobj assert_eq!((whole.width, whole.height, whole.planes.len()), (120, 120, 5)); let mut joined = vec![Vec::new(); 5]; let mut tops = Vec::new(); - separate(&pdf, 0, 216.0, &Options::default(), plate_scale, Some(7), &mut |band: Band| { + separate(&pdf, 0, 216.0, &Options::default(), plate_scale, BandLimit { pixels: MAX_PLATE_PIXELS, rows: Some(7) }, &mut |band: Band| { assert_eq!((band.plates.width, band.page_height, band.plates.inks.len()), (120, 120, 5)); tops.push((band.top, band.plates.height)); for (plane, part) in joined.iter_mut().zip(&band.plates.planes) { @@ -531,30 +539,58 @@ endstream endobj #[test] fn bands_reach_resolutions_past_the_plate_cap_and_can_stop() { let pdf = disc_and_spot(); - // 40 pt at 3700 dpi is 2055 pixels a side: 4.2 MP, past `MAX_PLATE_PIXELS`. - // (The whole-page entry point reduces by `plate_scale`; the bands below are not reduced.) + // The public whole-page limit still reduces a production-sized request without rendering it. assert!(plate_scale(40.0, 40.0, 3700.0 / 72.0) < 3700.0 / 72.0); + let cap = 40_000.0; + assert_eq!(MAX_PLATE_PIXELS, 4_000_000.0); + // Exactly N pixels keep their scale; N + 1 must reduce it before dimensions floor. + assert_eq!(plate_scale_within(200.0, 200.0, 1.0, cap), 1.0); + assert!(plate_scale_within(13.0, 3077.0, 1.0, cap) < 1.0); + + // 40 pt at 370 dpi is 205 pixels a side, past the small plate cap. + let mut whole = None; + separate( + &pdf, + 0, + 370.0, + &Options::default(), + |w, h, scale| plate_scale_within(w, h, scale, cap), + BandLimit { pixels: cap, rows: Some(u32::MAX) }, + &mut |band: Band| { + whole = Some(band.plates); + ControlFlow::Break(()) + }, + ) + .unwrap(); + let whole = whole.unwrap(); + assert!(whole.dpi < 370.0); + assert!((whole.dpi - 360.0).abs() < 0.01); + assert_eq!((whole.width, whole.height), (200, 200)); let mut bands = Vec::new(); - plates_in_bands(&pdf, 0, 3700.0, &Options::default(), |band| { + separate(&pdf, 0, 370.0, &Options::default(), banded_scale, BandLimit { pixels: cap, rows: None }, &mut |band| { let p = &band.plates; - assert!((p.width * p.height) as f32 <= MAX_PLATE_PIXELS); + assert!((p.width * p.height) as f32 <= cap); bands.push((band.top, p.height, p.width, p.dpi, band.page_height)); ControlFlow::Continue(()) }) .unwrap(); let &(_, _, width, dpi, page_height) = bands.first().unwrap(); - assert_eq!((width, page_height), (2055, 2055)); - assert!((dpi - 3700.0).abs() < 0.01); - assert_eq!(bands.iter().map(|b| b.1).sum::(), 2055); + assert_eq!((width, page_height), (205, 205)); + assert!((dpi - 370.0).abs() < 0.01); + assert_eq!(bands.iter().map(|b| b.1).sum::(), 205); + assert_eq!(bands.iter().map(|b| (b.0, b.1)).collect::>(), [(0, 195), (195, 10)]); let mut seen = 0; - plates_in_bands(&pdf, 0, 3700.0, &Options::default(), |_| { + separate(&pdf, 0, 370.0, &Options::default(), banded_scale, BandLimit { pixels: cap, rows: None }, &mut |_| { seen += 1; ControlFlow::Break(()) }) .unwrap(); assert_eq!(seen, 1); - assert!(matches!(plates_in_bands(&pdf, 0, f32::NAN, &Options::default(), |_| ControlFlow::Continue(())), Err(Error::InvalidDpi))); + assert!(matches!( + separate(&pdf, 0, f32::NAN, &Options::default(), banded_scale, BandLimit { pixels: cap, rows: None }, &mut |_| ControlFlow::Continue(()),), + Err(Error::InvalidDpi) + )); } /// A 10 × 2000 pt strip, black only in its bottom 10 pt. diff --git a/crates/prepress/tests/flatten_document.rs b/crates/prepress/tests/flatten_document.rs index cd9d14c8df..8cb685f227 100644 --- a/crates/prepress/tests/flatten_document.rs +++ b/crates/prepress/tests/flatten_document.rs @@ -117,6 +117,41 @@ fn opts() -> FlattenDocumentOptions { FlattenDocumentOptions { flatten: FlattenOptions { raster_dpi: 72.0, ..FlattenOptions::default() }, ..FlattenDocumentOptions::default() } } +#[test] +fn pdf_entry_points_keep_explicit_sweep_limits() { + use craft_prepress::flatten::{ + FlattenSweepLimits, flatten_document_with_limits, flatten_document_with_limits_and_progress, flatten_page_with_limits, + }; + let settings = SerializeSettings { no_device_cs: false, group_color_space: GroupColorSpace::Cmyk, ..Default::default() }; + let mut writer = Writer::new(settings, Metadata::default()); + let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(200.0, 160.0).unwrap()); + let mut surface = page.surface(); + rect(&mut surface, 20.0, 20.0, 120.0, 100.0, fill(255, 0, 0, 0)); + surface.push_opacity(NormalizedF32::new(0.5).unwrap()); + rect(&mut surface, 70.0, 60.0, 170.0, 130.0, fill(0, 255, 0, 0)); + surface.pop(); + surface.finish(); + page.finish(); + let source = writer.finish().unwrap(); + let options = opts(); + let (_, ordinary) = flatten_document(&source, &options).unwrap(); + assert_eq!(ordinary.totals.complex_groups, 0); + for limits in [FlattenSweepLimits { max_sweep_work: 1, ..Default::default() }, FlattenSweepLimits { max_sweep_units: 1, ..Default::default() }] { + let (_, document) = flatten_document_with_limits(&source, &options, &limits).unwrap(); + assert_eq!(document.totals.complex_groups, 1); + let mut progress = Vec::new(); + let (_, observed) = flatten_document_with_limits_and_progress(&source, &options, &limits, &mut |done, total| { + progress.push((done, total)); + }) + .unwrap(); + assert_eq!(observed, document); + assert_eq!(progress, [(1, 1)]); + let page_options = FlattenPageOptions { flatten: options.flatten, ..Default::default() }; + let (_, page) = flatten_page_with_limits(&source, 0, &page_options, &limits).unwrap(); + assert_eq!(page.flatten.complex_groups.len(), 1); + } +} + fn separate(pdf: &[u8], page: usize) -> Plates { plates(pdf, page, DPI, &Options::default()).unwrap() } diff --git a/crates/print/src/cups/mod.rs b/crates/print/src/cups/mod.rs index 970745d5aa..c6a1646fc3 100644 --- a/crates/print/src/cups/mod.rs +++ b/crates/print/src/cups/mod.rs @@ -212,7 +212,19 @@ enum Stream { Tcp(TcpStream), } -impl Stream { +/// A connection a [`DeadlineReader`] drives: before each read and write it is given the time +/// left as its timeout. +trait Connection: Read + Write { + fn set_timeouts(&self, timeout: Duration) -> std::io::Result<()>; + + /// One read after [`Self::set_timeouts`] failed with `error`: by default that error. + fn read_without_timeout(&mut self, error: std::io::Error, buf: &mut [u8]) -> std::io::Result { + let _ = buf; + Err(error) + } +} + +impl Connection for Stream { fn set_timeouts(&self, timeout: Duration) -> std::io::Result<()> { let (read, write) = match self { #[cfg(unix)] @@ -221,6 +233,23 @@ impl Stream { }; read.and(write) } + + #[cfg(target_os = "macos")] + fn read_without_timeout(&mut self, error: std::io::Error, buf: &mut [u8]) -> std::io::Result { + // Darwin rejects timeout updates on a disconnected Unix socket even + // when a complete reply is still buffered. Never fall back to a + // blocking read: drain at most this buffer, or fail on WouldBlock. + // Every subsequent read rechecks the same absolute deadline. + if error.raw_os_error() == Some(22) + && let Stream::Unix(stream) = self + { + stream.set_nonblocking(true)?; + let result = stream.read(buf); + let restored = stream.set_nonblocking(false); + return result.and_then(|count| restored.map(|()| count)); + } + Err(error) + } } impl Read for Stream { @@ -511,7 +540,7 @@ pub(crate) fn post(endpoints: &[Server], path: &str, body: &[u8], timeout: Durat /// Send one IPP request and read the reply's body. fn exchange(stream: &mut Stream, authority: &str, path: &str, body: &[u8], timeout: Duration) -> Result, Error> { - let mut stream = DeadlineReader { stream, end: Instant::now() + timeout }; + let mut stream = DeadlineReader { stream, end: Instant::now() + timeout, now: &Instant::now }; let head = format!( "POST {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() @@ -526,16 +555,18 @@ fn exchange(stream: &mut Stream, authority: &str, path: &str, body: &[u8], timeo Ok(reply) } -/// One absolute deadline shared by request writes and reply reads after connection. -struct DeadlineReader<'a> { - stream: &'a mut Stream, +/// One absolute deadline shared by request writes and reply reads after connection, kept +/// against the time `now` reads. +struct DeadlineReader<'a, S = Stream> { + stream: &'a mut S, end: Instant, + now: &'a dyn Fn() -> Instant, } -impl Write for DeadlineReader<'_> { +impl Write for DeadlineReader<'_, S> { fn write(&mut self, buf: &[u8]) -> std::io::Result { let left = self .end - .checked_duration_since(Instant::now()) + .checked_duration_since((self.now)()) .filter(|d| !d.is_zero()) .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "CUPS exchange deadline exceeded"))?; self.stream.set_timeouts(left)?; @@ -553,30 +584,15 @@ fn validate_reply_identity(request: &[u8], reply: &[u8]) -> Result<(), Error> { Ok(()) } -impl Read for DeadlineReader<'_> { +impl Read for DeadlineReader<'_, S> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let left = self .end - .checked_duration_since(Instant::now()) + .checked_duration_since((self.now)()) .filter(|d| !d.is_zero()) .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "CUPS reply deadline exceeded"))?; - #[cfg(not(target_os = "macos"))] - self.stream.set_timeouts(left)?; - #[cfg(target_os = "macos")] if let Err(error) = self.stream.set_timeouts(left) { - // Darwin rejects timeout updates on a disconnected Unix socket even - // when a complete reply is still buffered. Never fall back to a - // blocking read: drain at most this buffer, or fail on WouldBlock. - // Every subsequent read rechecks the same absolute deadline above. - if error.raw_os_error() == Some(22) - && let Stream::Unix(stream) = self.stream - { - stream.set_nonblocking(true)?; - let result = stream.read(buf); - let restored = stream.set_nonblocking(false); - return result.and_then(|count| restored.map(|()| count)); - } - return Err(error); + return self.stream.read_without_timeout(error, buf); } self.stream.read(buf) } diff --git a/crates/print/src/cups/tests.rs b/crates/print/src/cups/tests.rs index e7df135bf3..3fceca3ded 100644 --- a/crates/print/src/cups/tests.rs +++ b/crates/print/src/cups/tests.rs @@ -5,11 +5,14 @@ use super::*; use crate as spool; use crate::cups::{self as ipp, Server}; use craft_ui::testing::trial; +use std::cell::{Cell, RefCell}; use std::collections::VecDeque; use std::io::{Read, Write}; -use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver}; -use std::time::Duration; +use std::sync::{Arc, Mutex}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; const TIMEOUT: Duration = Duration::from_secs(2); @@ -19,6 +22,8 @@ const TIMEOUT: Duration = Duration::from_secs(2); struct FakeCups { server: Server, requests: Receiver>, + stopping: Arc, + listener: JoinHandle<()>, } impl FakeCups { @@ -28,15 +33,17 @@ impl FakeCups { let listener = std::os::unix::net::UnixListener::bind(&path)?; // The socket must outlive this function; the folder is left for the process to reap. std::mem::forget(dir); - let requests = listen_unix(listener, replies); - Ok(FakeCups { server: Server::Unix(path), requests }) + let stopping = Arc::new(AtomicBool::new(false)); + let (requests, listener) = listen_unix(listener, replies, stopping.clone()); + Ok(FakeCups { server: Server::Unix(path), requests, stopping, listener }) } fn on_tcp(replies: Vec>) -> std::io::Result { let listener = std::net::TcpListener::bind("127.0.0.1:0")?; let server = Server::Tcp(listener.local_addr()?); - let requests = listen_tcp(listener, replies); - Ok(FakeCups { server, requests }) + let stopping = Arc::new(AtomicBool::new(false)); + let (requests, listener) = listen_tcp(listener, replies, stopping.clone()); + Ok(FakeCups { server, requests, stopping, listener }) } fn request(&self) -> Result, mpsc::RecvTimeoutError> { @@ -47,28 +54,44 @@ impl FakeCups { fn endpoint(&self) -> &[Server] { std::slice::from_ref(&self.server) } + + /// Stops the server once it has served every connection made before this call, and returns + /// the requests it recorded: the channel is closed after the last of them. + fn stop(self) -> Receiver> { + self.stopping.store(true, Ordering::SeqCst); + // A connection of its own wakes the listener; it carries no request. + let _ = super::connect(&self.server); + self.listener.join().unwrap(); + self.requests + } } -fn listen_unix(listener: std::os::unix::net::UnixListener, replies: Vec>) -> Receiver> { +fn listen_unix(listener: std::os::unix::net::UnixListener, replies: Vec>, stopping: Arc) -> (Receiver>, JoinHandle<()>) { let (tx, rx) = mpsc::channel(); let replies = Mutex::new(VecDeque::from(replies)); - std::thread::spawn(move || { + let listening = std::thread::spawn(move || { for stream in listener.incoming().flatten() { serve(stream, &replies, &tx); + if stopping.load(Ordering::SeqCst) { + break; + } } }); - rx + (rx, listening) } -fn listen_tcp(listener: std::net::TcpListener, replies: Vec>) -> Receiver> { +fn listen_tcp(listener: std::net::TcpListener, replies: Vec>, stopping: Arc) -> (Receiver>, JoinHandle<()>) { let (tx, rx) = mpsc::channel(); let replies = Mutex::new(VecDeque::from(replies)); - std::thread::spawn(move || { + let listening = std::thread::spawn(move || { for stream in listener.incoming().flatten() { serve(stream, &replies, &tx); + if stopping.load(Ordering::SeqCst) { + break; + } } }); - rx + (rx, listening) } fn serve(mut stream: impl Read + Write, replies: &Mutex>>, requests: &mpsc::Sender>) { @@ -399,7 +422,8 @@ fn uncertain_submission_never_tries_the_second_endpoint() { let destination = super::Destination { name: "Studio".into(), is_class: false }; assert!(super::submit_at(&[first.server.clone(), second.server.clone()], &destination, b"pdf", &Job::default()).is_err()); let _ = first.request().unwrap(); - assert!(second.requests.recv_timeout(Duration::from_millis(100)).is_err()); + // Every connection the client made has been served once the second server stops. + assert!(matches!(second.stop().try_recv(), Err(mpsc::TryRecvError::Disconnected)), "the second endpoint got no request"); } #[trial] @@ -440,34 +464,62 @@ fn reply_identity_and_metadata_request_are_checked() { assert!(super::validate_reply_identity(&request, &reply).is_err()); } +/// A peer that trickles: each read gives one byte and each write takes one, and each takes 20 ms +/// on the clock `now` holds. It records every timeout it is given. +struct Trickle<'a> { + now: &'a Cell, + timeouts: RefCell>, +} + +impl Trickle<'_> { + fn step(&self) -> usize { + self.now.set(self.now.get() + Duration::from_millis(20)); + 1 + } +} + +impl Read for Trickle<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let Some(first) = buf.first_mut() else { return Ok(0) }; + *first = b'x'; + Ok(self.step()) + } +} + +impl Write for Trickle<'_> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if buf.is_empty() { Ok(0) } else { Ok(self.step()) } + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl super::Connection for Trickle<'_> { + fn set_timeouts(&self, timeout: Duration) -> std::io::Result<()> { + self.timeouts.borrow_mut().push(timeout); + Ok(()) + } +} + #[trial] fn slow_reply_cannot_reset_the_absolute_deadline() { - let (client, mut peer) = std::os::unix::net::UnixStream::pair().unwrap(); - let producer = std::thread::spawn(move || { - // Finite work and a joined handle: no abandoned timeout worker. - for _ in 0..20 { - if peer.write_all(b"x").is_err() { - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - }); - let start = std::time::Instant::now(); - let mut stream = super::Stream::Unix(client); - let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let start = Instant::now(); + let now = Cell::new(start); + let mut peer = Trickle { now: &now, timeouts: RefCell::default() }; + let mut reader = super::DeadlineReader { stream: &mut peer, end: start + Duration::from_millis(80), now: &|| now.get() }; let mut bytes = [0; 20]; - assert!(reader.read_exact(&mut bytes).is_err(), "trickle reads must not extend the absolute deadline"); - drop(stream); - producer.join().unwrap(); - assert!(start.elapsed() < Duration::from_secs(3)); + let error = reader.read_exact(&mut bytes).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::TimedOut, "trickle reads must not extend the absolute deadline"); + assert_eq!(*peer.timeouts.borrow(), [80, 60, 40, 20].map(Duration::from_millis), "each read gets only the time left"); } #[trial] fn blocked_upload_obeys_the_same_absolute_deadline() { - let (client, _peer) = std::os::unix::net::UnixStream::pair().unwrap(); - let start = std::time::Instant::now(); - let mut stream = super::Stream::Unix(client); - let mut writer = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let start = Instant::now(); + let now = Cell::new(start); + let mut peer = Trickle { now: &now, timeouts: RefCell::default() }; + let mut writer = super::DeadlineReader { stream: &mut peer, end: start + Duration::from_millis(80), now: &|| now.get() }; let chunk = [0u8; 64 * 1024]; let mut timed_out = false; // A peer that never drains cannot turn each partial write into a fresh timeout budget. @@ -478,7 +530,7 @@ fn blocked_upload_obeys_the_same_absolute_deadline() { } } assert!(timed_out, "blocked upload must terminate without a reader"); - assert!(start.elapsed() < Duration::from_secs(3)); + assert_eq!(*peer.timeouts.borrow(), [80, 60, 40, 20].map(Duration::from_millis), "each partial write gets only the time left"); } #[trial] @@ -573,24 +625,28 @@ fn closed_unix_peer_keeps_its_buffered_reply_readable_with_a_deadline() { peer.write_all(&http_reply(&body)).unwrap(); drop(peer); let mut stream = super::Stream::Unix(client); - let mut reader = super::DeadlineReader { stream: &mut stream, end: std::time::Instant::now() + Duration::from_secs(1) }; + let start = Instant::now(); + let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_secs(1), now: &|| start }; assert_eq!(super::read_reply(&mut reader).unwrap(), body); let mut byte = [0]; assert_eq!(reader.read(&mut byte).unwrap(), 0); - reader.end = std::time::Instant::now(); + reader.end = start; assert_eq!(reader.read(&mut byte).unwrap_err().kind(), std::io::ErrorKind::TimedOut); } +/// The read waits on the socket for the time left, then fails: the deadline is the socket's +/// timeout, never a blocking read. #[trial] fn stalled_unix_peer_still_fails_within_the_absolute_read_deadline() { let (client, _peer) = std::os::unix::net::UnixStream::pair().unwrap(); - let start = std::time::Instant::now(); + let start = Instant::now(); let mut stream = super::Stream::Unix(client); - let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80), now: &|| start }; let mut byte = [0]; let error = reader.read(&mut byte).unwrap_err(); assert!(matches!(error.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock)); - assert!(start.elapsed() < Duration::from_secs(3)); + let super::Stream::Unix(client) = &stream else { panic!("the stream is the unix socket") }; + assert_eq!(client.read_timeout().unwrap(), Some(Duration::from_millis(80)), "the socket waits only for the time left"); } #[test] diff --git a/crates/print/src/lib.rs b/crates/print/src/lib.rs index c2e2765d76..52ab060cb5 100644 --- a/crates/print/src/lib.rs +++ b/crates/print/src/lib.rs @@ -625,7 +625,7 @@ const DISCOVERY_LIMIT: std::time::Duration = std::time::Duration::from_secs(10); pub fn printers() -> Vec { #[cfg(all(unix, not(target_arch = "wasm32")))] { - printers_via(&mut lpstat_command(), QUEUES_LIMIT, &mut lpstat_e_command(), DISCOVERY_LIMIT) + printers_via(&mut lpstat_command(), QUEUES_LIMIT, &mut lpstat_e_command(), DISCOVERY_LIMIT, &Clock::REAL) } #[cfg(windows)] { @@ -637,18 +637,19 @@ pub fn printers() -> Vec { } } -/// [`printers`] with the two `lpstat` commands and their limits supplied, so tests can stand in a -/// command that hangs. +/// [`printers`] with the two `lpstat` commands, their limits and the clock the limits are kept +/// against supplied, so tests can stand in a command that hangs. #[cfg(all(unix, not(target_arch = "wasm32")))] fn printers_via( queues: &mut std::process::Command, queues_limit: std::time::Duration, available: &mut std::process::Command, available_limit: std::time::Duration, + clock: &Clock<'_>, ) -> Vec { // Exits 1 with only driverless printers ("No destinations added"); `-e` still finds them, so // the exit status isn't checked. - let queues = match output_within(queues, queues_limit) { + let queues = match output_within(queues, queues_limit, clock) { Ok(out) => String::from_utf8_lossy(&out).into_owned(), Err(e) if e.kind() == std::io::ErrorKind::NotFound => { // A Flatpak needs lpstat/lp bundled plus the CUPS socket and Avahi (see README). @@ -662,7 +663,7 @@ fn printers_via( }; // A spooler without `-e`, or one whose discovery doesn't answer in time, only loses the // driverless names. - let available = match output_within(available, available_limit) { + let available = match output_within(available, available_limit, clock) { Ok(out) => Some(String::from_utf8_lossy(&out).into_owned()), Err(e) => { log::info!("lpstat -e gave no driverless printers ({e})"); @@ -676,18 +677,32 @@ fn printers_via( /// output capped, and given `limit` to answer (none when it doesn't). #[cfg(all(unix, not(target_arch = "wasm32")))] fn queue_defaults(command: &mut std::process::Command, limit: std::time::Duration) -> Vec<(String, String)> { - output_within(command, limit).map(|out| parse_lpoptions(&String::from_utf8_lossy(&out))).unwrap_or_default() + output_within(command, limit, &Clock::REAL).map(|out| parse_lpoptions(&String::from_utf8_lossy(&out))).unwrap_or_default() } /// The most of a command's output that is read: far more than any `lpstat` listing. #[cfg(all(unix, not(target_arch = "wasm32")))] const OUTPUT_CAP: u64 = 4 << 20; -/// Run `command` and collect its standard output, giving it `limit`: a command still running -/// then is killed and reaped, and the error is `TimedOut`. Standard input and error are not -/// connected. The exit status is not checked, as `Command::output` leaves it to the caller. +/// The time [`output_within`] keeps a command's limit against (`now`), and how it waits before +/// it checks on the command again (`pause`). #[cfg(all(unix, not(target_arch = "wasm32")))] -fn output_within(command: &mut std::process::Command, limit: std::time::Duration) -> std::io::Result> { +struct Clock<'a> { + now: &'a dyn Fn() -> std::time::Instant, + pause: &'a dyn Fn(), +} + +#[cfg(all(unix, not(target_arch = "wasm32")))] +impl Clock<'static> { + /// The real clock, checking on the command every 10 ms. + const REAL: Clock<'static> = Clock { now: &std::time::Instant::now, pause: &|| std::thread::sleep(std::time::Duration::from_millis(10)) }; +} + +/// Run `command` and collect its standard output, giving it `limit` on `clock`: a command still +/// running then is killed and reaped, and the error is `TimedOut`. Standard input and error are +/// not connected. The exit status is not checked, as `Command::output` leaves it to the caller. +#[cfg(all(unix, not(target_arch = "wasm32")))] +fn output_within(command: &mut std::process::Command, limit: std::time::Duration, clock: &Clock<'_>) -> std::io::Result> { use std::io::Read as _; use std::process::Stdio; let mut child = command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn()?; @@ -717,23 +732,23 @@ fn output_within(command: &mut std::process::Command, limit: std::time::Duration return Err(e); } let timed_out = || std::io::Error::new(std::io::ErrorKind::TimedOut, format!("the command did not answer within {limit:?}")); - let deadline = std::time::Instant::now() + limit; + let deadline = (clock.now)() + limit; loop { match child.try_wait() { Ok(Some(_)) => { // A moment's grace, so output written just before an exit at the deadline counts. - let left = deadline.saturating_duration_since(std::time::Instant::now()).max(std::time::Duration::from_millis(100)); + let left = deadline.saturating_duration_since((clock.now)()).max(std::time::Duration::from_millis(100)); return match rx.recv_timeout(left) { Ok(read) => read, Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(timed_out()), Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(std::io::Error::other("the command's output was lost")), }; } - Ok(None) if std::time::Instant::now() >= deadline => { + Ok(None) if (clock.now)() >= deadline => { stop(&mut child); return Err(timed_out()); } - Ok(None) => std::thread::sleep(std::time::Duration::from_millis(10)), + Ok(None) => (clock.pause)(), Err(e) => { stop(&mut child); return Err(e); diff --git a/crates/print/src/spool_tests.rs b/crates/print/src/spool_tests.rs index 4627f3bc24..9fe23d9b46 100644 --- a/crates/print/src/spool_tests.rs +++ b/crates/print/src/spool_tests.rs @@ -3,12 +3,13 @@ //! process cleanup are the production ones, with no printer. use std::collections::VecDeque; -use std::io::Write; +use std::io::{BufRead, BufReader, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; use craft_host::ManualJobs; use craft_ui::testing::trial; @@ -26,6 +27,8 @@ const PRINT_MODE: &str = "CRAFT_TEST_PRINT_MODE"; /// Set on the child: where it marks the stages it reached, apart from the input folder, which /// the parent removes. const PRINT_MARKS: &str = "CRAFT_TEST_PRINT_MARKS"; +/// Set on the child: the loopback address of the [`Stages`] it reports each stage to. +const PRINT_STAGES: &str = "CRAFT_TEST_PRINT_STAGES"; const PDF: &[u8] = b"synthetic PDF"; /// One prepared job of [`Fake`]: its cancel's answer, whether it answers after a cancel, and the @@ -161,8 +164,16 @@ fn stand_in_print_helper() { let directory = PathBuf::from(directory); let marks = PathBuf::from(std::env::var_os(PRINT_MARKS).unwrap()); let mode = std::env::var(PRINT_MODE).unwrap_or_default(); + let stages = std::env::var(PRINT_STAGES).ok().map(|address| TcpStream::connect(address).unwrap()); + // Each stage is marked in the folder and reported to the parent. + let reached = |stage: &str| { + std::fs::write(marks.join(stage), stage).unwrap(); + if let Some(mut stages) = stages.as_ref() { + writeln!(stages, "{stage}").and_then(|()| stages.flush()).unwrap(); + } + }; if mode == "waking" { - std::fs::write(marks.join("waking"), b"starting").unwrap(); + reached("waking"); loop { std::thread::park(); } @@ -174,7 +185,7 @@ fn stand_in_print_helper() { |pdf, job, _token| { assert_eq!(pdf, PDF); assert_eq!(job.printer.as_deref(), Some("test queue")); - std::fs::write(marks.join("driver"), b"driver entered").unwrap(); + reached("driver"); match mode.as_str() { "held" => { let provider = Mutex::new(()); @@ -185,10 +196,11 @@ fn stand_in_print_helper() { } "crash" => std::process::exit(7), "sending" => { - std::fs::write(marks.join("sending"), b"sending").unwrap(); - while !marks.join("release").exists() { - std::thread::sleep(Duration::from_millis(5)); - } + reached("sending"); + // Sends until the parent releases it. + let mut release = String::new(); + BufReader::new(stages.as_ref().unwrap()).read_line(&mut release).unwrap(); + assert_eq!(release.trim_end(), "release"); Ok("spooled synthetic job".into()) } _ => Ok("spooled synthetic job".into()), @@ -198,14 +210,18 @@ fn stand_in_print_helper() { std::process::exit(i32::from(result.is_err())); } -/// Launches [`stand_in_print_helper`] over `directory` in `mode`, marking its stages in `marks`. -fn helper_command(directory: &Path, marks: &Path, mode: &str, may_be_killed: bool) -> std::io::Result { +/// Launches [`stand_in_print_helper`] over `directory` in `mode`, marking its stages in `marks` +/// and reporting them to `stages` when there is one. +fn helper_command(directory: &Path, marks: &Path, stages: Option, mode: &str, may_be_killed: bool) -> std::io::Result { let mut command = Command::new(std::env::current_exe()?); command .args(["--exact", "spool_tests::stand_in_print_helper", "--nocapture", "--"]) .env(PRINT_DIR, directory) .env(PRINT_MARKS, marks) .env(PRINT_MODE, mode); + if let Some(stages) = stages { + command.env(PRINT_STAGES, stages.to_string()); + } // A force-killed child can leave a partial LLVM profile; keep it in this trial's // temporary directory while normally exiting children retain their coverage. if may_be_killed && std::env::var_os("LLVM_PROFILE_FILE").is_some() { @@ -219,29 +235,69 @@ fn job() -> Job { Job { printer: Some("test queue".into()), ..Job::default() } } -/// Waits until the child has marked `path`, failing after [`LIMIT`]. -fn wait_for(path: &Path) { - let deadline = Instant::now() + LIMIT; - while !path.exists() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(5)); +/// The parent's end of one child's stage reports: the child connects once and sends a line for +/// each stage it reaches, and a child in `sending` waits for a line back. +struct Stages { + address: SocketAddr, + reached: Receiver, + connection: Receiver, +} + +impl Stages { + fn new() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let (report, reached) = channel(); + let (accepted, connection) = channel(); + std::thread::spawn(move || { + let Ok((stream, _)) = listener.accept() else { return }; + if let Ok(writer) = stream.try_clone() { + let _ = accepted.send(writer); + } + for line in BufReader::new(stream).lines() { + let Ok(line) = line else { break }; + if report.send(line).is_err() { + break; + } + } + }); + Stages { address, reached, connection } + } + + /// Waits until the child reports `stage`; [`LIMIT`] only guards against a hang. + fn wait_for(&self, stage: &str) { + loop { + match self.reached.recv_timeout(LIMIT) { + Ok(line) if line == stage => return, + Ok(_) => {} + Err(error) => panic!("the child never reached {stage}: {error}"), + } + } + } + + /// Lets a child in `sending` finish. + fn release(&self) { + let mut connection = self.connection.recv_timeout(LIMIT).unwrap(); + connection.write_all(b"release\n").and_then(|()| connection.flush()).unwrap(); } - assert!(path.exists(), "the child never reached {path:?}"); } /// Runs `submission` on a thread with the child in `mode`; the receiver gets its input folder. fn submit_in( submission: &Submission, marks: &Path, + stages: &Stages, mode: &'static str, may_be_killed: bool, ) -> (std::thread::JoinHandle>, Receiver) { let worker = submission.clone(); let marks = marks.to_path_buf(); + let stages = stages.address; let (folder, folders) = channel(); let running = std::thread::spawn(move || { worker.submit_with(PDF, &job(), |directory| { folder.send(directory.to_path_buf()).unwrap(); - helper_command(directory, &marks, mode, may_be_killed) + helper_command(directory, &marks, Some(stages), mode, may_be_killed) }) }); (running, folders) @@ -271,7 +327,7 @@ fn a_cancel_during_startup_never_starts_the_driver() { worker.submit_with(PDF, &job(), |directory| { started.send(directory.to_path_buf()).unwrap(); wait.recv().unwrap(); - helper_command(directory, &held, "held", true) + helper_command(directory, &held, None, "held", true) }) }); let directory = starting.recv_timeout(LIMIT).unwrap(); @@ -282,9 +338,10 @@ fn a_cancel_during_startup_never_starts_the_driver() { // Cancelled while the child is waking and has not acknowledged anything. let submission = Submission::new(); - let (running, folders) = submit_in(&submission, marks.path(), "waking", true); + let stages = Stages::new(); + let (running, folders) = submit_in(&submission, marks.path(), &stages, "waking", true); let directory = folders.recv_timeout(LIMIT).unwrap(); - wait_for(&marks.path().join("waking")); + stages.wait_for("waking"); assert!(submission.cancel(), "a process without a start grant cannot send anything"); assert_eq!(running.join().unwrap(), Err(CANCELLED.into())); assert!(!directory.exists()); @@ -296,13 +353,14 @@ fn a_cancel_during_startup_never_starts_the_driver() { fn a_refusal_while_sending_keeps_the_job() { let marks = tempfile::tempdir().unwrap(); let submission = Submission::new(); - let (running, folders) = submit_in(&submission, marks.path(), "sending", false); + let stages = Stages::new(); + let (running, folders) = submit_in(&submission, marks.path(), &stages, "sending", false); let directory = folders.recv_timeout(LIMIT).unwrap(); - wait_for(&marks.path().join("sending")); + stages.wait_for("sending"); assert!(!submission.cancel(), "a sending job refuses cancellation"); assert!(!submission.cancel(), "and keeps refusing it"); assert!(!running.is_finished(), "the child is retained until it finishes sending"); - std::fs::write(marks.path().join("release"), b"continue").unwrap(); + stages.release(); assert_eq!(running.join().unwrap(), Ok("spooled synthetic job".into())); assert!(!directory.exists()); } @@ -313,15 +371,16 @@ fn a_refusal_while_sending_keeps_the_job() { fn a_cancelled_driver_does_not_block_the_next_job() { let marks = tempfile::tempdir().unwrap(); let submission = Submission::new(); - let (running, folders) = submit_in(&submission, marks.path(), "held", true); + let stages = Stages::new(); + let (running, folders) = submit_in(&submission, marks.path(), &stages, "held", true); let directory = folders.recv_timeout(LIMIT).unwrap(); - wait_for(&marks.path().join("driver")); + stages.wait_for("driver"); assert!(!directory.join("input.pdf").exists(), "the stalled driver retains no plaintext PDF"); assert!(!directory.join("job.json").exists(), "loaded settings were erased before driver work"); assert!(submission.cancel(), "a stalled driver still acknowledges cancellation"); let next_marks = tempfile::tempdir().unwrap(); let next = Submission::new(); - assert_eq!(next.submit_with(PDF, &job(), |dir| helper_command(dir, next_marks.path(), "ready", false)), Ok("spooled synthetic job".into())); + assert_eq!(next.submit_with(PDF, &job(), |dir| helper_command(dir, next_marks.path(), None, "ready", false)), Ok("spooled synthetic job".into())); assert_eq!(running.join().unwrap(), Err(CANCELLED.into())); assert!(!directory.exists(), "the reaped helper's PDF and settings were removed"); assert!(!next.cancel(), "a completed job keeps its receipt"); @@ -338,7 +397,7 @@ fn helper_crashes_are_errors_and_inputs_are_bounded() { Submission::new() .submit_with(PDF, &job(), |dir| { inputs = Some(dir.to_path_buf()); - helper_command(dir, marks.path(), "crash", false) + helper_command(dir, marks.path(), None, "crash", false) }) .is_err() ); @@ -363,7 +422,8 @@ fn helper_crashes_are_errors_and_inputs_are_bounded() { let folder = tempfile::tempdir().unwrap(); std::fs::write(folder.path().join("job.json"), serde_json::to_vec(&Request::from_job(&job())).unwrap()).unwrap(); std::fs::write(folder.path().join("input.pdf"), PDF).unwrap(); - let mut child = helper_command(folder.path(), marks.path(), "held", false) + let stages = Stages::new(); + let mut child = helper_command(folder.path(), marks.path(), Some(stages.address), "held", false) .unwrap() .stdin(Stdio::piped()) .stdout(Stdio::null()) @@ -372,7 +432,7 @@ fn helper_crashes_are_errors_and_inputs_are_bounded() { .unwrap(); let mut input = child.stdin.take().unwrap(); input.write_all(b"start\n").and_then(|_| input.flush()).unwrap(); - wait_for(&marks.path().join("driver")); + stages.wait_for("driver"); drop(input); assert!(child.wait().unwrap().success(), "a vanished parent ends the waiting child"); assert!(!folder.path().join("input.pdf").exists()); diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs index cc86e6da61..3a735cd972 100644 --- a/crates/print/src/tests.rs +++ b/crates/print/src/tests.rs @@ -213,6 +213,7 @@ fn macos_offers_auto_select_where_the_driver_would_pick_its_default_tray() { pub(crate) mod lpstat_limits { use super::*; use craft_ui::testing::trial; + use std::cell::Cell; use std::process::Command; use std::time::{Duration, Instant}; @@ -222,16 +223,25 @@ pub(crate) mod lpstat_limits { c } - /// Discovery that hangs only loses the driverless printers; the queues are listed. + /// Discovery that hangs only loses the driverless printers; the queues are listed. The limits + /// are kept on a clock that moves 10 ms at each check on a command, so the hanging discovery + /// is stopped at its 30th check however slowly the checks run, and its late answer is never + /// read. #[trial] fn discovery_that_hangs_keeps_the_queues() { let mut queues = sh("printf 'printer Office_Laser is idle. enabled since Mon\\n\\tDescription: Office\\nsystem default destination: Office_Laser\\n'"); - let started = Instant::now(); - let found = printers_via(&mut queues, Duration::from_secs(5), &mut sh("sleep 30"), Duration::from_millis(300)); - assert_eq!(found.iter().map(|p| p.name.as_str()).collect::>(), ["Office_Laser"]); + let now = Cell::new(Instant::now()); + let pause = || { + // The queue listing needs real time to finish between checks. + std::thread::sleep(Duration::from_millis(10)); + now.set(now.get() + Duration::from_millis(10)); + }; + let clock = Clock { now: &|| now.get(), pause: &pause }; + let mut hangs = sh("sleep 30; echo Late_Printer"); + let found = printers_via(&mut queues, Duration::from_secs(5), &mut hangs, Duration::from_millis(300), &clock); + assert_eq!(found.iter().map(|p| p.name.as_str()).collect::>(), ["Office_Laser"], "the late answer is not waited for"); assert!(found[0].default); - assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); } } /// Driver settings `len` bytes long whose header says `size` + `extra`, filled with `fill`. diff --git a/crates/proof/README.md b/crates/proof/README.md index 84d811f811..b838a66211 100644 --- a/crates/proof/README.md +++ b/crates/proof/README.md @@ -20,6 +20,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = " | German | — | — | TeX patterns (embedded, or a Language pack) | | Bulgarian | — | — | syllable rules | | Gujarati, Hindi | the installed Hunspell dictionary (Hindi: nukta letters spelled either way) | generic checks | akshara rules (or a Language pack) | +| Marathi (mr) | its Language pack or Hunspell dictionary, as any pack language | — | akshara rules (or a Language pack) | Grammar rules, suggestion tuning and the rule-based hyphenation are code: they work in every build. diff --git a/crates/proof/src/affix/build.rs b/crates/proof/src/affix/build.rs index f6c68cd3c5..33b76ae979 100644 --- a/crates/proof/src/affix/build.rs +++ b/crates/proof/src/affix/build.rs @@ -1,5 +1,11 @@ //! Building an [`AffixDict`] from `.aff` and `.dic` text: stem and flag-set interning and the lookup index. +use std::collections::HashSet; +use std::hash::BuildHasherDefault; +use std::rc::Rc; + +use crate::patterns::FxHasher; + use super::flags::{EMOJI_SELECTOR, FlagKey}; use super::parse::{Conv, RawRule, Rules, parse_aff, parse_compound_rule, parse_cond}; use super::{ @@ -7,6 +13,55 @@ use super::{ MAX_STEM_FLAGS, MAX_WORD_BYTES, Rule, SfxGroup, casing, has, hash_str, }; +/// Parsed continuation flags used only while building the dictionary. Final AF aliases share +/// their strict parse; literal continuations keep their own flags. +enum ContinuationFlags { + Literal(Vec), + Alias { index: usize, flags: Rc<[FlagKey]> }, +} + +impl ContinuationFlags { + fn read(rules: &Rules, written: &str, aliases: &mut FxMap>) -> Result { + if let Some(index) = rules.alias_index(written) { + if let Some(flags) = aliases.get(&index) { + return Ok(Self::Alias { index, flags: Rc::clone(flags) }); + } + let flags: Rc<[FlagKey]> = rules.mode.parse(rules.flags(written))?.into(); + aliases.insert(index, Rc::clone(&flags)); + Ok(Self::Alias { index, flags }) + } else { + rules.mode.parse(rules.flags(written)).map(Self::Literal) + } + } + + fn as_slice(&self) -> &[FlagKey] { + match self { + Self::Literal(flags) => flags.as_slice(), + Self::Alias { flags, .. } => flags.as_ref(), + } + } + + fn interned_id( + &self, + ids: &FxMap, + d: &mut AffixDict, + set_ids: &mut FxMap, u32>, + alias_ids: &mut FxMap, + ) -> Result { + if let Self::Alias { index, .. } = self + && let Some(&id) = alias_ids.get(index) + { + return Ok(id); + } + let mut flags: Vec = self.as_slice().iter().filter_map(|k| ids.get(k).copied()).collect(); + let id = d.intern(set_ids, &mut flags)?; + if let Self::Alias { index, .. } = self { + alias_ids.insert(*index, id); + } + Ok(id) + } +} + /// A dictionary's stems as `(word, start, end, is a word)` ranges of one buffer of flag keys. type StemFlags = (Vec<(String, usize, usize, bool)>, Vec); @@ -240,12 +295,25 @@ impl AffixDict { let mode = rules.mode; let exclusion_keys = [rules.forbidden, rules.no_suggest, rules.substandard]; let (mut stems, stem_keys) = AffixDict::read_stem_flags(&rules, stems, entry_cap, max_flags)?; - let conts = |rs: &[RawRule]| rs.iter().map(|r| mode.parse(&r.4)).collect::, _>>(); - let (pfx_cont, sfx_cont) = (conts(&rules.prefixes)?, conts(&rules.suffixes)?); + // This strict cache is separate from the stem reader's lenient alias ranges. + let mut aliases: FxMap> = FxMap::default(); + let mut conts = |rs: &[RawRule]| rs.iter().map(|r| ContinuationFlags::read(&rules, &r.4, &mut aliases)).collect::, _>>(); + let pfx_cont = conts(&rules.prefixes)?; + let sfx_cont = conts(&rules.suffixes)?; // Flags: every one a rule, a stem or a directive uses gets an id, in key order. let mut distinct: FxMap = FxMap::default(); let all = rules.prefixes.iter().chain(&rules.suffixes).map(|r| r.0); - let all = all.chain(pfx_cont.iter().chain(&sfx_cont).flatten().copied()).chain(stem_keys.iter().copied()); + let mut seen_aliases: HashSet> = HashSet::default(); + let continuation_keys = pfx_cont + .iter() + .chain(&sfx_cont) + .filter(|cont| match cont { + ContinuationFlags::Literal(_) => true, + ContinuationFlags::Alias { index, .. } => seen_aliases.insert(*index), + }) + .flat_map(ContinuationFlags::as_slice) + .copied(); + let all = all.chain(continuation_keys).chain(stem_keys.iter().copied()); // NEEDAFFIX and CIRCUMFIX flags may only ever appear in rules' continuation classes. let directives = [rules.forbidden, rules.no_suggest, rules.substandard, rules.keepcase, rules.only_in_compound, rules.need_affix, rules.circumfix]; @@ -447,12 +515,14 @@ impl AffixDict { if dropped > 0 { log::debug!("affix dictionary: {dropped} homonym entries past {MAX_FLAGS_PER_STEM} merged flags kept only their exclusions"); } - let mut build_rules = |raw: Vec, conts: Vec>, d: &mut AffixDict| -> Result, String> { + // Cache only after the first actual rule use, preserving the pool's insertion order. + let mut alias_ids: FxMap = FxMap::default(); + let mut build_rules = |raw: Vec, conts: Vec, d: &mut AffixDict| -> Result, String> { raw.into_iter() .zip(conts) .map(|((flag, cross, strip, add, _, cond), cont)| { let flag = id_of(flag).ok_or("affix flag without an id")?; - let cont = d.intern(&mut set_ids, &mut cont.iter().filter_map(|&k| id_of(k)).collect())?; + let cont = cont.interned_id(&distinct, d, &mut set_ids, &mut alias_ids)?; Ok(Rule { flag, cross, strip: strip.into(), add: add.into(), cont, cond: parse_cond(&cond)?, cond_text: cond.into() }) }) .collect() diff --git a/crates/proof/src/affix/parse.rs b/crates/proof/src/affix/parse.rs index 33d676a30c..042ea2e6d8 100644 --- a/crates/proof/src/affix/parse.rs +++ b/crates/proof/src/affix/parse.rs @@ -297,7 +297,7 @@ impl Rules { /// themselves, or with an `AF` table the alias its leading digits number, as Hunspell reads /// them (`2x` is alias 2). A field without digits or an undefined alias reads as no flags: /// the stem is still a word, the rule still applies, without the flags (Hunspell warns). - fn flags<'a>(&'a self, written: &'a str) -> &'a str { + pub(super) fn flags<'a>(&'a self, written: &'a str) -> &'a str { if !self.aliases_on { return written; } @@ -502,12 +502,11 @@ pub(super) fn parse_aff(aff: &str, english: bool) -> Result { } } } - // Aliases may be declared after the rules that use them; resolve once all are read. + // Continuation aliases are resolved by build after every directive has been read. // Hunspell removes `IGNORE` characters from the appended text only: a stripped text that // holds one never matches a stem (stems lose them too), so the rule never applies. let resolve = |rules: &mut Vec, r: &Rules| { for rule in rules.iter_mut() { - rule.4 = r.flags(&rule.4).to_string(); rule.3 = r.strip_ignored(&rule.3); } }; diff --git a/crates/proof/src/affix/tests.rs b/crates/proof/src/affix/tests.rs index 945263fad8..d2608ba545 100644 --- a/crates/proof/src/affix/tests.rs +++ b/crates/proof/src/affix/tests.rs @@ -97,6 +97,34 @@ fn flag_aliases_stand_for_flag_sets() { assert!(undefined.check("kertok"), "the other entries keep their aliases"); let back = AffixDict::from_bytes(&d.to_bytes().unwrap()).unwrap(); assert!(back.contains("házokban") && !back.contains("házban"), "aliases are expanded in the compact format"); + + // Rule continuations bind the final AF table, even when its declared count is smaller. + let late = "SET UTF-8\nFLAG num\nCIRCUMFIX 30\nPFX 7 Y 1\nPFX 7 0 ne/2 .\nSFX 12 Y 1\nSFX 12 0 a/2 .\nAF 1\nAF 7,12\nAF 30\n"; + let d = AffixDict::from_hunspell(late, "1\ngrad/1\n", &[]).unwrap(); + assert!(d.contains("grad") && d.contains("negrada")); + assert!(!d.contains("negrad") && !d.contains("grada"), "both late continuation aliases carry the circumfix"); + let bytes = d.to_bytes().unwrap(); + assert!(miniz_oxide::inflate::decompress_to_vec(&bytes).unwrap().starts_with(b"WCAFF2\nFLAG num\n")); + let back = AffixDict::from_bytes(&bytes).unwrap(); + assert!(back.contains("grad") && back.contains("negrada")); + assert!(!back.contains("negrad") && !back.contains("grada")); + + // Repeated aliases across both directions share their final sets, including one already + // interned for a stem. Distinct alias indices may name the same continuation flags. + let shared = "FLAG num\nAF 3\nAF 7,12\nAF 12\nAF 12\nPFX 7 Y 2\nPFX 7 0 ne/2 .\nPFX 7 0 na/3 .\nSFX 12 Y 2\nSFX 12 0 a/3 .\nSFX 12 0 i/2 .\n"; + let literal = "FLAG num\nPFX 7 Y 2\nPFX 7 0 ne/12 .\nPFX 7 0 na/12 .\nSFX 12 Y 2\nSFX 12 0 a/12 .\nSFX 12 0 i/12 .\n"; + let shared = AffixDict::from_hunspell(shared, "2\ngrad/1\nother/2\n", &[]).unwrap(); + let literal = AffixDict::from_hunspell(literal, "2\ngrad/7,12\nother/12\n", &[]).unwrap(); + for word in ["grad", "other", "negrad", "nagrad", "grada", "gradi", "othera", "otheri", "negrada", "negradi", "nagrada", "nagradi"] { + assert!(shared.contains(word) && literal.contains(word), "{word}"); + } + for word in ["neother", "naother", "gradz"] { + assert!(!shared.contains(word) && !literal.contains(word), "{word}"); + } + let bytes = shared.to_bytes().unwrap(); + assert_eq!(bytes, literal.to_bytes().unwrap(), "alias identity does not change the compact bytes"); + let back = AffixDict::from_bytes(&bytes).unwrap(); + assert_eq!(back.to_bytes().unwrap(), bytes, "the shared continuation sets survive compact reloading"); } /// CHECKSHARPS answers as Hunspell 1.7 gives them on the same files (`*` correct, `&` not). @@ -510,3 +538,42 @@ fn displayed_casing_uses_normalization_and_native_homonym_policy() { assert!(plain.can_suggest_cased("Q", "Q")); assert!(!plain.can_suggest_cased(&"x".repeat(MAX_INPUT_BYTES + 1), "NORMAL")); } + +#[test] +fn continuation_aliases_use_the_final_mode_and_keep_stem_parsing_lenient() { + // AF text uses the final numeric mode; an unused malformed alias is not read strictly. + let aff = "AF 2\nAF 1,2\nAF x2\nFLAG num\nSFX 1 Y 1\nSFX 1 0 a/1 .\nSFX 2 Y 1\nSFX 2 0 b .\n"; + let d = AffixDict::from_hunspell(aff, "1\nw/1\n", &[]).unwrap(); + assert!(d.check("wa") && d.check("wab")); + let dic = "2\nw/1\nodd/2\n"; + let d = AffixDict::from_hunspell(aff, dic, &[]).unwrap(); + assert!(d.check("odd") && !d.check("odda") && !d.check("oddb"), "the stem's malformed alias is read leniently"); + let strict = format!("{aff}SFX 3 Y 1\nSFX 3 0 c/2 .\n"); + let without_stem = AffixDict::from_hunspell(&strict, "1\nw/1\n", &[]).unwrap_err(); + assert!(without_stem.contains("`x2` is not a flag number"), "{without_stem}"); + assert_eq!( + AffixDict::from_hunspell(&strict, dic, &[]).unwrap_err(), + without_stem, + "the lenient stem cache cannot validate a strict continuation" + ); +} + +#[test] +fn continuation_alias_errors_keep_the_existing_precedence() { + let aliases = "FLAG num\nAF 3\nAF 1,2,3\nAF prefix_bad\nAF suffix_bad\n"; + let prefix = "PFX 1 Y 1\nPFX 1 0 pre/2 .\n"; + let suffix = "SFX 2 Y 1\nSFX 2 0 s/3 .\n"; + let prefix_error = AffixDict::from_hunspell(&format!("{aliases}{prefix}"), "0\n", &[]).unwrap_err(); + let suffix_error = AffixDict::from_hunspell(&format!("{aliases}{suffix}"), "0\n", &[]).unwrap_err(); + assert_ne!(prefix_error, suffix_error); + let both = format!("{aliases}{suffix}{prefix}"); + assert_eq!(AffixDict::from_hunspell(&both, "0\n", &[]).unwrap_err(), prefix_error, "prefix errors precede input-earlier suffix errors"); + let dic = "1\nword/1\n"; + let stem_error = AffixDict::from_hunspell_capped(aliases, dic, &[], false, 2).unwrap_err(); + assert!(stem_error.contains("stems carry more than 2 flags"), "{stem_error}"); + assert_eq!( + AffixDict::from_hunspell_capped(&both, dic, &[], false, 2).unwrap_err(), + stem_error, + "stem aggregate limits precede either continuation error" + ); +} diff --git a/crates/proof/src/gu/mod.rs b/crates/proof/src/gu/mod.rs index d511c4ecd3..c3c6fe483b 100644 --- a/crates/proof/src/gu/mod.rs +++ b/crates/proof/src/gu/mod.rs @@ -130,6 +130,34 @@ mod tests { } } + /// A zero-width joiner or non-joiner in a conjunct (`પુસ્` U+200D `તક`) keeps the word whole, + /// and the word is found under the dictionary's spelling, which has no joiner. + #[test] + fn words_with_joiners_are_one_word_and_spelled() { + test_dict::install(); + for word in ["પુસ્\u{200D}તક", "પુસ્\u{200C}તકોમાં"] { + let text = format!("ઘર {word} ગામ"); + let at = text.find(word).unwrap(); + assert!(crate::words(&text).contains(&(at, at + word.len())), "{word:?}"); + assert!(is_correct(word), "{word:?}"); + let issues = crate::check_text(&text, &[(0..text.len(), crate::ProofLang::Gu)]); + assert!(issues.is_empty(), "{word:?}: {issues:?}"); + } + // Still a misspelling with a joiner, and a joiner at a word's edge is not in the word. + assert!(!is_correct("પુસ્\u{200D}તકક")); + let text = "ઘર\u{200D} ગામ"; + assert!(crate::words(text).contains(&(0, "ઘર".len()))); + // A word with a joiner written twice is a repeated word. + let text = "પુસ્\u{200D}તક પુસ્\u{200D}તક"; + let issues = crate::check_grammar_in(text, crate::ProofLang::Gu); + assert!(issues.iter().any(|i| i.start == 0 && i.end == text.len()), "{issues:?}"); + // A word Gujarati repeats on purpose (`જલ્દી જલ્દી`) still is one when typed with a joiner. + for text in ["જલ્\u{200D}દી જલ્\u{200D}દી", "જલ્\u{200C}દી જલ્\u{200C}દી"] { + let issues = crate::check_grammar_in(text, crate::ProofLang::Gu); + assert!(issues.is_empty(), "{text:?}: {issues:?}"); + } + } + #[test] fn forbidden_words_are_rejected() { test_dict::install(); diff --git a/crates/proof/src/hi/mod.rs b/crates/proof/src/hi/mod.rs index 047f78607a..3adb055c26 100644 --- a/crates/proof/src/hi/mod.rs +++ b/crates/proof/src/hi/mod.rs @@ -143,6 +143,22 @@ mod tests { test_dict::install(); } + /// A zero-width joiner or non-joiner after a virama (`क्` U+200D `ष`) keeps the word whole, and + /// the word is found under the dictionary's spelling, which has no joiner. + #[test] + fn words_with_joiners_are_one_word_and_spelled() { + test_dict::install(); + for word in ["परीक्\u{200D}षण", "परीक्\u{200C}षण", "मित्\u{200D}रों"] { + let text = format!("घर {word} पानी।"); + let at = text.find(word).unwrap(); + assert!(crate::words(&text).contains(&(at, at + word.len())), "{word:?}"); + assert!(is_correct(word), "{word:?}"); + let issues = crate::check_text(&text, &[(0..text.len(), crate::ProofLang::Hi)]); + assert!(issues.is_empty(), "{word:?}: {issues:?}"); + } + assert!(!is_correct("परीक्\u{200D}षणण")); + } + #[test] fn user_dictionary_applies() { test_dict::install(); diff --git a/crates/proof/src/hyphen.rs b/crates/proof/src/hyphen.rs index 471067a16f..f8569a194c 100644 --- a/crates/proof/src/hyphen.rs +++ b/crates/proof/src/hyphen.rs @@ -15,7 +15,7 @@ //! //! **Bulgarian**: the Bulgarian syllable rules ([`crate::bg`]); no pattern file or word list. //! -//! **Gujarati and Hindi**: breaks between aksharas, never inside a conjunct or between a +//! **Gujarati, Hindi and Marathi**: breaks between aksharas, never inside a conjunct or between a //! consonant and its vowel sign ([`crate::indic`], rules from the script's Unicode encoding); no //! pattern file. //! @@ -120,7 +120,7 @@ pub enum Source { Patterns, /// A heuristic for a language without a dictionary or patterns. Heuristic, - /// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati and Hindi [`crate::indic`]). + /// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati, Hindi and Marathi [`crate::indic`]). Rules, /// No break points: the word is too short or no source applies. None, @@ -135,6 +135,13 @@ fn is_word_char(c: char) -> bool { c.is_alphabetic() || is_apostrophe(c) || unicode_normalization::char::is_combining_mark(c) } +/// [`is_word_char`] in `lang`. In a language with Indic rules a zero-width joiner or non-joiner +/// is part of the word too: it shapes a conjunct inside an akshara ([`crate::indic`]). In any +/// other language it still ends a letter run (Persian's ZWNJ between a word's parts). +fn is_word_char_in(c: char, lang: ProofLang) -> bool { + is_word_char(c) || (crate::indic::is_joiner(c) && crate::indic::Script::of(lang.built_in()).is_some()) +} + /// Unrestricted break points of one lowercase core (letters and `'` only, no leading/trailing `'`). fn core_breaks(core: &[char], lang: ProofLang) -> (Vec, Source) { let n = core.len(); @@ -160,7 +167,7 @@ fn core_breaks(core: &[char], lang: ProofLang) -> (Vec, Source) { if lang == ProofLang::Bg && core.iter().all(|&c| crate::bg::is_letter(c)) { return (crate::bg::points(core), Source::Rules); } - // Gujarati and Hindi words break between aksharas ([`crate::indic`]); other words in their runs + // Gujarati, Hindi and Marathi words break between aksharas ([`crate::indic`]); other words in their runs // (`WordCraft`) are hyphenated as English. if let Some(script) = crate::indic::Script::of(lang) && core.iter().all(|&c| script.is_letter(c)) @@ -235,9 +242,10 @@ fn composed_chars(core: &[char]) -> (Vec, Vec>) { (nfc, starts) } -/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish and Gujarati: a -/// word in their script (the guard their rules use) whose letters the patterns know, so a word with a -/// letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian +/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish, Gujarati, Hindi +/// and Marathi: a word in their script (the guard their rules use; for the Indic ones, the script's +/// letters and marks and the joiners inside a conjunct, [`crate::indic`]) whose letters the +/// patterns know, so a word with a letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian /// and German: every word, as their embedded patterns do. Any other language: a word whose letters /// the patterns know. fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool { @@ -246,7 +254,9 @@ fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool { ProofLang::Bg => core.iter().all(|&c| crate::bg::is_letter(c)) && pack_knows(pats, core), ProofLang::Tr => core.iter().all(|&c| crate::tr::hyphen::is_letter(c)) && pack_knows(pats, core), ProofLang::Pl | ProofLang::Pt | ProofLang::It | ProofLang::De => true, - ProofLang::Gu => core.iter().all(|&c| crate::gu::is_gujarati_char(c)) && pack_knows(pats, core), + _ if crate::indic::Script::of(lang).is_some() => { + crate::indic::Script::of(lang).is_some_and(|s| core.iter().all(|&c| s.is_letter(c))) && pack_knows(pats, core) + } _ => pats.values(core).is_some(), } } @@ -322,12 +332,12 @@ pub fn word_breaks_in(word: &str, lang: ProofLang) -> (Vec, Source) { let mut src = Source::None; let mut i = 0; while i < chars.len() { - if !is_word_char(chars[i]) { + if !is_word_char_in(chars[i], lang) { i += 1; continue; } let mut j = i; - while j < chars.len() && is_word_char(chars[j]) { + while j < chars.len() && is_word_char_in(chars[j], lang) { j += 1; } let (mut a, mut b) = (i, j); @@ -381,7 +391,7 @@ pub fn hyphen_points_in(word: &str, lim: &Limits, lang: ProofLang) -> Vec let mut i = 0; while i < chars.len() { let mut j = i; - while chars.get(j).is_some_and(|c| is_word_char(*c)) { + while chars.get(j).is_some_and(|c| is_word_char_in(*c, lang)) { j += 1; } let (mut a, mut b) = (i, j); diff --git a/crates/proof/src/hyphen/tests.rs b/crates/proof/src/hyphen/tests.rs index 38dcd55eae..124c265c45 100644 --- a/crates/proof/src/hyphen/tests.rs +++ b/crates/proof/src/hyphen/tests.rs @@ -195,6 +195,18 @@ fn gujarati_pack_patterns_fit_checks_script_and_exceptions() { assert!(!pack_patterns_fit(ProofLang::Gu, &pats, &en_word)); } +/// CodeRabbit on craft-libs#3905: a word with a joiner in a conjunct still reaches its pack's +/// exception word (here: no break at all), in Gujarati and Hindi. +#[test] +fn indic_pack_exceptions_reach_words_with_joiners() { + for (lang, word) in [(ProofLang::Gu, "પુસ્\u{200D}તક"), (ProofLang::Hi, "पुस्\u{200D}तक")] { + let pats = Patterns::parse(&format!("1ક 1क \\hyphenation{{{word}}}")); + let core: Vec = word.chars().collect(); + assert!(pack_patterns_fit(lang, &pats, &core), "{lang:?}"); + assert_eq!(core_breaks_patterns(&pats, &core), (vec![], Source::Dictionary), "{lang:?}"); + } +} + /// storytold/vectorcraft#4947: Gujarati text breaks between aksharas, within the paragraph's /// limits, where it used to fall to the English rules and get no break at all; a Latin word in /// a Gujarati run is still hyphenated as English. @@ -208,6 +220,8 @@ fn gujarati_breaks_between_aksharas_within_the_limits() { assert_eq!(gu("અમદાવાદ"), "અમ-દા-વાદ"); assert_eq!(gu("«ગુજરાતી»"), "«ગુ-જ-રા-તી»", "punctuation around the word"); assert_eq!(gu("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En)); + // A joiner in a conjunct doesn't cut the word in two (each part then too short to break). + assert_eq!(gu("પુસ્\u{200D}તક"), "પુ-સ્\u{200D}તક"); } /// Hindi text breaks between Devanagari aksharas by the same rules, where it used to get no @@ -221,3 +235,12 @@ fn hindi_breaks_between_aksharas_within_the_limits() { assert_eq!(hi("«विद्यार्थी»"), "«वि-द्या-र्थी»", "punctuation around the word"); assert_eq!(hi("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En)); } + +/// storytold/vectorcraft#4947: Marathi, a pack language (`mr`), breaks between aksharas as Hindi +/// does, within the paragraph's limits. +#[test] +fn marathi_breaks_between_aksharas() { + let mr = ProofLang::from_tag(Some("mr-IN")); + assert_eq!(hyphenate_word_in("महाराष्ट्र", &Limits::default(), mr), "महा-रा-ष्ट्र"); + assert_eq!(word_breaks_in("महाराष्ट्र", mr).1, Source::Rules); +} diff --git a/crates/proof/src/indic.rs b/crates/proof/src/indic.rs index d94cf46612..313e9c38bd 100644 --- a/crates/proof/src/indic.rs +++ b/crates/proof/src/indic.rs @@ -7,12 +7,15 @@ //! independent vowel that does not follow a virama: `ગુ-જ-રા-તી`, `વિ-દ્યા-ર્થી`, `સં-સ્કૃત`, //! `हि-न्दी`. A vowel sign, a mark or the second consonant of a conjunct never starts a line. //! Nor does a dead consonant — one ending in a virama with no consonant after it (`વાક્`) — since -//! it has no vowel of its own and is the end of the syllable before. +//! it has no vowel of its own and is the end of the syllable before. A zero-width joiner or +//! non-joiner after a virama (`સ્` U+200D `ત`) only chooses how the conjunct is drawn: it stays +//! inside the akshara, and no break goes next to a joiner. //! //! The rules come from the scripts' Unicode encoding alone; no pattern file or word list is //! read (and none is borrowed). The Brahmic blocks share one layout (the ISCII order), so a //! script is its block's start and a few script-specific code points (`Script::kind`). -//! Gujarati ([`ProofLang::Gu`]) and Hindi ([`ProofLang::Hi`], [`Script::Devanagari`]) use them; +//! Gujarati ([`ProofLang::Gu`]), Hindi ([`ProofLang::Hi`]) and Marathi (the pack language `mr`) +//! use them, Hindi and Marathi with [`Script::Devanagari`]; //! another language written in one of these scripts is one more line in [`Script::of`]. //! //! A single akshara left at the end or start of a line is ruled out by the paragraph's @@ -43,6 +46,14 @@ enum Kind { /// A vowel sign, nukta, anusvara, candrabindu, visarga or other mark (and the avagraha): /// belongs to the akshara before it. Mark, + /// A zero-width joiner or non-joiner: shapes the conjunct around it, in the same akshara. + Joiner, +} + +/// Is `c` a zero-width joiner or non-joiner (U+200D, U+200C)? Inside an Indic word it shapes a +/// conjunct, so it is part of the word (as in Unicode's word boundaries, UAX #29). +pub fn is_joiner(c: char) -> bool { + matches!(c, '\u{200C}' | '\u{200D}') } impl Script { @@ -51,6 +62,9 @@ impl Script { match lang { ProofLang::Gu => Some(Script::Gujarati), ProofLang::Hi => Some(Script::Devanagari), + // Marathi has no proofing language of its own: `mr`, `mr-IN` and `mar` are pack + // languages, spelled from their pack or Hunspell dictionary. + ProofLang::Pack(l) if matches!(l.primary(), "mr" | "mar") => Some(Script::Devanagari), _ => None, } } @@ -66,6 +80,9 @@ impl Script { /// What `c` is in this script, or `None` for a character outside the script's letters and /// marks (another script, a digit, a danda, `ॐ`, the abbreviation sign…). fn kind(self, c: char) -> Option { + if is_joiner(c) { + return Some(Kind::Joiner); + } let o = u32::from(c).checked_sub(self.base()).filter(|&o| o < 0x80)?; let dev = self == Script::Devanagari; Some(match o { @@ -94,7 +111,8 @@ impl Script { }) } - /// Is `c` one of this script's letters or marks (the characters [`points`] splits)? + /// Is `c` one of this script's letters or marks, or a joiner (the characters [`points`] + /// splits)? pub fn is_letter(self, c: char) -> bool { self.kind(c).is_some() } @@ -109,7 +127,7 @@ pub fn points(script: Script, word: &[char]) -> Vec { }; let at = |i: usize| kinds.get(i).copied(); // Has the akshara starting at `i` a vowel (independent, a sign, or the inherent one)? Only a - // consonant cluster ending in a virama (`ક્`, `ન્ત્`) has none. + // consonant cluster ending in a virama (`ક્`, `ન્ત્`, with or without a joiner) has none. let live = |i: usize| { let mut j = i; loop { @@ -117,19 +135,24 @@ pub fn points(script: Script, word: &[char]) -> Vec { return true; } j += 1; - while at(j) == Some(Kind::Mark) { + while matches!(at(j), Some(Kind::Mark | Kind::Joiner)) { j += 1; } if at(j) != Some(Kind::Virama) { return true; } j += 1; + while at(j) == Some(Kind::Joiner) { + j += 1; + } if at(j) != Some(Kind::Consonant) { return false; } } }; - (1..word.len()).filter(|&i| matches!(at(i), Some(Kind::Vowel | Kind::Consonant)) && at(i - 1) != Some(Kind::Virama) && live(i)).collect() + (1..word.len()) + .filter(|&i| matches!(at(i), Some(Kind::Vowel | Kind::Consonant)) && !matches!(at(i - 1), Some(Kind::Virama | Kind::Joiner)) && live(i)) + .collect() } #[cfg(test)] @@ -213,11 +236,27 @@ mod tests { assert_eq!(hi("ગુજરાતી"), "ગુજરાતી", "Gujarati is not Devanagari"); } - /// Gujarati and Hindi are mapped to their scripts, other languages to none. + /// CodeRabbit on craft-libs#3901: a joiner after a virama stays inside its conjunct, the break + /// before the conjunct remains, and no break goes next to a joiner. + #[test] + fn joiners_stay_inside_the_akshara() { + assert_eq!(gu("પુસ્\u{200D}તક"), "પુ-સ્\u{200D}ત-ક"); + assert_eq!(gu("પુસ્\u{200C}તક"), "પુ-સ્\u{200C}ત-ક"); + assert_eq!(gu("વાક્\u{200D}"), "વાક્\u{200D}", "still a dead consonant"); + assert_eq!(gu("ક\u{200D}ખ"), "ક\u{200D}ખ", "a joiner outside a conjunct"); + assert_eq!(hi("क्\u{200D}षमा"), "क्\u{200D}ष-मा"); + } + + /// Gujarati, Hindi and Marathi (a pack language, by any of its tags) are mapped to their + /// scripts, other languages (another pack language among them) to none. #[test] fn languages_map_to_their_script() { assert_eq!(Script::of(ProofLang::Gu), Some(Script::Gujarati)); assert_eq!(Script::of(ProofLang::Hi), Some(Script::Devanagari)); + for tag in ["mr", "mr-IN", "mar"] { + assert_eq!(Script::of(ProofLang::from_tag(Some(tag))), Some(Script::Devanagari), "{tag}"); + } + assert_eq!(Script::of(ProofLang::from_tag(Some("ne"))), None); assert_eq!(Script::of(ProofLang::En), None); assert_eq!(Script::of(ProofLang::Bg), None); } diff --git a/crates/proof/src/lib.rs b/crates/proof/src/lib.rs index abc9c8e542..86dd9cb9d8 100644 --- a/crates/proof/src/lib.rs +++ b/crates/proof/src/lib.rs @@ -489,13 +489,32 @@ fn in_dialect(s: &str, word: &str, lang: ProofLang) -> String { } /// Words in `text`: (byte start, byte end). Combining marks belong to the word they follow, so a -/// word typed decomposed (`tambie\u{301}n`, NFD) is one word, as its precomposed form is. +/// word typed decomposed (`tambie\u{301}n`, NFD) is one word, as its precomposed form is. A +/// zero-width joiner or non-joiner between two letters, digits or marks is inside the word, as in +/// Unicode's word boundaries (UAX #29): Indic text uses one to choose how a conjunct is drawn +/// (`क्` U+200D `ष`, `પુસ્` U+200D `તક`). A joiner at a word's edge is not part of it. pub fn words(text: &str) -> Vec<(usize, usize)> { + use indic::is_joiner; let mut out = Vec::new(); let mut start: Option = None; - let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '’' || c == '-' || unicode_normalization::char::is_combining_mark(c); + let is_core = |c: char| c.is_alphanumeric() || unicode_normalization::char::is_combining_mark(c); + let is_w = |c: char| is_core(c) || c == '\'' || c == '’' || c == '-'; + // The char before was a letter, digit or mark, or a joiner kept after one. + let mut after_core = false; + // Is the first char after the current run of joiners a letter, digit or mark? Looked up once + // per run, so a long run of joiners costs linear time, not quadratic. + let mut run_ends_core: Option = None; for (i, c) in text.char_indices() { - match (start, is_w(c)) { + let w = if is_joiner(c) { + after_core + && *run_ends_core + .get_or_insert_with(|| text.get(i + c.len_utf8()..).and_then(|rest| rest.chars().find(|&n| !is_joiner(n))).is_some_and(is_core)) + } else { + run_ends_core = None; + is_w(c) + }; + after_core = if is_joiner(c) { w } else { is_core(c) }; + match (start, w) { (None, true) => start = Some(i), (Some(s), false) => { out.push((s, i)); diff --git a/crates/proof/src/script_checks.rs b/crates/proof/src/script_checks.rs index 49f1bdd5c9..76bac2fe7a 100644 --- a/crates/proof/src/script_checks.rs +++ b/crates/proof/src/script_checks.rs @@ -46,10 +46,13 @@ pub(crate) fn is_correct(script: &Script, d: &AffixDict, word: &str, opts: &crat } /// Is one word (no hyphens) in the dictionary or the user dictionary, spelled as it is or as the -/// script's [`Script::variant`]? +/// script's [`Script::variant`]? A word with a zero-width joiner or non-joiner (`પુસ્` U+200D +/// `તક`) is tried as typed, then without its joiners, as a dictionary that ignores them +/// (Hunspell's `IGNORE`) would: they choose how a conjunct is drawn, not how the word is spelled. fn known(script: &Script, d: &AffixDict, w: &str) -> bool { let listed = |w: &str| d.check(w) || crate::in_user_dictionary(&w.to_lowercase()); - listed(w) || script.variant.and_then(|v| v(w)).is_some_and(|v| listed(&v)) + let spelled = |w: &str| listed(w) || script.variant.and_then(|v| v(w)).is_some_and(|v| listed(&v)); + spelled(w) || (w.contains(crate::indic::is_joiner) && spelled(&w.replace(crate::indic::is_joiner, ""))) } /// A language's script, messages and choices for [`check`]. @@ -91,9 +94,11 @@ fn repeated_words(text: &str, ws: &[(usize, usize)], rules: &Rules, v: &mut Vec< let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue }; if !gap.is_empty() && gap.chars().all(char::is_whitespace) - && w0.chars().all(|c| c.is_alphabetic() || (rules.script.is_letter)(c)) + && w0.chars().all(|c| c.is_alphabetic() || (rules.script.is_letter)(c) || crate::indic::is_joiner(c)) && w0 == w1 - && (rules.flag_repeat)(w0) + // The words a language repeats on purpose are listed without joiners (`જલ્દી`), so + // `જલ્` U+200D `દી` twice is the same intentional repeat. + && (rules.flag_repeat)(&w0.replace(crate::indic::is_joiner, "")) { v.push(issue(rules, *a0, *b1, format!("{}: “{w1}”", rules.repeated_word), vec![w0.to_string()])); } diff --git a/crates/proof/src/tests.rs b/crates/proof/src/tests.rs index 15f3c3c75f..04da0307c8 100644 --- a/crates/proof/src/tests.rs +++ b/crates/proof/src/tests.rs @@ -627,11 +627,47 @@ fn mixed_language_paragraphs_check_each_run_in_its_language() { assert!(v.iter().all(|i| i.lang == ProofLang::It && i.message == "Possibile errore di ortografia"), "{v:?}"); } +/// Every [`ProofLang`], for `mixed_spans_never_panic` to draw from. `fr` stands for the +/// [`ProofLang::Pack`] languages (and runs the French grammar rules, which need no dictionary). +fn every_lang() -> Vec { + use ProofLang as L; + // Stops compiling when a language is added: add it to the list below too. + let _ = |l: L| match l { + L::En | L::EnGb | L::EnAu | L::EnCa | L::Pl | L::Bg | L::Pt | L::It | L::Hr | L::Tr | L::Ru | L::Cs | L::Id => (), + L::Es | L::EsMx | L::Es419 | L::EsUy | L::Gu | L::Hi | L::De | L::Pack(_) | L::Other => (), + }; + let fr = ProofLang::from_tag(Some("fr")); + assert!(matches!(fr, L::Pack(_)), "{fr:?}"); + vec![ + L::En, + L::EnGb, + L::EnAu, + L::EnCa, + L::Pl, + L::Bg, + L::Pt, + L::It, + L::Hr, + L::Tr, + L::Ru, + L::Cs, + L::Id, + L::Es, + L::EsMx, + L::Es419, + L::EsUy, + L::Gu, + L::Hi, + L::De, + fr, + L::Other, + ] +} + proptest::proptest! { #[test] - fn mixed_spans_never_panic(s in "\\PC{0,60}", cuts in proptest::collection::vec((0usize..80, 0usize..80, 0u8..16), 0..6)) { - let langs = [ProofLang::En, ProofLang::EnGb, ProofLang::EnCa, ProofLang::Pl, ProofLang::Pt, ProofLang::It, ProofLang::Tr, ProofLang::Ru, ProofLang::Cs, ProofLang::Id, ProofLang::Gu, ProofLang::Hi, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, ProofLang::Other]; - let spans: Vec<(Range, ProofLang)> = cuts.iter().map(|&(a, b, l)| (a.min(b)..a.max(b), langs[l as usize % langs.len()])).collect(); + fn mixed_spans_never_panic(s in "\\PC{0,60}", cuts in proptest::collection::vec((0usize..80, 0usize..80, proptest::sample::select(every_lang())), 0..6)) { + let spans: Vec<(Range, ProofLang)> = cuts.iter().map(|&(a, b, l)| (a.min(b)..a.max(b), l)).collect(); for i in check_text(&s, &spans) { proptest::prop_assert!(i.start <= i.end && i.end <= s.len()); } diff --git a/crates/proto/src/imap/gmail_labels_tests.rs b/crates/proto/src/imap/gmail_labels_tests.rs index 1673af4e31..797a26a737 100644 --- a/crates/proto/src/imap/gmail_labels_tests.rs +++ b/crates/proto/src/imap/gmail_labels_tests.rs @@ -236,3 +236,112 @@ fn a_small_folders_listing_still_has_its_cap() { assert!(matches!(imap.uid_fetch_flags_labels("1:*"), Err(ProtoError::Protocol(_)))); assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); } + +// Small private budgets exercise the real parser alongside the default-cap controls above. +fn small_limits() -> Limits { + Limits { + responses: 1_000, + command_text: MAX_COMMAND_TEXT / 256, + fetch_text: MAX_FETCH_TEXT / 256, + flag_bytes: MAX_FLAG_BYTES / 256, + label_bytes: MAX_GMAIL_LABEL_BYTES / 256, + } +} + +#[test] +fn small_limits_a_big_folders_listing_is_not_cut_short_for_its_size() { + // The listing still exceeds an ordinary command's text cap, with every UID retained. + let limits = small_limits(); + let count: u32 = 1_200; + let mut server = String::with_capacity(count as usize * 200); + for uid in 1..=count { + server += &format!( + "* {uid} FETCH (FLAGS (\\Seen) UID {uid} X-GM-LABELS (\\Inbox \\Important \"Work/Clients and partners\" \"Receipts 2026\" \"Travel/Japan\"))\r\n" + ); + } + assert!(server.len() > limits.command_text); + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume_with_limits(&mut s, limits); + imap.selected = Selected { exists: count, uid_validity: 1, uid_next: count + 1 }; + let got = imap.uid_fetch_flags_labels("1:*"); + assert_eq!(got.as_ref().map(|got| got.len()), Ok(count as usize)); + assert_eq!(got.unwrap().into_iter().map(|f| f.uid).collect::>(), (1..=count).collect::>()); + // The room is the listing's alone: the next command has the usual cap again. + assert_eq!(imap.text_cap, limits.command_text); +} + +#[test] +fn small_limits_a_mailbox_claimed_huge_cant_fill_memory_with_flags() { + // Any server (no Gmail here): ten million messages claimed, then message after message with + // every flag it may have. The text it may send is capped, and so are the flags kept: the + // listing fails, and never hands back messages that seem to have lost their flags. + assert_eq!(MAX_RESPONSES, 250_000); + assert_eq!(MAX_COMMAND_TEXT, 32 << 20); + assert_eq!(MAX_FETCH_TEXT, 256 << 20); + assert_eq!(MAX_FLAG_BYTES, 256 << 20); + assert_eq!(MAX_GMAIL_LABEL_BYTES, 32 << 20); + let limits = small_limits(); + let flags: Vec = (0..MAX_FLAGS).map(|n| format!("f{n}")).collect(); + let flags = flags.join(" "); + let mut server = String::new(); + let mut uid = 0u32; + while server.len() < limits.fetch_text / 4 { + uid += 1; + server += &format!("* {uid} FETCH (UID {uid} FLAGS ({flags}))\r\n"); + } + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume_with_limits(&mut s, limits); + imap.selected = Selected { exists: 10_000_000, uid_validity: 1, uid_next: 0 }; + let got = imap.uid_fetch_flags("1:*"); + assert!(matches!(&got, Err(ProtoError::Protocol(m)) if format!("{m:?}").contains("more flags")), "{:?}", got.as_ref().map(Vec::len)); + assert_eq!(imap.text_cap, limits.command_text); + // And what it may send at all stays within the ceiling, however many messages are claimed. + let mut s = Script::new(format!("* OK {}\r\n", "x".repeat(60_000)).repeat(limits.fetch_text / 60_000 + 8)); + let mut imap = Imap::resume_with_limits(&mut s, limits); + imap.selected = Selected { exists: u32::MAX, uid_validity: 1, uid_next: 0 }; + assert!(matches!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn flag_and_label_budgets_count_stored_bytes() { + // Flags are all-or-nothing; the entry and each String count, not only its characters. + for extra in [0, 1] { + let mut limits = small_limits(); + limits.flag_bytes = ENTRY_OVERHEAD + FLAG_OVERHEAD + 1; + let flag = "f".repeat(1 + extra); + let mut s = Script::new(format!("* 1 FETCH (UID 1 FLAGS ({flag}))\r\nA0001 OK done\r\n")); + { + let mut imap = Imap::resume_with_limits(&mut s, limits); + imap.selected = Selected { exists: 1, uid_validity: 1, uid_next: 2 }; + let got = imap.uid_fetch_flags("1:*"); + if extra == 0 { + assert_eq!(got.unwrap().into_iter().map(|f| (f.uid, f.flags)).collect::>(), [(1, vec!["f".to_string()])]); + } else { + assert!(matches!(got, Err(ProtoError::Protocol(m)) if m.to_string().contains("more flags"))); + } + assert_eq!(imap.response_cap, limits.responses); + assert_eq!(imap.text_cap, limits.command_text); + } + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS)\r\n"); + assert!(s.finished()); + } + // Labels have a soft budget: keep the exact fit, but leave an over-budget label unset. + for extra in [0, 1] { + let mut limits = small_limits(); + limits.label_bytes = LABEL_OVERHEAD + 1; + let label = "a".repeat(1 + extra); + let mut s = Script::new(format!("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS ({label}))\r\nA0001 OK done\r\n")); + { + let mut imap = Imap::resume_with_limits(&mut s, limits); + imap.selected = Selected { exists: 1, uid_validity: 1, uid_next: 2 }; + let got = imap.uid_fetch_flags_labels("1:*").unwrap(); + assert_eq!(got.into_iter().map(|f| (f.uid, f.gmail_labels)).collect::>(), [(1, if extra == 0 { owned(&["a"]) } else { None })]); + assert_eq!(imap.response_cap, limits.responses); + assert_eq!(imap.text_cap, limits.command_text); + } + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS X-GM-LABELS)\r\n"); + assert!(s.finished()); + } +} diff --git a/crates/proto/src/imap/limits_tests.rs b/crates/proto/src/imap/limits_tests.rs index f0afbd5dc8..1dd485ecd5 100644 --- a/crates/proto/src/imap/limits_tests.rs +++ b/crates/proto/src/imap/limits_tests.rs @@ -222,3 +222,111 @@ fn brackets_in_flag_keywords_do_not_consume_body_sections() { assert_eq!(opened(&mut s, 1, 4).uid_fetch_message(3).unwrap().unwrap().body, Some(b"ok".to_vec())); } } + +// Small private budgets exercise the real parser alongside the default-cap controls above. +fn small_limits() -> Limits { + Limits { + responses: 1_000, + command_text: MAX_COMMAND_TEXT / 256, + fetch_text: MAX_FETCH_TEXT / 256, + flag_bytes: MAX_FLAG_BYTES / 256, + label_bytes: MAX_GMAIL_LABEL_BYTES / 256, + } +} + +fn opened_with_limits(s: &mut Script, exists: u32, uid_next: u32, limits: Limits) -> Imap<&mut Script> { + let mut imap = Imap::resume_with_limits(s, limits); + imap.selected = Selected { exists, uid_validity: 1, uid_next }; + imap +} + +#[test] +fn small_limits_a_flood_of_long_lines_ends_the_command() { + let limits = small_limits(); + let pad = padding(); + // Three lines of 60 KiB exceed the small command floor, below the per-line cap. + let server = flood(3, |n| format!("* {n} FETCH (UID {} FLAGS ({pad}))\r\n", n + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + let err = opened_with_limits(&mut s, 10, 20, limits).uid_fetch_flags("1:*").unwrap_err(); + assert!(matches!(err, ProtoError::Protocol(ref m) if m.to_string().contains("too much")), "{err:?}"); + // The same in a list. + let server = flood(3, |n| format!("* LIST () \"/\" \"{n}{pad}\"\r\n")) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + assert!(matches!(opened_with_limits(&mut s, 0, 0, limits).list(), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn small_limits_a_folder_with_more_messages_than_other_commands_may_answer_still_reads() { + let limits = small_limits(); + let exists = 1_200u32; + let lines = |n: u32| flood(n as usize, |i| format!("* {i} FETCH (UID {} FLAGS ())\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(lines(exists)); + let mut imap = opened_with_limits(&mut s, exists, exists + 1, limits); + assert_eq!(imap.uid_fetch_flags("1:*").unwrap().len(), exists as usize); + assert_eq!(imap.response_cap, limits.responses); + let sizes = flood(exists as usize, |i| format!("* {i} FETCH (UID {} RFC822.SIZE 1)\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(sizes); + let mut imap = opened_with_limits(&mut s, exists, exists + 1, limits); + assert_eq!(imap.uid_fetch_sizes("1:*").unwrap().len(), exists as usize); + assert_eq!(imap.response_cap, limits.responses); + // Responses that are not messages still end at the cap for that folder, and the next command is back to the usual one. + let noise = "* OK still here\r\n".repeat(2 * exists as usize + FETCH_SLACK + 1) + "A0001 OK done\r\n"; + let mut s = Script::new(noise); + let mut imap = opened_with_limits(&mut s, exists, exists + 1, limits); + assert!(matches!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); + assert_eq!(imap.response_cap, limits.responses); + // The tagged answer itself consumes one response: N-1 noise lines plus that answer fit. + let cap = 2 * exists as usize + FETCH_SLACK; + for extra in [0, 1] { + let noise = "* OK still here\r\n".repeat(cap - 1 + extra) + "A0001 OK done\r\n"; + let mut s = Script::new(noise); + let mut imap = opened_with_limits(&mut s, exists, exists + 1, limits); + let got = imap.uid_fetch_sizes("1:*"); + if extra == 0 { + assert_eq!(got, Ok(Vec::new())); + } else { + assert!(matches!(got, Err(ProtoError::Protocol(m)) if m.to_string().contains("too many responses"))); + } + assert_eq!(imap.response_cap, limits.responses); + } +} + +#[test] +fn command_text_budget_counts_exact_bytes() { + // Every byte outside literals counts, including each CRLF and the final tagged answer. + let transcript = |bytes: usize| { + let done = "A0001 OK done\r\n"; + let mut left = bytes - done.len(); + let mut server = String::new(); + while left > MAX_LINE { + let line = format!("* OK {}\r\n", "x".repeat(60 * 1024)); + left -= line.len(); + server += &line; + } + assert!(left >= 7); + server += &format!("* OK {}\r\n", "x".repeat(left - 7)); + server += done; + assert_eq!(server.len(), bytes); + server + }; + let limits = small_limits(); + // LIST and a small FETCH use the command floor; a huge claimed mailbox uses the ceiling. + for (list, exists, cap) in [(true, 0, limits.command_text), (false, 10, limits.command_text), (false, u32::MAX, limits.fetch_text)] { + for extra in [0, 1] { + let mut s = Script::new(transcript(cap + extra)); + { + let mut imap = opened_with_limits(&mut s, exists, 0, limits); + let got = if list { imap.list().map(|got| got.len()) } else { imap.uid_fetch_flags("1:*").map(|got| got.len()) }; + if extra == 0 { + assert_eq!(got, Ok(0)); + } else { + assert!(matches!(got, Err(ProtoError::Protocol(m)) if m.to_string().contains("too much"))); + } + assert_eq!(imap.response_cap, limits.responses); + assert_eq!(imap.text_cap, limits.command_text); + } + assert_eq!(s.sent(), if list { "A0001 LIST \"\" \"*\"\r\n" } else { "A0001 UID FETCH 1:* (UID FLAGS)\r\n" }); + assert!(s.finished()); + } + } +} diff --git a/crates/proto/src/imap/mod.rs b/crates/proto/src/imap/mod.rs index 42a5713e27..4fd489be5f 100644 --- a/crates/proto/src/imap/mod.rs +++ b/crates/proto/src/imap/mod.rs @@ -102,9 +102,32 @@ const MAX_FOUND: usize = 1_000; /// in: as many as fit the longest line read, at the longest a UID is written. pub const MAX_GMAIL_FOUND: usize = 5_000; +/// Budgets shared by the commands of one session. Public constructors use the production caps. +#[derive(Clone, Copy)] +struct Limits { + responses: usize, + command_text: usize, + fetch_text: usize, + flag_bytes: usize, + label_bytes: usize, +} + +impl Default for Limits { + fn default() -> Self { + Self { + responses: MAX_RESPONSES, + command_text: MAX_COMMAND_TEXT, + fetch_text: MAX_FETCH_TEXT, + flag_bytes: MAX_FLAG_BYTES, + label_bytes: MAX_GMAIL_LABEL_BYTES, + } + } +} + /// An IMAP session on a stream. pub struct Imap { wire: Wire, + limits: Limits, /// The number in the next command's tag. next_tag: u32, secrets: Secrets, @@ -470,8 +493,8 @@ impl Wanted { /// Most responses a fetch of this mailbox may bring: one for each message it may report, but /// never fewer than any other command. - fn responses(&self) -> usize { - self.cap.max(MAX_RESPONSES) + fn responses(&self, minimum: usize) -> usize { + self.cap.max(minimum) } fn wants(&self, uid: u32) -> bool { @@ -678,8 +701,13 @@ impl Imap { /// Continue on a stream that already greeted (after the caller wrapped it in TLS). pub fn resume(stream: S) -> Self { + Self::resume_with_limits(stream, Limits::default()) + } + + fn resume_with_limits(stream: S, limits: Limits) -> Self { Imap { wire: Wire::new(stream), + limits, next_tag: 1, secrets: Secrets::default(), capabilities: None, @@ -689,8 +717,8 @@ impl Imap { appended: Vec::new(), leaving: false, text_seen: 0, - response_cap: MAX_RESPONSES, - text_cap: MAX_COMMAND_TEXT, + response_cap: limits.responses, + text_cap: limits.command_text, skip_long: false, skipped: false, idle_tag: None, @@ -884,6 +912,7 @@ impl Imap { fn fetch_flags(&mut self, set: &str, ids: bool, labels_wanted: bool) -> Result, ProtoError> { type FetchedFlags = (Vec, Option, Option>); + let limits = self.limits; let mut found: BTreeMap = BTreeMap::new(); // The bytes of labels and of flags kept so far, all messages together. let mut label_bytes = 0usize; @@ -896,12 +925,12 @@ impl Imap { }; let command = Self::fetch(set, items)?; let mut wanted = Wanted::new(set, &self.selected).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; - self.response_cap = wanted.responses(); + self.response_cap = wanted.responses(self.limits.responses); let claimed = usize::try_from(self.selected.exists).unwrap_or(usize::MAX); - self.text_cap = claimed.saturating_mul(FETCH_TEXT_PER_MESSAGE).clamp(MAX_COMMAND_TEXT, MAX_FETCH_TEXT); + self.text_cap = claimed.saturating_mul(FETCH_TEXT_PER_MESSAGE).clamp(limits.command_text, limits.fetch_text); let answered = self.run(command, &mut |values| { // A response with a UID shows the message is there, even one that forgot the flags. - if flag_bytes <= MAX_FLAG_BYTES + if flag_bytes <= limits.flag_bytes && let Some(item) = Item::from(values) && wanted.wants(item.uid) && (found.contains_key(&item.uid) || wanted.room(found.len())) @@ -911,7 +940,7 @@ impl Imap { let size = item.flags.iter().flatten().map(|flag| flag.len().saturating_add(FLAG_OVERHEAD)).sum::(); let entry = if found.contains_key(&item.uid) { 0 } else { ENTRY_OVERHEAD }; flag_bytes = flag_bytes.saturating_add(size).saturating_add(entry); - if flag_bytes > MAX_FLAG_BYTES { + if flag_bytes > limits.flag_bytes { return; } let (flags, id, labels) = found.entry(item.uid).or_default(); @@ -924,17 +953,17 @@ impl Imap { } if labels_wanted && let Some(later) = item.gmail_labels { let size = later.iter().map(|label| label.len().saturating_add(LABEL_OVERHEAD)).sum::(); - if label_bytes.saturating_add(size) <= MAX_GMAIL_LABEL_BYTES { + if label_bytes.saturating_add(size) <= limits.label_bytes { label_bytes = label_bytes.saturating_add(size); *labels = Some(later); } } } }); - self.response_cap = MAX_RESPONSES; - self.text_cap = MAX_COMMAND_TEXT; + self.response_cap = limits.responses; + self.text_cap = limits.command_text; answered?; - if flag_bytes > MAX_FLAG_BYTES { + if flag_bytes > limits.flag_bytes { return Err(ProtoError::Protocol(said!("more flags than one listing keeps"))); } wanted.check()?; @@ -949,7 +978,7 @@ impl Imap { let mut out: Vec<(u32, u64)> = Vec::new(); let command = Self::fetch(set, "(UID RFC822.SIZE)")?; let mut wanted = Wanted::new(set, &self.selected).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; - self.response_cap = wanted.responses(); + self.response_cap = wanted.responses(self.limits.responses); let answered = self.run(command, &mut |values| { if let Some(Item { uid, size: Some(size), .. }) = Item::from(values) && wanted.wants(uid) @@ -958,7 +987,7 @@ impl Imap { out.push((uid, size)); } }); - self.response_cap = MAX_RESPONSES; + self.response_cap = self.limits.responses; answered?; wanted.check()?; out.sort_by_key(|(uid, _)| *uid); diff --git a/crates/proto/src/imap/status.rs b/crates/proto/src/imap/status.rs index 3c378308a3..74251040c9 100644 --- a/crates/proto/src/imap/status.rs +++ b/crates/proto/src/imap/status.rs @@ -8,7 +8,7 @@ use std::io::{Read, Write}; use super::parse::{Status, Value}; -use super::{Command, Imap, MAX_COMMAND_TEXT, MAX_QUOTED, Part, Response}; +use super::{Command, Imap, MAX_QUOTED, Part, Response}; use crate::i18n::said; use crate::{ProtoError, for_trace}; @@ -144,7 +144,7 @@ impl Imap { self.note_status(&line); } Response::Data(values) => { - if self.text_seen > MAX_COMMAND_TEXT { + if self.text_seen > self.limits.command_text { return Err(ProtoError::Protocol(said!("the server sent too much in answer to one command"))); } self.note_data(&values); diff --git a/crates/ps/src/write.rs b/crates/ps/src/write.rs index 09793a8ebe..85c37e5a70 100644 --- a/crates/ps/src/write.rs +++ b/crates/ps/src/write.rs @@ -606,7 +606,7 @@ mod tests { let step = craft_testkit::hostile::divisor(); let (mut integer_path, mut visited) = (0usize, 0usize); let samples = number_samples(); - for places in 0..=12 { + for places in 0..=10 { for v in samples.iter().copied().skip(places as usize % step).step_by(step) { visited += 1; let mut expected = String::from("x "); diff --git a/crates/psd/README.md b/crates/psd/README.md index 7a7bfa2d7d..40ddd9bdfd 100644 --- a/crates/psd/README.md +++ b/crates/psd/README.md @@ -155,6 +155,7 @@ testgen::{all_cases, merged_only, layered, small, sample_descriptor, pattern_pla | Builder | – | ✓ | – | RGB / gray / CMYK at 8/16 bit, masks, groups, blend modes, opacity, fill, visibility, clipping | | Patterns | ✓ | ✓ | ✓ | `Patt` / `Pat2` / `Pat3`, `.pat`, and `.abr` embedded patterns; non-empty tiles allow in-bounds channel subrectangles, decoded size is capped and PackBits expansion is input-bounded | | Actions (`.atn`) | ✓ | ✓ | ✓ | `atn::parse` / `atn::write`: version-16 sets (Photoshop 6+): actions with function key, modifiers and colour; steps with event code or string name, panel name, enabled/dialog flags and their descriptor. Exact round trip for version-16 files, except that flag and Boolean bytes other than 0 or 1 are written back as 1 and trailing bytes after the last action are dropped (with a parse warning); version-12 (Photoshop 5) files are read too and written back as version 16 | +| Toolbar presets (`.tbr`) | ✓ | ✓ | ✓ | `tbr::read` / `tbr::write`: the toolbar and extra-tools groups with each tool's four-char key and shortcut, the Show toggles and the hidden-extras shortcut flag. Entries that aren't tools are skipped, and missing or mistyped flags read as their defaults; files over 64 KiB are refused. `write` refuses a preset `read` would refuse: more than 256 groups in a list or tools in a group, or over 64 KiB | Pattern channel subrectangles are padded with zeroes to the tile rectangle. All channel metadata is checked before any plane is decoded, against one `PatternBudget` shared by every diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 5b84fcb91a..51347be3ae 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -97,6 +97,7 @@ pub mod slices; pub mod smart; pub mod source; pub mod tagged; +pub mod tbr; #[cfg(any(test, feature = "test-support"))] // Test-data generator (tests and fuzz seeds only): failing loudly is the point. #[allow(clippy::expect_used)] diff --git a/crates/psd/src/tbr.rs b/crates/psd/src/tbr.rs new file mode 100644 index 0000000000..a3168c3518 --- /dev/null +++ b/crates/psd/src/tbr.rs @@ -0,0 +1,208 @@ +//! Toolbar presets (`.tbr`): one action descriptor with no file header. +//! +//! Layout from saved presets measured for storytold/photocraft#14624; no external implementation +//! copied. The descriptor's name is a lone NUL and its class `null`, and it holds these 11 keys in +//! this order: `tver` (long, 1), `tpad` (long, 0), the five Show toggles `fgbg`, `qkmm`, `sImI`, +//! `scmd` and `shov` (bool), `nana` (bool, false in saved files), `ddkb` (bool) and the two lists +//! `tlst` (toolbar) and `oflt` (extra tools). Each list holds groups, each group a list of tool +//! objects `{toolKey: long, keyboardShortcut: TEXT}`, where `toolKey` is a four-char id and +//! `keyboardShortcut` is left out for a tool without one. +//! +//! This module reads and writes that layout only. Which tool a key names, and what a shortcut +//! means, is the caller's. + +use crate::descriptor::{Descriptor, Id, ParseLimits, UnicodeString, Value}; +use crate::error::{PsdError, Result}; + +/// The largest preset read. A preset with every tool is about 3 KiB. +pub const MAX_BYTES: usize = 64 * 1024; + +/// Per-container limits for a preset's descriptors and lists (hostile input). +const LIMITS: ParseLimits = ParseLimits { max_descriptor_items: 64, max_list_items: 256 }; + +/// A tool's shortcut in a preset. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Shortcut { + /// No `keyboardShortcut` key. + Absent, + /// A `keyboardShortcut` text, without its trailing NUL. It can be empty. + Text(String), + /// A `keyboardShortcut` that isn't text. It is not written back. + NotText, +} + +/// One tool in a group. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Tool { + /// The four-char tool id (`toolKey`). + pub key: [u8; 4], + /// Its shortcut. + pub shortcut: Shortcut, +} + +/// A toolbar preset. [`Default`] is the values a preset holds when nothing is set: version 1, +/// every Show toggle on, the other flags off, both lists empty. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ToolbarPreset { + /// `tver`: the format version. + pub version: i32, + /// `tpad`: 0 in saved files; meaning unknown. + pub pad: i32, + /// `fgbg`: show the foreground and background colours. + pub show_colors: bool, + /// `qkmm`: show the quick mask mode button. + pub show_quick_mask: bool, + /// `sImI`: show the add-or-generate-images button. + pub show_add_images: bool, + /// `scmd`: show the screen mode button. + pub show_screen_mode: bool, + /// `shov`: show the slot that opens the extra tools. + pub show_extras_slot: bool, + /// `nana`: false in saved files; meaning unknown. + pub nana: bool, + /// `ddkb`: shortcuts of tools that sit only in the extra tools are off. + pub disable_extras_shortcuts: bool, + /// `tlst`: the toolbar's groups, in order. + pub toolbar: Vec>, + /// `oflt`: the extra tools' groups, in order. + pub extras: Vec>, +} + +impl Default for ToolbarPreset { + fn default() -> Self { + Self { + version: 1, + pad: 0, + show_colors: true, + show_quick_mask: true, + show_add_images: true, + show_screen_mode: true, + show_extras_slot: true, + nana: false, + disable_extras_shortcuts: false, + toolbar: Vec::new(), + extras: Vec::new(), + } + } +} + +/// A descriptor as presets hold them: the name is a lone NUL, the class `null`. +fn object() -> Descriptor { + Descriptor { name: UnicodeString::new_nul(""), class_id: Id::new("null"), items: Vec::new() } +} + +/// Write a preset: the 11 keys in their order, each tool as `{toolKey, keyboardShortcut}`, and +/// `keyboardShortcut` only for a [`Shortcut::Text`]. +/// +/// A preset [`read`] would refuse is an error instead: a list with more groups, or a group with +/// more tools, than [`read`] takes, or bytes over [`MAX_BYTES`]. +pub fn write(preset: &ToolbarPreset) -> Result> { + let max_entries = usize::try_from(LIMITS.max_list_items).unwrap_or(usize::MAX); + for groups in [&preset.toolbar, &preset.extras] { + if groups.len() > max_entries { + return Err(PsdError::LimitExceeded("toolbar preset groups")); + } + if groups.iter().any(|group| group.len() > max_entries) { + return Err(PsdError::LimitExceeded("toolbar preset tools in a group")); + } + } + let groups = |groups: &[Vec]| -> Value { + Value::List( + groups + .iter() + .map(|group| { + Value::List( + group + .iter() + .map(|tool| { + let d = object().with("toolKey", Value::Integer(i32::from_be_bytes(tool.key))); + Value::Descriptor(match &tool.shortcut { + Shortcut::Text(s) => d.with("keyboardShortcut", Value::Text(UnicodeString::new_nul(s))), + Shortcut::Absent | Shortcut::NotText => d, + }) + }) + .collect(), + ) + }) + .collect(), + ) + }; + let bytes = object() + .with("tver", Value::Integer(preset.version)) + .with("tpad", Value::Integer(preset.pad)) + .with("fgbg", Value::Boolean(preset.show_colors)) + .with("qkmm", Value::Boolean(preset.show_quick_mask)) + .with("sImI", Value::Boolean(preset.show_add_images)) + .with("scmd", Value::Boolean(preset.show_screen_mode)) + .with("shov", Value::Boolean(preset.show_extras_slot)) + .with("nana", Value::Boolean(preset.nana)) + .with("ddkb", Value::Boolean(preset.disable_extras_shortcuts)) + .with("tlst", groups(&preset.toolbar)) + .with("oflt", groups(&preset.extras)) + .to_bytes(); + if bytes.len() > MAX_BYTES { + return Err(PsdError::LimitExceeded("toolbar preset bytes")); + } + Ok(bytes) +} + +/// Read a preset. The file must be one whole descriptor of at most [`MAX_BYTES`] whose `tlst` and +/// `oflt` are lists of groups; anything else is an error. A group entry that isn't an object with +/// an integer `toolKey` is skipped. A flag or number that is missing or of another type reads as +/// its [`Default`]. +pub fn read(bytes: &[u8]) -> Result { + if bytes.len() > MAX_BYTES { + return Err(PsdError::LimitExceeded("toolbar preset bytes")); + } + let (d, used) = Descriptor::parse_prefix_with_limits(bytes, LIMITS)?; + if used != bytes.len() { + return Err(PsdError::invalid("trailing bytes after the toolbar preset")); + } + let lists = |key: &str| -> Result>> { + let Some(Value::List(groups)) = d.get(key) else { return Err(PsdError::invalid(format!("toolbar preset: `{key}` is missing"))) }; + groups + .iter() + .map(|group| { + let Value::List(tools) = group else { + return Err(PsdError::invalid(format!("toolbar preset: `{key}` holds something other than a tool group"))); + }; + Ok(tools.iter().filter_map(tool).collect()) + }) + .collect() + }; + let (toolbar, extras) = (lists("tlst")?, lists("oflt")?); + let def = ToolbarPreset::default(); + let int = |key: &str, or: i32| match d.get(key) { + Some(Value::Integer(v)) => *v, + _ => or, + }; + let flag = |key: &str, or: bool| match d.get(key) { + Some(Value::Boolean(v)) => *v, + _ => or, + }; + Ok(ToolbarPreset { + version: int("tver", def.version), + pad: int("tpad", def.pad), + show_colors: flag("fgbg", def.show_colors), + show_quick_mask: flag("qkmm", def.show_quick_mask), + show_add_images: flag("sImI", def.show_add_images), + show_screen_mode: flag("scmd", def.show_screen_mode), + show_extras_slot: flag("shov", def.show_extras_slot), + nana: flag("nana", def.nana), + disable_extras_shortcuts: flag("ddkb", def.disable_extras_shortcuts), + toolbar, + extras, + }) +} + +/// A group entry as a tool, or `None` when it isn't an object with an integer `toolKey`. +fn tool(entry: &Value) -> Option { + let Value::Descriptor(t) = entry else { return None }; + let Some(Value::Integer(key)) = t.get("toolKey") else { return None }; + let shortcut = match t.get("keyboardShortcut") { + None => Shortcut::Absent, + Some(Value::Text(s)) => Shortcut::Text(s.to_string_lossy()), + Some(_) => Shortcut::NotText, + }; + Some(Tool { key: key.to_be_bytes(), shortcut }) +} diff --git a/crates/psd/tests/it/main.rs b/crates/psd/tests/it/main.rs index 4e78641e65..c84cf0bbcc 100644 --- a/crates/psd/tests/it/main.rs +++ b/crates/psd/tests/it/main.rs @@ -37,3 +37,4 @@ mod atn_sidecar; mod csh; mod metadata_resources; mod resource_limits; +mod tbr; diff --git a/crates/psd/tests/it/tbr.rs b/crates/psd/tests/it/tbr.rs new file mode 100644 index 0000000000..1055b07ca7 --- /dev/null +++ b/crates/psd/tests/it/tbr.rs @@ -0,0 +1,124 @@ +//! Toolbar presets (`.tbr`): the measured layout, round trips and hostile input +//! (storytold/photocraft#14624). + +use craft_psd::PsdError; +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value}; +use craft_psd::tbr::{self, MAX_BYTES, Shortcut, Tool, ToolbarPreset}; + +fn tool(key: &[u8; 4], shortcut: Shortcut) -> Tool { + Tool { key: *key, shortcut } +} + +fn text(s: &str) -> Shortcut { + Shortcut::Text(s.into()) +} + +/// A preset with two toolbar groups and one extras group, shortcuts present, empty and absent. +fn sample() -> ToolbarPreset { + ToolbarPreset { + toolbar: vec![vec![tool(b"arwT", text("V")), tool(b"ArtT", text("V"))], vec![tool(b"blur", Shortcut::Absent)]], + extras: vec![vec![tool(b"zoom", text(""))]], + ..ToolbarPreset::default() + } +} + +/// A descriptor as presets hold them: the name is a lone NUL, the class `null`. +fn object() -> Descriptor { + Descriptor { name: UnicodeString::new_nul(""), class_id: Id::new("null"), items: Vec::new() } +} + +#[test] +fn a_written_preset_has_the_measured_layout() { + let bytes = tbr::write(&sample()).unwrap(); + // Name: one NUL; class `null`. + assert_eq!(bytes[..14], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, b'n', b'u', b'l', b'l']); + let d = Descriptor::from_bytes(&bytes).unwrap(); + let keys: Vec = d.items.iter().map(|(k, _)| String::from_utf8_lossy(k.as_bytes()).into_owned()).collect(); + assert_eq!(keys, ["tver", "tpad", "fgbg", "qkmm", "sImI", "scmd", "shov", "nana", "ddkb", "tlst", "oflt"]); + let Some(Value::List(groups)) = d.get("tlst") else { panic!("tlst is a list") }; + let Value::List(first) = &groups[0] else { panic!("a group is a list") }; + let Value::Descriptor(mv) = &first[0] else { panic!("a tool is an object") }; + assert_eq!(mv.get("toolKey"), Some(&Value::Integer(i32::from_be_bytes(*b"arwT")))); + assert_eq!(mv.get_text("keyboardShortcut").as_deref(), Some("V")); + let Value::List(second) = &groups[1] else { panic!("a group is a list") }; + let Value::Descriptor(blur) = &second[0] else { panic!("a tool is an object") }; + assert!(blur.get("keyboardShortcut").is_none(), "a tool without a shortcut has no keyboardShortcut"); +} + +#[test] +fn a_preset_round_trips_every_value() { + let def = ToolbarPreset::default(); + let changed = ToolbarPreset { + version: def.version + 1, + pad: def.pad + 7, + show_colors: !def.show_colors, + show_quick_mask: !def.show_quick_mask, + show_add_images: !def.show_add_images, + show_screen_mode: !def.show_screen_mode, + show_extras_slot: !def.show_extras_slot, + nana: !def.nana, + disable_extras_shortcuts: !def.disable_extras_shortcuts, + ..sample() + }; + for preset in [ToolbarPreset::default(), sample(), changed] { + assert_eq!(tbr::read(&tbr::write(&preset).unwrap()).unwrap(), preset); + } +} + +/// Entries that aren't tools are skipped, a shortcut that isn't text says so, and a preset that +/// leaves out its flags reads them as the defaults. +#[test] +fn a_hand_made_preset_keeps_its_tools_and_skips_the_rest() { + let mv = object().with("toolKey", Value::Integer(i32::from_be_bytes(*b"arwT"))).with("keyboardShortcut", Value::Integer(5)); + let group = Value::List(vec![Value::Integer(3), Value::Descriptor(object().with("other", Value::Boolean(true))), Value::Descriptor(mv)]); + let bytes = object().with("tlst", Value::List(vec![group])).with("oflt", Value::List(vec![])).to_bytes(); + let preset = tbr::read(&bytes).unwrap(); + assert_eq!(preset.toolbar, [vec![tool(b"arwT", Shortcut::NotText)]]); + assert_eq!(ToolbarPreset { toolbar: Vec::new(), ..preset }, ToolbarPreset::default()); +} + +#[test] +fn a_damaged_preset_is_refused() { + let good = tbr::write(&sample()).unwrap(); + let mut bad: Vec> = vec![Vec::new(), vec![b'x'; 100], [good.as_slice(), &[0]].concat(), vec![0; MAX_BYTES + 1]]; + bad.extend((1..good.len()).map(|n| good[..n].to_vec())); + bad.push(object().with("tver", Value::Integer(1)).to_bytes()); + bad.push(object().with("tlst", Value::List(vec![Value::Integer(3)])).with("oflt", Value::List(vec![])).to_bytes()); + // A group longer than any toolbar. + let crowded = Value::List((0..300).map(|_| Value::Descriptor(object().with("toolKey", Value::Integer(1)))).collect()); + bad.push(object().with("tlst", Value::List(vec![crowded])).with("oflt", Value::List(vec![])).to_bytes()); + for bytes in &bad { + assert!(tbr::read(bytes).is_err(), "{} bytes were read as a preset", bytes.len()); + } +} + +/// The writer stops where the reader does: a preset at each limit round trips, and one past it is +/// a limit error rather than bytes the reader would refuse. +#[test] +fn a_preset_at_the_limits_round_trips_and_one_past_them_is_refused() { + let tools = |n: usize| (0..n).map(|_| tool(b"blur", Shortcut::Absent)).collect::>(); + let at_limit = [ + ToolbarPreset { toolbar: vec![tools(256)], ..ToolbarPreset::default() }, + ToolbarPreset { extras: vec![Vec::new(); 256], ..ToolbarPreset::default() }, + ]; + let past_limit = [ + ToolbarPreset { toolbar: vec![tools(257)], ..ToolbarPreset::default() }, + ToolbarPreset { extras: vec![Vec::new(); 257], ..ToolbarPreset::default() }, + ]; + for preset in at_limit { + assert_eq!(tbr::read(&tbr::write(&preset).unwrap()).unwrap(), preset); + } + for preset in past_limit { + assert!(matches!(tbr::write(&preset), Err(PsdError::LimitExceeded(_)))); + } + + // A shortcut long enough to bring the file within one UTF-16 unit of MAX_BYTES, then one + // unit longer. + let long = |n: usize| ToolbarPreset { toolbar: vec![vec![tool(b"blur", text(&"x".repeat(n)))]], ..ToolbarPreset::default() }; + let base = tbr::write(&long(0)).unwrap().len(); + let fits = long((MAX_BYTES - base) / 2); + let bytes = tbr::write(&fits).unwrap(); + assert!(bytes.len() <= MAX_BYTES && bytes.len() + 2 > MAX_BYTES, "{} bytes is not at the limit", bytes.len()); + assert_eq!(tbr::read(&bytes).unwrap(), fits); + assert!(matches!(tbr::write(&long((MAX_BYTES - base) / 2 + 1)), Err(PsdError::LimitExceeded(_)))); +} diff --git a/crates/rtf/src/doc/shape.rs b/crates/rtf/src/doc/shape.rs index 71b0007fc6..2023b95c88 100644 --- a/crates/rtf/src/doc/shape.rs +++ b/crates/rtf/src/doc/shape.rs @@ -413,7 +413,7 @@ impl Reader { } let blocks = std::mem::take(&mut s.blocks); s.read = true; - self.para.inlines.push(Inline::Shape { kind, w, h, float: Some(Box::new(f)), blocks, look, path: None }); + self.para.inlines.push(Inline::Shape { kind, w, h, float: Some(Box::new(f)), blocks, look, path: None, link: None }); self.para_has = true; } } diff --git a/crates/scopes/Cargo.toml b/crates/scopes/Cargo.toml new file mode 100644 index 0000000000..dbdd448b29 --- /dev/null +++ b/crates/scopes/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "craft-scopes" +description = "Video scope math: waveform, parade, histogram and vectorscopes from RGBA8 or NV12 frames, with numeric summaries and trace images" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-color = { workspace = true } +serde = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/scopes/NOTICE b/crates/scopes/NOTICE new file mode 100644 index 0000000000..fe894b8f0f --- /dev/null +++ b/crates/scopes/NOTICE @@ -0,0 +1,9 @@ +craft-scopes +Licensed under the MIT license or the Apache License, Version 2.0, at your option. + +The scope math, summaries and trace painting come from FilmCraft's `crates/scopes` +(https://github.com/storytold/filmcraft, commit 3f137a7ed420cac79b32145f5243b7f98b31f71c), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors. +The HDR histogram bins come from LightCraft's `crates/raster/src/histogram.rs` +(https://github.com/storytold/lightcraft, commit aa08a77060c0cca737dcc29b5db814cbc07ae611), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the LightCraft contributors. diff --git a/crates/scopes/README.md b/crates/scopes/README.md new file mode 100644 index 0000000000..bd21c86e89 --- /dev/null +++ b/crates/scopes/README.md @@ -0,0 +1,74 @@ +# craft-scopes + +Video scope math for a Craft app's scopes panel: the waveform, parade, histogram and the YUV and +HLS vectorscopes of a frame, as count grids, with numeric summaries and trace images. The crate +depends only on `craft-color` and `serde`, has no UI, and builds for `wasm32-unknown-unknown`. + +The `scopes` feature of `craft` re-exports this crate as `craft::scopes`. + +| Item | What | +|---|---| +| `Frame` | a borrowed frame: `Rgba8` with a row stride, or `Nv12` (Y' plane and interleaved Cb Cr plane, each with its own stride, plus the matrix and range) | +| `Signal` | a frame's R'G'B' code values, decimated by nearest-sample picking to at most 480 × 270 (`fill`, `fill_max`, `from_rgba8`, `from_rgba_f32_with` with `linear_to_pq` for HDR, `from_fn`) | +| `waveform`, `waveform_into` | RGB, luma, luma and chroma, or luma and chroma with the chroma hidden: one count grid per trace (columns = signal width, `rows` levels) | +| `parade`, `parade_into` | RGB, YUV, or RGB and luma traces, drawn side by side | +| `histogram`, `histogram_into` | 256 bins of R', G', B', Y'; samples below 0 and above 1 are counted separately | +| `histogram_hdr_into`, `HdrBins` | 256 bins of linear values: black to SDR white sRGB-encoded in the first half, then equal stops above SDR white | +| `vectorscope_yuv`, `vectorscope_yuv_into` | Cb right, Cr up, ±0.6; `targets(matrix, amplitude)` gives the six color-bar targets, `SKIN_TONE_DEG` is 123° | +| `vectorscope_hls`, `vectorscope_hls_into` | hue as the angle (red at the matrix's YUV red angle, then yellow, green, cyan, blue, magenta counter-clockwise), HLS saturation as the radius | +| `compute`, `compute_into` | one scope by `ScopeKind`, with the waveform and parade traces from `Params::waveform` and `Params::parade` | +| `summary` | levels (min, max and mean in percent) per channel and per column range, the densest vectorscope cells with angle and magnitude, a coarse vectorscope | +| `paint` | count grids to premultiplied RGBA8 (log intensity, additive traces, Brightness gain; vectorscope points spread over 3 × 3), with `*_into` forms that take a `Scratch` | + +Settings types (all serde, camelCase): `ScopeKind`, `WaveformType`, `ParadeType`, `ColorSpace` +(Automatic, Rec. 601, Rec. 709 and Rec. 2100 for the BT.601, BT.709 and BT.2020 NCL matrices), +`Scale` (8-bit, Float, HDR), `Brightness` and `Targets` (75 %, 100 %). Their `label` strings are +English; an app translates them before showing them. `ScopeKind`, `Computed`, `Frame` and +`FrameError` are `#[non_exhaustive]`, so a later scope or frame format is not a breaking change. + +## Reusing buffers + +Each `*_into` function writes into a value the caller keeps between frames. After the first frame +of a size, `Signal::fill`, the `*_into` scopes and the `paint::*_into` painters do not allocate. +`summary` allocates its results. + +## Input checks + +`Frame::validate` (called by `Signal::fill`) returns a `FrameError` for a stride shorter than a +row, a plane shorter than its rows, or a size that overflows; the signal is then empty. A signal +holds at most 1920 × 1080 samples whatever size `fill_max` is asked for, and a grid at most 1920 +columns. `Params` clamps `rows` to 2..=4096 and `vector_size` to 3..=1023, rounding an even size up to the next odd one. Grid and vectorscope +lookups outside the grid return 0. `Signal::from_fn` cuts a larger size to 1920 × 1080, and the +painters paint nothing for a hand-built grid wider than 1920 columns or taller than 4096 rows, or a +vectorscope larger than 1023. Summaries leave NaN and infinite samples out. + +## Definitions + +- Y'CbCr from R'G'B' with the matrix's Kr and Kb (ITU-R BT.601-7, BT.709-6, BT.2020-2 NCL), Cb and + Cr in −0.5…0.5. YC chroma amplitude is √(Cb² + Cr²), plotted at Y' ± C. +- NV12 code values are normalized with the frame's range (limited: Y' 16–235, Cb and Cr 16–240; + full: 0–255) and turned into R'G'B' with its matrix. Each Cb Cr pair covers 2 × 2 pixels. +- Waveform rows span 0…1 with clamping (values clamped first) or −0.1…1.1 without (values + outside are dropped). With 256 rows an 8-bit code value `c` lands on row `c`. +- HDR: linear working values (1.0 = 203 cd/m², ITU-R BT.2408) to SMPTE ST 2084 PQ code values; the + axis is 0…10 000 cd/m². SDR frames on the HDR scale use BT.1886 (γ 2.4, 100 cd/m² white). + +## Tests + +`src/tests.rs` uses generated frames with known values: a flat color lands in exact histogram bins; +a 256-step ramp fills every bin and puts column `x` on row `x`; 75 % color bars put each parade +column on its code value and each bar on its vectorscope target cell (BT.601, BT.709, BT.2020); the +8-bit limited-range BT.709 code values of the 100 % color bars in SMPTE RP 219-1 decode from NV12 +to their R'G'B' within 1.5 codes; strided and packed RGBA read the same samples; bad strides, short +planes and overflowing sizes give errors; the `*_into` functions match the allocating ones and keep +their buffers across frames; hostile parameters and inconsistent signals stay bounded; HDR bins +split SDR and stops for any split. + +## Speed + +`cargo test --release -p craft-scopes perf -- --ignored --nocapture` decimates a 1920 × 1080 frame +and times each scope on the 480 × 270 signal. + +## License + +MIT OR Apache-2.0. `NOTICE` names the code this crate started from. diff --git a/crates/scopes/src/frame.rs b/crates/scopes/src/frame.rs new file mode 100644 index 0000000000..4725f18d6e --- /dev/null +++ b/crates/scopes/src/frame.rs @@ -0,0 +1,93 @@ +//! Borrowed frames the scopes read: 8-bit R'G'B'A, or 8-bit NV12 (a Y' plane and an interleaved +//! Cb Cr plane at half width and half height), each with its own row stride. + +use std::fmt; + +use craft_color::{Matrix, Range}; + +/// A frame borrowed from its owner (a readback buffer, a decoder, a capture). Strides are in bytes. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub enum Frame<'a> { + /// R'G'B'A, 4 bytes per pixel, `stride` bytes per row (at least `width * 4`). Alpha is ignored. + Rgba8 { width: usize, height: usize, stride: usize, data: &'a [u8] }, + /// Y' at full size and Cb Cr pairs at half width and half height (rounded up). `matrix` and + /// `range` say how the code values turn back into R'G'B'. + Nv12 { width: usize, height: usize, y: &'a [u8], y_stride: usize, uv: &'a [u8], uv_stride: usize, matrix: Matrix, range: Range }, +} + +/// Why a [`Frame`] cannot be read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum FrameError { + /// A row stride shorter than one row of samples. + Stride { plane: &'static str, stride: usize, needed: usize }, + /// A plane shorter than its rows. + Short { plane: &'static str, len: usize, needed: usize }, + /// The frame's size in bytes overflows `usize`. + TooLarge, +} + +impl fmt::Display for FrameError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FrameError::Stride { plane, stride, needed } => write!(f, "{plane} plane stride {stride} is shorter than a row ({needed} bytes)"), + FrameError::Short { plane, len, needed } => write!(f, "{plane} plane holds {len} bytes; the frame needs {needed}"), + FrameError::TooLarge => write!(f, "the frame is too large to address"), + } + } +} + +impl std::error::Error for FrameError {} + +/// Bytes a plane of `rows` rows needs: every row but the last at `stride`, the last one `row_bytes`. +fn plane_len(rows: usize, stride: usize, row_bytes: usize) -> Option { + if rows == 0 { Some(0) } else { stride.checked_mul(rows - 1)?.checked_add(row_bytes) } +} + +fn check_plane(plane: &'static str, len: usize, rows: usize, stride: usize, row_bytes: usize) -> Result<(), FrameError> { + if rows == 0 || row_bytes == 0 { + return Ok(()); + } + if stride < row_bytes { + return Err(FrameError::Stride { plane, stride, needed: row_bytes }); + } + let needed = plane_len(rows, stride, row_bytes).ok_or(FrameError::TooLarge)?; + if len < needed { + return Err(FrameError::Short { plane, len, needed }); + } + Ok(()) +} + +impl Frame<'_> { + pub fn width(&self) -> usize { + match *self { + Frame::Rgba8 { width, .. } | Frame::Nv12 { width, .. } => width, + } + } + + pub fn height(&self) -> usize { + match *self { + Frame::Rgba8 { height, .. } | Frame::Nv12 { height, .. } => height, + } + } + + /// Checks that every row of every plane lies inside its slice. A frame with no width or no + /// height is valid and has no samples. + pub fn validate(&self) -> Result<(), FrameError> { + if self.width() == 0 || self.height() == 0 { + return Ok(()); + } + match *self { + Frame::Rgba8 { width, height, stride, data } => { + let row = width.checked_mul(4).ok_or(FrameError::TooLarge)?; + check_plane("RGBA", data.len(), height, stride, row) + } + Frame::Nv12 { width, height, y, y_stride, uv, uv_stride, .. } => { + check_plane("Y", y.len(), height, y_stride, width)?; + let uv_row = width.div_ceil(2).checked_mul(2).ok_or(FrameError::TooLarge)?; + check_plane("UV", uv.len(), height.div_ceil(2), uv_stride, uv_row) + } + } + } +} diff --git a/crates/scopes/src/lib.rs b/crates/scopes/src/lib.rs new file mode 100644 index 0000000000..0e83ccc9b4 --- /dev/null +++ b/crates/scopes/src/lib.rs @@ -0,0 +1,1074 @@ +//! Video scope math (no UI): the waveform, parade, histogram and the YUV and HLS vectorscopes of +//! a frame, as count grids ("how many samples land on this cell"), plus numeric summaries +//! ([`summary`]) and the density-to-pixels mapping a UI draws ([`paint`]). +//! +//! The input is a [`Signal`]: the frame's R'G'B' code values (display-encoded, 0..1 nominal; +//! values outside it are super-whites and sub-blacks of float or HDR frames), decimated to at most +//! [`MAX_W`] × [`MAX_H`] samples by nearest-sample picking (no averaging, so flat colors and test +//! patterns land on exact cells). [`Signal::fill`] reads a borrowed RGBA8 or NV12 [`Frame`] with +//! any row stride. Y'CbCr comes from the scope's matrix (BT.601, BT.709 or BT.2020 NCL; +//! `craft_color::rgb_to_ycbcr`). +//! +//! | Scope | Grid | Columns × rows | +//! |---|---|---| +//! | Waveform RGB / luma / luma and chroma / luma and chroma with the chroma hidden | per trace: R, G, B / Y / Y and C (Y ± \|CbCr\|) / Y | signal width × `rows` | +//! | Parade RGB / YUV / RGB and luma | per trace: R, G, B / Y, Cb + ½, Cr + ½ / R, G, B, Y | signal width × `rows` (drawn side by side) | +//! | Histogram | 256 bins per channel R, G, B, Y | — | +//! | YUV vectorscope | Cb horizontal, Cr up, ±[`VECTOR_EXTENT`] | `vector_size`² | +//! | HLS vectorscope | hue as the angle (red at the YUV red angle), HLS saturation as the radius (1 = 0.5) | `vector_size`² | +//! +//! [`compute`] picks the waveform and parade traces from [`Params::waveform`] and +//! [`Params::parade`]. +//! +//! Waveform rows cover `[lo, hi]` = `[0, 1]` with clamping on (values clamped first) and +//! `[-0.1, 1.1]` without (values outside are dropped). With 256 rows over `[0, 1]`, an 8-bit code +//! value `c` lands exactly on row `c`. +//! +//! Every `*_into` function writes into a value the caller keeps between frames. Once that value +//! and the [`Signal`] have grown to the frame's size, the call does not allocate. + +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +pub mod frame; +pub mod paint; +pub mod summary; +#[cfg(test)] +mod tests; + +pub use craft_color::{Matrix, Range}; +use craft_color::{normalize_c, normalize_y, rgb_to_ycbcr, ycbcr_to_rgb}; +pub use frame::{Frame, FrameError}; +use serde::{Deserialize, Serialize}; + +/// Largest decimated signal (a 1080p frame is sampled every 4th pixel both ways). +pub const MAX_W: usize = 480; +pub const MAX_H: usize = 270; + +/// Largest signal [`Signal::fill_max`] and [`Signal::fill_rgba_f32_with`] make, whatever size they +/// are asked for, and the most columns a [`Grid`] holds. +pub const MAX_SIGNAL_W: usize = 1920; +pub const MAX_SIGNAL_H: usize = 1080; + +/// Most waveform and parade levels a [`Params`] or a [`Grid`] can hold; larger values are clamped. +pub const MAX_ROWS: usize = 4096; +/// Largest vectorscope grid a [`Params`] can ask for; larger values are clamped. +pub const MAX_VECTOR_SIZE: usize = 1023; + +/// Half-width of the vectorscope plane in Cb/Cr units (the 100 % targets of every matrix fit). +pub const VECTOR_EXTENT: f32 = 0.6; + +/// The skin-tone line (the "I" axis of NTSC): 123° counter-clockwise from +Cb. +pub const SKIN_TONE_DEG: f32 = 123.0; + +// ------------------------------------------------------------------------------------ settings + +/// A scope. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub enum ScopeKind { + VectorscopeYuv, + VectorscopeHls, + Histogram, + Parade, + #[default] + Waveform, +} + +impl ScopeKind { + pub const ALL: [ScopeKind; 5] = + [ScopeKind::VectorscopeYuv, ScopeKind::VectorscopeHls, ScopeKind::Histogram, ScopeKind::Parade, ScopeKind::Waveform]; + /// Stable id (`"vectorscopeYuv"`…), as in JSON. + pub fn name(self) -> &'static str { + match self { + ScopeKind::VectorscopeYuv => "vectorscopeYuv", + ScopeKind::VectorscopeHls => "vectorscopeHls", + ScopeKind::Histogram => "histogram", + ScopeKind::Parade => "parade", + ScopeKind::Waveform => "waveform", + } + } + /// English label; an app translates it before showing it. + pub fn label(self) -> &'static str { + match self { + ScopeKind::VectorscopeYuv => "YUV vectorscope", + ScopeKind::VectorscopeHls => "HLS vectorscope", + ScopeKind::Histogram => "Histogram", + ScopeKind::Parade => "Parade", + ScopeKind::Waveform => "Waveform", + } + } + /// By id or label, ignoring case, spaces and dashes (`"vectorscope"` = the YUV one). + pub fn from_name(s: &str) -> Option { + let n = norm(s); + if n == "vectorscope" || n == "yuv" { + return Some(ScopeKind::VectorscopeYuv); + } + if n == "hls" { + return Some(ScopeKind::VectorscopeHls); + } + Self::ALL.into_iter().find(|k| norm(k.name()) == n || norm(k.label()) == n) + } +} + +fn norm(s: &str) -> String { + s.chars().filter(|c| c.is_alphanumeric()).collect::().to_ascii_lowercase() +} + +/// Waveform type. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WaveformType { + #[default] + Rgb, + Luma, + Yc, + YcNoChroma, +} + +impl WaveformType { + pub const ALL: [WaveformType; 4] = [WaveformType::Rgb, WaveformType::Luma, WaveformType::Yc, WaveformType::YcNoChroma]; + pub fn label(self) -> &'static str { + match self { + WaveformType::Rgb => "RGB", + WaveformType::Luma => "Luma", + WaveformType::Yc => "Luma and chroma", + WaveformType::YcNoChroma => "Luma and chroma, chroma hidden", + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n) + } +} + +/// Parade type. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ParadeType { + #[default] + Rgb, + Yuv, + RgbWhite, +} + +impl ParadeType { + pub const ALL: [ParadeType; 3] = [ParadeType::Rgb, ParadeType::Yuv, ParadeType::RgbWhite]; + pub fn label(self) -> &'static str { + match self { + ParadeType::Rgb => "RGB", + ParadeType::Yuv => "YUV", + ParadeType::RgbWhite => "RGB and luma", + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n) + } +} + +/// The scopes' color space (the Y'CbCr matrix; Rec. 2100 also means an HDR signal). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ColorSpace { + /// Follow the source: Rec. 2100 for an HDR working space, else Rec. 709. + #[default] + Auto, + Rec601, + Rec709, + Rec2100, +} + +impl ColorSpace { + pub const ALL: [ColorSpace; 4] = [ColorSpace::Auto, ColorSpace::Rec601, ColorSpace::Rec709, ColorSpace::Rec2100]; + pub fn label(self) -> &'static str { + match self { + ColorSpace::Auto => "Automatic", + ColorSpace::Rec601 => "Rec. 601", + ColorSpace::Rec709 => "Rec. 709", + ColorSpace::Rec2100 => "Rec. 2100", + } + } + /// `Auto` resolved for a source (`hdr`: its working space is PQ or HLG). + pub fn resolve(self, hdr: bool) -> ColorSpace { + match self { + ColorSpace::Auto if hdr => ColorSpace::Rec2100, + ColorSpace::Auto => ColorSpace::Rec709, + c => c, + } + } + pub fn matrix(self) -> Matrix { + match self { + ColorSpace::Rec601 => Matrix::Bt601, + ColorSpace::Rec2100 => Matrix::Bt2020Ncl, + _ => Matrix::Bt709, + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n || norm(k.label()).trim_start_matches("rec") == n) + } +} + +/// Signal scale (the bit-depth choice): the labels of the levels axis. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Scale { + /// 0–255 code values. + #[default] + Bits8, + /// 0.0–1.0. + Float, + /// cd/m² on a PQ axis (0–10 000). + Hdr, +} + +impl Scale { + pub const ALL: [Scale; 3] = [Scale::Bits8, Scale::Float, Scale::Hdr]; + pub fn label(self) -> &'static str { + match self { + Scale::Bits8 => "8-bit", + Scale::Float => "Float", + Scale::Hdr => "HDR", + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n) + } +} + +/// Trace brightness. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Brightness { + Dimmed, + #[default] + Normal, + Bright, +} + +impl Brightness { + pub const ALL: [Brightness; 3] = [Brightness::Dimmed, Brightness::Normal, Brightness::Bright]; + pub fn label(self) -> &'static str { + match self { + Brightness::Dimmed => "Dimmed", + Brightness::Normal => "Normal", + Brightness::Bright => "Bright", + } + } + /// Multiplier of the trace intensity. + pub fn gain(self) -> f32 { + match self { + Brightness::Dimmed => 0.55, + Brightness::Normal => 1.0, + Brightness::Bright => 1.6, + } + } +} + +/// Which color-bar targets the YUV vectorscope draws. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Targets { + #[default] + #[serde(rename = "75")] + Percent75, + #[serde(rename = "100")] + Percent100, +} + +impl Targets { + pub fn amplitude(self) -> f32 { + match self { + Targets::Percent75 => 0.75, + Targets::Percent100 => 1.0, + } + } + pub fn label(self) -> &'static str { + match self { + Targets::Percent75 => "75%", + Targets::Percent100 => "100%", + } + } +} + +/// How scopes are computed. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Params { + pub matrix: Matrix, + /// Clamping: values are clamped to 0..1 before they are plotted. + pub clamp: bool, + /// Waveform and parade levels (2..=[`MAX_ROWS`]). + pub rows: usize, + /// Vectorscope grid size (square; 3..=[`MAX_VECTOR_SIZE`]). An even size is rounded up to the + /// next odd one, so the center is a cell. + pub vector_size: usize, + /// The traces [`compute`] draws for [`ScopeKind::Waveform`]. + pub waveform: WaveformType, + /// The traces [`compute`] draws for [`ScopeKind::Parade`]. + pub parade: ParadeType, +} + +impl Default for Params { + fn default() -> Self { + Params { matrix: Matrix::Bt709, clamp: true, rows: 256, vector_size: 255, waveform: WaveformType::Rgb, parade: ParadeType::Rgb } + } +} + +impl Params { + /// The plotted value range of waveform rows. + pub fn range(&self) -> (f32, f32) { + if self.clamp { (0.0, 1.0) } else { (-0.1, 1.1) } + } + fn rows(&self) -> usize { + self.rows.clamp(2, MAX_ROWS) + } + fn vector_size(&self) -> usize { + (self.vector_size.clamp(3, MAX_VECTOR_SIZE) | 1).min(MAX_VECTOR_SIZE) + } +} + +// ------------------------------------------------------------------------------------ signal + +/// A frame's R'G'B' samples (decimated), row-major: `rgb[y * w + x]`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Signal { + pub w: usize, + pub h: usize, + pub rgb: Vec<[f32; 3]>, +} + +/// Decimation steps for a `w × h` frame read into at most `max_w × max_h` samples (each capped to +/// [`MAX_SIGNAL_W`] × [`MAX_SIGNAL_H`]). +fn steps(w: usize, h: usize, max_w: usize, max_h: usize) -> (usize, usize) { + let (max_w, max_h) = (max_w.clamp(1, MAX_SIGNAL_W), max_h.clamp(1, MAX_SIGNAL_H)); + (w.div_ceil(max_w).max(1), h.div_ceil(max_h).max(1)) +} + +impl Signal { + /// From tightly packed RGBA8 (code / 255), decimated to [`MAX_W`] × [`MAX_H`]. A buffer + /// shorter than `w * h * 4` gives an empty signal. + pub fn from_rgba8(w: usize, h: usize, px: &[u8]) -> Signal { + Self::from_rgba8_max(w, h, px, MAX_W, MAX_H) + } + + pub fn from_rgba8_max(w: usize, h: usize, px: &[u8], max_w: usize, max_h: usize) -> Signal { + let mut s = Signal::default(); + let Some(stride) = w.checked_mul(4) else { return s }; + if s.fill_max(&Frame::Rgba8 { width: w, height: h, stride, data: px }, max_w, max_h).is_err() { + s.clear(); + } + s + } + + /// Reads `frame` into this signal, decimated to [`MAX_W`] × [`MAX_H`], reusing its buffer. + pub fn fill(&mut self, frame: &Frame<'_>) -> Result<(), FrameError> { + self.fill_max(frame, MAX_W, MAX_H) + } + + /// Reads `frame` into this signal, decimated to at most `max_w` × `max_h` samples (never more + /// than [`MAX_SIGNAL_W`] × [`MAX_SIGNAL_H`]). The buffer is reused, so the call does not + /// allocate once it has held a frame this size. On an error the signal is left empty. + pub fn fill_max(&mut self, frame: &Frame<'_>, max_w: usize, max_h: usize) -> Result<(), FrameError> { + self.clear(); + frame.validate()?; + let (w, h) = (frame.width(), frame.height()); + if w == 0 || h == 0 { + return Ok(()); + } + let (sx, sy) = steps(w, h, max_w, max_h); + let (ow, oh) = (w.div_ceil(sx), h.div_ceil(sy)); + self.rgb.reserve(ow.saturating_mul(oh)); + match *frame { + Frame::Rgba8 { stride, data, .. } => { + let lut: [f32; 256] = std::array::from_fn(|i| i as f32 / 255.0); + for y in (0..h).step_by(sy) { + let row = data.get(y * stride..).unwrap_or(&[]); + for x in (0..w).step_by(sx) { + let c = match row.get(x * 4..x * 4 + 3) { + Some(&[r, g, b]) => [lut[r as usize], lut[g as usize], lut[b as usize]], + _ => [0.0; 3], + }; + self.rgb.push(c); + } + } + } + Frame::Nv12 { y: yp, y_stride, uv, uv_stride, matrix, range, .. } => { + let ylut: [f32; 256] = std::array::from_fn(|i| normalize_y(i as u32, 8, range).unwrap_or(0.0)); + let clut: [f32; 256] = std::array::from_fn(|i| normalize_c(i as u32, 8, range).unwrap_or(0.0)); + for y in (0..h).step_by(sy) { + let yrow = yp.get(y * y_stride..).unwrap_or(&[]); + let crow = uv.get((y / 2) * uv_stride..).unwrap_or(&[]); + for x in (0..w).step_by(sx) { + let c = match (yrow.get(x), crow.get((x / 2) * 2..(x / 2) * 2 + 2)) { + (Some(&l), Some(&[cb, cr])) => ycbcr_to_rgb(ylut[l as usize], clut[cb as usize], clut[cr as usize], matrix), + _ => [0.0; 3], + }; + self.rgb.push(c); + } + } + } + } + self.w = ow; + self.h = oh; + Ok(()) + } + + /// From tightly packed RGBA f32 pixels through `map` (for example linear light to PQ code + /// values), decimated. A buffer shorter than `w * h * 4` gives an empty signal. + pub fn from_rgba_f32_with(w: usize, h: usize, px: &[f32], max_w: usize, max_h: usize, map: impl Fn([f32; 4]) -> [f32; 3]) -> Signal { + let mut s = Signal::default(); + s.fill_rgba_f32_with(w, h, px, max_w, max_h, map); + s + } + + /// [`Signal::from_rgba_f32_with`] into this signal, reusing its buffer. + pub fn fill_rgba_f32_with(&mut self, w: usize, h: usize, px: &[f32], max_w: usize, max_h: usize, map: impl Fn([f32; 4]) -> [f32; 3]) { + self.clear(); + let needed = w.checked_mul(h).and_then(|n| n.checked_mul(4)); + if w == 0 || h == 0 || needed.is_none_or(|n| px.len() < n) { + return; + } + let (sx, sy) = steps(w, h, max_w, max_h); + let (ow, oh) = (w.div_ceil(sx), h.div_ceil(sy)); + self.rgb.reserve(ow.saturating_mul(oh)); + for y in (0..h).step_by(sy) { + for x in (0..w).step_by(sx) { + let i = (y * w + x) * 4; + let c = match px.get(i..i + 4) { + Some(&[r, g, b, a]) => map([r, g, b, a]), + _ => [0.0; 3], + }; + self.rgb.push(c); + } + } + self.w = ow; + self.h = oh; + } + + /// A synthetic signal (tests, generated patterns), at most [`MAX_SIGNAL_W`] × [`MAX_SIGNAL_H`]: + /// a larger size is cut to that. + pub fn from_fn(w: usize, h: usize, f: impl Fn(usize, usize) -> [f32; 3]) -> Signal { + let (w, h) = (w.min(MAX_SIGNAL_W), h.min(MAX_SIGNAL_H)); + let mut rgb = Vec::with_capacity(w * h); + for y in 0..h { + for x in 0..w { + rgb.push(f(x, y)); + } + } + Signal { w, h, rgb } + } + + /// Every sample through `f` (for example SDR code values to PQ for the HDR scale). + pub fn map(&self, f: impl Fn([f32; 3]) -> [f32; 3]) -> Signal { + Signal { w: self.w, h: self.h, rgb: self.rgb.iter().map(|c| f(*c)).collect() } + } + + /// Empties the signal and keeps its buffer. + pub fn clear(&mut self) { + self.w = 0; + self.h = 0; + self.rgb.clear(); + } + + pub fn len(&self) -> usize { + self.rgb.len() + } + pub fn is_empty(&self) -> bool { + self.rgb.is_empty() + } + + /// The rows of samples, each `w` long. A signal whose `w` and `rgb` disagree yields only + /// whole rows. + fn rows(&self) -> std::slice::ChunksExact<'_, [f32; 3]> { + self.rgb.chunks_exact(self.w.max(1)) + } + + /// Columns the grids of this signal have: `w`, or 0 when there are no samples. + fn cols(&self) -> usize { + if self.rgb.is_empty() { 0 } else { self.w.min(self.rgb.len()) } + } +} + +/// Linear light (1.0 = reference white = 203 cd/m², premultiplied RGBA) to PQ code values, for +/// HDR scopes: 0..1 on the axis is 0..10 000 cd/m². +pub fn linear_to_pq([r, g, b, a]: [f32; 4]) -> [f32; 3] { + let a = if a > 1e-6 { a } else { 1.0 }; + let white = craft_color::REFERENCE_WHITE_NITS as f32; + let f = |v: f32| craft_color::pq_inverse_eotf(((v / a).max(0.0) * white / 10_000.0).clamp(0.0, 1.0)); + [f(r), f(g), f(b)] +} + +/// An SDR code value (BT.1886, 100 cd/m² white) on the PQ axis (the HDR scale of an SDR frame). +pub fn sdr_to_pq(v: f32) -> f32 { + craft_color::pq_inverse_eotf((v.clamp(0.0, 1.0).powf(2.4) * 100.0 / 10_000.0).clamp(0.0, 1.0)) +} + +/// cd/m² to height on the PQ axis (0..1). +pub fn nits_to_pq(nits: f32) -> f32 { + craft_color::pq_inverse_eotf((nits / 10_000.0).clamp(0.0, 1.0)) +} + +// ------------------------------------------------------------------------------------ grids + +/// A count grid: `data[row * cols + col]`, row 0 = the lowest level. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Grid { + pub name: &'static str, + pub cols: usize, + pub rows: usize, + pub data: Vec, +} + +impl Grid { + pub fn new(name: &'static str, cols: usize, rows: usize) -> Grid { + let mut g = Grid::default(); + g.reset(name, cols, rows); + g + } + /// Zeroes the grid at a new size (at most [`MAX_SIGNAL_W`] columns and [`MAX_ROWS`] rows), + /// reusing its buffer. + pub fn reset(&mut self, name: &'static str, cols: usize, rows: usize) { + self.name = name; + self.cols = cols.min(MAX_SIGNAL_W); + self.rows = rows.min(MAX_ROWS); + self.data.clear(); + self.data.resize(self.cols * self.rows, 0); + } + /// The count of a cell (0 outside the grid). + pub fn at(&self, col: usize, row: usize) -> u32 { + if col >= self.cols || row >= self.rows { + return 0; + } + row.checked_mul(self.cols).and_then(|i| i.checked_add(col)).and_then(|i| self.data.get(i)).copied().unwrap_or(0) + } + pub fn total(&self) -> u64 { + self.data.iter().map(|&c| c as u64).sum() + } + pub fn max(&self) -> u32 { + self.data.iter().copied().max().unwrap_or(0) + } + /// The rows hit in a column, lowest first. + pub fn rows_in(&self, col: usize) -> Vec { + (0..self.rows).filter(|&r| self.at(col, r) > 0).collect() + } + #[inline] + fn hit(&mut self, col: usize, row: usize) { + if col >= self.cols || row >= self.rows { + return; + } + if let Some(c) = self.data.get_mut(row * self.cols + col) { + *c = c.saturating_add(1); + } + } +} + +/// Waveform or parade: one grid per trace, columns = the signal's width. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Waveform { + pub lo: f32, + pub hi: f32, + /// Levels of every trace. + pub rows: usize, + /// Samples per column (the signal's height). + pub per_column: usize, + pub traces: Vec, +} + +impl Waveform { + pub fn trace(&self, name: &str) -> Option<&Grid> { + self.traces.iter().find(|t| t.name == name) + } + /// The value at the center of a row. + pub fn level(&self, row: usize) -> f32 { + self.lo + (self.hi - self.lo) * row as f32 / (self.rows.max(2) - 1) as f32 + } +} + +/// Row of value `v` in `[lo, hi]` over `rows` levels (None outside, for NaN, or with fewer than +/// two rows or an empty range). +#[inline] +pub fn row_of(v: f32, lo: f32, hi: f32, rows: usize) -> Option { + if rows < 2 || hi <= lo { + return None; + } + let t = (v - lo) / (hi - lo); + if !(0.0..=1.0).contains(&t) { + return None; + } + Some(((t * (rows - 1) as f32).round() as usize).min(rows - 1)) +} + +/// Up to 4 (trace, value) pairs per sample. +type Hits = ([(u8, f32); 4], usize); + +fn build_into(s: &Signal, p: &Params, names: &[&'static str], out: &mut Waveform, sample: impl Fn([f32; 3]) -> Hits) { + let (lo, hi) = p.range(); + let rows = p.rows(); + let cols = s.cols(); + out.traces.truncate(names.len()); + while out.traces.len() < names.len() { + out.traces.push(Grid::default()); + } + for (g, &name) in out.traces.iter_mut().zip(names) { + g.reset(name, cols, rows); + } + let mut per_column = 0; + if cols > 0 { + for row in s.rows() { + per_column += 1; + for (x, &c) in row.iter().enumerate() { + let c = if p.clamp { c.map(|v| v.clamp(0.0, 1.0)) } else { c }; + let (hits, n) = sample(c); + for &(t, v) in hits.get(..n).unwrap_or(&[]) { + let v = if p.clamp { v.clamp(0.0, 1.0) } else { v }; + if let (Some(r), Some(g)) = (row_of(v, lo, hi, rows), out.traces.get_mut(t as usize)) { + g.hit(x, r); + } + } + } + } + } + out.lo = lo; + out.hi = hi; + out.rows = rows; + out.per_column = per_column; +} + +/// The waveform of a signal. +pub fn waveform(s: &Signal, kind: WaveformType, p: &Params) -> Waveform { + let mut w = Waveform::default(); + waveform_into(s, kind, p, &mut w); + w +} + +/// [`waveform`] into `out`, reusing its grids. +pub fn waveform_into(s: &Signal, kind: WaveformType, p: &Params, out: &mut Waveform) { + let m = p.matrix; + let z = (0u8, 0.0f32); + match kind { + WaveformType::Rgb => build_into(s, p, &["R", "G", "B"], out, |[r, g, b]| ([(0, r), (1, g), (2, b), z], 3)), + WaveformType::Luma | WaveformType::YcNoChroma => build_into(s, p, &["Y"], out, |[r, g, b]| ([(0, rgb_to_ycbcr(r, g, b, m)[0]), z, z, z], 1)), + WaveformType::Yc => build_into(s, p, &["Y", "C"], out, |[r, g, b]| { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + let c = (cb * cb + cr * cr).sqrt(); + ([(0, y), (1, y + c), (1, y - c), z], if c > 1e-6 { 3 } else { 2 }) + }), + } +} + +/// The parade of a signal (the traces are drawn side by side). +pub fn parade(s: &Signal, kind: ParadeType, p: &Params) -> Waveform { + let mut w = Waveform::default(); + parade_into(s, kind, p, &mut w); + w +} + +/// [`parade`] into `out`, reusing its grids. +pub fn parade_into(s: &Signal, kind: ParadeType, p: &Params, out: &mut Waveform) { + let m = p.matrix; + let z = (0u8, 0.0f32); + match kind { + ParadeType::Rgb => build_into(s, p, &["R", "G", "B"], out, |[r, g, b]| ([(0, r), (1, g), (2, b), z], 3)), + ParadeType::RgbWhite => { + build_into(s, p, &["R", "G", "B", "Y"], out, |[r, g, b]| ([(0, r), (1, g), (2, b), (3, rgb_to_ycbcr(r, g, b, m)[0])], 4)) + } + ParadeType::Yuv => build_into(s, p, &["Y", "Cb", "Cr"], out, |[r, g, b]| { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + ([(0, y), (1, cb + 0.5), (2, cr + 0.5), z], 3) + }), + } +} + +// ------------------------------------------------------------------------------------ histogram + +/// 256-bin histograms of R', G', B' and Y'. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Histogram { + pub r: Vec, + pub g: Vec, + pub b: Vec, + pub y: Vec, + pub samples: u32, + /// Samples below 0 or above the top bin per channel (R, G, B, Y). With clamping they are + /// also counted in the first or last bin of an SDR histogram. + pub below: [u32; 4], + pub above: [u32; 4], + /// How an HDR histogram splits its bins; `None` for an SDR histogram. + #[serde(skip_serializing_if = "Option::is_none")] + pub hdr: Option, + /// HDR histograms: samples with any of R, G and B above SDR white (0 for SDR histograms). + pub above_sdr_samples: u32, +} + +pub const BINS: usize = 256; + +impl Histogram { + fn reset(&mut self, hdr: Option) { + for v in [&mut self.r, &mut self.g, &mut self.b, &mut self.y] { + v.clear(); + v.resize(BINS, 0); + } + self.samples = 0; + self.below = [0; 4]; + self.above = [0; 4]; + self.hdr = hdr; + self.above_sdr_samples = 0; + } + fn channel(&mut self, i: usize) -> &mut Vec { + match i { + 0 => &mut self.r, + 1 => &mut self.g, + 2 => &mut self.b, + _ => &mut self.y, + } + } + fn count(&mut self, i: usize, bin: usize) { + if let Some(c) = self.channel(i).get_mut(bin) { + *c = c.saturating_add(1); + } + } +} + +/// Bin of a value (None when outside 0..1). +#[inline] +pub fn bin_of(v: f32) -> Option { + if (0.0..=1.0 + 1e-6).contains(&v) { Some(((v * 255.0).round() as usize).min(BINS - 1)) } else { None } +} + +pub fn histogram(s: &Signal, p: &Params) -> Histogram { + let mut h = Histogram::default(); + histogram_into(s, p, &mut h); + h +} + +/// [`histogram`] into `out`, reusing its bins. +pub fn histogram_into(s: &Signal, p: &Params, out: &mut Histogram) { + out.reset(None); + out.samples = u32::try_from(s.len()).unwrap_or(u32::MAX); + for &[r, g, b] in &s.rgb { + let y = rgb_to_ycbcr(r, g, b, p.matrix)[0]; + // With clamping, the luma bin comes from the clamped R'G'B', as on the waveform; `below` + // and `above` count the luma of the sample as it is. + let y_bin = if p.clamp { + let [cr, cg, cb] = [r, g, b].map(|v| v.clamp(0.0, 1.0)); + rgb_to_ycbcr(cr, cg, cb, p.matrix)[0] + } else { + y + }; + for (i, (v, at)) in [(r, r), (g, g), (b, b), (y, y_bin)].into_iter().enumerate() { + if !v.is_nan() && bin_of(v).is_none() { + let side = if v < 0.0 { &mut out.below[i] } else { &mut out.above[i] }; + *side = side.saturating_add(1); + } + match bin_of(at) { + Some(k) => out.count(i, k), + None if at.is_nan() || !p.clamp => {} + None => out.count(i, if at < 0.0 { 0 } else { BINS - 1 }), + } + } + } +} + +/// The split of an HDR histogram: bins below `from` cover black to SDR white (sRGB-encoded, as an +/// SDR histogram), and bins `from..256` cover `0..stops` stops above SDR white in equal steps. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HdrBins { + pub from: usize, + pub stops: f32, +} + +impl HdrBins { + /// SDR takes the left half of the bins. + pub const DEFAULT_FROM: usize = BINS / 2; + + /// The default split reaching `stops` stops above SDR white. + pub fn new(stops: f32) -> HdrBins { + HdrBins { from: Self::DEFAULT_FROM, stops } + } + + /// The bin of a linear value (1 = SDR white; NaN and negatives count as black). Any `from` + /// and any `stops` give a bin inside the histogram. + pub fn bin(self, v: f32) -> usize { + let last = BINS - 1; + let from = self.from.clamp(2, last); + if v.is_nan() || v <= 0.0 { + return 0; + } + if v <= 1.0 { + let e = craft_color::linear_to_srgb(v); + return ((e * (from - 1) as f32 + 0.5) as usize).min(from - 1); + } + let t = (v.log2() / self.stops()).clamp(0.0, 1.0); + (from + (t * (last - from) as f32 + 0.5) as usize).min(last) + } + + fn stops(self) -> f32 { + if self.stops.is_finite() { self.stops.max(1e-3) } else { 1e-3 } + } + + /// The linear value the last bin reaches. + pub fn top(self) -> f32 { + self.stops().exp2() + } +} + +/// The HDR histogram of a signal of linear values (1 = SDR white): R, G, B and the luma of +/// `matrix`, split by `bins`. Negative values count in `below`, values past [`HdrBins::top`] in +/// `above`; both also land in the first or last bin. +pub fn histogram_hdr_into(linear: &Signal, matrix: Matrix, bins: HdrBins, out: &mut Histogram) { + out.reset(Some(bins)); + out.samples = u32::try_from(linear.len()).unwrap_or(u32::MAX); + let (kr, kb) = matrix.kr_kb(); + let top = bins.top(); + for &[r, g, b] in &linear.rgb { + if r > 1.0 || g > 1.0 || b > 1.0 { + out.above_sdr_samples = out.above_sdr_samples.saturating_add(1); + } + let y = kr * r + (1.0 - kr - kb) * g + kb * b; + for (i, v) in [r, g, b, y].into_iter().enumerate() { + out.count(i, bins.bin(v)); + if v < 0.0 { + out.below[i] = out.below[i].saturating_add(1); + } else if v > top { + out.above[i] = out.above[i].saturating_add(1); + } + } + } +} + +/// Fraction of samples with any of R, G and B above SDR white (0 for SDR histograms). +pub fn above_sdr(h: &Histogram) -> f32 { + if h.hdr.is_none() || h.samples == 0 { + return 0.0; + } + (h.above_sdr_samples as f32 / h.samples as f32).min(1.0) +} + +// ------------------------------------------------------------------------------------ vectorscopes + +/// A vectorscope: `data[y * size + x]`, x = Cb (right = +), y = Cr (row 0 = top = +Cr). +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Vectorscope { + pub size: usize, + pub extent: f32, + pub data: Vec, + pub samples: u32, + /// Mean (Cb, Cr) of the plotted points. + pub mean: [f32; 2], + /// The matrix the points were plotted with; [`paint::vectorscope`] colors them with it. + pub matrix: Matrix, + /// Whether the points are HLS (hue as the angle from the matrix's red, saturation as the + /// radius) instead of (Cb, Cr). + pub hls: bool, +} + +/// Cell of a (Cb, Cr) point on a `size`² plane spanning ±`extent` (None outside, for NaN, or for a +/// plane under 2 cells or with no extent). +#[inline] +pub fn cell_of(cb: f32, cr: f32, size: usize, extent: f32) -> Option<(usize, usize)> { + if size < 2 || extent.is_nan() || extent <= 0.0 { + return None; + } + let n = (size - 1) as f32; + let fx = (cb / extent * 0.5 + 0.5) * n; + let fy = (0.5 - cr / extent * 0.5) * n; + if !(0.0..=n).contains(&fx) || !(0.0..=n).contains(&fy) { + return None; + } + Some((fx.round() as usize, fy.round() as usize)) +} + +impl Vectorscope { + fn reset(&mut self, size: usize, matrix: Matrix, hls: bool) { + self.size = size; + self.matrix = matrix; + self.hls = hls; + self.extent = VECTOR_EXTENT; + self.data.clear(); + self.data.resize(size.saturating_mul(size), 0); + self.samples = 0; + self.mean = [0.0; 2]; + } + /// The count of a cell (0 outside the plane). + pub fn at(&self, x: usize, y: usize) -> u32 { + if x >= self.size || y >= self.size { + return 0; + } + y.checked_mul(self.size).and_then(|i| i.checked_add(x)).and_then(|i| self.data.get(i)).copied().unwrap_or(0) + } + pub fn cell(&self, cb: f32, cr: f32) -> Option<(usize, usize)> { + cell_of(cb, cr, self.size, self.extent) + } + /// (Cb, Cr) at the center of a cell. + pub fn point(&self, x: usize, y: usize) -> [f32; 2] { + let n = self.size.saturating_sub(1).max(1) as f32; + [(x as f32 / n - 0.5) * 2.0 * self.extent, (0.5 - y as f32 / n) * 2.0 * self.extent] + } + #[inline] + fn plot(&mut self, cb: f32, cr: f32, sum: &mut [f64; 2]) { + if let Some((x, y)) = self.cell(cb, cr) + && let Some(c) = self.data.get_mut(y * self.size + x) + { + *c = c.saturating_add(1); + self.samples = self.samples.saturating_add(1); + sum[0] += cb as f64; + sum[1] += cr as f64; + } + } + fn finish(&mut self, sum: [f64; 2]) { + if self.samples > 0 { + self.mean = [(sum[0] / self.samples as f64) as f32, (sum[1] / self.samples as f64) as f32]; + } + } +} + +/// The YUV vectorscope (Cb, Cr of each sample). +pub fn vectorscope_yuv(s: &Signal, p: &Params) -> Vectorscope { + let mut v = Vectorscope::default(); + vectorscope_yuv_into(s, p, &mut v); + v +} + +/// [`vectorscope_yuv`] into `out`, reusing its plane. +pub fn vectorscope_yuv_into(s: &Signal, p: &Params, out: &mut Vectorscope) { + out.reset(p.vector_size(), p.matrix, false); + let mut sum = [0f64; 2]; + for &c in &s.rgb { + let [r, g, b] = if p.clamp { c.map(|x| x.clamp(0.0, 1.0)) } else { c }; + let [_, cb, cr] = rgb_to_ycbcr(r, g, b, p.matrix); + out.plot(cb, cr, &mut sum); + } + out.finish(sum); +} + +/// Angle (degrees, counter-clockwise from +Cb, 0..360) of a chroma point. +pub fn angle_deg(cb: f32, cr: f32) -> f32 { + cr.atan2(cb).to_degrees().rem_euclid(360.0) +} + +/// The angle of pure red on a matrix's vectorscope (BT.709 ≈ 103°): the HLS scope puts hue 0 there. +pub fn red_angle(m: Matrix) -> f32 { + let [_, cb, cr] = rgb_to_ycbcr(1.0, 0.0, 0.0, m); + angle_deg(cb, cr) +} + +/// A sample's point on the HLS vectorscope: hue as the angle from red (counter-clockwise, red, +/// yellow, green, cyan, blue, magenta), HLS saturation as the radius (1 = 0.5). +pub fn hls_point([r, g, b]: [f32; 3], m: Matrix) -> [f32; 2] { + let [h, s, _] = craft_color::rgb_to_hsl(r, g, b); + let a = (red_angle(m) + h * 360.0).to_radians(); + let rad = s.clamp(0.0, 1.0) * 0.5; + [rad * a.cos(), rad * a.sin()] +} + +/// Hue steps of the HLS vectorscope's direction table (0.1°). +const HUE_STEPS: usize = 3600; + +/// The HLS vectorscope. +pub fn vectorscope_hls(s: &Signal, p: &Params) -> Vectorscope { + let mut v = Vectorscope::default(); + vectorscope_hls_into(s, p, &mut v); + v +} + +/// [`vectorscope_hls`] into `out`, reusing its plane. +pub fn vectorscope_hls_into(s: &Signal, p: &Params, out: &mut Vectorscope) { + out.reset(p.vector_size(), p.matrix, true); + let mut sum = [0f64; 2]; + // hue to unit direction, tabulated at 0.1° on the stack (trigonometry per sample is the slow part) + let red = red_angle(p.matrix); + let dirs: [[f32; 2]; HUE_STEPS + 1] = std::array::from_fn(|i| { + let a = (red + i as f32 / 10.0).to_radians(); + [a.cos(), a.sin()] + }); + for &c in &s.rgb { + let [r, g, b] = if p.clamp { c.map(|x| x.clamp(0.0, 1.0)) } else { c }; + let [h, sat, _] = craft_color::rgb_to_hsl(r, g, b); + let [dx, dy] = dirs.get(((h * HUE_STEPS as f32).round() as usize).min(HUE_STEPS)).copied().unwrap_or([1.0, 0.0]); + let rad = sat.clamp(0.0, 1.0) * 0.5; + out.plot(rad * dx, rad * dy, &mut sum); + } + out.finish(sum); +} + +/// A color-bar target of the YUV vectorscope. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct Target { + pub name: &'static str, + pub rgb: [f32; 3], + pub cb: f32, + pub cr: f32, +} + +/// The six color-bar targets (R, Mg, B, Cy, G, Yl) at `amplitude` (0.75 or 1.0). +pub fn targets(m: Matrix, amplitude: f32) -> [Target; 6] { + let a = amplitude; + let t = |name, rgb: [f32; 3]| { + let [_, cb, cr] = rgb_to_ycbcr(rgb[0], rgb[1], rgb[2], m); + Target { name, rgb, cb, cr } + }; + [t("R", [a, 0.0, 0.0]), t("Mg", [a, 0.0, a]), t("B", [0.0, 0.0, a]), t("Cy", [0.0, a, a]), t("G", [0.0, a, 0.0]), t("Yl", [a, a, 0.0])] +} + +/// Hue labels of the HLS vectorscope at radius 0.5: (name, Cb, Cr). +pub fn hls_targets(m: Matrix) -> [(&'static str, f32, f32); 6] { + let red = red_angle(m); + let at = |name, h: f32| { + let a = (red + h).to_radians(); + (name, 0.5 * a.cos(), 0.5 * a.sin()) + }; + [at("R", 0.0), at("Yl", 60.0), at("G", 120.0), at("Cy", 180.0), at("B", 240.0), at("Mg", 300.0)] +} + +// ------------------------------------------------------------------------------------ all scopes + +/// One computed scope. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum Computed { + Waveform(Waveform), + Parade(Waveform), + Histogram(Histogram), + Vectorscope(Vectorscope), +} + +impl Default for Computed { + fn default() -> Self { + Computed::Waveform(Waveform::default()) + } +} + +/// Compute one scope. +pub fn compute(kind: ScopeKind, s: &Signal, p: &Params) -> Computed { + let mut c = Computed::default(); + compute_into(kind, s, p, &mut c); + c +} + +/// [`compute`] into `out`. While `kind` stays the same, the buffers of the previous result are +/// reused. +pub fn compute_into(kind: ScopeKind, s: &Signal, p: &Params, out: &mut Computed) { + match (kind, &mut *out) { + (ScopeKind::Waveform, Computed::Waveform(w)) => waveform_into(s, p.waveform, p, w), + (ScopeKind::Parade, Computed::Parade(w)) => parade_into(s, p.parade, p, w), + (ScopeKind::Histogram, Computed::Histogram(h)) => histogram_into(s, p, h), + (ScopeKind::VectorscopeYuv, Computed::Vectorscope(v)) => vectorscope_yuv_into(s, p, v), + (ScopeKind::VectorscopeHls, Computed::Vectorscope(v)) => vectorscope_hls_into(s, p, v), + _ => { + // a different kind: move the old grids over where the shapes match + let old = std::mem::take(out); + *out = match (kind, old) { + (ScopeKind::Waveform, Computed::Parade(w)) => Computed::Waveform(w), + (ScopeKind::Parade, Computed::Waveform(w)) => Computed::Parade(w), + (ScopeKind::Waveform, _) => Computed::Waveform(Waveform::default()), + (ScopeKind::Parade, _) => Computed::Parade(Waveform::default()), + (ScopeKind::Histogram, _) => Computed::Histogram(Histogram::default()), + (ScopeKind::VectorscopeYuv | ScopeKind::VectorscopeHls, Computed::Vectorscope(v)) => Computed::Vectorscope(v), + (ScopeKind::VectorscopeYuv | ScopeKind::VectorscopeHls, _) => Computed::Vectorscope(Vectorscope::default()), + }; + compute_into(kind, s, p, out); + } + } +} diff --git a/crates/scopes/src/paint.rs b/crates/scopes/src/paint.rs new file mode 100644 index 0000000000..fff26ea9a2 --- /dev/null +++ b/crates/scopes/src/paint.rs @@ -0,0 +1,166 @@ +//! Count grids to pixels: the trace images a UI uploads as textures. +//! +//! A cell's intensity grows with the logarithm of its count relative to a reference count (a +//! "full" cell: a flat color puts a whole column of samples on one waveform cell), so sparse +//! detail stays visible next to flat areas, like a phosphor trace. Traces of several grids add +//! up (R + G + B traces that coincide read white). +//! +//! The `*_into` functions write into buffers the caller keeps ([`Scratch`] and the output `Vec`), +//! so painting the same size again does not allocate. + +use crate::{Grid, MAX_ROWS, MAX_SIGNAL_W, MAX_VECTOR_SIZE, Vectorscope}; + +/// Intensity 0..1 of a cell holding `count` samples (`reference` = a full cell, `gain` = the +/// Brightness setting). +#[inline] +pub fn intensity(count: u32, reference: f32, gain: f32) -> f32 { + if count == 0 { + return 0.0; + } + let r = (1.0 + reference.max(1.0)).ln(); + (gain * (0.12 + 0.88 * (1.0 + count as f32).ln() / r)).clamp(0.0, 1.0) +} + +/// Working buffers of the painters, kept between frames. +#[derive(Clone, Debug, Default)] +pub struct Scratch { + acc: Vec<[f32; 3]>, + level: Vec, + tint: Vec<[f32; 3]>, +} + +fn reset(v: &mut Vec, n: usize, value: T) { + v.clear(); + v.resize(n, value); +} + +/// Paint grids of equal size with colors (0..1 RGB), additively, into premultiplied RGBA8 with the +/// highest row at the top. Empty cells are transparent. Grids of another size than the first are +/// skipped. +pub fn grids(layers: &[(&Grid, [f32; 3])], reference: f32, gain: f32) -> (usize, usize, Vec) { + let mut out = Vec::new(); + let (w, h) = grids_into(layers, reference, gain, &mut Scratch::default(), &mut out); + (w, h, out) +} + +/// [`grids`] into `out` (resized to `w * h * 4`), returning `(w, h)`. A first grid wider than +/// [`MAX_SIGNAL_W`] or taller than [`MAX_ROWS`] paints nothing and gives `(0, 0)`. +pub fn grids_into(layers: &[(&Grid, [f32; 3])], reference: f32, gain: f32, scratch: &mut Scratch, out: &mut Vec) -> (usize, usize) { + let Some((first, _)) = layers.first().filter(|(g, _)| g.cols <= MAX_SIGNAL_W && g.rows <= MAX_ROWS) else { + out.clear(); + return (0, 0); + }; + let (w, h) = (first.cols, first.rows); + let n = w.saturating_mul(h); + reset(out, n.saturating_mul(4), 0u8); + reset(&mut scratch.acc, n, [0f32; 3]); + for (g, col) in layers { + if g.cols != w || g.rows != h || g.data.len() < n { + continue; + } + for (row, counts) in g.data.chunks_exact(w.max(1)).take(h).enumerate() { + let dst = (h - 1 - row) * w; + let Some(acc) = scratch.acc.get_mut(dst..dst + w) else { continue }; + for (a, &c) in acc.iter_mut().zip(counts) { + if c > 0 { + let i = intensity(c, reference, gain); + for k in 0..3 { + a[k] += col[k] * i; + } + } + } + } + } + for (o, a) in out.as_chunks_mut::<4>().0.iter_mut().zip(&scratch.acc) { + let m = a[0].max(a[1]).max(a[2]); + if m <= 0.0 { + continue; + } + o[0] = (a[0].min(1.0) * 255.0).round() as u8; + o[1] = (a[1].min(1.0) * 255.0).round() as u8; + o[2] = (a[2].min(1.0) * 255.0).round() as u8; + o[3] = (m.min(1.0) * 255.0).round() as u8; + } + (w, h) +} + +/// The reference count of a waveform cell: half a column. +pub fn waveform_reference(per_column: usize) -> f32 { + (per_column as f32 / 2.0).max(1.0) +} + +/// The 3 × 3 spread of a vectorscope point: (dy, dx, weight). +const SPREAD: [(i64, i64, f32); 9] = + [(0, 0, 1.0), (-1, 0, 0.6), (1, 0, 0.6), (0, -1, 0.6), (0, 1, 0.6), (-1, -1, 0.35), (-1, 1, 0.35), (1, -1, 0.35), (1, 1, 0.35)]; + +/// Paint a vectorscope: each point takes the color of its own position (hue = angle) when +/// `colorize`, else `col`, and spreads over its 3 × 3 neighborhood (falling off), so isolated +/// points stay visible when the scope is drawn smaller than its grid. Premultiplied RGBA8, row +/// 0 = +Cr. +pub fn vectorscope(v: &Vectorscope, col: [f32; 3], gain: f32, colorize: bool) -> (usize, usize, Vec) { + let mut out = Vec::new(); + let (w, h) = vectorscope_into(v, col, gain, colorize, &mut Scratch::default(), &mut out); + (w, h, out) +} + +/// [`vectorscope`] into `out` (resized to `size² * 4`), returning `(size, size)`. A vectorscope +/// larger than [`MAX_VECTOR_SIZE`] paints nothing and gives `(0, 0)`. +pub fn vectorscope_into(v: &Vectorscope, col: [f32; 3], gain: f32, colorize: bool, scratch: &mut Scratch, out: &mut Vec) -> (usize, usize) { + if v.size > MAX_VECTOR_SIZE { + out.clear(); + return (0, 0); + } + let n = v.size; + let cells = n.saturating_mul(n); + let reference = (v.samples as f32 / 64.0).max(1.0); + reset(&mut scratch.level, cells, 0f32); + reset(&mut scratch.tint, cells, [0f32; 3]); + for y in 0..n { + for x in 0..n { + let c = v.at(x, y); + if c == 0 { + continue; + } + let i = intensity(c, reference, gain); + let t = if colorize { + let [px, py] = v.point(x, y); + // the color at this point with mid lightness, desaturated towards white + let [r, g, b] = if v.hls { + let hue = ((crate::angle_deg(px, py) - crate::red_angle(v.matrix)) / 360.0).rem_euclid(1.0); + let sat = (px.hypot(py) / 0.5).clamp(0.0, 1.0); + craft_color::hsl_to_rgb(hue, sat * 0.8, 0.5) + } else { + craft_color::ycbcr_to_rgb(0.6, px * 0.8, py * 0.8, v.matrix) + }; + [0.55 + 0.45 * r.clamp(0.0, 1.0), 0.55 + 0.45 * g.clamp(0.0, 1.0), 0.55 + 0.45 * b.clamp(0.0, 1.0)] + } else { + col + }; + for (dy, dx, w) in SPREAD { + let (yy, xx) = (y as i64 + dy, x as i64 + dx); + if yy < 0 || xx < 0 || yy >= n as i64 || xx >= n as i64 { + continue; + } + let k = yy as usize * n + xx as usize; + if let (Some(l), Some(tk)) = (scratch.level.get_mut(k), scratch.tint.get_mut(k)) + && i * w > *l + { + *l = i * w; + *tk = t; + } + } + } + } + reset(out, cells.saturating_mul(4), 0u8); + for ((o, l), t) in out.as_chunks_mut::<4>().0.iter_mut().zip(&scratch.level).zip(&scratch.tint) { + if *l > 0.0 { + o.copy_from_slice(&[ + (t[0] * l * 255.0).round() as u8, + (t[1] * l * 255.0).round() as u8, + (t[2] * l * 255.0).round() as u8, + (l * 255.0).round() as u8, + ]); + } + } + (n, n) +} diff --git a/crates/scopes/src/summary.rs b/crates/scopes/src/summary.rs new file mode 100644 index 0000000000..a8c73d00a4 --- /dev/null +++ b/crates/scopes/src/summary.rs @@ -0,0 +1,199 @@ +//! Numeric summaries of scopes, for agents and control clients checking color without looking. +//! Levels are in percent of full scale (IRE-like: code value / 255 × 100 for 8-bit signals). + +use craft_color::rgb_to_ycbcr; +use serde::Serialize; + +use crate::{Grid, MAX_ROWS, MAX_SIGNAL_W, MAX_VECTOR_SIZE, Matrix, Signal, Vectorscope, Waveform, angle_deg, red_angle}; + +/// Minimum, maximum and mean of a set of levels (percent). +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct Level { + pub min: f64, + pub max: f64, + pub mean: f64, +} + +#[derive(Default)] +struct Acc { + min: f32, + max: f32, + sum: f64, + n: u64, +} + +impl Acc { + /// Adds `count` samples at `v`; NaN and infinite values are left out. + fn add(&mut self, v: f32, count: u64) { + if !v.is_finite() { + return; + } + if self.n == 0 { + self.min = v; + self.max = v; + } else { + self.min = self.min.min(v); + self.max = self.max.max(v); + } + self.sum += v as f64 * count as f64; + self.n += count; + } + fn level(&self) -> Option { + (self.n > 0).then(|| Level { min: round2(self.min), max: round2(self.max), mean: round2(self.sum / self.n as f64) }) + } +} + +/// Rounded to 0.01 (as f64, so JSON shows `78.43`, not the f32's `78.43000030517578`). +fn round2(v: impl Into) -> f64 { + (v.into() * 100.0).round() / 100.0 +} + +/// Per-channel levels of the signal itself (R', G', B', Y'), exact (not from grid cells). NaN and +/// infinite values are left out of every level and of the chroma mean. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChannelStats { + pub r: Level, + pub g: Level, + pub b: Level, + pub y: Level, + /// Mean chroma (Cb, Cr) in −50..50 and its angle and magnitude (percent of 0.5). + pub chroma_mean: [f64; 2], + pub hue_deg: f64, + pub saturation: f64, +} + +pub fn channel_stats(s: &Signal, m: Matrix) -> Option { + if s.is_empty() { + return None; + } + let mut acc: [Acc; 4] = Default::default(); + let (mut cb_sum, mut cr_sum, mut chroma_n) = (0f64, 0f64, 0u64); + for &[r, g, b] in &s.rgb { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + for (a, v) in acc.iter_mut().zip([r, g, b, y]) { + a.add(v * 100.0, 1); + } + if cb.is_finite() && cr.is_finite() { + cb_sum += cb as f64; + cr_sum += cr as f64; + chroma_n += 1; + } + } + let n = chroma_n.max(1) as f64; + let (cb, cr) = ((cb_sum / n) as f32, (cr_sum / n) as f32); + let [r, g, b, y] = &acc; + Some(ChannelStats { + r: r.level()?, + g: g.level()?, + b: b.level()?, + y: y.level()?, + chroma_mean: [round2(cb * 100.0), round2(cr * 100.0)], + hue_deg: round2(angle_deg(cb, cr)), + saturation: round2((cb * cb + cr * cr).sqrt() / 0.5 * 100.0), + }) +} + +/// A trace split into `buckets` column ranges, each with the levels its cells hold (None when a +/// range holds no samples). A grid wider than [`MAX_SIGNAL_W`] or taller than [`MAX_ROWS`] gives +/// no ranges. +pub fn trace_columns(w: &Waveform, g: &Grid, buckets: usize) -> Vec> { + if g.cols > MAX_SIGNAL_W || g.rows > MAX_ROWS { + return Vec::new(); + } + let buckets = buckets.clamp(1, g.cols.max(1)); + (0..buckets) + .map(|b| { + let (c0, c1) = (b * g.cols / buckets, ((b + 1) * g.cols / buckets).max(b * g.cols / buckets + 1).min(g.cols)); + let mut a = Acc::default(); + for col in c0..c1 { + for row in 0..g.rows { + let n = g.at(col, row); + if n > 0 { + a.add(w.level(row) * 100.0, n as u64); + } + } + } + a.level() + }) + .collect() +} + +/// A dense spot of a vectorscope. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Peak { + /// Cell coordinates on the scope's grid. + pub x: usize, + pub y: usize, + /// Cb, Cr at the cell center (percent: −50..50 is the nominal range). + pub cb: f64, + pub cr: f64, + /// Degrees counter-clockwise from +Cb; on an HLS scope, the hue (0 = red, 120 = green). + pub angle_deg: f64, + /// Distance from the center in percent of 0.5 (100 % red in BT.709 ≈ 102.6). + pub magnitude: f64, + /// Share of the plotted samples in this cell (0..1). + pub share: f64, +} + +/// The `n` densest cells holding at least `min_share` of the samples, densest first. A vectorscope +/// larger than [`MAX_VECTOR_SIZE`] gives no peaks. +pub fn peaks(v: &Vectorscope, n: usize, min_share: f32) -> Vec { + if v.size > MAX_VECTOR_SIZE { + return Vec::new(); + } + let total = v.samples.max(1) as f32; + let size = v.size.max(1); + // entries past the size² plane are not cells + let plane = v.size * v.size; + let mut cells: Vec<(u32, usize)> = v.data.iter().take(plane).enumerate().filter(|(_, c)| **c > 0).map(|(i, c)| (*c, i)).collect(); + cells.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + cells + .into_iter() + .filter(|(c, _)| *c as f32 / total >= min_share) + .take(n) + .map(|(c, i)| { + let (x, y) = (i % size, i / size); + let [cb, cr] = v.point(x, y); + // the center cell has no hue + let angle = if v.hls && (cb, cr) != (0.0, 0.0) { + (angle_deg(cb, cr) - red_angle(v.matrix)).rem_euclid(360.0) + } else if v.hls { + 0.0 + } else { + angle_deg(cb, cr) + }; + Peak { + x, + y, + cb: round2(cb * 100.0), + cr: round2(cr * 100.0), + angle_deg: round2(angle), + magnitude: round2((cb * cb + cr * cr).sqrt() / 0.5 * 100.0), + share: (c as f64 / total as f64 * 10_000.0).round() / 10_000.0, + } + }) + .collect() +} + +/// Sparse cells of a vectorscope re-binned to `size`² (for a coarse numeric picture): `[x, y, count]`. +/// A vectorscope larger than [`MAX_VECTOR_SIZE`] gives no cells. +pub fn coarse(v: &Vectorscope, size: usize) -> Vec<[u32; 3]> { + if v.size > MAX_VECTOR_SIZE { + return Vec::new(); + } + let size = size.clamp(1, v.size.max(1)); + let mut out = vec![0u32; size * size]; + for y in 0..v.size { + for x in 0..v.size { + let c = v.at(x, y); + if c > 0 + && let Some(cell) = out.get_mut((y * size / v.size) * size + x * size / v.size) + { + *cell = cell.saturating_add(c); + } + } + } + out.iter().enumerate().filter(|(_, c)| **c > 0).map(|(i, c)| [(i % size) as u32, (i / size) as u32, *c]).collect() +} diff --git a/crates/scopes/src/tests.rs b/crates/scopes/src/tests.rs new file mode 100644 index 0000000000..747ceaa5e8 --- /dev/null +++ b/crates/scopes/src/tests.rs @@ -0,0 +1,670 @@ +//! Scope math on generated frames with known values. + +use crate::*; +use craft_color::rgb_to_ycbcr; + +fn rgba8(w: usize, h: usize, mut f: impl FnMut(usize, usize) -> [u8; 3]) -> Vec { + let mut px = Vec::with_capacity(w * h * 4); + for y in 0..h { + for x in 0..w { + let [r, g, b] = f(x, y); + px.extend_from_slice(&[r, g, b, 255]); + } + } + px +} + +fn solid(w: usize, h: usize, c: [u8; 3]) -> Signal { + Signal::from_rgba8(w, h, &rgba8(w, h, |_, _| c)) +} + +/// 75 % color bars (code 191): white, yellow, cyan, green, magenta, red, blue, black; 32 px each. +const BAR: u8 = 191; +const BARS: [[u8; 3]; 8] = [[BAR, BAR, BAR], [BAR, BAR, 0], [0, BAR, BAR], [0, BAR, 0], [BAR, 0, BAR], [BAR, 0, 0], [0, 0, BAR], [0, 0, 0]]; + +fn bars() -> Signal { + Signal::from_rgba8(256, 16, &rgba8(256, 16, |x, _| BARS[x / 32])) +} + +fn code(v: u8) -> f32 { + v as f32 / 255.0 +} + +#[test] +fn single_color_lands_in_exact_histogram_bins() { + let s = solid(64, 36, [200, 100, 50]); + let n = 64 * 36; + let h = histogram(&s, &Params::default()); + assert_eq!(h.samples, n); + assert_eq!((h.r[200], h.g[100], h.b[50]), (n, n, n)); + assert_eq!(h.r.iter().sum::(), n); + let y = rgb_to_ycbcr(code(200), code(100), code(50), Matrix::Bt709)[0]; + assert_eq!(h.y[(y * 255.0).round() as usize], n); + assert_eq!((h.below, h.above, h.hdr), ([0; 4], [0; 4], None)); +} + +#[test] +fn ramp_fills_every_bin_and_waveform_row_equals_code_value() { + let s = Signal::from_rgba8(256, 10, &rgba8(256, 10, |x, _| [x as u8; 3])); + let p = Params::default(); + let h = histogram(&s, &p); + for k in 0..256 { + assert_eq!((h.r[k], h.g[k], h.b[k], h.y[k]), (10, 10, 10, 10), "bin {k}"); + } + for kind in [WaveformType::Luma, WaveformType::YcNoChroma] { + let w = waveform(&s, kind, &p); + let y = w.trace("Y").unwrap(); + for x in 0..256 { + assert_eq!(y.rows_in(x), vec![x], "{kind:?} column {x}"); + assert_eq!(y.at(x, x), 10); + } + } + let w = waveform(&s, WaveformType::Rgb, &p); + assert_eq!(w.traces.len(), 3); + for t in &w.traces { + assert!((0..256).all(|x| t.rows_in(x) == vec![x]), "{}", t.name); + } +} + +#[test] +fn color_bars_parade_levels_and_vectorscope_targets() { + let s = bars(); + let p = Params::default(); + // RGB parade: every bar column holds its channel's code value exactly + let par = parade(&s, ParadeType::Rgb, &p); + for (ch, name) in ["R", "G", "B"].iter().enumerate() { + let t = par.trace(name).unwrap(); + for (i, bar) in BARS.iter().enumerate() { + for x in i * 32..(i + 1) * 32 { + assert_eq!(t.rows_in(x), vec![bar[ch] as usize], "{name} bar {i}"); + assert_eq!(t.at(x, bar[ch] as usize), 16); + } + } + } + // RGB-White adds the luma trace; YUV has Y, Cb, Cr + assert_eq!(parade(&s, ParadeType::RgbWhite, &p).traces.iter().map(|t| t.name).collect::>(), ["R", "G", "B", "Y"]); + assert_eq!(parade(&s, ParadeType::Yuv, &p).traces.iter().map(|t| t.name).collect::>(), ["Y", "Cb", "Cr"]); + // Vectorscope: each colored bar on its 75 % target cell, white and black in the center + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + let p = Params { matrix: m, ..Params::default() }; + let v = vectorscope_yuv(&s, &p); + assert_eq!(v.samples, 256 * 16); + let bar_samples = 32 * 16; + for t in targets(m, code(BAR)) { + let (x, y) = v.cell(t.cb, t.cr).unwrap(); + assert_eq!(v.at(x, y), bar_samples, "{m:?} {}", t.name); + } + let (cx, cy) = v.cell(0.0, 0.0).unwrap(); + assert_eq!(v.at(cx, cy), 2 * bar_samples); + // the densest spots: the center (two bars), then the six targets + let pk = summary::peaks(&v, 10, 0.01); + assert_eq!(pk.len(), 7); + assert_eq!((pk[0].x, pk[0].y, pk[0].share), (cx, cy, 0.25)); + assert!(pk[1..].iter().all(|k| k.share == 0.125)); + } +} + +#[test] +fn vectorscope_positions_of_primaries_are_known() { + let p = Params::default(); + // BT.709 red: Cb = −0.2126 / 1.8556 = −0.11457, Cr = 0.5 + let v = vectorscope_yuv(&solid(8, 8, [255, 0, 0]), &p); + let pk = summary::peaks(&v, 1, 0.0)[0]; + assert_eq!((pk.x, pk.y), (103, 21)); + assert_eq!((pk.share, v.samples), (1.0, 64)); + assert!((red_angle(Matrix::Bt709) - 102.906).abs() < 0.01, "{}", red_angle(Matrix::Bt709)); + assert!((red_angle(Matrix::Bt601) - 108.645).abs() < 0.01, "{}", red_angle(Matrix::Bt601)); + // the mean chroma of a flat color is its own + let [_, cb, cr] = rgb_to_ycbcr(1.0, 0.0, 0.0, Matrix::Bt709); + assert!((v.mean[0] - cb).abs() < 1e-6 && (v.mean[1] - cr).abs() < 1e-6); + // greys sit in the center for every matrix + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + let v = vectorscope_yuv(&solid(4, 4, [77, 77, 77]), &Params { matrix: m, ..p }); + assert_eq!(v.at(127, 127), 16, "{m:?}"); + } + // the skin-tone line sits between red and yellow + let yl = targets(Matrix::Bt709, 1.0)[5]; + assert!(red_angle(Matrix::Bt709) < SKIN_TONE_DEG && SKIN_TONE_DEG < angle_deg(yl.cb, yl.cr)); +} + +#[test] +fn hls_vectorscope_puts_hue_on_the_angle_and_saturation_on_the_radius() { + let p = Params::default(); + let red = red_angle(p.matrix); + for (rgb, hue) in + [([255, 0, 0], 0.0f32), ([255, 255, 0], 60.0), ([0, 255, 0], 120.0), ([0, 255, 255], 180.0), ([0, 0, 255], 240.0), ([255, 0, 255], 300.0)] + { + let v = vectorscope_hls(&solid(4, 4, rgb), &p); + let a = (red + hue).to_radians(); + let want = cell_of(0.5 * a.cos(), 0.5 * a.sin(), p.vector_size, VECTOR_EXTENT).unwrap(); + let pk = summary::peaks(&v, 1, 0.0)[0]; + assert_eq!((pk.x, pk.y), want, "{rgb:?}"); + assert!((pk.magnitude - 100.0).abs() < 0.6, "{rgb:?} {}", pk.magnitude); + // the per-sample helper agrees with the tabulated scope + let [cb, cr] = hls_point(rgb.map(code), p.matrix); + assert_eq!(cell_of(cb, cr, p.vector_size, VECTOR_EXTENT), Some(want), "{rgb:?}"); + } + // half-saturated red (HSL s = 0.5) at half the radius; grey in the center + let v = vectorscope_hls(&solid(4, 4, [191, 64, 64]), &p); + let pk = summary::peaks(&v, 1, 0.0)[0]; + let hue_off = pk.angle_deg.min(360.0 - pk.angle_deg); + assert!((pk.magnitude - 50.0).abs() < 1.0 && hue_off < 0.5, "{pk:?}"); + let v = vectorscope_hls(&solid(4, 4, [90, 90, 90]), &p); + assert_eq!(v.at(127, 127), 16); + let pk = summary::peaks(&v, 1, 0.0)[0]; + assert_eq!((pk.angle_deg, pk.magnitude), (0.0, 0.0), "{pk:?}"); + // Clamp Signal off: an over-range sample keeps its own hue + let over = Signal::from_fn(1, 1, |_, _| [1.2, 0.5, 0.0]); + let inside = Signal::from_fn(1, 1, |_, _| [1.0, 0.5, 0.0]); + let off = Params { clamp: false, ..p }; + let peak = |s: &Signal, p: &Params| summary::peaks(&vectorscope_hls(s, p), 1, 0.0)[0]; + assert_ne!((peak(&over, &off).x, peak(&over, &off).y), (peak(&inside, &off).x, peak(&inside, &off).y)); + assert_eq!((peak(&over, &p).x, peak(&over, &p).y), (peak(&inside, &p).x, peak(&inside, &p).y)); +} + +#[test] +fn yc_waveform_draws_chroma_around_luma() { + let p = Params::default(); + let w = waveform(&solid(4, 4, [128, 128, 128]), WaveformType::Yc, &p); + assert_eq!((w.trace("Y").unwrap().rows_in(0), w.trace("C").unwrap().rows_in(0)), (vec![128], vec![128])); + let w = waveform(&solid(4, 4, [255, 0, 0]), WaveformType::Yc, &p); + let [y, cb, cr] = rgb_to_ycbcr(1.0, 0.0, 0.0, Matrix::Bt709); + let c = (cb * cb + cr * cr).sqrt(); + let row = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as usize; + assert_eq!(w.trace("Y").unwrap().rows_in(2), vec![row(y)]); + assert_eq!(w.trace("C").unwrap().rows_in(2), vec![row(y - c), row(y + c)]); +} + +#[test] +fn yuv_parade_offsets_chroma_to_mid_scale() { + let w = parade(&solid(4, 4, [128, 128, 128]), ParadeType::Yuv, &Params::default()); + assert_eq!(w.trace("Y").unwrap().rows_in(0), vec![128]); + assert_eq!(w.trace("Cb").unwrap().rows_in(0), vec![128]); + assert_eq!(w.trace("Cr").unwrap().rows_in(0), vec![128]); +} + +#[test] +fn decimation_keeps_whole_samples() { + let px = rgba8(1920, 1080, |x, y| [(x % 256) as u8, (y % 256) as u8, 7]); + let s = Signal::from_rgba8(1920, 1080, &px); + assert_eq!((s.w, s.h), (480, 270)); + assert_eq!(s.rgb[1], [code(4), 0.0, code(7)]); + assert_eq!(s.rgb[480], [0.0, code(4), code(7)]); + let s = Signal::from_rgba8(1921, 9, &rgba8(1921, 9, |_, _| [1, 2, 3])); + assert_eq!((s.w, s.h), (385, 9)); + assert!(Signal::from_rgba8(10, 10, &[0; 12]).is_empty()); +} + +#[test] +fn clamp_signal_controls_out_of_range_values() { + let s = Signal::from_fn(4, 4, |x, _| if x < 2 { [1.2, 0.5, -0.05] } else { [0.5, 0.5, 0.5] }); + let on = Params::default(); + let off = Params { clamp: false, ..on }; + let h = histogram(&s, &on); + assert_eq!((h.r[255], h.above[0], h.b[0], h.below[2]), (8, 8, 8, 8)); + let h = histogram(&s, &off); + assert_eq!((h.r[255], h.above[0], h.b[0], h.below[2]), (0, 8, 0, 8)); + // with clamping, the histogram's luma comes from the clamped R'G'B', as the waveform's does + let hot = Signal::from_fn(1, 1, |_, _| [2.0, -1.0, 0.0]); + let rows = waveform(&hot, WaveformType::Luma, &on).trace("Y").unwrap().rows_in(0); + let hh = histogram(&hot, &on); + assert_eq!(hh.y.iter().position(|&c| c > 0), rows.first().copied()); + // and the luma of the sample as it is still counts as out of range + assert_eq!((hh.below[3], hh.above[3]), (1, 0)); + let white = histogram(&Signal::from_fn(1, 1, |_, _| [2.0; 3]), &on); + assert_eq!((white.y[255], white.above[3]), (1, 1)); + // waveform: clamped onto the top row, or plotted above 100 % within −10..110 + let w = waveform(&s, WaveformType::Rgb, &on); + assert_eq!(w.trace("R").unwrap().rows_in(0), vec![255]); + let w = waveform(&s, WaveformType::Rgb, &off); + assert_eq!((w.lo, w.hi), (-0.1, 1.1)); + assert!(w.trace("R").unwrap().rows_in(0).is_empty(), "1.2 is outside −10..110"); + let r = w.trace("B").unwrap().rows_in(0); + assert_eq!(r, vec![row_of(-0.05, -0.1, 1.1, 256).unwrap()]); +} + +#[test] +fn hdr_axis_helpers() { + assert!(nits_to_pq(0.0) < 1e-5); + assert!((nits_to_pq(10_000.0) - 1.0).abs() < 1e-6); + // reference white (203 cd/m²) ≈ 58 % of the PQ range (BT.2408) + let w = linear_to_pq([1.0, 1.0, 1.0, 1.0])[0]; + assert!((w - nits_to_pq(203.0)).abs() < 1e-6 && (w - 0.58).abs() < 0.01, "{w}"); + // premultiplied: half-covered white is still white + assert!((linear_to_pq([0.5, 0.5, 0.5, 0.5])[0] - w).abs() < 1e-6); + assert!((sdr_to_pq(1.0) - nits_to_pq(100.0)).abs() < 1e-6); +} + +#[test] +fn nan_and_empty_signals_do_not_panic() { + let s = Signal::from_fn(3, 3, |x, _| if x == 1 { [f32::NAN; 3] } else { [0.5; 3] }); + for clamp in [true, false] { + let p = Params { clamp, ..Params::default() }; + for k in ScopeKind::ALL { + let _ = compute(k, &s, &Params { waveform: WaveformType::Yc, parade: ParadeType::RgbWhite, ..p }); + let _ = compute(k, &Signal::default(), &p); + } + } + assert!(summary::channel_stats(&Signal::default(), Matrix::Bt709).is_none()); + // NaN and infinite samples are left out of the levels, so every number stays finite + let st = summary::channel_stats(&s, Matrix::Bt709).unwrap(); + assert_eq!((st.r.min, st.r.max, st.r.mean, st.y.mean), (50.0, 50.0, 50.0, 50.0)); + assert!(st.chroma_mean.iter().all(|v| v.is_finite()) && st.saturation.is_finite()); + let inf = Signal::from_fn(2, 1, |x, _| if x == 0 { [f32::INFINITY, 0.25, 0.25] } else { [0.25; 3] }); + let st = summary::channel_stats(&inf, Matrix::Bt709).unwrap(); + assert_eq!((st.r.max, st.g.mean), (25.0, 25.0)); + assert!(summary::channel_stats(&Signal::from_fn(1, 1, |_, _| [f32::NAN; 3]), Matrix::Bt709).is_none()); +} + +#[test] +fn summaries_report_levels_in_percent() { + let s = solid(8, 8, [200, 100, 50]); + let st = summary::channel_stats(&s, Matrix::Bt709).unwrap(); + assert_eq!((st.r.mean, st.g.mean, st.b.mean), (78.43, 39.22, 19.61)); + assert_eq!((st.r.min, st.r.max), (78.43, 78.43)); + // a two-level frame: left half black, right half white + let s = Signal::from_rgba8(100, 4, &rgba8(100, 4, |x, _| if x < 50 { [0; 3] } else { [255; 3] })); + let w = waveform(&s, WaveformType::Luma, &Params::default()); + let cols = summary::trace_columns(&w, w.trace("Y").unwrap(), 4); + assert_eq!(cols.len(), 4); + assert_eq!(cols[0].unwrap(), summary::Level { min: 0.0, max: 0.0, mean: 0.0 }); + assert_eq!(cols[3].unwrap(), summary::Level { min: 100.0, max: 100.0, mean: 100.0 }); + assert_eq!((cols[1].unwrap().max, cols[2].unwrap().min), (0.0, 100.0)); + let c = summary::coarse(&vectorscope_yuv(&bars(), &Params::default()), 16); + assert_eq!(c.iter().map(|e| e[2]).sum::(), 256 * 16); +} + +#[test] +fn paint_adds_traces_and_leaves_empty_cells_transparent() { + let s = solid(4, 8, [128, 128, 128]); + let w = waveform(&s, WaveformType::Rgb, &Params::default()); + let layers: Vec<(&Grid, [f32; 3])> = w.traces.iter().zip([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]).collect(); + let (pw, ph, px) = paint::grids(&layers, paint::waveform_reference(w.per_column), 1.0); + assert_eq!((pw, ph, px.len()), (4, 256, 4 * 256 * 4)); + // row 128 from the bottom = image row 127; R+G+B coincide → white + let i = (127 * 4) * 4; + assert_eq!(&px[i..i + 4], &[255, 255, 255, 255]); + assert_eq!(&px[0..4], &[0, 0, 0, 0]); + // dimmed is darker than bright + assert!(paint::intensity(3, 100.0, Brightness::Dimmed.gain()) < paint::intensity(3, 100.0, Brightness::Bright.gain())); + let v = vectorscope_yuv(&bars(), &Params::default()); + let (n, _, vp) = paint::vectorscope(&v, [1.0; 3], 1.0, true); + assert_eq!(vp.len(), n * n * 4); + // seven spots of 3 × 3 texels each (none touch) + assert_eq!(vp.as_chunks::<4>().0.iter().filter(|p| p[3] > 0).count(), 7 * 9); +} + +#[test] +fn names_round_trip() { + for k in ScopeKind::ALL { + assert_eq!(ScopeKind::from_name(k.name()), Some(k)); + assert_eq!(ScopeKind::from_name(k.label()), Some(k)); + assert_eq!(serde_json::to_value(k).unwrap(), serde_json::Value::from(k.name())); + } + assert_eq!(ScopeKind::from_name("vectorscope"), Some(ScopeKind::VectorscopeYuv)); + assert_eq!(WaveformType::from_name("Luma and chroma, chroma hidden"), Some(WaveformType::YcNoChroma)); + assert_eq!(WaveformType::from_name("ycNoChroma"), Some(WaveformType::YcNoChroma)); + assert_eq!(ParadeType::from_name("rgb and luma"), Some(ParadeType::RgbWhite)); + assert_eq!(ColorSpace::from_name("709"), Some(ColorSpace::Rec709)); + assert_eq!(ColorSpace::from_name("Rec. 2100"), Some(ColorSpace::Rec2100)); + assert_eq!(Scale::from_name("8 bit"), Some(Scale::Bits8)); + assert_eq!(serde_json::to_value(Targets::Percent100).unwrap(), serde_json::Value::from("100")); + assert_eq!(ColorSpace::Auto.resolve(true), ColorSpace::Rec2100); + assert_eq!(ColorSpace::Auto.resolve(false).matrix(), Matrix::Bt709); +} + +// ------------------------------------------------------------------------------------ frames + +/// An NV12 frame of `w × h` with every pixel at one (Y', Cb, Cr) code value, `pad` spare bytes at +/// the end of each row of both planes. +fn nv12(w: usize, h: usize, pad: usize, [y, cb, cr]: [u8; 3]) -> (Vec, usize, Vec, usize) { + let ys = w + pad; + let cs = w.div_ceil(2) * 2 + pad; + let mut yp = vec![0xEE; ys * h]; + let mut uv = vec![0xEE; cs * h.div_ceil(2)]; + for row in yp.chunks_mut(ys) { + row[..w].fill(y); + } + for row in uv.chunks_mut(cs) { + for pair in row[..w.div_ceil(2) * 2].chunks_mut(2) { + pair.copy_from_slice(&[cb, cr]); + } + } + (yp, ys, uv, cs) +} + +fn read_nv12(w: usize, h: usize, pad: usize, ycc: [u8; 3], matrix: Matrix, range: Range) -> Signal { + let (y, y_stride, uv, uv_stride) = nv12(w, h, pad, ycc); + let mut s = Signal::default(); + s.fill(&Frame::Nv12 { width: w, height: h, y: &y, y_stride, uv: &uv, uv_stride, matrix, range }).unwrap(); + s +} + +/// 8-bit limited-range BT.709 code values of the 100 % color bars (SMPTE RP 219-1, table 1; +/// the Y'CbCr equations of ITU-R BT.709-6 item 3), decoded back to R'G'B'. +#[test] +fn nv12_bt709_limited_bars_decode_to_their_rgb() { + let bars: [([u8; 3], [f32; 3]); 8] = [ + ([235, 128, 128], [1.0, 1.0, 1.0]), + ([219, 16, 138], [1.0, 1.0, 0.0]), + ([188, 154, 16], [0.0, 1.0, 1.0]), + ([173, 42, 26], [0.0, 1.0, 0.0]), + ([78, 214, 230], [1.0, 0.0, 1.0]), + ([63, 102, 240], [1.0, 0.0, 0.0]), + ([32, 240, 118], [0.0, 0.0, 1.0]), + ([16, 128, 128], [0.0, 0.0, 0.0]), + ]; + for (ycc, want) in bars { + let s = read_nv12(6, 4, 0, ycc, Matrix::Bt709, Range::Limited); + assert_eq!((s.w, s.h, s.len()), (6, 4, 24)); + for got in &s.rgb { + for k in 0..3 { + // the published code values are rounded to whole codes: within 1.5 codes of 255 + assert!((got[k] - want[k]).abs() < 1.5 / 255.0, "{ycc:?}: {got:?} vs {want:?}"); + } + } + } +} + +#[test] +fn nv12_full_range_and_odd_sizes() { + // full range: Y' 255 with neutral chroma is white, Y' 0 is black + let s = read_nv12(5, 3, 3, [255, 128, 128], Matrix::Bt601, Range::Full); + assert_eq!((s.w, s.h), (5, 3)); + assert!(s.rgb.iter().all(|c| c.iter().all(|v| (v - 1.0).abs() < 0.01)), "{:?}", s.rgb[0]); + let s = read_nv12(1, 1, 0, [0, 128, 128], Matrix::Bt601, Range::Full); + assert!(s.rgb[0].iter().all(|v| v.abs() < 0.01), "{:?}", s.rgb[0]); + // a grey NV12 frame and the same grey as RGBA8 give the same histogram luma bin + let s = read_nv12(7, 5, 1, [126, 128, 128], Matrix::Bt709, Range::Limited); + let h = histogram(&s, &Params::default()); + let grey = ((126.0 - 16.0) / 219.0 * 255.0f32).round() as usize; + assert_eq!(h.y[grey], 35); +} + +#[test] +fn rgba_with_a_stride_reads_the_same_samples_as_packed_rgba() { + let (w, h) = (9, 5); + let packed = rgba8(w, h, |x, y| [x as u8 * 20, y as u8 * 40, 3]); + let stride = w * 4 + 12; + let mut strided = vec![0xAB; stride * h]; + for y in 0..h { + strided[y * stride..y * stride + w * 4].copy_from_slice(&packed[y * w * 4..(y + 1) * w * 4]); + } + let mut s = Signal::default(); + s.fill(&Frame::Rgba8 { width: w, height: h, stride, data: &strided }).unwrap(); + assert_eq!(s, Signal::from_rgba8(w, h, &packed)); + // the last row needs only its own pixels, not a whole stride + s.fill(&Frame::Rgba8 { width: w, height: h, stride, data: &strided[..stride * (h - 1) + w * 4] }).unwrap(); + assert_eq!(s.len(), w * h); +} + +#[test] +fn bad_frames_give_errors_and_an_empty_signal() { + let px = [0u8; 64]; + let mut s = solid(2, 2, [1, 2, 3]); + assert_eq!(s.fill(&Frame::Rgba8 { width: 4, height: 4, stride: 8, data: &px }), Err(FrameError::Stride { plane: "RGBA", stride: 8, needed: 16 })); + assert!(s.is_empty()); + assert_eq!(s.fill(&Frame::Rgba8 { width: 4, height: 5, stride: 16, data: &px }), Err(FrameError::Short { plane: "RGBA", len: 64, needed: 80 })); + assert_eq!(s.fill(&Frame::Rgba8 { width: usize::MAX, height: 2, stride: 16, data: &px }), Err(FrameError::TooLarge)); + assert_eq!(s.fill(&Frame::Rgba8 { width: 4, height: usize::MAX, stride: usize::MAX / 2, data: &px }), Err(FrameError::TooLarge)); + let nv = |width, height, y: &[u8], y_stride, uv: &[u8], uv_stride| { + let mut s = Signal::default(); + s.fill(&Frame::Nv12 { width, height, y, y_stride, uv, uv_stride, matrix: Matrix::Bt709, range: Range::Limited }) + }; + assert_eq!(nv(4, 4, &px[..16], 4, &px[..7], 4), Err(FrameError::Short { plane: "UV", len: 7, needed: 8 })); + assert_eq!(nv(5, 2, &px[..10], 5, &px[..6], 5), Err(FrameError::Stride { plane: "UV", stride: 5, needed: 6 })); + assert_eq!(nv(4, 4, &px[..15], 4, &px[..8], 4), Err(FrameError::Short { plane: "Y", len: 15, needed: 16 })); + // a frame with no area is valid and empty + assert_eq!(nv(0, 4, &[], 0, &[], 0), Ok(())); + assert_eq!(s.fill(&Frame::Rgba8 { width: 3, height: 0, stride: 0, data: &[] }), Ok(())); + assert_eq!(s.fill(&Frame::Rgba8 { width: usize::MAX, height: 0, stride: 0, data: &[] }), Ok(())); + assert_eq!(nv(usize::MAX, 0, &[], 0, &[], 0), Ok(())); + assert!(s.is_empty()); + assert!(FrameError::TooLarge.to_string().contains("too large")); +} + +#[test] +fn colorized_vectorscope_points_use_the_scope_matrix() { + let s = Signal::from_fn(1, 1, |_, _| [0.0, 1.0, 0.0]); + let p = Params { matrix: Matrix::Bt2020Ncl, ..Params::default() }; + let v = vectorscope_yuv(&s, &p); + assert_eq!(v.matrix, Matrix::Bt2020Ncl); + let [_, cb, cr] = rgb_to_ycbcr(0.0, 1.0, 0.0, Matrix::Bt2020Ncl); + let (x, y) = v.cell(cb, cr).unwrap(); + let (n, _, img) = paint::vectorscope(&v, [1.0; 3], 1.0, true); + let px = &img[(y * n + x) * 4..(y * n + x) * 4 + 4]; + let [ccb, ccr] = v.point(x, y); + let tint = |m| craft_color::ycbcr_to_rgb(0.6, ccb * 0.8, ccr * 0.8, m).map(|c: f32| 0.55 + 0.45 * c.clamp(0.0, 1.0)); + let l = f32::from(px[3]) / 255.0; + let got = [0, 1, 2].map(|i| f32::from(px[i]) / 255.0 / l); + let (want, other) = (tint(Matrix::Bt2020Ncl), tint(Matrix::Bt709)); + let err = |t: [f32; 3]| (0..3).map(|i| (got[i] - t[i]).abs()).fold(0.0f32, f32::max); + assert!(err(want) < 0.005, "{got:?} vs {want:?}"); + assert!(err(other) > 0.01, "the BT.709 tint {other:?} is not told apart from {want:?}"); + // HLS points are colored by their hue: saturated yellow paints yellow, not orange + let yellow = Signal::from_fn(1, 1, |_, _| [1.0, 1.0, 0.0]); + let v = vectorscope_hls(&yellow, &Params::default()); + assert!(v.hls); + let [hx, hy] = hls_point([1.0, 1.0, 0.0], Matrix::Bt709); + let (x, y) = v.cell(hx, hy).unwrap(); + let (n, _, img) = paint::vectorscope(&v, [1.0; 3], 1.0, true); + let px = &img[(y * n + x) * 4..(y * n + x) * 4 + 3]; + assert!(px[0].abs_diff(px[1]) <= 6 && px[2] + 40 < px[1], "{px:?}"); + // HLS peaks report the hue: yellow at 60°, green at 120° + assert!((summary::peaks(&v, 1, 0.0)[0].angle_deg - 60.0).abs() < 1.0, "{:?}", summary::peaks(&v, 1, 0.0)); + let green = vectorscope_hls(&Signal::from_fn(1, 1, |_, _| [0.0, 1.0, 0.0]), &Params { matrix: Matrix::Bt601, ..Params::default() }); + assert!((summary::peaks(&green, 1, 0.0)[0].angle_deg - 120.0).abs() < 1.0, "{:?}", summary::peaks(&green, 1, 0.0)); +} + +// ------------------------------------------------------------------------------------ reuse + +#[test] +fn into_functions_match_the_allocating_ones_and_keep_their_buffers() { + let frame_px = rgba8(1920, 1080, |x, y| [(x % 251) as u8, (y % 241) as u8, ((x + y) % 239) as u8]); + let frame = Frame::Rgba8 { width: 1920, height: 1080, stride: 1920 * 4, data: &frame_px }; + let p = Params::default(); + let mut s = Signal::default(); + let mut w = Waveform::default(); + let mut h = Histogram::default(); + let mut v = Vectorscope::default(); + let mut scratch = paint::Scratch::default(); + let mut img = Vec::new(); + let mut c = Computed::default(); + let mut run = |s: &mut Signal| { + s.fill(&frame).unwrap(); + waveform_into(s, WaveformType::Yc, &p, &mut w); + histogram_into(s, &p, &mut h); + vectorscope_hls_into(s, &p, &mut v); + let layers: Vec<(&Grid, [f32; 3])> = w.traces.iter().map(|t| (t, [1.0; 3])).collect(); + paint::grids_into(&layers, 10.0, 1.0, &mut scratch, &mut img); + compute_into(ScopeKind::Parade, s, &Params { parade: ParadeType::RgbWhite, ..p }, &mut c); + (s.rgb.as_ptr(), w.traces[1].data.as_ptr(), h.y.as_ptr(), v.data.as_ptr(), img.as_ptr(), w.clone(), h.clone(), v.clone(), c.clone()) + }; + let first = run(&mut s); + let second = run(&mut s); + assert_eq!((first.0, first.1, first.2, first.3, first.4), (second.0, second.1, second.2, second.3, second.4), "buffers were reallocated"); + assert_eq!(second.5, waveform(&s, WaveformType::Yc, &p)); + assert_eq!(second.6, histogram(&s, &p)); + assert_eq!(second.7, vectorscope_hls(&s, &p)); + assert_eq!(second.8, compute(ScopeKind::Parade, &s, &Params { parade: ParadeType::RgbWhite, ..p })); + // switching kinds keeps working and gives the same result as a fresh compute + let mut c = Computed::default(); + let lp = Params { waveform: WaveformType::Luma, parade: ParadeType::Yuv, ..p }; + for k in [ScopeKind::Parade, ScopeKind::Histogram, ScopeKind::VectorscopeYuv, ScopeKind::VectorscopeHls, ScopeKind::Waveform, ScopeKind::Parade] { + compute_into(k, &s, &lp, &mut c); + assert_eq!(c, compute(k, &s, &lp), "{k:?}"); + } +} + +// ------------------------------------------------------------------------------------ hostile input + +#[test] +fn hostile_params_and_signals_stay_bounded() { + let s = bars(); + // rows and grid sizes are clamped + let w = waveform(&s, WaveformType::Rgb, &Params { rows: usize::MAX, ..Params::default() }); + assert_eq!(w.traces[0].rows, MAX_ROWS); + let w = waveform(&s, WaveformType::Rgb, &Params { rows: 0, ..Params::default() }); + assert_eq!(w.traces[0].rows, 2); + let v = vectorscope_yuv(&s, &Params { vector_size: usize::MAX, ..Params::default() }); + assert_eq!(v.size, MAX_VECTOR_SIZE); + let v = vectorscope_hls(&s, &Params { vector_size: 0, ..Params::default() }); + assert_eq!((v.size, v.samples), (3, 256 * 16)); + // an even size becomes odd, so a gray sample lands on the center cell with no magnitude + let gray = Signal::from_fn(1, 1, |_, _| [0.5; 3]); + let v = vectorscope_yuv(&gray, &Params { vector_size: 256, ..Params::default() }); + assert_eq!(v.size, 257); + assert_eq!(v.cell(0.0, 0.0), Some((128, 128))); + assert_eq!(v.point(128, 128), [0.0, 0.0]); + // a signal whose public fields disagree reads only whole rows and never indexes past them + let odd = Signal { w: 1000, h: 1000, rgb: vec![[0.5; 3]; 10] }; + let w = waveform(&odd, WaveformType::Rgb, &Params::default()); + assert_eq!((w.traces[0].cols, w.per_column, w.traces[0].total()), (10, 0, 0)); + // sizes asked for past the caps are clamped, and samples past a clamped grid are dropped + let px = rgba8(2000, 4, |_, _| [9, 9, 9]); + let mut big = Signal::default(); + big.fill_max(&Frame::Rgba8 { width: 2000, height: 4, stride: 8000, data: &px }, usize::MAX, usize::MAX).unwrap(); + assert_eq!((big.w, big.h), (1000, 4), "2000 columns decimated by 2 to fit 1920"); + let f = Signal::from_rgba_f32_with(4000, 1, &vec![0.5; 16_000], usize::MAX, usize::MAX, |p| [p[0], p[1], p[2]]); + assert_eq!(f.w, 1334, "4000 columns decimated by 3"); + let g = Grid::new("Y", usize::MAX, usize::MAX); + assert_eq!((g.cols, g.rows, g.data.len()), (MAX_SIGNAL_W, MAX_ROWS, MAX_SIGNAL_W * MAX_ROWS)); + let wide = Signal::from_fn(3000, 2, |_, _| [0.5; 3]); + let w = waveform(&wide, WaveformType::Luma, &Params::default()); + assert_eq!((w.traces[0].cols, w.traces[0].total()), (MAX_SIGNAL_W, 2 * MAX_SIGNAL_W as u64)); + let wide = Signal { w: usize::MAX, h: 0, rgb: Vec::new() }; + assert_eq!(waveform(&wide, WaveformType::Luma, &Params::default()).traces[0].data.len(), 0); + // helpers outside their range answer None or 0 instead of panicking + assert_eq!(row_of(0.5, 0.0, 1.0, 1), None); + assert_eq!(row_of(0.5, 1.0, 1.0, 256), None); + assert_eq!(cell_of(0.0, 0.0, 1, VECTOR_EXTENT), None); + assert_eq!(cell_of(0.0, 0.0, 255, f32::NAN), None); + let g = Grid::new("Y", 3, 3); + assert_eq!((g.at(3, 0), g.at(0, 3), g.at(0, usize::MAX), g.at(usize::MAX, usize::MAX)), (0, 0, 0, 0)); + let v = vectorscope_yuv(&s, &Params::default()); + assert_eq!((v.at(0, usize::MAX), v.at(usize::MAX, 0)), (0, 0)); + let empty = Vectorscope::default(); + assert!(summary::coarse(&empty, 0).is_empty()); + assert!(summary::peaks(&empty, 5, 0.0).is_empty()); + assert_eq!(empty.at(0, 0), 0); +} + +#[test] +fn hand_built_values_past_the_caps_paint_nothing() { + let huge = Signal::from_fn(usize::MAX, 2, |_, _| [0.5; 3]); + assert_eq!((huge.w, huge.h, huge.len()), (MAX_SIGNAL_W, 2, 2 * MAX_SIGNAL_W)); + let mut scratch = paint::Scratch::default(); + let mut out = vec![1u8; 4]; + let v = Vectorscope { size: usize::MAX, ..Vectorscope::default() }; + assert_eq!(paint::vectorscope_into(&v, [1.0; 3], 1.0, true, &mut scratch, &mut out), (0, 0)); + assert!(out.is_empty()); + assert!(summary::coarse(&v, usize::MAX).is_empty()); + let big = Vectorscope { size: MAX_VECTOR_SIZE + 1, data: vec![1; 4], samples: 4, ..Vectorscope::default() }; + assert!(summary::peaks(&big, 5, 0.0).is_empty()); + assert!(summary::coarse(&big, 4).is_empty()); + // entries past the size² plane are not cells + let mut data = vec![0; 10]; + data[9] = 5; + let trailing = Vectorscope { size: 3, extent: VECTOR_EXTENT, data, samples: 5, ..Vectorscope::default() }; + assert!(summary::peaks(&trailing, 5, 0.0).is_empty()); + assert!(summary::coarse(&trailing, 3).is_empty()); + let g = Grid { name: "Y", cols: usize::MAX, rows: usize::MAX, data: Vec::new() }; + out.push(1); + assert_eq!(paint::grids_into(&[(&g, [1.0; 3])], 1.0, 1.0, &mut scratch, &mut out), (0, 0)); + assert!(out.is_empty()); + assert!(summary::trace_columns(&Waveform::default(), &g, usize::MAX).is_empty()); + let tall = Grid { name: "Y", cols: 4, rows: MAX_ROWS + 1, data: Vec::new() }; + assert_eq!(paint::grids_into(&[(&tall, [1.0; 3])], 1.0, 1.0, &mut scratch, &mut out), (0, 0)); +} + +// ------------------------------------------------------------------------------------ HDR + +#[test] +fn hdr_bins_split_sdr_and_stops() { + let px = Signal { w: 5, h: 1, rgb: vec![[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [4.0, 4.0, 4.0], [16.0, 16.0, 16.0], [f32::NAN, -1.0, f32::INFINITY]] }; + let mut h = Histogram::default(); + histogram_hdr_into(&px, Matrix::Bt709, HdrBins::new(4.0), &mut h); + let b = h.hdr.unwrap(); + assert_eq!(h.samples, 5); + assert_eq!(b.bin(1.0), b.from - 1, "SDR white is the last SDR bin"); + assert_eq!(b.bin(16.0), 255); + assert_eq!(b.bin(1e9), 255); + let two = b.bin(4.0); + assert!(two > b.from && two < 255, "{two}"); + assert_eq!(h.r[0], 2, "black and NaN"); + assert_eq!(h.b[255], 2, "16 and +inf"); + assert_eq!((h.below[1], h.above[2]), (1, 1), "-1 below, +inf above 2^4"); + assert!((above_sdr(&h) - 0.6).abs() < 1e-6, "{}", above_sdr(&h)); + // over-white samples in different channels each count once + let split = Signal { w: 2, h: 1, rgb: vec![[2.0, 0.5, 0.5], [0.5, 0.5, 2.0]] }; + histogram_hdr_into(&split, Matrix::Bt709, HdrBins::new(4.0), &mut h); + assert_eq!((h.above_sdr_samples, above_sdr(&h)), (2, 1.0)); + histogram_hdr_into(&Signal::default(), Matrix::Bt709, HdrBins::new(4.0), &mut h); + assert_eq!(above_sdr(&h), 0.0); + assert_eq!(above_sdr(&histogram(&bars(), &Params::default())), 0.0); + // the SDR half follows the sRGB curve: linear 0.5 is about 73.5 % of the way to SDR white + let half = b.bin(0.5); + assert_eq!(half, (craft_color::linear_to_srgb(0.5) * 127.0 + 0.5) as usize); +} + +/// A hand-built split outside the bins (any `from`, any `stops`) never panics and stays in range. +#[test] +fn hdr_bins_with_any_split_stay_in_range() { + for from in [0, 1, 2, 128, 255, 256, usize::MAX] { + for stops in [0.0, 3.0, f32::NAN, f32::INFINITY] { + let b = HdrBins { from, stops }; + for v in [f32::NAN, -1.0, 0.0, 0.5, 1.0, 2.0, 1e9] { + assert!(b.bin(v) < BINS, "{from} {stops} {v}"); + } + let mut h = Histogram::default(); + histogram_hdr_into(&Signal { w: 1, h: 1, rgb: vec![[2.0; 3]] }, Matrix::Bt2020Ncl, b, &mut h); + assert!((0.0..=1.0).contains(&above_sdr(&h))); + } + } +} + +/// `cargo test --release -p craft-scopes perf -- --ignored --nocapture` +#[test] +#[ignore] +fn perf_scopes_at_1080p() { + let mut seed = 0x1234_5678u32; + let px = rgba8(1920, 1080, |_, _| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + [seed as u8, (seed >> 8) as u8, (seed >> 16) as u8] + }); + let reps = 20; + let mut s = Signal::default(); + let frame = Frame::Rgba8 { width: 1920, height: 1080, stride: 1920 * 4, data: &px }; + let t = std::time::Instant::now(); + for _ in 0..reps { + s.fill(&frame).unwrap(); + } + println!("decimate RGBA 1920x1080: {:.3} ms", t.elapsed().as_secs_f64() * 1000.0 / reps as f64); + let (y, y_stride, uv, uv_stride) = nv12(1920, 1080, 0, [100, 120, 140]); + let nv = Frame::Nv12 { width: 1920, height: 1080, y: &y, y_stride, uv: &uv, uv_stride, matrix: Matrix::Bt709, range: Range::Limited }; + let t = std::time::Instant::now(); + for _ in 0..reps { + s.fill(&nv).unwrap(); + } + println!("decimate NV12 1920x1080: {:.3} ms", t.elapsed().as_secs_f64() * 1000.0 / reps as f64); + s.fill(&frame).unwrap(); + let p = Params::default(); + let mut c = Computed::default(); + for (k, wt, pt) in [ + (ScopeKind::Waveform, WaveformType::Rgb, ParadeType::Rgb), + (ScopeKind::Waveform, WaveformType::Yc, ParadeType::Rgb), + (ScopeKind::Parade, WaveformType::Rgb, ParadeType::RgbWhite), + (ScopeKind::Histogram, WaveformType::Rgb, ParadeType::Rgb), + (ScopeKind::VectorscopeYuv, WaveformType::Rgb, ParadeType::Rgb), + (ScopeKind::VectorscopeHls, WaveformType::Rgb, ParadeType::Rgb), + ] { + let t = std::time::Instant::now(); + for _ in 0..reps { + compute_into(k, &s, &Params { waveform: wt, parade: pt, ..p }, &mut c); + std::hint::black_box(&c); + } + println!("{k:?} {wt:?}/{pt:?}: {:.3} ms", t.elapsed().as_secs_f64() * 1000.0 / reps as f64); + } +} diff --git a/crates/stream-codecs/src/jbig2.rs b/crates/stream-codecs/src/jbig2.rs index e95841d387..d99780c267 100644 --- a/crates/stream-codecs/src/jbig2.rs +++ b/crates/stream-codecs/src/jbig2.rs @@ -56,9 +56,20 @@ const PAD: usize = 4; /// /// Errors: as [`encode_jbig2_generic`]. pub fn encode_jbig2(data: &[u8], columns: u32, rows: u32) -> Result, CodecError> { + encode_jbig2_capped(data, columns, rows, symbols::MAX_SYMBOLS, symbols::MAX_SYMBOL_PIXELS, symbols::MAX_CODED_SYMBOLS) +} + +fn encode_jbig2_capped( + data: &[u8], + columns: u32, + rows: u32, + max_symbols: usize, + max_symbol_pixels: usize, + max_coded_symbols: usize, +) -> Result, CodecError> { let generic = encode_jbig2_generic(data, columns, rows)?; let samples = rows_to_encode(data, columns, rows).ok(); - Ok(match samples.and_then(|s| symbols::encode(s, columns, rows)) { + Ok(match samples.and_then(|s| symbols::encode(s, columns, rows, max_symbols, max_symbol_pixels, max_coded_symbols)) { Some(coded) if coded.len() < generic.len() => coded, _ => generic, }) diff --git a/crates/stream-codecs/src/jbig2/symbols.rs b/crates/stream-codecs/src/jbig2/symbols.rs index 33e16c13d5..3fb288c2a7 100644 --- a/crates/stream-codecs/src/jbig2/symbols.rs +++ b/crates/stream-codecs/src/jbig2/symbols.rs @@ -23,14 +23,14 @@ const MAX_RUNS: usize = 1 << 20; /// The most distinct marks sorted into symbols, and the most pixels their bitmaps may hold /// together: past either the image is left to generic coding. These bound the memory they take. -const MAX_SYMBOLS: usize = 1 << 16; -const MAX_SYMBOL_PIXELS: usize = 1 << 24; +pub(super) const MAX_SYMBOLS: usize = 1 << 16; +pub(super) const MAX_SYMBOL_PIXELS: usize = 1 << 24; /// The most symbols one plan codes. `hayro-jbig2`, the decoder the Craft apps render JBIG2 with, /// refuses a dictionary whose new and exported symbols pass 65,535 together, and a plan exports /// every symbol it codes, so it refuses 32,768 or more; others may too, so a plan with more isn't /// made. -const MAX_CODED_SYMBOLS: usize = (1 << 15) - 1; +pub(super) const MAX_CODED_SYMBOLS: usize = (1 << 15) - 1; /// The most symbol instances one text region places. `hayro-jbig2`, the decoder the Craft apps render JBIG2 with, /// refuses a text region of more than 10,000 (a page it then draws blank), so a page with more is @@ -115,9 +115,16 @@ struct Shared { /// every mark of at most [`MAX_SYMBOL_SIDE`] a side as a symbol, or only those with a copy. /// `None` when neither plan has from two to [`MAX_CODED_SYMBOLS`] symbols, or the image is too /// large or too busy to look at. -pub(super) fn encode(samples: &[u8], columns: u32, rows: u32) -> Option> { - let page = page(samples, columns)?; - [1, 2].into_iter().filter_map(|copies| plan(&page, columns, rows, copies, None, None)).min_by_key(Vec::len) +pub(super) fn encode( + samples: &[u8], + columns: u32, + rows: u32, + max_symbols: usize, + max_symbol_pixels: usize, + max_coded_symbols: usize, +) -> Option> { + let page = page_with_limits(samples, columns, max_symbols, max_symbol_pixels)?; + [1, 2].into_iter().filter_map(|copies| plan_within(&page, columns, rows, copies, None, None, max_coded_symbols)).min_by_key(Vec::len) } /// Images, each as [`encode`] takes one, symbol coded sharing one dictionary: the globals' data, a @@ -206,6 +213,10 @@ fn find(table: &[Symbol], by_hash: &HashMap>, s: &Symbol) -> Optio /// The image's marks and symbols; `None` past the limits above. fn page(samples: &[u8], columns: u32) -> Option { + page_with_limits(samples, columns, MAX_SYMBOLS, MAX_SYMBOL_PIXELS) +} + +fn page_with_limits(samples: &[u8], columns: u32, max_symbols: usize, max_symbol_pixels: usize) -> Option { let width = usize::try_from(columns).ok()?; let stride = width.div_ceil(8); if stride == 0 { @@ -214,7 +225,7 @@ fn page(samples: &[u8], columns: u32) -> Option { let runs = black_runs(samples, width, stride)?; let (marks, order) = marks(&runs); let mut page = Page { runs, marks, order, symbols: Vec::new(), copies: Vec::new(), large: Vec::new() }; - symbols(&mut page)?; + symbols(&mut page, max_symbols, max_symbol_pixels)?; Some(page) } @@ -355,7 +366,7 @@ fn pixels(mark: &Mark, runs: &[Run], order: &[u32]) -> Vec { /// Sorts the marks into symbols: exact copies share one. `None` past [`MAX_SYMBOLS`] or /// [`MAX_SYMBOL_PIXELS`]. -fn symbols(page: &mut Page) -> Option<()> { +fn symbols(page: &mut Page, max_symbols: usize, max_symbol_pixels: usize) -> Option<()> { let mut by_hash: HashMap> = HashMap::new(); let mut kept = 0usize; for (m, mark) in page.marks.iter().enumerate() { @@ -371,7 +382,7 @@ fn symbols(page: &mut Page) -> Option<()> { Some(id) => id, None => { kept = kept.checked_add(symbol.pixels.len())?; - if kept > MAX_SYMBOL_PIXELS || symbols.len() == MAX_SYMBOLS { + if kept > max_symbol_pixels || symbols.len() == max_symbols { return None; } let id = u32::try_from(symbols.len()).ok()?; @@ -1007,6 +1018,86 @@ mod tests { assert!(page(&data, columns).is_none()); } + /// Small limits cover bitmap memory and the real selector without full-size fixtures. + #[test] + fn small_symbol_limits_cover_memory_and_generic_fallback() { + assert_eq!(MAX_CODED_SYMBOLS, 32_767); + assert_eq!(MAX_SYMBOLS, 65_536); + assert_eq!(MAX_SYMBOL_PIXELS, 16_777_216); + // `n` distinct marks of 17 x 3 (full top and bottom rows joined by a code of 1 to n, in + // binary, on the row between), then `again` more with the codes 1 and 2 in turn. + let codes = |n: usize, again: usize| { + let across = (n + again).min(256); + let (columns, rows) = (across * 18, (n + again).div_ceil(across) * 4); + let mut picture = vec![vec![0u8; columns]; rows]; + for k in 0..n + again { + let (x, y) = (k % across * 18, k / across * 4); + let code = if k < n { k + 1 } else { (k - n) % 2 + 1 }; + picture[y][x..x + 17].fill(1); + picture[y + 2][x..x + 17].fill(1); + for b in (0..17).filter(|b| code >> b & 1 == 1) { + picture[y + 1][x + b] = 1; + } + } + (samples(&picture), columns as u32, rows as u32) + }; + let cap = 63; + let capped_encode = + |data: &[u8], columns, rows| super::super::encode_jbig2_capped(data, columns, rows, MAX_SYMBOLS, MAX_SYMBOL_PIXELS, cap).unwrap(); + let (data, columns, rows) = codes(cap, 0); + let at_cap = page(&data, columns).unwrap(); + assert_eq!(decode(&plan_within(&at_cap, columns, rows, 1, None, None, cap).unwrap()), unpack(&data, columns, rows)); + // One more distinct mark, each once: neither plan is made, so the real selector keeps + // the generic stream unchanged. + let (data, columns, rows) = codes(cap + 1, 0); + let past = page(&data, columns).unwrap(); + assert!(plan_within(&past, columns, rows, 1, None, None, cap).is_none() && plan_within(&past, columns, rows, 2, None, None, cap).is_none()); + assert_eq!(capped_encode(&data, columns, rows), encode_jbig2_generic(&data, columns, rows).unwrap()); + // With two of them repeated, the second plan codes those two. + let (data, columns, rows) = codes(cap + 1, 200); + let past = page(&data, columns).unwrap(); + assert!(plan_within(&past, columns, rows, 1, None, None, cap).is_none()); + assert_eq!(decode(&plan_within(&past, columns, rows, 2, None, None, cap).unwrap()), unpack(&data, columns, rows)); + // Above text whose letters repeat, that second plan is the one the real selector keeps: + // the first, of every mark, would code too many symbols. + let mut picture: Bitmap = vec![vec![0u8; 64 * 18]; 4]; + for k in 0..=cap { + let x = k * 18; + picture[0][x..x + 17].fill(1); + picture[2][x..x + 17].fill(1); + for b in (0..17).filter(|b| (k + 1) >> b & 1 == 1) { + picture[1][x + b] = 1; + } + } + picture.extend(text(64 * 18, 120, &glyphs(40, 7), 11)); + let data = samples(&picture); + let (columns, rows) = (picture[0].len() as u32, picture.len() as u32); + let coded = capped_encode(&data, columns, rows); + assert_eq!(segment_types(&coded)[1], 0, "symbol coded"); + assert_eq!(decode(&coded), unpack(&data, columns, rows)); + let symbol_cap = 8; + let (data, columns, _) = codes(symbol_cap, 0); + assert_eq!(page_with_limits(&data, columns, symbol_cap, MAX_SYMBOL_PIXELS).map(|p| p.symbols.len()), Some(symbol_cap)); + let (data, columns, _) = codes(symbol_cap + 1, 0); + assert!(page_with_limits(&data, columns, symbol_cap, MAX_SYMBOL_PIXELS).is_none()); + // Bitmap area, including white pixels in a symbol's box, is the memory guard's unit. + // A 3 x 3 square with a white center and a solid 2 x 3 square hold exactly 15 bitmap + // pixels (14 black); a separate dot adds one. + let mut picture = vec![vec![0u8; 12]; 3]; + for row in &mut picture { + row[0..3].fill(1); + row[5..7].fill(1); + } + picture[1][1] = 0; + let data = samples(&picture); + let at_cap = page_with_limits(&data, 12, MAX_SYMBOLS, 15).unwrap(); + assert_eq!(at_cap.symbols.len(), 2); + assert_eq!(at_cap.symbols.iter().map(|s| s.pixels.len()).sum::(), 15); + assert_eq!(decode(&plan(&at_cap, 12, 3, 1, None, None).unwrap()), unpack(&data, 12, 3)); + picture[0][10] = 1; + assert!(page_with_limits(&samples(&picture), 12, MAX_SYMBOLS, 15).is_none()); + } + /// More than 10,000 marks are placed by several text regions, each of at most 10,000 (more /// than `hayro-jbig2` accepts in one), over bands of rows, all referring to /// the dictionary, which each region but the last keeps retained; the generic region comes @@ -1347,7 +1438,7 @@ mod tests { #[test] fn any_input_returns(data in proptest::collection::vec(0u8..=255, 0..600), columns in 0u32..5000, rows in 0u32..80) { let _ = encode_jbig2(&data, columns, rows); - let _ = encode(&data, columns, rows); + let _ = encode(&data, columns, rows, MAX_SYMBOLS, MAX_SYMBOL_PIXELS, MAX_CODED_SYMBOLS); let _ = encode_shared(&[(&data, columns, rows), (&data, columns, rows.saturating_sub(1))]); } } diff --git a/crates/svg/src/doc_style.rs b/crates/svg/src/doc_style.rs index 39b3e9208c..d52b5e2642 100644 --- a/crates/svg/src/doc_style.rs +++ b/crates/svg/src/doc_style.rs @@ -179,10 +179,33 @@ fn css_length_units(property: &str, value: String) -> String { out } +/// Normalize supported CSS value identifiers without changing opaque payloads or raw attributes. +fn css_value(property: &str, value: String) -> String { + let mut value = css_length_units(property, value); + let token = value.trim(); + let keywords: &[&str] = match property { + "display" => &["none"], + "visibility" => &["visible", "hidden", "collapse"], + "fill-rule" => &["nonzero", "evenodd"], + "stroke-linecap" => &["butt", "round", "square"], + "stroke-linejoin" => &["miter", "round", "bevel"], + "fill" | "stroke" => &["none", "currentColor"], + _ => &[], + }; + let start = value.len() - value.trim_start().len(); + if let Some(keyword) = keywords.iter().find(|keyword| token.eq_ignore_ascii_case(keyword)) { + let end = start + token.len(); + value.replace_range(start..end, keyword); + } else if matches!(property, "fill" | "stroke") && token.get(..4).is_some_and(|prefix| prefix.eq_ignore_ascii_case("url(")) { + value.replace_range(start..start + 3, "url"); + } + value +} + /// Collect the declared properties of an element: presentation attributes, then CSS rules /// (by specificity and source order, bounded by `charge_css`), then the inline `style` attribute. -/// Supported numeric length-unit suffixes are normalized only for CSS declarations; raw -/// presentation attributes retain their existing spelling and length compatibility. +/// Supported numeric length-unit suffixes and value identifiers are normalized only for +/// CSS declarations; raw presentation attributes retain their existing spelling and compatibility. pub fn declared(n: roxmltree::Node, css: &StyleSheet, charge_css: impl FnMut(usize) -> bool) -> HashMap { let mut out = HashMap::new(); for a in n.attributes() { @@ -193,12 +216,12 @@ pub fn declared(n: roxmltree::Node, css: &StyleSheet, charge_css: impl FnMut(usi let mut css_values = HashMap::new(); css.apply(n.tag_name().name(), n.attribute("id"), n.attribute("class").unwrap_or_default(), &mut css_values, charge_css); out.extend(css_values.into_iter().map(|(k, v)| { - let v = css_length_units(&k, v); + let v = css_value(&k, v); (k, v) })); if let Some(st) = n.attribute("style") { for (k, v) in declarations(st) { - let v = css_length_units(&k, v); + let v = css_value(&k, v); out.insert(k, v); } } @@ -662,6 +685,125 @@ mod tests { assert_eq!(attr_len(rect, "width", 'x', &st, 200.0, 100.0), 0.0); } + #[test] + fn css_value_identifier_case() { + // CSS Values 3 section 3.1: keywords are ASCII case-insensitive. CSS Syntax 3 + // section 4.3.4 matches the url function identifier without folding its payload. + let seed = Style { + fill: Some(PaintRef::Color([0.0, 1.0, 0.0, 1.0])), + stroke: Some(PaintRef::Color([0.0, 0.0, 1.0, 1.0])), + color: [1.0, 0.0, 0.0, 1.0], + ..Style::default() + }; + let evaluate = |property: &str, value: &str, inline: bool| { + let declaration = format!("{property}:{value}"); + let inline_style = + if inline { format!(" style=\"{}\"", declaration.replace('&', "&").replace('"', """)) } else { String::new() }; + let xml = format!(""); + let doc = roxmltree::Document::parse(&xml).unwrap(); + let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let mut css = StyleSheet::default(); + if !inline { + parse_css(&format!(".a {{ {declaration} }}"), &mut css).unwrap(); + css.index(); + } + let d = declared(rect, &css, |_| true); + let mut st = seed.clone(); + let (opacity, display) = cascade(rect, &css, &mut st, 200.0, 100.0, |_| true); + assert_eq!(opacity, 1.0); + (d, st, display) + }; + let cases = [ + ("display", "none", "NONE", seed.clone(), false), + ("visibility", "hidden", "HIDDEN", Style { visible: false, ..seed.clone() }, true), + ("visibility", "collapse", "CoLlApSe", Style { visible: false, ..seed.clone() }, true), + ("visibility", "visible", "VISIBLE", seed.clone(), true), + ("fill-rule", "evenodd", "EVENODD", Style { fill_rule: FillRule::EvenOdd, ..seed.clone() }, true), + ("fill-rule", "nonzero", "NONZERO", seed.clone(), true), + ("stroke-linecap", "round", "ROUND", Style { cap: Cap::Round, ..seed.clone() }, true), + ("stroke-linecap", "square", "SqUaRe", Style { cap: Cap::Square, ..seed.clone() }, true), + ("stroke-linecap", "butt", "BUTT", seed.clone(), true), + ("stroke-linejoin", "round", "ROUND", Style { join: Join::Round, ..seed.clone() }, true), + ("stroke-linejoin", "bevel", "BeVeL", Style { join: Join::Bevel, ..seed.clone() }, true), + ("stroke-linejoin", "miter", "MITER", seed.clone(), true), + ("fill", "none", "NONE", Style { fill: None, ..seed.clone() }, true), + ("stroke", "none", "NoNe", Style { stroke: None, ..seed.clone() }, true), + ("fill", "currentColor", "CURRENTCOLOR", Style { fill: Some(PaintRef::Current), ..seed.clone() }, true), + ("stroke", "currentColor", "CuRrEnTcOlOr", Style { stroke: Some(PaintRef::Current), ..seed.clone() }, true), + ("fill", "url('#PaintID')", "URL('#PaintID')", Style { fill: Some(PaintRef::Url("PaintID".into(), None)), ..seed.clone() }, true), + ( + "stroke", + "url(\"#StrokeID\") red", + "uRl(\"#StrokeID\") red", + Style { stroke: Some(PaintRef::Url("StrokeID".into(), Some([1.0, 0.0, 0.0, 1.0]))), ..seed.clone() }, + true, + ), + ]; + // Every lower-case functional control runs before collecting any failing counterpart. + for (property, lower, _, expected, display) in &cases { + for inline in [false, true] { + let (_, actual, actual_display) = evaluate(property, lower, inline); + assert_eq!(&actual, expected, "lower control {property}:{lower}, inline={inline}"); + assert_eq!(&actual_display, display); + } + } + let mut mismatches = Vec::new(); + for (property, _, mixed, expected, display) in &cases { + for inline in [false, true] { + let (_, actual, actual_display) = evaluate(property, mixed, inline); + if &actual != expected || &actual_display != display { + let origin = if inline { "inline" } else { "stylesheet" }; + let sector = if mixed.get(..4).is_some_and(|prefix| prefix.eq_ignore_ascii_case("url(")) { "url" } else { "keyword" }; + mismatches.push(format!("{property} {sector} {origin}: {mixed}, style={actual:?}, display={actual_display}")); + } + } + } + // Preserve raw XML/direct-helper compatibility, including the case-sensitive ID. + let raw = roxmltree::Document::parse( + r##""##, + ) + .unwrap(); + let rect = raw.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let d = declared(rect, &StyleSheet::default(), |_| true); + for attribute in rect.attributes() { + assert_eq!(d.get(attribute.name()).map(String::as_str), Some(attribute.value())); + } + let mut raw_style = seed.clone(); + assert_eq!(cascade(rect, &StyleSheet::default(), &mut raw_style, 200.0, 100.0, |_| true), (1.0, true)); + assert_eq!(raw_style, seed); + assert_eq!(paint_ref("url('#PaintID')"), Some(Some(PaintRef::Url("PaintID".into(), None)))); + assert_eq!(paint_ref("URL('#PaintID')"), None); + assert_eq!(paint_ref("NONE"), None); + assert_eq!(paint_ref("CURRENTCOLOR"), None); + // Unsupported expressions and unrelated values must retain their exact spelling. + for (property, value) in [ + ("fill", "var(--Case, URL('#PaintID'))"), + ("stroke", "PaintFunction('#PaintID')"), + ("fill", "\"URL(#PaintID)\""), + ("display", "var(--Case, NONE)"), + ("visibility", "inherit"), + ("font-size", "LARGE"), + ("color", "ReD"), + ] { + for inline in [false, true] { + let (d, _, _) = evaluate(property, value, inline); + assert_eq!(d.get(property).map(String::as_str), Some(value)); + } + } + // The suffix includes quotes, URI/fragment case and the complete fallback spelling. + for property in ["fill", "stroke"] { + for inline in [false, true] { + let value = "URL('Case/Art.svg#PaintID') ReD"; + let (d, _, _) = evaluate(property, value, inline); + if d.get(property).map(String::as_str) != Some("url('Case/Art.svg#PaintID') ReD") { + let origin = if inline { "inline" } else { "stylesheet" }; + mismatches.push(format!("{property} url {origin}: identifier/payload spelling")); + } + } + } + assert!(mismatches.is_empty(), "CSS identifier case mismatches: {mismatches:?}"); + } + #[test] fn cascade_applies_inheritance_and_display() { let doc = roxmltree::Document::parse( diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index e80ca5a08b..3221b11b29 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -5,13 +5,44 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Source-level platform regression guards, test deadlines, hostile-input helpers and a reentrant test lock for the Craft application suite" +description = "Source-level platform regression guards, test deadlines, hostile-input helpers, a reentrant test lock and skip-or-fail helpers for the Craft application suite" publish = false +[features] +default = [] +# Image comparison, PNG reading and writing, and golden reference checks. +image = ["dep:png"] +# `mcp::McpChild`: an MCP stdio test client. +mcp = ["dep:serde_json"] +# Pinned-corpus manifests and the `corpus::pinned` test gate (native only). +corpus = ["dep:sha2", "dep:libc"] +# `font-coverage`: `skip::craft_fonts_cover`, which parses font data with skrifa. +font-coverage = ["dep:skrifa"] + [dependencies] +png = { version = "0.18", optional = true } +sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +skrifa = { workspace = true, optional = true } +toml = { version = "1", default-features = false, features = ["parse", "serde", "std"] } +serde_json = { workspace = true, optional = true } [target.'cfg(unix)'.dependencies] +libc = { version = "0.2", optional = true } rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } +[dev-dependencies] +tempfile = "3" + +[[test]] +name = "mcp" +required-features = ["mcp"] + +[[test]] +name = "mcp_child" +harness = false +required-features = ["mcp"] + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 3adaf23762..5786e326e5 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -99,25 +99,40 @@ fn no_std_instant_in_code_the_web_build_runs() { } ``` +## Test fonts + +The `fonts` module makes test fonts from font bytes the caller supplies. It reads no file and no environment variable, prints nothing, and builds for `wasm32-unknown-unknown`. + +- **`fonts::rename_family(bytes, from, to)`** returns a copy of one standalone face with the family name `from` replaced by `to`, which must have the same length in UTF-16 code units. It changes the family name records (name IDs 1, 16 and 21) whose value is `from`, and full names (ID 4) that are `from` or start with `from` and a space. At least one family record must hold `from`. It reads UTF-16BE and Macintosh Roman records, writes only ASCII names into Macintosh Roman records, leaves the PostScript name (ID 6), other names and other tables as they are, and writes the `name` table checksum and the `head` table's `checkSumAdjustment`. +- **`fonts::collection(faces)`** returns a TrueType collection (TTC 1.0) holding standalone faces. Each face gets its own copy of every table, tables start on four-byte boundaries, offsets count from the start of the collection, `checkSumAdjustment` is zero, and every table checksum matches the bytes in the collection. + +Both return a `fonts::FontError` instead of panicking: names of different lengths, a name that no family record holds, a face shorter than its table directory, a table or name string out of range, a collection given as a face, or output past the 4 GiB a collection's offsets reach. The layouts come from the OpenType font file and `name` table chapters: and . + +The tests that call the copies in VectorCraft, DesignCraft and WordCraft need each app's font database and its bundled fonts, so they stay in the apps. `tests/it/fonts.rs` tests the module on faces it assembles from bytes. + ## deadline The `deadline` module is not built for `wasm32`. -`with_deadline(limit, label, f)` runs `f` on its own thread and returns its value. When `f` does not -finish within the limit, the test fails with a message that names `label`, the limit and the variable -that sets it. A panic in `f` is raised again in the test with its original payload. The limit counts -from the call, including the time spent starting the thread. When `f` returns or panics after the -limit has passed, the test fails with the label and the limit, and with the panic's message if it has -one. +The limits in this module guard against a hang. Elapsed time does not decide a result: a test fails on +a limit only when nothing has arrived by then. -`wait_until(limit, what, cond)` calls `cond` on the test's thread until it returns `true`. It calls -`cond` at once, then after pauses that start at 1 ms and double up to 50 ms, and does not call it -again once the limit has passed. When the limit passes first, or `cond` returns `true` only after the -limit has passed, the test fails with a message that names `what`. +`with_deadline(limit, label, f)` runs `f` on its own thread and returns its value. A panic in `f` is +raised again in the test with its original payload. A value or panic that arrives after the limit is +still the result. When `f` has neither returned nor panicked within the limit, the test fails with a +message that names `label`, the limit and the variable that sets it. The limit counts from the start +of the thread. + +`wait_until(limit, what, &signal, cond)` calls `cond` on the test's thread at once, and again each +time another thread calls `signal.raise()`, until `cond` returns `true`. The thread that changes the +state `cond` reads raises the `Signal` after each change. A raise that comes while `cond` runs makes +`wait_until` call `cond` again straight after. The limit counts from the start of the call. When the +limit has passed and the latest call of `cond` returned `false`, the test fails with a message that +names `what`, even if the signal is still being raised. ```rust use std::time::Duration; -use craft_testkit::deadline::{DeadlineLimit, wait_until, with_deadline}; +use craft_testkit::deadline::{DeadlineLimit, Signal, wait_until, with_deadline}; // The default of 30 s; CRAFT_TEST_TIMEOUT_SECS replaces it. let pixels = with_deadline(Duration::from_secs(30), "decode seed 7", move || decode(&bytes)); @@ -126,7 +141,9 @@ let pixels = with_deadline(Duration::from_secs(30), "decode seed 7", move || dec let limit = DeadlineLimit::new(Duration::from_secs(30)).with_variable("FILMCRAFT_HOSTILE_TIMEOUT_SECS"); with_deadline(limit, "hostile input 12", move || parse(&input)); -wait_until(Duration::from_secs(10), "the export to finish", || job.is_done()); +// The export job calls `done.raise()` after it changes its state. +let done = Signal::new(); +wait_until(Duration::from_secs(10), "the export to finish", &done, || job.is_done()); ``` ### The limit variable @@ -150,12 +167,14 @@ calls this module's. ### Limits -- A body that runs past its limit fails the test, but its thread is left running until the test - process exits. A body that never returns can keep the test binary alive after its tests finish. -- `wait_until` checks its limit only between calls of `cond`. A `cond` that blocks is not interrupted, - so it must return promptly. -- Neither function returns elapsed time. Tests of this crate use channel handshakes, and the only time - bounds in them are the limits under test. +- When a body has no result within its limit, the test fails, but the body's thread is left running + until the test process exits. A body that never returns can keep the test binary alive after its + tests finish. +- A `cond` that blocks is not interrupted, so it must return promptly. +- A state change that nobody signals is not seen: when the signal is not raised, `wait_until` fails + at the limit even if `cond` would now return `true`. +- Neither function returns elapsed time. Tests of this crate use channel handshakes and an injected + wait in place of the limits. ## hostile @@ -169,8 +188,10 @@ yields no copies. `mutations` and `Rng` build for `wasm32`. `hammer(&config, seed, parse)` runs `parse` on the unmodified seed, on every truncation of it (lengths 0 to one less than its length), and on `mutations(seed, rounds)`. The cases run one after -another on one worker thread, and the test's thread fails the test when a case runs past its limit. -A case that finishes after its limit also fails the test. The test fails on the first case that +another on one worker thread, and the test's thread fails the test when a case is still running once +its limit has passed since it started. The limit guards against a hang: a case that finishes passes +or fails on what `parse` did, however long it took, and the number of cases depends only on the seed, +the rounds and the divisor. The test fails on the first case that panics or does not finish, with a message that names the config's label, the case (`the unmodified seed`, `truncation to N` or the edits), the input's length and the panic's message. `parse` must be `Fn(&[u8]) + Send + Sync + 'static`, since a case that does not finish keeps running @@ -237,6 +258,174 @@ Changes from `craft-media-testkit`'s `hammer`: - `parse` is owned and runs on a worker thread. A closure that borrows from the test needs its data moved or shared with an `Arc`. +## `image` feature + +`craft-testkit = { ..., features = ["image"] }` adds `craft_testkit::image` and `assert_similar!`. It depends on `png` 0.18. + +| Item | What it does | +|---|---| +| `Rgba8`, `Gray8` | Borrowed 8-bit views. `new` returns an error when a side is 0 or the buffer is not exactly `width × height × channels` bytes. | +| `diff_rgba`, `diff_gray` | `DiffStats`: differing pixels, maximum and mean absolute sample difference, nearest-rank p99 of each pixel's largest difference, and PSNR with a peak of 255. RGBA counts alpha as a fourth sample. | +| `psnr(a, b, peak)` | PSNR of two `u8` or `u16` planes. The caller passes the peak (255, 1023, 4095, 65535). Equal planes give `f64::INFINITY`; empty or unequal planes and a peak that is not finite and positive are errors. | +| `Tolerance`, `compare_rgba`, `compare_gray` | Gates for maximum difference, p99, minimum PSNR and the share of bad pixels, each inclusive. With `neighborhood`, a pixel is bad only when nothing in the other image's 3×3 window is within `channel`, checked in both directions. | +| `diff_image` | An opaque RGBA image of each absolute sample difference times 8, with alpha differences shown in every color channel. | +| `decode_png`, `encode_png`, `encode_gray_png`, `read_png`, `write_png`, `write_gray_png` | 8-bit PNG reading and writing under `PngLimits` (default 16,384 × 16,384 pixels, 64 MiB encoded, 256 MiB decoded). Palette, low bit depths, 16-bit samples, `tRNS` and interlacing are converted to 8-bit gray or RGBA. Gamma, ICC and sRGB chunks are not applied. | +| `check_golden`, `assert_similar!` | Compare an image with a reference PNG. The reference is written only when the variable named in `GoldenOptions::bless_var` (default `CRAFT_BLESS`) is exactly `1`; otherwise a missing reference is an error. A failed check writes `.actual.png` and `.diff.png` into `GoldenOptions::failures_dir`, using `-1`, `-2` and so on rather than replacing a file. `assert_similar!` fails the calling test. | + +The views, statistics, PSNR, tolerances, the difference image and the in-memory PNG functions build for `wasm32`. The file functions, the bless variable and the golden check are native only. + +```rust +use craft_testkit::image::{GoldenOptions, Rgba8, Tolerance}; + +let options = GoldenOptions { bless_var: "FILMCRAFT_BLESS", ..GoldenOptions::new(&failures, "title_card") }; +let tolerance = Tolerance { min_psnr: Some(45.0), max_abs: Some(12), max_p99: Some(2), ..Tolerance::EXACT }; +craft_testkit::assert_similar!(&reference, Rgba8::new(width, height, &pixels)?, tolerance, options); +``` + +## fixtures + +The `fixtures` module (native targets only) generates missing test fixtures and shares them between test runs and processes: + +- `fixtures_root(var)` is the nonempty value of `var` (default `CRAFT_FIXTURES_DIR`) or `/target/fixtures`. The workspace is the one that holds the package under test, found from the `CARGO_MANIFEST_DIR` that Cargo and nextest set when they run tests: the folder named by the package's `package.workspace` key, or else the nearest folder whose `Cargo.toml` has a `[workspace]` table. A test binary run without `CARGO_MANIFEST_DIR` needs the root variable. `CARGO_TARGET_DIR` does not move the root. `fixtures_dir(sub, var)` creates a folder below the root and rejects an absolute `sub`, one containing `..`, and on Windows one with a drive inside it (`group\C:outside`). It creates the folder one level at a time and returns an error, without creating the rest, when a level resolves outside the root or is not a folder, for example a symbolic link or junction under the root that points elsewhere. The check uses paths, so it does not detect a folder that another process replaces with a link while the call runs or after it returns. +- `temp_path(out)` creates a new, empty sibling of `out` with `create_new`, keeping the extension. A name that already exists is never reused. +- `publish(tmp, out)` moves a nonempty regular file into place while holding a lock on `.fixture-lock`. When `out` is already a nonempty regular file, it is kept and `tmp` is removed; the check reads only the type and length of `out`, so a nonempty `out` that cannot be read is kept too. A directory at `out` is an error, and so are an `out` whose name ends with `.fixture-lock` and a file system that does not support the lock. +- `generate(out, required_var, make)` and `generate_with(out, required, make)` return a cached fixture without calling `make`, or run `make` on a claimed temporary file and publish it. The temporary file is removed when `make` fails, panics, writes nothing or makes `out` name the temporary file, and such an `out` is not returned. When `make` fails after another process published `out`, the published file is returned. A fixture that cannot be made follows the [skip](#skip) rule with the required variable `generate` is given (default `CRAFT_TEST_REQUIRED`): unset or empty prints `SKIPPED: ` on standard error and returns `None`, `1` fails the test, and any other value, `0` included, fails the test as a configuration error. Only `generate` reads the required variable. `generate_with` uses the caller's `required` value instead: `true` fails the test, and `false` prints the skip line and returns `None`. +- `run_generator(cmd, env, max_output)` runs a generator with `env` added to the child's environment only, and keeps at most `max_output` bytes of each output stream (`DEFAULT_MAX_OUTPUT` is 64 KiB). The variables and stream settings stay on `cmd`, so use a new `Command` for each call that needs a clean environment. +- `report(name, status)` and `generate_and_report(name, outputs, generate)` print one of these lines on standard output, which FilmCraft's `cargo xtask fixtures` counts: + + ```text + FIXTURE made + FIXTURE cached + FIXTURE skipped + ``` + +A complete fixture is a nonempty regular file. A consumer that needs a valid media file checks its format after generation. + +## mcp + +The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The module is built on every target except `wasm32`, and it opens no network connection. + +`McpChild::spawn(path, args, env)` starts an MCP server program with its stdin and stdout piped. The variables in `env` are set for the child only; the test process's environment is not changed. `McpChild::connect(reader, writer, limits)` talks to a server that runs in the test process; its reading thread stops when the server drops its end of `reader`, or at the next line the server writes after `close()`. Each message is one line of JSON-RPC 2.0, as the [MCP stdio transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) describes. + +| Call | What it does | +|---|---| +| `initialize(version)` | Sends `initialize` with `version` (`mcp::PROTOCOL_VERSION` is `2025-06-18`), validates the reply, then sends `notifications/initialized`. The result must contain `capabilities` and `serverInfo` objects, with string `serverInfo.name` and `serverInfo.version` fields. Invalid fields return `Protocol` and close the connection. A reply with another version returns `UnsupportedVersion` and closes the connection. | +| `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Well-formed replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. | +| `call_tool(name, args)`, `call_tool_within(.., timeout)` | Sends `tools/call` and returns the tool result unchanged, `content` and `isError` included. | +| `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. | +| `notify(method, params)` | Sends a notification, which has no id and gets no reply. | +| `take_notifications()` | Returns the notifications kept so far without waiting. | +| `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. After the child exits, it waits up to 5 s for the rest of stderr to be read. | + +Tool results require a `content` array. Optional `isError` must be a boolean, and optional +`structuredContent` and `_meta` must be objects. Both tool helpers reject a malformed envelope +with `Protocol` and close the connection. Requests and notifications from the server require +object-valued `params` when that field is present. `close()` drains and discards stdout while +waiting for the child; incoming output does not extend the grace period. + +While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. Server requests require string or integer IDs. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error and close the connection; later calls return `Closed`. A terminal failure discards queued writes and unread messages. A write already in progress may finish. After the end of stdout or an I/O error, `close()` or dropping the connection reaps the child. Other terminal failures stop and reap it immediately. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics. + +`McpLimits` holds the limits. These defaults are the crate's own values: + +| Field | Default | Range | +|---|---|---| +| `max_line_bytes` | 64 MiB, for one stdout line, for the whole `list_tools` result, and for the total compact JSON bytes of retained notifications | at least 1 | +| `request_timeout` | 30 s | more than zero, at most 1 hour | +| `initialize_timeout` | 60 s | more than zero, at most 1 hour | +| `close_grace` | 2 s | at most 1 hour | +| `max_pages` | 64 | at least 1 | +| `max_notifications` | 0 (notifications are not kept); oldest entries are dropped to satisfy both this count and the `max_line_bytes` byte budget | at most 4096 | +| `stderr_tail_bytes` | 0 (stderr goes to the null device); otherwise the last bytes written are kept | at most 16 MiB | + +A notification whose compact JSON encoding exceeds `max_line_bytes` is discarded without removing previously retained notifications. + +`McpLimits::timeouts_from_var(name)` sets both deadlines from a variable that holds a whole number of seconds from 1 to 3600; `mcp::TIMEOUT_VAR` (`CRAFT_TEST_MCP_TIMEOUT_SECS`) is the default name. Any other value returns an error. + +```rust +use craft_testkit::mcp::{McpChild, PROTOCOL_VERSION}; + +let mut mcp = McpChild::spawn(env!("CARGO_BIN_EXE_my-cli"), ["mcp"], [("MYCRAFT_CONFIG_DIR", dir.path())])?; +mcp.initialize(PROTOCOL_VERSION)?; +let result = mcp.call_tool("doc.new", serde_json::json!({}))?; +assert!(!result["isError"].as_bool().unwrap_or(false)); +assert!(mcp.close()?.status.is_some_and(|s| s.success())); +``` + +The tests that start a real child are in `tests/mcp_child.rs`, a target with `harness = false`: the child is that test program, and the standard harness writes its own lines on stdout. Both test targets build to nothing on `wasm32`. + +## corpus + +`craft_testkit::corpus` is behind the `corpus` feature and is native only. It parses a corpus manifest and checks a folder of files against it. + +A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 hexadecimal digits in either case, the path relative to the corpus folder with `/` between its parts, and optional license and URL columns. Blank lines and lines whose first character other than a space or a tab is `#` are skipped. LF and CRLF line endings are both read. + +- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a control character (NUL included), and a path listed twice. An empty optional column is `None`. The parser does not check that a name is valid on a given file system: a name Windows reserves (`<`, `>`, `"`, `|`, `?`, `*`, a trailing `.` or space, a device name such as `NUL`) or two names that differ only in case are accepted, so a manifest must use names that every file system it is verified on supports. +- `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. +- `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. +- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. After the open, `verify` also checks that the opened file is inside `dir`: on Linux, Android and Apple platforms by the path the kernel reports for the open file, and on other Unix systems, or on Linux and Android when `/proc/self/fd` cannot be read, by resolving the listed path again and comparing its device and inode with the opened file's. On Apple platforms an error from the path query fails verification with `VerifyError::Read` instead of falling back to the second lookup. That second lookup goes through the path again, so a folder changed during it is not detected. On Windows the location of the opened file is not checked again, so a part of the path changed into a link out of `dir` between the check and the open is not detected. In every case the opened file must still have the listed SHA-256. +- `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. With the folder variable unset, it calls `skip::skip` with the reason `corpus not given: set to its folder` and the required variable `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`), so the [skip](#skip) rule applies: unset or empty prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`, `1` fails the test, and any other value, `0` included, fails the test as a configuration error. With the folder variable set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. A `var` that is empty or holds `=` or a NUL character fails the test before the environment is read. Otherwise it returns the folder. + +`Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. + +## skip + +The `skip` module is not built for `wasm32`. A test that needs something a test environment may lack +(a program, a corpus file, the craft-fonts faces) skips or fails under one rule: + +The variable is read only when something is missing. + +| Value | Result | +|---|---| +| Not set or empty | The helper prints `SKIPPED: ` and one line feed to stderr, and the test returns and passes. Carriage returns and line feeds in the reason are printed as `\r` and `\n`. | +| `1` | The test fails. No skip line is printed. | +| Any other value, such as `0`, `true`, `yes`, ` 1` or `1` followed by a line feed | The test fails with the reason and the variable's name and value. No skip line is printed. | +| Not Unicode | The test fails with the reason and the variable's name. No skip line is printed. | + +A variable name that is empty or holds `=` or a NUL character also fails the test, before the +environment is read. + +`skip::required(var)` returns the same decision without failing the test: `Ok(false)`, `Ok(true)`, +or a `RequiredError` that names the variable. Every module of this crate that reads a required +variable reads it with `skip::required`, so one rule applies to all of them. + +The caller passes the name its repository uses today, such as `CRAFT_MEDIA_REQUIRE_ORACLES`, +`CRAFT_PDF_ORACLES_REQUIRED`, `PDFCRAFT_ORACLES_REQUIRED` or `FILMCRAFT_REQUIRE_ORACLES`. +`skip::REQUIRED_VAR` (`CRAFT_TEST_REQUIRED`) is the default name. + +```rust +use craft_testkit::skip::{REQUIRED_VAR, craft_fonts, skip}; + +#[test] +fn renders_with_qpdf() { + let qpdf = craft_testkit::or_skip!(find_qpdf(), REQUIRED_VAR); + // ... +} + +#[test] +fn draws_japanese() { + if !craft_fonts(HAS_CRAFT_FONTS, CRAFT_FONTS_REQUIRED) { + return; + } + // ... +} +``` + +`or_skip!` evaluates a `Result` once, binds the `Ok` value, and on `Err` skips with the error's +`Display` text as the reason. The two-argument form returns `()`; a test that returns a `Result` +passes the value to return as the third argument, for example `Ok(())`. + +`craft_fonts(present, required)` takes both values from the caller's build: a build constant, an +`option_env!` value, or the table `craft-fonts-build` generates. A required failure names +`CRAFT_FONTS_REQUIRED=1`. + +`craft_fonts_cover(text, faces)` needs the `font-coverage` feature, which adds skrifa. It returns +`true` when one face maps every character of `text` that is not whitespace. Each face is font data +with its index in a collection (`0` for a single font). A face that does not parse covers nothing, +and coverage is not combined across faces. + +The module does not change the process environment. Its tests that read a real variable run the +test binary again as a child process with that variable set. + ## serial `serial` is native only. @@ -276,6 +465,16 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie |---|---|---|---| | `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | +### fonts + +| Module | Source | Path | Commit | +|---|---|---|---| +| `fonts` | storytold/vectorcraft, `rename` and `collection` | `crates/text/src/tests/sysfonts.rs` | `bada8e1710` | +| `fonts` | storytold/vectorcraft, `renamed` | `crates/testkit/src/fonts.rs` | `bada8e1710` | +| `fonts` | storytold/designcraft, the family renaming and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `8b169f8ee7` | +| `fonts` | storytold/wordcraft, `renamed_to` and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `f8c66d0692` | +| `fonts` | storytold/wordcraft, `renamed` | `crates/fonts/src/fontdb/user/tests.rs` | `f8c66d0692` | + ### deadline | Code | Repository | Path | SHA | @@ -295,6 +494,45 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie |---|---|---|---| | `Rng`, the edits of `mutations` and `hammer` | storytold/craft-libs | `crates/media-testkit/src/hostile.rs` | `75a654f4` | +### image + +| Code | Source | +|---|---| +| Statistics, PNG reading and writing, golden check | FilmCraft `crates/testkit/src/golden.rs` at `e4ab3c6a99` | +| Per-pixel channel tolerance and bad-pixel share | AniCraft `crates/engine/tests/golden/mod.rs` at `3435e98681` | +| Gray view and 3×3 neighborhood comparison | PdfCraft `crates/oracle/src/pixels.rs` at `eead454105` | + +### fixtures + +| Part | Repository | Path | Commit | +|---|---|---|---| +| Locations, publication with winner reuse, reporting, and the moved tests | storytold/filmcraft | `crates/testkit/src/fixtures.rs` | `e4ab3c6a99` | +| `generate_with` and the required rule, with `failed_generator_skips_when_optional` and `failed_generator_fails_when_required` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` | `75a654f4f8` | + +### mcp + +| Code | Repository | Path | SHA | +|---|---|---|---| +| `Conn`, `request`, `call_tool`, `MAX_LINE`, deadlines, and the 14 tests of `child_tests.rs`, written again here | storytold/craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs` | `e8b31cb0` | +| The MCP end-to-end helpers | storytold/vectorcraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | `460d2119` | +| `mcp_recv` | storytold/photocraft | `apps/photocraft-cli/tests/it/cli.rs` | `58d11d91` | + +### corpus + +| Code | Repository | Path | SHA | +|---|---|---|---| +| The manifest rows and the digest check of `pinned` | storytold/craft-libs | `crates/affinity/tests/support/corpus.rs:18-35` | `75a654f4` | + +### skip + +| Code | Repository | Path | Commit | +|---|---|---|---| +| `skip!`, `record` | storytold/lightcraft | `crates/testkit/src/lib.rs` | `7ebbb17a82` | +| `or_skip!`, `REQUIRED_VAR` | storytold/pdfcraft | `crates/oracle/src/lib.rs` | `ee9bf28126` | +| `require_*!`, `skip` | storytold/filmcraft | `crates/testkit/src/lib.rs`, `crates/testkit/src/oracle.rs` | `cff7e1442e` | +| `skip`, `skip_with` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` | `75a654f4f8` | +| `craft_fonts_cover` | storytold/gridcraft | `crates/ui-egui/src/theme.rs` | `06c2b1440b` | + ### rng | Module | Source | Path | Commit | @@ -312,6 +550,14 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie | PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | | FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | +### fonts + +| Consumer | Guard | Replaces | State | +|---|---|---|---| +| VectorCraft | `fonts::rename_family`, `fonts::collection` | `crates/text/src/tests/sysfonts.rs` and `crates/testkit/src/fonts.rs` helpers | Not started | +| DesignCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` helpers | Not started | +| WordCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` and `crates/fonts/src/fontdb/user/tests.rs` helpers | Not started | + ### rng | Consumer | Code it replaces | State | @@ -345,6 +591,62 @@ An adoption keeps the variable name the app uses today. CADCraft's and TextureCraft's loops make other edits than `mutations`. Their adoptions say which cases change, and keep the test names. +### image + +| Consumer | Today | State | +|---|---|---| +| FilmCraft | `golden.rs`, `FILMCRAFT_BLESS` | Not started | +| AniCraft | `crates/engine/tests/golden/mod.rs`, `UPDATE_GOLDENS` | Not started | +| PdfCraft | `pdfcraft-oracle` `pixels.rs` | Not started | +| VectorCraft | `crates/testkit/src/raster.rs` (comparison only) | Not started | +| DesignCraft | `crates/render/tests/it/effects.rs`, `DESIGNCRAFT_BLESS` | Not started | + +### fixtures + +| Consumer | Copy it replaces | State | +|---|---|---| +| FilmCraft | `crates/testkit/src/fixtures.rs` (passes `FILMCRAFT_FIXTURES_DIR` and `FILMCRAFT_REQUIRE_ORACLES`) | Not switched | +| EffectCraft | `crates/media/tests/it/footage.rs` | Not switched | +| craft-libs `audio` and `video` tests | `crates/audio/tests/codecs/testkit.rs`, `crates/video/tests/vp8/common/mod.rs` | Not switched | +| `craft-media-testkit` | its `fixtures` module and `temp_path` (keeps its public names) | Not switched | + +### mcp + +| Consumer | Code it replaces | State | +|---|---|---| +| VectorCraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | Pending | +| PhotoCraft | `apps/photocraft-cli/tests/it/cli.rs` | Pending | +| CADCraft, DeckCraft, DesignCraft, EffectCraft | the MCP helpers in their CLI tests | Pending | +| FigCraft, FilmCraft, GridCraft, LightCraft, PdfCraft, SoundCraft | the MCP helpers in their CLI tests | Pending | +| craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs`, production code | Kept as it is | + +### corpus + +| Consumer | Code it replaces | State | +|---|---|---| +| craft-libs `affinity` | `tests/support/corpus.rs`, which parses `corpus.tsv` (four tab-separated columns) and checks the folder `AFFINITY_CORPUS` names | Pending | +| craft-libs `raw` | `tests/it/raf_corpus_manifest.rs`, which checks the rows of the tab-separated `docs/raf-corpus.sha256` but not the files | Pending | +| LightCraft | `crates/raw/tests/it/corpus.rs` checks the RAF list | Pending | +| PhotoCraft | `crates/io/tests/it/corpus.rs` and `xtask/*-corpus.sha256` (two-space lists, to be converted to tabs) | Pending | +| CADCraft | `crates/io/src/roundtrip/tests.rs` scans `CADCRAFT_CORPUS_DIR` without a checksum list | Pending: needs a pinned list first | +| VectorCraft | `crates/affinity/tests/support/corpus.rs` reads a two-space list, to be converted to tabs | Pending | + +### skip + +| Consumer | Code it replaces | State | +|---|---|---| +| LightCraft | `lightcraft-testkit`'s `skip!`, which keeps its JSON skip log on top of `skip` | Not started | +| PdfCraft | `pdfcraft-oracle`'s `or_skip!`, which reads any value of `PDFCRAFT_ORACLES_REQUIRED` | Not started | +| FilmCraft | `filmcraft-testkit`'s `require_*!` and `skip`, which accept `1`, `true`, `yes` and `on` | Not started | +| GridCraft | `craft_fonts_cover`, which reads GridCraft's embedded face table | Not started | +| craft-libs `craft-media-testkit` | `skip` and `skip_with`, which accept `1`, `true`, `yes` and `on` | Not started | +| craft-libs `pdf` tests | `or_skip!` in `crates/pdf/tests/cos/oracle.rs`, which reads any value of `CRAFT_PDF_ORACLES_REQUIRED` | Not started | + +After an adoption, an app that reads any value as required skips on an empty value, and fails as +a configuration error on every other value except `1`, `0` included. An app that accepts `true`, `yes` +and `on` fails on those values as a configuration error. +Each adoption says which values change and keeps the variable name. + ### serial | Consumer | Module | Switched | diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs new file mode 100644 index 0000000000..96d6460074 --- /dev/null +++ b/crates/testkit/src/corpus.rs @@ -0,0 +1,1063 @@ +//! Pinned test corpora: a folder of files listed in a manifest, each checked against its SHA-256. +//! +//! A manifest has one tab-separated row per file: the SHA-256 as 64 hexadecimal digits, the +//! file's path relative to the corpus folder, and optional license and URL columns. In this +//! example each `\t` stands for one tab character: +//! +//! ```text +//! # Public Affinity documents +//! cc8ca0db0d8fc545eb29153be900f153fa6b7b7eac068d05e54a502aba1264fe\tafdesignload-color.afdesign\tMIT\thttps://example.org/color.afdesign +//! 9a17f500d09fb3b1a70d24aabdc2882955ec3eac3700a474549e6100be3a8484\tmore/layer_mode.afdesign +//! ``` +//! +//! [`Manifest::parse`] skips blank lines and lines whose first character other than a space or a +//! tab is `#`. A `#` later in a row is part of that row. It returns a [`ManifestError`] naming the +//! line of a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal +//! digits, a path that is empty, absolute or leaves the folder, or a path listed twice. Paths use +//! `/` between their parts. +//! +//! [`pinned`] is the gate a test calls: it returns the corpus folder named by a variable after +//! checking every listed file. When the variable is unset it skips or fails the test under the +//! rule of [`skip`](crate::skip::skip), and it fails the test on any other failure. [`verify`] +//! runs the same check and returns a [`VerifyError`] instead of failing. No function here +//! downloads a file or changes the process environment. +//! +//! Every input has a size limit, set by [`Limits`]: a manifest of at most 1 MiB and 10,000 rows, +//! and files of at most 8 GiB each, read 64 KiB at a time. + +use std::collections::HashSet; +use std::ffi::OsString; +use std::fmt; +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +/// The variable [`pinned`] reads when the caller names none. +pub const DEFAULT_VAR: &str = "CRAFT_CORPUS"; + +/// The suffix [`pinned`] adds to the folder variable's name to form the name of the variable that +/// makes the corpus required. +pub const REQUIRED_SUFFIX: &str = "_REQUIRED"; + +/// The size of each read while a file is hashed. +const CHUNK: usize = 64 * 1024; + +/// Size limits for a manifest and for the files it lists. An input over a limit is an error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest manifest in bytes. Default 1 MiB. + pub max_manifest_bytes: usize, + /// The most rows a manifest may list. Default 10,000. + pub max_entries: usize, + /// The largest listed file in bytes. Default 8 GiB. + pub max_file_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_manifest_bytes: 1024 * 1024, max_entries: 10_000, max_file_bytes: 8 * 1024 * 1024 * 1024 } + } +} + +/// One row of a manifest. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + digest: [u8; 32], + path: String, + license: Option, + url: Option, + line: usize, +} + +impl Entry { + /// The file's SHA-256. + pub fn digest(&self) -> &[u8; 32] { + &self.digest + } + + /// The file's path relative to the corpus folder, with `/` between its parts. + pub fn path(&self) -> &str { + &self.path + } + + /// The license column, when the row has one that is not empty. + pub fn license(&self) -> Option<&str> { + self.license.as_deref() + } + + /// The URL column, when the row has one that is not empty. + pub fn url(&self) -> Option<&str> { + self.url.as_deref() + } + + /// The 1-based line of the manifest that holds the row. + pub fn line(&self) -> usize { + self.line + } + + /// The file's path under `dir`. + fn path_in(&self, dir: &Path) -> PathBuf { + let mut path = dir.to_path_buf(); + path.extend(self.path.split('/')); + path + } +} + +/// A parsed manifest: the rows in the order the manifest lists them. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Manifest { + entries: Vec, +} + +impl Manifest { + /// Parses `text` under the default [`Limits`]. + pub fn parse(text: &str) -> Result { + Self::parse_with_limits(text, &Limits::default()) + } + + /// Parses `text`. A manifest longer than `limits.max_manifest_bytes` or with more than + /// `limits.max_entries` rows is an error. + pub fn parse_with_limits(text: &str, limits: &Limits) -> Result { + if text.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let mut entries: Vec = Vec::new(); + let mut seen: HashSet<&str> = HashSet::new(); + for (index, raw) in text.lines().enumerate() { + let line = index + 1; + let content = raw.trim_start_matches([' ', '\t']); + if content.trim().is_empty() || content.starts_with('#') { + continue; + } + if entries.len() == limits.max_entries { + return Err(ManifestError::TooManyEntries { limit: limits.max_entries }); + } + let columns: Vec<&str> = raw.split('\t').collect(); + if !(2..=4).contains(&columns.len()) { + return Err(ManifestError::Columns { line, found: columns.len() }); + } + let digest = parse_digest(columns[0]).ok_or(ManifestError::Digest { line })?; + let path = columns[1]; + check_path(path).map_err(|reason| ManifestError::Path { line, reason })?; + if !seen.insert(path) { + let first = entries.iter().find(|e| e.path == path).map_or(0, |e| e.line); + return Err(ManifestError::Duplicate { line, first }); + } + let optional = |i: usize| columns.get(i).filter(|c| !c.is_empty()).map(|c| (*c).to_owned()); + entries.push(Entry { digest, path: path.to_owned(), license: optional(2), url: optional(3), line }); + } + Ok(Self { entries }) + } + + /// Reads and parses the manifest file at `path`. A path that is not a regular file is refused + /// before it is opened. Reading stops after `limits.max_manifest_bytes` bytes plus one, so an + /// oversized file is not read whole. + pub fn read(path: &Path, limits: &Limits) -> Result { + if !std::fs::metadata(path).map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let file = open_for_reading(path).map_err(ManifestError::Io)?; + if !file.metadata().map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let cap = u64::try_from(limits.max_manifest_bytes).unwrap_or(u64::MAX).saturating_add(1); + let mut bytes = Vec::new(); + file.take(cap).read_to_end(&mut bytes).map_err(ManifestError::Io)?; + if bytes.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let text = String::from_utf8(bytes).map_err(|_| ManifestError::NotUtf8)?; + Self::parse_with_limits(&text, limits) + } + + /// The rows, in manifest order. + pub fn entries(&self) -> &[Entry] { + &self.entries + } + + /// The paths of the rows, in manifest order. + pub fn names(&self) -> impl Iterator { + self.entries.iter().map(Entry::path) + } +} + +/// Decodes 64 ASCII hexadecimal digits, in either case. +fn parse_digest(text: &str) -> Option<[u8; 32]> { + let bytes = text.as_bytes(); + if bytes.len() != 64 { + return None; + } + let mut digest = [0u8; 32]; + let (pairs, _) = bytes.as_chunks::<2>(); + for (out, &[high, low]) in digest.iter_mut().zip(pairs) { + let high = char::from(high).to_digit(16)?; + let low = char::from(low).to_digit(16)?; + *out = u8::try_from(high * 16 + low).ok()?; + } + Some(digest) +} + +/// Checks that `path` is relative and stays in the corpus folder: parts separated by `/`, none +/// empty, `.` or `..`, and no `\`, `:` or control character (NUL included) anywhere, so no +/// platform reads a row as an absolute path or a path outside the folder. It does not check that +/// each name is valid on a given file system: a name Windows reserves (`<>"|?*`, a trailing `.` or +/// space, a device name such as `NUL`) or one that differs from another only in case is accepted, +/// and the manifest must use names the file systems it is verified on support. +fn check_path(path: &str) -> Result<(), PathError> { + if path.is_empty() { + return Err(PathError::Empty); + } + if path.contains(['\\', ':']) || path.chars().any(char::is_control) { + return Err(PathError::Character); + } + for part in path.split('/') { + match part { + "" => return Err(if path.starts_with('/') { PathError::Absolute } else { PathError::EmptyPart }), + "." | ".." => return Err(PathError::DotPart), + _ => {} + } + } + Ok(()) +} + +/// Why a manifest path was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PathError { + /// The path is empty. + Empty, + /// The path starts with `/`. + Absolute, + /// The path has an empty part (`a//b`, or a trailing `/`). + EmptyPart, + /// The path has a `.` or `..` part. + DotPart, + /// The path holds a `\`, a `:` or a control character. + Character, +} + +impl fmt::Display for PathError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Empty => "the path is empty", + Self::Absolute => "the path is absolute", + Self::EmptyPart => "the path has an empty part", + Self::DotPart => "the path has a . or .. part", + Self::Character => "the path holds a \\, a : or a control character", + }) + } +} + +/// Why a manifest could not be read or parsed. +#[derive(Debug)] +pub enum ManifestError { + /// The manifest is longer than the limit in bytes. + TooLarge { + /// The limit in bytes. + limit: usize, + }, + /// The manifest lists more rows than the limit. + TooManyEntries { + /// The limit in rows. + limit: usize, + }, + /// A row does not have 2, 3 or 4 tab-separated columns. + Columns { + /// The 1-based line of the row. + line: usize, + /// The number of columns found. + found: usize, + }, + /// A row's digest is not 64 hexadecimal digits. + Digest { + /// The 1-based line of the row. + line: usize, + }, + /// A row's path is refused. + Path { + /// The 1-based line of the row. + line: usize, + /// Why the path is refused. + reason: PathError, + }, + /// A row repeats the path of an earlier row. + Duplicate { + /// The 1-based line of the repeated row. + line: usize, + /// The 1-based line of the earlier row. + first: usize, + }, + /// The manifest path does not name a regular file. + NotAFile, + /// The manifest file is not UTF-8. + NotUtf8, + /// The manifest file could not be read. + Io(io::Error), +} + +impl fmt::Display for ManifestError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TooLarge { limit } => write!(f, "the manifest is longer than {limit} bytes"), + Self::TooManyEntries { limit } => write!(f, "the manifest lists more than {limit} files"), + Self::Columns { line, found } => write!(f, "line {line}: {found} tab-separated columns, expected 2 to 4"), + Self::Digest { line } => write!(f, "line {line}: the SHA-256 is not 64 hexadecimal digits"), + Self::Path { line, reason } => write!(f, "line {line}: {reason}"), + Self::Duplicate { line, first } => write!(f, "line {line}: the path is already listed on line {first}"), + Self::NotAFile => f.write_str("the manifest is not a regular file"), + Self::NotUtf8 => f.write_str("the manifest is not UTF-8"), + Self::Io(error) => write!(f, "the manifest could not be read: {error}"), + } + } +} + +impl std::error::Error for ManifestError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + _ => None, + } + } +} + +/// Why a corpus folder does not match its manifest. +#[derive(Debug)] +pub enum VerifyError { + /// The manifest lists no files, so the folder would be accepted without a check. + EmptyManifest, + /// The corpus folder could not be resolved. + Folder { + /// The folder. + dir: PathBuf, + /// The error resolving it. + error: io::Error, + }, + /// A listed file is missing or could not be resolved. + Missing { + /// The path the manifest lists. + path: String, + /// The error resolving it. + error: io::Error, + }, + /// A listed path resolves outside the corpus folder, through a symbolic link. + Escapes { + /// The path the manifest lists. + path: String, + }, + /// A listed path is not a regular file. + NotAFile { + /// The path the manifest lists. + path: String, + }, + /// A listed file is larger than the limit. + TooLarge { + /// The path the manifest lists. + path: String, + /// The limit in bytes. + limit: u64, + }, + /// A listed file could not be read. + Read { + /// The path the manifest lists. + path: String, + /// The read error. + error: io::Error, + }, + /// A listed file's SHA-256 differs from the manifest's. + Modified { + /// The path the manifest lists. + path: String, + }, +} + +impl fmt::Display for VerifyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyManifest => f.write_str("the manifest lists no files"), + Self::Folder { dir, error } => write!(f, "corpus folder {}: {error}", dir.display()), + Self::Missing { path, error } => write!(f, "{path}: missing: {error}"), + Self::Escapes { path } => write!(f, "{path}: resolves outside the corpus folder"), + Self::NotAFile { path } => write!(f, "{path}: not a regular file"), + Self::TooLarge { path, limit } => write!(f, "{path}: larger than {limit} bytes"), + Self::Read { path, error } => write!(f, "{path}: {error}"), + Self::Modified { path } => write!(f, "{path}: SHA-256 differs from the manifest"), + } + } +} + +impl std::error::Error for VerifyError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Folder { error, .. } | Self::Missing { error, .. } | Self::Read { error, .. } => Some(error), + _ => None, + } + } +} + +/// Checks every file `manifest` lists in `dir` under the default [`Limits`]. +pub fn verify(dir: &Path, manifest: &Manifest) -> Result<(), VerifyError> { + verify_with_limits(dir, manifest, &Limits::default()) +} + +/// Checks every file `manifest` lists in `dir`: each must resolve inside `dir` after symbolic +/// links are followed, be a regular file of at most `limits.max_file_bytes` bytes, and have the +/// listed SHA-256. Returns the first failure in manifest order. An empty manifest is an error. +/// +/// The resolved path is checked before the file is opened. On Unix the opened file is checked +/// again: on Linux, Android and Apple platforms by the path the kernel reports for it, and +/// elsewhere, or on Linux and Android without that path, by resolving the listed path a second time +/// and comparing device and inode. That second lookup does not detect a folder inside `dir` that is +/// changed while it runs. On Windows the opened file's location is not checked again, so a part of +/// the path changed into a link out of `dir` between the check and the open is not detected. In +/// each case the file must still have the listed SHA-256. +pub fn verify_with_limits(dir: &Path, manifest: &Manifest, limits: &Limits) -> Result<(), VerifyError> { + if manifest.entries.is_empty() { + return Err(VerifyError::EmptyManifest); + } + let root = dir.canonicalize().map_err(|error| VerifyError::Folder { dir: dir.to_path_buf(), error })?; + let mut buf = vec![0u8; CHUNK]; + for entry in &manifest.entries { + verify_entry(&root, entry, limits, &mut buf)?; + } + Ok(()) +} + +fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Result<(), VerifyError> { + verify_entry_with(root, entry, limits, buf, open_for_reading) +} + +/// [`verify_entry`] with the function that opens the resolved path; tests change the path in it. +fn verify_entry_with( + root: &Path, + entry: &Entry, + limits: &Limits, + buf: &mut [u8], + open: impl FnOnce(&Path) -> io::Result, +) -> Result<(), VerifyError> { + let path = || entry.path.clone(); + let target = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; + if !target.starts_with(root) { + return Err(VerifyError::Escapes { path: path() }); + } + let kind = std::fs::metadata(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + if !kind.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + let file = open(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + let meta = file.metadata().map_err(|error| VerifyError::Read { path: path(), error })?; + if !meta.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + #[cfg(unix)] + opened_file_is_inside(root, entry, &file, &meta)?; + if meta.len() > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + let mut reader = file.take(limits.max_file_bytes.saturating_add(1)); + let mut hasher = Sha256::new(); + let mut total: u64 = 0; + loop { + let n = match reader.read(buf) { + Ok(0) => break, + Ok(n) => n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(VerifyError::Read { path: path(), error }), + }; + total = total.saturating_add(n as u64); + if total > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + hasher.update(&buf[..n]); + } + if hasher.finalize().as_slice() != entry.digest.as_slice() { + return Err(VerifyError::Modified { path: path() }); + } + Ok(()) +} + +/// Checks, after the open, that the opened file is inside `root`, so a path changed into a link out +/// of the folder between the first check and the open is refused. On Linux, Android and Apple +/// platforms the kernel reports the open file's path, which must start with `root`; on Apple +/// platforms an error from that query fails the check with [`VerifyError::Read`]. On other Unix +/// systems, and on Linux and Android when `/proc/self/fd` cannot be read, the entry's path is +/// resolved again and must lead, without a link in its last part, to the opened file (the same +/// device and inode). +#[cfg(unix)] +fn opened_file_is_inside(root: &Path, entry: &Entry, file: &File, opened: &std::fs::Metadata) -> Result<(), VerifyError> { + use std::os::unix::fs::MetadataExt; + let path = || entry.path.clone(); + if let Some(actual) = opened_path(file).map_err(|error| VerifyError::Read { path: path(), error })? { + return if actual.starts_with(root) { Ok(()) } else { Err(VerifyError::Escapes { path: path() }) }; + } + let again = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; + let now = std::fs::symlink_metadata(&again).map_err(|error| VerifyError::Read { path: path(), error })?; + if !again.starts_with(root) || (now.dev(), now.ino()) != (opened.dev(), opened.ino()) { + return Err(VerifyError::Escapes { path: path() }); + } + Ok(()) +} + +/// The path of the file `file` has open, as the kernel reports it in `/proc/self/fd`, or `None` +/// when that cannot be read (for example without a mounted `/proc`). +#[cfg(any(target_os = "linux", target_os = "android"))] +#[allow(clippy::unnecessary_wraps)] +fn opened_path(file: &File) -> io::Result> { + use std::os::fd::AsRawFd; + Ok(std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()) +} + +/// The path of the file `file` has open, as the kernel reports it. +#[cfg(target_vendor = "apple")] +fn opened_path(file: &File) -> io::Result> { + use std::os::unix::ffi::OsStringExt; + let path = rustix::fs::getpath(file)?; + Ok(Some(PathBuf::from(OsString::from_vec(path.into_bytes())))) +} + +/// `None`: the platform does not report the path of an open file. +#[cfg(all(unix, not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))))] +fn opened_path(_file: &File) -> io::Result> { + Ok(None) +} + +/// Opens `path` for reading. On Unix the file is opened with `O_NONBLOCK`, so a path that was +/// replaced by a named pipe after its type was checked opens at once instead of waiting for a +/// writer; the caller checks the opened file's type. Reads from a regular file are not affected. +fn open_for_reading(path: &Path) -> io::Result { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK); + } + options.open(path) +} + +/// The corpus folder the variable `var` names (default [`DEFAULT_VAR`]), after every file +/// `manifest` lists has been checked with [`verify`]. +/// +/// - Folder variable unset: calls [`skip`](crate::skip::skip) with the reason +/// `corpus not given: set to its folder` and the variable named `var` plus +/// [`REQUIRED_SUFFIX`] (by default `CRAFT_CORPUS_REQUIRED`). When that variable is unset or +/// empty, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns +/// `None`. When it is `1`, it fails the test. Any other value, `0` included, fails the test as a +/// configuration error. +/// - Folder variable set, even to an empty value: fails the test unless the manifest parses and +/// every listed file matches. +/// +/// A `var` that is empty or holds `=` or a NUL character fails the test before the environment is +/// read. It fails the test with a panic whose message names the variable and the failure. +#[allow(clippy::panic)] +pub fn pinned(var: Option<&str>, manifest: &str) -> Option { + let var = var.unwrap_or(DEFAULT_VAR); + if let Err(message) = check_var(var) { + panic!("{message}"); + } + match gate(std::env::var_os(var), var, manifest) { + Ok(Some(dir)) => Some(dir), + Ok(None) => { + let required_var = format!("{var}{REQUIRED_SUFFIX}"); + let _ = crate::skip::skip(&format!("corpus not given: set {var} to its folder"), &required_var); + None + } + Err(message) => panic!("{message}"), + } +} + +/// Refuses a folder variable name that is empty or holds `=` or a NUL character, the names +/// [`skip::required`](crate::skip::required) refuses. +fn check_var(var: &str) -> Result<(), String> { + if var.is_empty() || var.contains(['=', '\0']) { + return Err(format!("{var:?} cannot name the corpus folder variable: it is empty or holds `=` or a NUL character")); + } + Ok(()) +} + +/// The decision of [`pinned`] on the folder variable's value, without reading the environment or +/// printing: `Ok(None)` when the variable is unset, which [`pinned`] passes to +/// [`skip`](crate::skip::skip), and `Err` holds the message the test fails with. +fn gate(folder: Option, var: &str, manifest: &str) -> Result, String> { + let Some(folder) = folder else { + return Ok(None); + }; + if folder.is_empty() { + return Err(format!("{var} is set but empty")); + } + let dir = PathBuf::from(folder); + let manifest = Manifest::parse(manifest).map_err(|e| format!("corpus manifest for {var}: {e}"))?; + verify(&dir, &manifest).map_err(|e| format!("pinned corpus in {} ({var}): {e}", dir.display()))?; + Ok(Some(dir)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Command, Output}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// The case the child process runs; unset in an ordinary test run. + const CHILD_CASE: &str = "CRAFT_TESTKIT_CORPUS_CHILD"; + /// The folder variable the child's `pinned` reads. + const VAR: &str = "CRAFT_TESTKIT_CORPUS_DIR"; + /// The required variable that goes with [`VAR`]. + const REQUIRED: &str = "CRAFT_TESTKIT_CORPUS_DIR_REQUIRED"; + + const HELLO: &[u8] = b"hello world"; + /// SHA-256 of `hello world`. + const HELLO_SHA: &str = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"; + const EMPTY_SHA: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + + /// A folder under the system temporary folder, removed on drop. + struct Scratch(PathBuf); + + impl Scratch { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("craft_testkit_corpus_{}_{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create scratch folder"); + Self(dir) + } + + fn write(&self, rel: &str, bytes: &[u8]) -> PathBuf { + let path = self.0.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + std::fs::write(&path, bytes).expect("write file"); + path + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn parse_err(text: &str) -> ManifestError { + Manifest::parse(text).expect_err("the manifest is refused") + } + + #[test] + fn comments_are_skipped() { + let text = format!("# pinned corpus\n # indented comment\n\t# tab-indented comment\n{HELLO_SHA}\thello.txt\n#{EMPTY_SHA}\tempty.txt\n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.names().collect::>(), ["hello.txt"]); + assert_eq!(manifest.entries()[0].line(), 4); + } + + #[test] + fn a_hash_inside_a_row_is_not_a_comment() { + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tdir/#1.txt\tMIT\thttps://example.org/a#b\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.path(), "dir/#1.txt"); + assert_eq!(entry.url(), Some("https://example.org/a#b")); + } + + #[test] + fn blank_lines_are_skipped() { + let text = format!("\n \n\t\n{HELLO_SHA}\thello.txt\n\n{EMPTY_SHA}\tempty.txt\n \t \n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.entries().len(), 2); + assert_eq!(manifest.entries()[0].line(), 4); + assert_eq!(manifest.entries()[1].line(), 6); + assert_eq!(Manifest::parse("").expect("parse").entries().len(), 0); + } + + #[test] + fn malformed_row_is_error() { + assert!(matches!(parse_err(HELLO_SHA), ManifestError::Columns { line: 1, found: 1 })); + assert!(matches!(parse_err(&format!("# c\n{HELLO_SHA} hello.txt\n")), ManifestError::Columns { line: 2, found: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\ta\tMIT\turl\textra\n")), ManifestError::Columns { line: 1, found: 5 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\t\n")), ManifestError::Path { line: 1, reason: PathError::Empty })); + assert!(matches!(parse_err("\thello.txt\n"), ManifestError::Digest { line: 1 })); + } + + #[test] + fn wrong_digest_length_is_error() { + assert!(matches!(parse_err(&format!("{}\ta\n", &HELLO_SHA[..63])), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}0\ta\n")), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!(" {HELLO_SHA}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn non_hex_digest_is_error() { + let bad = format!("{}g", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{bad}\ta\n")), ManifestError::Digest { line: 1 })); + let sign = format!("+{}", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{sign}\ta\n")), ManifestError::Digest { line: 1 })); + let wide = format!("{}é", &HELLO_SHA[..62]); + assert!(matches!(parse_err(&format!("{wide}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn rows_take_two_to_four_columns_and_empty_optional_columns_are_none() { + let text = format!( + "{HELLO_SHA}\ta.txt\n{HELLO_SHA}\tb.txt\tMIT\n{HELLO_SHA}\tc.txt\tMIT\thttps://example.org/c\n{HELLO_SHA}\td.txt\t\n{HELLO_SHA}\te.txt\t\thttps://example.org/e\n" + ); + let manifest = Manifest::parse(&text).expect("parse"); + let cols: Vec<_> = manifest.entries().iter().map(|e| (e.path(), e.license(), e.url())).collect(); + assert_eq!( + cols, + [ + ("a.txt", None, None), + ("b.txt", Some("MIT"), None), + ("c.txt", Some("MIT"), Some("https://example.org/c")), + ("d.txt", None, None), + ("e.txt", None, Some("https://example.org/e")), + ] + ); + } + + #[test] + fn crlf_lines_and_uppercase_digests_parse() { + let upper = HELLO_SHA.to_ascii_uppercase(); + let manifest = Manifest::parse(&format!("# c\r\n{upper}\thello.txt\tMIT\r\n\r\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.license(), Some("MIT")); + assert_eq!(entry.digest()[..4], [0xb9, 0x4d, 0x27, 0xb9]); + assert_eq!(entry.digest(), Manifest::parse(&format!("{HELLO_SHA}\thello.txt")).expect("parse").entries()[0].digest()); + } + + #[test] + fn duplicate_path_is_error() { + let text = format!("{HELLO_SHA}\ta/b.txt\n# c\n{HELLO_SHA}\ta/b.txt\n"); + assert!(matches!(parse_err(&text), ManifestError::Duplicate { line: 3, first: 1 })); + } + + #[test] + fn paths_that_leave_the_folder_are_errors() { + let cases = [ + ("/etc/passwd", PathError::Absolute), + ("../outside", PathError::DotPart), + ("a/../../outside", PathError::DotPart), + ("./a", PathError::DotPart), + ("a//b", PathError::EmptyPart), + ("a/", PathError::EmptyPart), + ("C:/Windows/win.ini", PathError::Character), + ("C:a", PathError::Character), + ("\\\\server\\share\\a", PathError::Character), + ("a\\..\\..\\b", PathError::Character), + ("a\u{1}b", PathError::Character), + ("a\u{7f}b", PathError::Character), + ("a\u{85}b", PathError::Character), + ]; + for (path, expected) in cases { + match parse_err(&format!("{HELLO_SHA}\t{path}\n")) { + ManifestError::Path { line: 1, reason } => assert_eq!(reason, expected, "{path}"), + other => panic!("{path}: {other}"), + } + } + } + + #[test] + fn manifest_limits_are_errors() { + let text = format!("{HELLO_SHA}\ta\n{HELLO_SHA}\tb\n"); + let limits = Limits { max_entries: 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooManyEntries { limit: 1 }))); + let limits = Limits { max_entries: 2, ..Limits::default() }; + assert_eq!(Manifest::parse_with_limits(&text, &limits).expect("parse").entries().len(), 2); + + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooLarge { .. }))); + let limits = Limits { max_manifest_bytes: text.len(), ..Limits::default() }; + assert!(Manifest::parse_with_limits(&text, &limits).is_ok()); + + let scratch = Scratch::new(); + let path = scratch.write("corpus.tsv", text.as_bytes()); + assert_eq!(Manifest::read(&path, &Limits::default()).expect("read").entries().len(), 2); + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::read(&path, &limits), Err(ManifestError::TooLarge { .. }))); + let bad = scratch.write("bad.tsv", b"\xff\xfe"); + assert!(matches!(Manifest::read(&bad, &Limits::default()), Err(ManifestError::NotUtf8))); + assert!(matches!(Manifest::read(&scratch.0.join("absent.tsv"), &Limits::default()), Err(ManifestError::Io(_)))); + } + + fn hello_corpus() -> (Scratch, Manifest) { + let scratch = Scratch::new(); + scratch.write("hello.txt", HELLO); + scratch.write("sub/empty.bin", b""); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\tMIT\n{EMPTY_SHA}\tsub/empty.bin\n")).expect("parse"); + (scratch, manifest) + } + + #[test] + fn a_matching_folder_verifies() { + let (scratch, manifest) = hello_corpus(); + verify(&scratch.0, &manifest).expect("the corpus matches"); + } + + #[test] + fn missing_file_fails() { + let (scratch, manifest) = hello_corpus(); + std::fs::remove_file(scratch.0.join("sub").join("empty.bin")).expect("remove"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Missing { path, .. }) => assert_eq!(path, "sub/empty.bin"), + other => panic!("{other:?}"), + } + assert!(matches!(verify(&scratch.0.join("absent"), &manifest), Err(VerifyError::Folder { .. }))); + } + + #[test] + fn modified_file_fails() { + let (scratch, manifest) = hello_corpus(); + scratch.write("hello.txt", b"hello world!"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Modified { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + } + + #[test] + fn an_empty_manifest_or_a_folder_entry_fails() { + let (scratch, _) = hello_corpus(); + assert!(matches!(verify(&scratch.0, &Manifest::default()), Err(VerifyError::EmptyManifest))); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tsub\n")).expect("parse"); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::NotAFile { .. }))); + } + + /// A named pipe is refused before it is opened; opening one for reading waits for a writer. + #[cfg(unix)] + #[test] + fn a_named_pipe_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("pipe"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tpipe\n")).expect("parse"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::NotAFile { path }) => assert_eq!(path, "pipe"), + other => panic!("{other:?}"), + } + } + + /// A manifest path that names a named pipe or a folder is refused before it is opened. + #[cfg(unix)] + #[test] + fn a_manifest_that_is_not_a_file_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("corpus.tsv"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + assert!(matches!(Manifest::read(&scratch.0, &Limits::default()), Err(ManifestError::NotAFile))); + assert!(matches!(Manifest::read(&fifo, &Limits::default()), Err(ManifestError::NotAFile))); + } + + /// Files are opened with `O_NONBLOCK`, read back from the open file's status flags in + /// `/proc/self/fdinfo`, so a path replaced by a named pipe after its type was checked opens at + /// once instead of waiting for a writer. + #[cfg(target_os = "linux")] + #[test] + fn files_are_opened_with_o_nonblock() { + use std::os::fd::AsRawFd; + let (scratch, _) = hello_corpus(); + let file = open_for_reading(&scratch.0.join("hello.txt")).expect("open"); + let info = std::fs::read_to_string(format!("/proc/self/fdinfo/{}", file.as_raw_fd())).expect("read fdinfo"); + let flags = info.lines().find_map(|line| line.strip_prefix("flags:")).map(str::trim).expect("flags line"); + let flags = i32::from_str_radix(flags, 8).expect("octal flags"); + assert_ne!(flags & libc::O_NONBLOCK, 0, "flags {flags:o}"); + } + + #[test] + fn file_size_limit_is_error() { + let (scratch, manifest) = hello_corpus(); + let limits = Limits { max_file_bytes: HELLO.len() as u64, ..Limits::default() }; + verify_with_limits(&scratch.0, &manifest, &limits).expect("a file at the limit passes"); + let limits = Limits { max_file_bytes: HELLO.len() as u64 - 1, ..Limits::default() }; + match verify_with_limits(&scratch.0, &manifest, &limits) { + Err(VerifyError::TooLarge { path, limit }) => assert_eq!((path.as_str(), limit), ("hello.txt", 10)), + other => panic!("{other:?}"), + } + } + + #[test] + fn a_file_larger_than_one_read_hashes_whole() { + let scratch = Scratch::new(); + let bytes: Vec = (0..CHUNK * 2 + 7).map(|i| (i % 251) as u8).collect(); + scratch.write("big.bin", &bytes); + let hex: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); + let manifest = Manifest::parse(&format!("{hex}\tbig.bin\n")).expect("parse"); + verify(&scratch.0, &manifest).expect("the whole file is hashed"); + scratch.write("big.bin", &bytes[..CHUNK]); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::Modified { .. }))); + } + + #[cfg(unix)] + #[test] + fn a_symbolic_link_out_of_the_folder_fails() { + let outside = Scratch::new(); + let target = outside.write("hello.txt", HELLO); + let corpus = Scratch::new(); + std::os::unix::fs::symlink(&target, corpus.0.join("hello.txt")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\n")).expect("parse"); + match verify(&corpus.0, &manifest) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + std::os::unix::fs::symlink(&outside.0, corpus.0.join("out")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tout/hello.txt\n")).expect("parse"); + assert!(matches!(verify(&corpus.0, &manifest), Err(VerifyError::Escapes { .. }))); + } + + /// A file opened outside the folder, as after the listed path was changed into a link between + /// the first check and the open, is refused even when its contents match. + #[cfg(unix)] + #[test] + fn a_file_opened_outside_the_folder_fails() { + let (scratch, manifest) = hello_corpus(); + let outside = Scratch::new(); + let other = outside.write("hello.txt", HELLO); + let root = scratch.0.canonicalize().expect("canonical folder"); + let entry = &manifest.entries[0]; + let opened = File::open(&other).expect("open the outside file"); + let meta = opened.metadata().expect("metadata"); + match opened_file_is_inside(&root, entry, &opened, &meta) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + let listed = File::open(root.join("hello.txt")).expect("open the listed file"); + let meta = listed.metadata().expect("metadata"); + opened_file_is_inside(&root, entry, &listed, &meta).expect("the listed file passes"); + } + + /// `verify` refuses a listed file that is changed into a link out of the folder after it was + /// resolved and before it is opened, even when the outside file's contents match. + #[cfg(unix)] + #[test] + fn a_file_changed_into_an_outside_link_before_the_open_fails() { + let (scratch, manifest) = hello_corpus(); + let outside = Scratch::new(); + let other = outside.write("hello.txt", HELLO); + let root = scratch.0.canonicalize().expect("canonical folder"); + let mut buf = vec![0u8; CHUNK]; + let swap = |path: &Path| { + std::fs::remove_file(path)?; + std::os::unix::fs::symlink(&other, path)?; + open_for_reading(path) + }; + match verify_entry_with(&root, &manifest.entries[0], &Limits::default(), &mut buf, swap) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + } + + #[test] + fn the_gate_leaves_only_an_unset_folder_to_skip() { + let (scratch, _) = hello_corpus(); + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + assert_eq!(gate(None, VAR, &manifest), Ok(None)); + let dir = scratch.0.clone().into_os_string(); + assert_eq!(gate(Some(dir.clone()), VAR, &manifest), Ok(Some(scratch.0.clone()))); + let empty = gate(Some(OsString::new()), VAR, &manifest).expect_err("empty"); + assert!(empty.contains("empty"), "{empty}"); + let bad = gate(Some(dir.clone()), VAR, "# c\nnot a row\n").expect_err("bad manifest"); + assert!(bad.contains("line 2"), "{bad}"); + let missing = gate(Some(dir), VAR, &format!("{EMPTY_SHA}\tabsent.bin\n")).expect_err("missing"); + assert!(missing.contains("absent.bin"), "{missing}"); + } + + /// Runs `child` below in a new process of this test binary with the given variables set and + /// every other corpus variable removed, so no test changes this process's environment. + fn run_child(case: &str, vars: &[(&str, &str)]) -> Output { + let exe = std::env::current_exe().expect("the test binary's path"); + let mut cmd = Command::new(exe); + cmd.args(["corpus::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); + for name in [VAR, REQUIRED, DEFAULT_VAR, "CRAFT_CORPUS_REQUIRED"] { + cmd.env_remove(name); + } + for (name, value) in vars { + cmd.env(name, value); + } + cmd.output().expect("run the test binary") + } + + #[test] + fn child() { + let Some(case) = std::env::var_os(CHILD_CASE) else { + return; + }; + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + let found = match case.to_str() { + Some("named") => pinned(Some(VAR), &manifest), + Some("default") => pinned(None, &manifest), + other => panic!("unknown child case {other:?}"), + }; + eprintln!("pinned returned {}", found.map_or_else(|| "none".to_owned(), |d| d.display().to_string())); + } + + #[test] + fn an_unset_folder_follows_the_skip_rule() { + for value in [None, Some("")] { + let vars: Vec<(&str, &str)> = value.map(|v| (REQUIRED, v)).into_iter().collect(); + let out = run_child("named", &vars); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{value:?}: {err}"); + assert_eq!(err.matches(&format!("SKIPPED: corpus not given: set {VAR} to its folder\n")).count(), 1, "{value:?}: {err}"); + assert!(err.contains("pinned returned none"), "{value:?}: {err}"); + } + let out = run_child("named", &[(REQUIRED, "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("corpus not given: set {VAR} to its folder, and {REQUIRED}=1 forbids skipping")), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("pinned returned"), "{err}"); + for value in ["0", "true", " 1", "1\n"] { + let out = run_child("named", &[(REQUIRED, value)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{value:?}: {err}"); + assert!(err.contains(&format!("{REQUIRED}={value:?} is not empty or 1")), "{value:?}: {err}"); + assert!(!err.contains("SKIPPED:"), "{value:?}: {err}"); + assert!(!err.contains("pinned returned"), "{value:?}: {err}"); + } + } + + #[test] + fn pinned_reads_the_named_folder_and_fails_on_a_bad_one() { + let (scratch, _) = hello_corpus(); + let dir = scratch.0.to_str().expect("a UTF-8 temporary path"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains(&format!("pinned returned {dir}")), "{err}"); + + scratch.write("hello.txt", b"changed"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("hello.txt: SHA-256 differs from the manifest"), "{err}"); + + let out = run_child("named", &[(VAR, "")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("{VAR} is set but empty")), "{err}"); + } + + #[test] + fn a_bad_folder_variable_name_fails_before_the_environment_is_read() { + for name in ["", "A=B", "A\0B"] { + assert!(check_var(name).is_err(), "{name:?}"); + let result = std::panic::catch_unwind(|| pinned(Some(name), "not a manifest")); + let payload = result.expect_err(&format!("{name:?} should fail the test")); + let message = payload.downcast_ref::().map(String::as_str).unwrap_or_default(); + assert!(message.contains("cannot name the corpus folder variable"), "{name:?}: {message}"); + } + assert_eq!(check_var(VAR), Ok(())); + } + + #[test] + fn pinned_defaults_to_craft_corpus() { + let out = run_child("default", &[]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: corpus not given: set CRAFT_CORPUS to its folder\n"), "{err}"); + + let out = run_child("default", &[("CRAFT_CORPUS_REQUIRED", "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_CORPUS_REQUIRED=1 forbids skipping"), "{err}"); + } +} diff --git a/crates/testkit/src/deadline.rs b/crates/testkit/src/deadline.rs index 918719e6bc..9e00f9a606 100644 --- a/crates/testkit/src/deadline.rs +++ b/crates/testkit/src/deadline.rs @@ -1,11 +1,18 @@ //! Limits on how long a test waits. //! -//! [`with_deadline`] runs a test body on its own thread and returns its value. When the body does not -//! finish within the limit, the test fails with the call's label, the limit and the variable that sets -//! it. A panic in the body is raised again in the test with its original payload. +//! A limit here guards against a hang and does not decide a result. A value or panic that a body +//! produces is the call's result whenever it arrives, and a test fails on the limit only when nothing +//! has arrived by then. //! -//! [`wait_until`] calls a condition on the test's thread until it returns `true`, pausing between -//! calls, and fails the test with its description when the limit passes first. +//! [`with_deadline`] runs a test body on its own thread and returns its value. A panic in the body is +//! raised again in the test with its original payload. When the body has neither returned nor +//! panicked within the limit, the test fails with the call's label, the limit and the variable that +//! sets it. +//! +//! [`wait_until`] calls a condition on the test's thread, and calls it again each time another +//! thread raises the [`Signal`] the call waits on. It returns when the condition returns `true`, and +//! fails the test with its description when the limit has passed since the call began and the latest +//! call of the condition returned `false`. //! //! A limit is a default [`Duration`] and the name of a variable that replaces it. A plain `Duration` //! reads [`DEFAULT_VARIABLE`]; [`DeadlineLimit::with_variable`] names another one. The variable holds @@ -13,30 +20,23 @@ //! fractional, not Unicode, zero, or larger than a `u64` fails the test that reads it, as does a zero //! default and a limit past the latest time the platform's clock can represent. //! -//! Neither function can stop code that does not return. A body that runs past its limit fails the -//! test, and its thread is left running until the test process exits. A condition that blocks is -//! not interrupted: [`wait_until`] checks its limit only between calls, so a condition must return -//! promptly. +//! Neither function can stop code that does not return. When a body does not finish within its +//! limit, the test fails and the body's thread is left running until the test process exits. A +//! condition that blocks is not interrupted, so a condition must return promptly. use std::any::Any; use std::ffi::OsString; use std::fmt; use std::io; use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; -use std::sync::mpsc::{self, RecvTimeoutError, Sender}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::thread; use std::time::{Duration, Instant}; /// The variable a limit reads unless [`DeadlineLimit::with_variable`] names another. pub const DEFAULT_VARIABLE: &str = "CRAFT_TEST_TIMEOUT_SECS"; -/// The first pause of [`wait_until`] between two calls of its condition. -const FIRST_PAUSE: Duration = Duration::from_millis(1); - -/// The longest pause of [`wait_until`]: each pause doubles up to this. -const MAX_PAUSE: Duration = Duration::from_millis(50); - /// The name of the thread [`with_deadline`] runs a body on. const WORKER_NAME: &str = "craft-testkit deadline"; @@ -91,15 +91,50 @@ impl From for DeadlineLimit<'static> { } } -/// Runs `f` on its own thread and returns its value, failing the calling test when `f` does not -/// finish within `limit`. +/// A signal that [`wait_until`] waits on: the thread that changes the state a condition reads raises +/// it after each change, and every call waiting on it then calls its condition again. /// -/// The failure names `label`, the limit and the variable that sets it. A panic in `f` is raised -/// again here with its original payload. The limit is read and checked before `f` starts, and a -/// limit that is not valid fails the test without running `f`. The limit counts from the call, so -/// the time spent starting the thread counts against it. When `f` returns or panics after the limit -/// has passed, the test fails with the label and the limit, and with the panic's message if it has -/// one. When the limit passes, the thread running `f` is left running. +/// ``` +/// use craft_testkit::deadline::Signal; +/// +/// let signal = Signal::new(); +/// // A raise with no call waiting is kept: the next wait sees it and calls its condition again. +/// signal.raise(); +/// ``` +#[derive(Debug, Default)] +pub struct Signal { + /// How many times the signal has been raised, wrapping. + raised: Mutex, + changed: Condvar, +} + +impl Signal { + /// A signal that has not been raised. + pub fn new() -> Self { + Self::default() + } + + /// Wakes every [`wait_until`] call waiting on this signal, so that each calls its condition again. + pub fn raise(&self) { + let mut raised = self.lock(); + *raised = raised.wrapping_add(1); + self.changed.notify_all(); + } + + fn lock(&self) -> MutexGuard<'_, u64> { + self.raised.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +/// Runs `f` on its own thread and returns its value, failing the calling test when `f` has neither +/// returned nor panicked within `limit`. +/// +/// A panic in `f` is raised again here with its original payload. The limit guards against a hang: +/// a value or panic that `f` produces is the result whenever it arrives, and the test fails on the +/// limit only when `f` has produced neither by then. That failure names `label`, the limit and the +/// variable that sets it, and the thread running `f` is left running. The limit is read and checked +/// before `f` starts, and a limit that is not valid fails the test without running `f`. The limit +/// counts from the start of the thread running `f`. /// /// ``` /// use std::time::Duration; @@ -112,46 +147,51 @@ impl From for DeadlineLimit<'static> { #[allow(clippy::panic)] #[track_caller] pub fn with_deadline<'a, T: Send + 'static>(limit: impl Into>, label: &str, f: impl FnOnce() -> T + Send + 'static) -> T { - let start = Instant::now(); - match run_with_deadline(limit.into(), label, f, read_variable, spawn_worker, Arc::new(move || start.elapsed())) { + match run_with_deadline(limit.into(), label, f, read_variable, spawn_worker, |rx, limit| rx.recv_timeout(limit)) { Ok(value) => value, Err(Failure::Panic(payload)) => resume_unwind(payload), Err(Failure::Message(message)) => panic!("{message}"), } } -/// Calls `cond` on the calling thread until it returns `true`, failing the calling test when the -/// limit passes first. +/// Calls `cond` on the calling thread, and again each time `signal` is raised, until it returns +/// `true`, failing the calling test when the limit has passed since the call began and the latest +/// call of `cond` returned `false`. /// -/// `cond` is called at once, and then after pauses that grow from 1 ms to 50 ms, but not again once -/// the limit has passed. The failure names `what`, the limit and the variable that sets it. A `true` -/// that `cond` returns after the limit has passed also fails the test. A panic in `cond` reaches the -/// caller unchanged. `cond` runs on the calling thread and is not interrupted, so it must return -/// promptly. +/// `cond` is called at once. A raise that comes while `cond` runs is not lost: `cond` is called +/// again straight after. The limit guards against a hang and counts from the start of the call, so +/// a signal that keeps being raised while `cond` stays `false` still fails the test. `cond` is +/// called before the limit is checked, so a condition that holds is never failed by it. The failure +/// names `what`, the limit and the +/// variable that sets it. A panic in `cond` reaches the caller unchanged. `cond` runs on the calling +/// thread and is not interrupted, so it must return promptly. The threads that change what `cond` +/// reads raise `signal` after each change. /// /// ``` /// use std::sync::atomic::{AtomicBool, Ordering}; /// use std::time::Duration; -/// use craft_testkit::deadline::wait_until; +/// use craft_testkit::deadline::{Signal, wait_until}; /// /// let ready = AtomicBool::new(false); +/// let signal = Signal::new(); /// std::thread::scope(|s| { -/// s.spawn(|| ready.store(true, Ordering::SeqCst)); -/// wait_until(Duration::from_secs(30), "the worker to start", || ready.load(Ordering::SeqCst)); +/// s.spawn(|| { +/// ready.store(true, Ordering::SeqCst); +/// signal.raise(); +/// }); +/// wait_until(Duration::from_secs(30), "the worker to start", &signal, || ready.load(Ordering::SeqCst)); /// }); /// ``` // Failing the calling test is what this function is for. #[allow(clippy::panic)] #[track_caller] -pub fn wait_until<'a>(limit: impl Into>, what: &str, mut cond: impl FnMut() -> bool) { +pub fn wait_until<'a>(limit: impl Into>, what: &str, signal: &Signal, mut cond: impl FnMut() -> bool) { let limit = limit.into(); - let start = Instant::now(); - let resolved = match resolve(&limit, read_variable, start) { + let resolved = match resolve(&limit, read_variable, Instant::now()) { Ok(resolved) => resolved, Err(error) => panic!("waiting for {what}: {error}"), }; - let mut elapsed = || start.elapsed(); - if let Err(message) = poll_until(&resolved, what, &mut cond, &mut elapsed, &mut thread::sleep) { + if let Err(message) = wait_for_signal(&resolved, what, signal, &mut cond, Instant::now, wait_for_raise) { panic!("{message}"); } } @@ -265,8 +305,8 @@ fn spawn_worker(job: Job, done: Sender<()>) -> io::Result<()> { .map(drop) } -/// The body's result and the clock reading when it finished, filled in by the worker. -type Slot = Arc, Duration)>>>; +/// The body's result, filled in by the worker. +type Slot = Arc>>>; /// How a [`with_deadline`] call failed. enum Failure { @@ -276,52 +316,32 @@ enum Failure { Message(String), } -/// A clock that returns the time since a [`with_deadline`] call started. -type Clock = Arc Duration + Send + Sync>; - -/// The text of a panic payload that holds a message. -fn panic_text(payload: &(dyn Any + Send)) -> Option<&str> { - payload.downcast_ref::().map(String::as_str).or_else(|| payload.downcast_ref::<&str>().copied()) -} - -/// [`with_deadline`] with the variable lookup, the thread start and the clock passed in. Starting -/// the worker counts against the limit. The worker stores the body's result with the clock reading -/// when it finished, under a lock, and then sends on the channel `spawn` receives. When the wait -/// times out, the stored result is still used if it is there, so a body that finished in time passes -/// even when its thread sends late. +/// [`with_deadline`] with the variable lookup, the thread start and the wait for the worker passed +/// in. The worker stores the body's result under a lock and then sends on the channel `spawn` +/// receives. `wait` waits on that channel for at most the limit. Whatever `wait` returns, a stored +/// result is the call's result, so the limit fails the call only when the body has produced nothing. fn run_with_deadline( limit: DeadlineLimit<'_>, label: &str, f: impl FnOnce() -> T + Send + 'static, lookup: impl FnOnce(&str) -> Option, spawn: impl FnOnce(Job, Sender<()>) -> io::Result<()>, - clock: Clock, + wait: impl FnOnce(&Receiver<()>, Duration) -> Result<(), RecvTimeoutError>, ) -> Result { let resolved = resolve(&limit, lookup, Instant::now()).map_err(|error| Failure::Message(format!("{label}: {error}")))?; let (tx, rx) = mpsc::channel(); let slot: Slot = Arc::new(Mutex::new(None)); let worker_slot = Arc::clone(&slot); - let worker_clock = Arc::clone(&clock); let job: Job = Box::new(move || { let result = catch_unwind(AssertUnwindSafe(f)); - // The clock is read under the lock: once the caller finds the slot empty after its limit, - // any later reading is past the limit too. - let mut stored = worker_slot.lock().unwrap_or_else(PoisonError::into_inner); - *stored = Some((result, worker_clock())); + *worker_slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(result); }); spawn(job, tx).map_err(|error| Failure::Message(format!("{label}: could not start the worker thread: {error}")))?; - let waited = rx.recv_timeout(resolved.limit.saturating_sub(clock())); + let waited = wait(&rx, resolved.limit); let stored = slot.lock().unwrap_or_else(PoisonError::into_inner).take(); match (stored, waited) { - (Some((result, finished)), _) if finished > resolved.limit => { - let panicked = match &result { - Ok(_) => String::new(), - Err(payload) => format!(" (it panicked: {})", panic_text(payload.as_ref()).unwrap_or("a payload that is not a message")), - }; - Err(Failure::Message(format!("{label} finished only after its limit of {resolved}{panicked}"))) - } - (Some((Ok(value), _)), _) => Ok(value), - (Some((Err(payload), _)), _) => Err(Failure::Panic(payload)), + (Some(Ok(value)), _) => Ok(value), + (Some(Err(payload)), _) => Err(Failure::Panic(payload)), (None, Err(RecvTimeoutError::Timeout)) => { Err(Failure::Message(format!("{label} did not finish within {resolved}; its thread is left running"))) } @@ -329,44 +349,49 @@ fn run_with_deadline( } } -/// The loop of [`wait_until`], with the clock and the pause passed in. `elapsed` returns the time -/// since the wait started. -fn poll_until( +/// Waits on `changed` while `raised` still reads `seen`, for at most `limit`. Returns the guard and +/// whether the limit passed with no raise. +fn wait_for_raise<'g>(changed: &Condvar, raised: MutexGuard<'g, u64>, seen: u64, limit: Duration) -> (MutexGuard<'g, u64>, bool) { + let (raised, result) = changed.wait_timeout_while(raised, limit, |count| *count == seen).unwrap_or_else(PoisonError::into_inner); + (raised, result.timed_out()) +} + +/// The loop of [`wait_until`], with the clock and the wait for a raise passed in. The raise count is +/// read before each call of `cond`, so a raise during the call ends the next wait at once. The limit +/// counts from the start of the loop, and each wait lasts at most the time left. +fn wait_for_signal( resolved: &Resolved<'_>, what: &str, + signal: &Signal, cond: &mut dyn FnMut() -> bool, - elapsed: &mut dyn FnMut() -> Duration, - pause: &mut dyn FnMut(Duration), + now: impl Fn() -> Instant, + wait: impl for<'g> Fn(&Condvar, MutexGuard<'g, u64>, u64, Duration) -> (MutexGuard<'g, u64>, bool), ) -> Result<(), String> { - let mut next_pause = FIRST_PAUSE; - let mut first = true; + let start = now(); + let mut seen = *signal.lock(); loop { - // After the first call, the condition is called only while the limit has not passed. - if !first && elapsed() >= resolved.limit { - return Err(format!("timed out waiting for {what} within {resolved}")); - } - first = false; - let held = cond(); - let spent = elapsed(); - if held && spent <= resolved.limit { + if cond() { return Ok(()); } - if held { - return Err(format!("timed out waiting for {what} within {resolved} (it held only after the limit had passed)")); + let remaining = resolved.limit.saturating_sub(now().saturating_duration_since(start)); + if remaining.is_zero() { + return Err(format!("timed out waiting for {what} within {resolved}: the condition still returned false at the limit")); } - if spent < resolved.limit { - pause(next_pause.min(resolved.limit - spent)); + let (raised, timed_out) = wait(&signal.changed, signal.lock(), seen, remaining); + if timed_out { + return Err(format!("timed out waiting for {what} within {resolved}: the signal was not raised after the last check")); } - next_pause = next_pause.saturating_mul(2).min(MAX_PAUSE); + seen = *raised; } } #[cfg(test)] mod tests { use super::*; + use std::cell::RefCell; use std::ffi::OsStr; use std::process::Command; - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::sync::atomic::{AtomicBool, Ordering}; /// A variable no test sets, so the environment cannot lengthen a test's short limit. const UNSET: &str = "CRAFT_TESTKIT_DEADLINE_UNSET_IN_TESTS"; @@ -400,6 +425,27 @@ mod tests { } } + /// A wait for the worker that returns at once, as when the limit passes with nothing received. + fn limit_passes(_: &Receiver<()>, _: Duration) -> Result<(), RecvTimeoutError> { + Err(RecvTimeoutError::Timeout) + } + + /// Runs `run_with_deadline` with its limit passing before the body has a result, and returns the + /// failure's message. The body runs on its own thread and blocks until the call has returned. + fn hung(limit: DeadlineLimit<'_>, label: &str, value: T) -> String { + let (gate, gate_rx) = mpsc::channel::<()>(); + let (done_tx, done) = mpsc::channel(); + let body = move || { + let _ = gate_rx.recv(); + done_tx.send(()).unwrap(); + value + }; + let result = run_with_deadline(limit, label, body, |_| None, spawn_worker, limit_passes); + drop(gate); + done.recv().unwrap(); + failure_message(result) + } + /// Runs `child_reads_its_variable` in a child process with `CHILD_VARIABLE` set to `value`, and /// returns what the child printed. The child must fail. fn run_child(value: &OsStr) -> String { @@ -442,21 +488,9 @@ mod tests { } #[test] - #[should_panic(expected = "seed 7 byte 3 did not finish within 50ms")] fn a_hang_fails_and_names_the_input() { - let (gate, gate_rx) = mpsc::channel::<()>(); - let (done_tx, done) = mpsc::channel(); - let result = catch_unwind(AssertUnwindSafe(|| { - with_deadline(short(), "seed 7 byte 3", move || { - let _ = gate_rx.recv(); - done_tx.send(()).unwrap(); - }) - })); - drop(gate); - done.recv().unwrap(); - if let Err(payload) = result { - resume_unwind(payload); - } + let text = hung(short(), "seed 7 byte 3", ()); + assert!(text.contains("seed 7 byte 3 did not finish within 50ms"), "{text}"); } #[test] @@ -467,14 +501,9 @@ mod tests { } #[test] - #[should_panic(expected = "did not finish within")] fn with_deadline_times_out() { - let (gate, gate_rx) = mpsc::channel::<()>(); - let result = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), "blocked body", move || gate_rx.recv().unwrap_or_default()))); - drop(gate); - if let Err(payload) = result { - resume_unwind(payload); - } + let text = hung(short(), "blocked body", 7u8); + assert!(text.contains("did not finish within") && text.contains("its thread is left running"), "{text}"); } #[test] @@ -492,14 +521,7 @@ mod tests { #[test] fn timeout_names_this_call_only() { - let call = |label: &'static str| { - thread::spawn(move || { - let (gate, gate_rx) = mpsc::channel::<()>(); - let result = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), label, move || gate_rx.recv().unwrap_or_default()))); - drop(gate); - message(result.unwrap_err()) - }) - }; + let call = |label: &'static str| thread::spawn(move || hung(short(), label, ())); let first = call("first call"); let second = call("second call"); let first = first.join().unwrap(); @@ -517,13 +539,10 @@ mod tests { 7 }) }); - let (gate, gate_rx) = mpsc::channel::<()>(); - let short_call = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), "short call", move || gate_rx.recv().unwrap_or_default()))); - let text = message(short_call.unwrap_err()); + let text = hung(short(), "short call", ()); assert!(text.contains("short call") && text.contains("50ms") && !text.contains("long call"), "{text}"); release.send(()).unwrap(); assert_eq!(long_call.join().unwrap(), 7); - drop(gate); } #[test] @@ -533,7 +552,7 @@ mod tests { ran.store(true, Ordering::SeqCst); Err(io::Error::other("no threads left")) }; - let result = run_with_deadline(long(), "no thread", || (), |_| None, spawn, Arc::new(|| Duration::ZERO)); + let result = run_with_deadline(long(), "no thread", || (), |_| None, spawn, limit_passes); let text = failure_message(result); assert!(ran.load(Ordering::SeqCst)); assert!(text.contains("no thread: could not start the worker thread: no threads left"), "{text}"); @@ -579,10 +598,10 @@ mod tests { ran.store(true, Ordering::SeqCst); Ok(()) }; - let text = failure_message(run_with_deadline(huge, "huge", || (), |_| None, spawn, Arc::new(|| Duration::ZERO))); + let text = failure_message(run_with_deadline(huge, "huge", || (), |_| None, spawn, limit_passes)); assert!(text.contains("ends past the latest time"), "{text}"); assert!(!ran.load(Ordering::SeqCst), "the body started"); - let text = message(catch_unwind(|| wait_until(huge, "a huge limit", || true)).unwrap_err()); + let text = message(catch_unwind(|| wait_until(huge, "a huge limit", &Signal::new(), || true)).unwrap_err()); assert!(text.contains("waiting for a huge limit: the limit of") && text.contains("ends past the latest time"), "{text}"); } @@ -619,22 +638,20 @@ mod tests { #[test] fn wait_until_returns_on_condition() { let ready = &AtomicBool::new(false); + let signal = &Signal::new(); let (asked, asked_rx) = mpsc::channel(); - let (stored, stored_rx) = mpsc::channel(); thread::scope(|s| { s.spawn(move || { asked_rx.recv().unwrap(); ready.store(true, Ordering::SeqCst); - stored.send(()).unwrap(); + signal.raise(); }); let mut calls = 0; - wait_until(long(), "the flag", || { + wait_until(long(), "the flag", signal, || { calls += 1; if calls == 1 { - // The flag is set before this call returns, and it still answers false, so the - // condition is called a second time whatever order the threads run in. + // The other thread sets the flag only after this call has started. asked.send(()).unwrap(); - stored_rx.recv().unwrap(); return false; } ready.load(Ordering::SeqCst) @@ -644,145 +661,137 @@ mod tests { } #[test] - #[should_panic(expected = "timed out waiting for the export to finish within 50ms")] - fn wait_until_times_out_with_label() { - wait_until(short(), "the export to finish", || false); + fn a_raise_during_the_condition_ends_the_next_wait_at_once() { + let signal = Signal::new(); + let mut calls = 0; + let mut cond = || { + calls += 1; + if calls == 1 { + signal.raise(); + } + calls == 2 + }; + let result = wait_for_signal(&fake_resolved(Duration::from_secs(600)), "a raise", &signal, &mut cond, Instant::now, |_, raised, seen, _| { + assert_ne!(*raised, seen, "the raise made during the condition was lost"); + (raised, false) + }); + assert_eq!(result, Ok(())); + assert_eq!(calls, 2); } + #[test] + fn wait_until_times_out_with_label() { + let mut calls = 0; + let mut cond = || { + calls += 1; + false + }; + let resolved = fake_resolved(Duration::from_millis(50)); + let text = wait_for_signal(&resolved, "the export to finish", &Signal::new(), &mut cond, Instant::now, |_, raised, _, _| (raised, true)) + .unwrap_err(); + assert!(text.starts_with("timed out waiting for the export to finish within 50ms"), "{text}"); + assert!(text.ends_with("the signal was not raised after the last check"), "{text}"); + assert_eq!(calls, 1); + } + + #[test] + fn raises_that_never_satisfy_the_condition_fail_at_the_limit() { + // A clock that moves 20 s on each reading, and a wait that always reports a raise. + let start = Instant::now(); + let readings = std::cell::Cell::new(0u32); + let now = || { + let n = readings.get(); + readings.set(n + 1); + start + Duration::from_secs(20) * n + }; + let mut calls = 0; + let mut cond = || { + calls += 1; + false + }; + let resolved = fake_resolved(Duration::from_secs(60)); + let text = wait_for_signal(&resolved, "a progress tick", &Signal::new(), &mut cond, now, |_, mut raised, _, _| { + *raised = raised.wrapping_add(1); + (raised, false) + }) + .unwrap_err(); + assert!(text.starts_with("timed out waiting for a progress tick within 60s"), "{text}"); + assert!(text.ends_with("the condition still returned false at the limit"), "{text}"); + assert_eq!(calls, 3); + } + + #[test] + fn a_thread_raising_in_a_loop_cannot_hold_wait_until_past_the_limit() { + let stop = Arc::new(AtomicBool::new(false)); + let signal = Arc::new(Signal::new()); + let raiser = { + let (stop, signal) = (Arc::clone(&stop), Arc::clone(&signal)); + thread::spawn(move || { + while !stop.load(Ordering::SeqCst) { + signal.raise(); + thread::yield_now(); + } + }) + }; + let waiter_signal = Arc::clone(&signal); + let guard = DeadlineLimit::new(Duration::from_secs(30)).with_variable(UNSET); + let outcome = with_deadline(guard, "wait_until under constant raises", move || { + catch_unwind(AssertUnwindSafe(|| wait_until(short(), "a condition that never holds", &waiter_signal, || false))).map_err(message) + }); + stop.store(true, Ordering::SeqCst); + raiser.join().unwrap(); + let text = outcome.unwrap_err(); + assert!(text.contains("timed out waiting for a condition that never holds within 50ms"), "{text}"); + } #[test] #[should_panic(expected = "condition boom")] fn wait_until_propagates_condition_panic() { - wait_until(long(), "a panicking condition", || panic!("condition boom")); + wait_until(long(), "a panicking condition", &Signal::new(), || panic!("condition boom")); } #[test] fn wait_until_keeps_a_typed_condition_payload() { #[derive(Debug, PartialEq)] struct Marker(u32); - let payload = catch_unwind(|| wait_until(long(), "a typed panic", || std::panic::panic_any(Marker(9)))).unwrap_err(); + let payload = catch_unwind(|| wait_until(long(), "a typed panic", &Signal::new(), || std::panic::panic_any(Marker(9)))).unwrap_err(); assert_eq!(payload.downcast_ref::(), Some(&Marker(9))); } - /// A default limit for the loop tests, which pass their own clock. + /// A limit for the loop tests, which pass their own wait. fn fake_resolved(limit: Duration) -> Resolved<'static> { Resolved { limit, variable: UNSET, from_variable: false } } - #[test] - fn wait_until_rejects_a_true_after_the_limit() { - let resolved = fake_resolved(Duration::from_millis(10)); - let mut now = Duration::ZERO; - let mut cond = || true; - // The condition took 11 ms to return. - let mut elapsed = || { - now += Duration::from_millis(11); - now - }; - let result = poll_until(&resolved, "a late flag", &mut cond, &mut elapsed, &mut |_| panic!("paused")); - let text = result.unwrap_err(); - assert!(text.contains("timed out waiting for a late flag") && text.contains("held only after the limit"), "{text}"); - } - - #[test] - fn wait_until_pauses_grow_and_stop_at_the_limit() { - let resolved = fake_resolved(Duration::from_millis(100)); - let now = std::cell::Cell::new(Duration::ZERO); - let mut pauses = Vec::new(); - let mut calls = 0; - let mut cond = || { - calls += 1; - false - }; - let mut elapsed = || now.get(); - let mut pause = |d: Duration| { - pauses.push(d); - now.set(now.get() + d); - }; - let result = poll_until(&resolved, "never", &mut cond, &mut elapsed, &mut pause); - assert!(result.is_err()); - let ms: Vec = pauses.iter().map(Duration::as_millis).collect(); - // 1 + 2 + 4 + 8 + 16 + 32 = 63, then the 37 ms left, after which the limit is reached. - assert_eq!(ms, [1, 2, 4, 8, 16, 32, 37]); - // One call before each pause, and none after the last one. - assert_eq!(calls, 7); - } - - #[test] - fn wait_until_stops_calling_after_an_overshooting_pause() { - let resolved = fake_resolved(Duration::from_millis(100)); - let now = std::cell::Cell::new(Duration::from_millis(99)); - let mut calls = 0; - let mut cond = || { - calls += 1; - false - }; - let mut elapsed = || now.get(); - // The thread wakes 50 ms late from the 1 ms pause. - let mut pause = |d: Duration| now.set(now.get() + d + Duration::from_millis(50)); - let result = poll_until(&resolved, "late wake", &mut cond, &mut elapsed, &mut pause); - assert!(result.unwrap_err().contains("timed out waiting for late wake")); - assert_eq!(calls, 1); - } - - /// Runs `run_with_deadline` with a 5 s limit on a fake clock. The worker runs on the calling - /// thread: the clock reads `start_secs` while the body runs and `received_secs` when the result - /// is received. When `sends` is false, the worker stores its result but does not send, as if its - /// thread stopped running between the two. - fn on_fake_clock( - f: impl FnOnce() -> T + Send + 'static, - start_secs: u64, - received_secs: u64, - sends: bool, - ) -> Result { - let now = Arc::new(AtomicU64::new(0)); - let clock_now = Arc::clone(&now); - let clock: Clock = Arc::new(move || Duration::from_secs(clock_now.load(Ordering::SeqCst))); - let unsent = std::cell::RefCell::new(None); + /// Runs `run_with_deadline` on `f` with the body's result arriving only after the limit has + /// passed: the body does not start until the wait for it, which runs it on the calling thread + /// and then reports that the limit passed. The worker never sends. + fn finishing_after_the_limit(f: impl FnOnce() -> T + Send + 'static) -> Result { + let held = RefCell::new(None); let spawn = |job: Job, done: Sender<()>| { - now.store(start_secs, Ordering::SeqCst); - job(); - now.store(received_secs, Ordering::SeqCst); - if sends { - let _ = done.send(()); - } else { - // Kept alive so that the wait times out instead of seeing a closed channel. - *unsent.borrow_mut() = Some(done); - } + *held.borrow_mut() = Some((job, done)); Ok(()) }; - let limit = DeadlineLimit::new(Duration::from_secs(5)).with_variable(UNSET); - run_with_deadline(limit, "fake clock", f, |_| None, spawn, clock) + let wait = |_: &Receiver<()>, _: Duration| { + if let Some((job, _done)) = held.borrow_mut().take() { + job(); + } + Err(RecvTimeoutError::Timeout) + }; + run_with_deadline(short(), "late body", f, |_| None, spawn, wait) } #[test] - fn a_value_returned_after_the_limit_fails() { - let text = failure_message(on_fake_clock(|| 1, 6, 6, true)); - assert!(text.contains("fake clock finished only after its limit of 5s"), "{text}"); + fn a_value_that_arrives_after_the_limit_is_returned() { + assert!(matches!(finishing_after_the_limit(|| 1), Ok(1))); } #[test] - fn a_value_finished_in_time_but_received_late_passes() { - assert!(matches!(on_fake_clock(|| 1, 1, 6, true), Ok(1))); - } - - #[test] - fn a_value_finished_in_time_but_sent_late_passes() { - assert!(matches!(on_fake_clock(|| 1, 1, 6, false), Ok(1))); - } - - #[test] - fn a_panic_finished_in_time_but_sent_late_keeps_its_payload() { - let payload = match on_fake_clock(|| -> u8 { panic!("early boom") }, 1, 6, false) { + fn a_panic_that_arrives_after_the_limit_keeps_its_payload() { + let payload = match finishing_after_the_limit(|| -> u8 { panic!("late boom") }) { Err(Failure::Panic(payload)) => payload, Ok(_) => panic!("the call did not fail"), Err(Failure::Message(text)) => panic!("the payload was replaced: {text}"), }; - assert_eq!(message(payload), "early boom"); - } - - #[test] - fn a_panic_after_the_limit_names_the_limit_and_the_panic() { - let text = failure_message(on_fake_clock(|| -> u8 { panic!("late boom") }, 6, 6, true)); - assert!(text.contains("fake clock finished only after its limit of 5s") && text.ends_with("(it panicked: late boom)"), "{text}"); + assert_eq!(message(payload), "late boom"); } } diff --git a/crates/testkit/src/fixtures.rs b/crates/testkit/src/fixtures.rs new file mode 100644 index 0000000000..9b01b154c6 --- /dev/null +++ b/crates/testkit/src/fixtures.rs @@ -0,0 +1,1319 @@ +//! Fixture locations and race-free generation of fixture files. +//! +//! Generated fixtures live in `/target/fixtures//` whatever `CARGO_TARGET_DIR` is, so test runs +//! with private target folders share one generated set. A variable the caller names (default +//! [`ROOT_VAR`]) overrides the root. A fixture is complete when it is a nonempty regular file; a +//! consumer that needs stronger validation checks the format after generation. +//! +//! [`generate`] and [`generate_with`] return a complete cached fixture without calling the generator. +//! Otherwise the generator writes a temporary sibling claimed by [`temp_path`], and [`publish`] moves it +//! into place under a per-output lock, keeping a complete file that another process published first. +//! A fixture that cannot be made skips or fails the test under the [`skip`](crate::skip) rule, with +//! the required variable the caller names (default [`skip::REQUIRED_VAR`](crate::skip::REQUIRED_VAR)). +//! +//! [`report`] and [`generate_and_report`] print `FIXTURE made `, `FIXTURE cached ` and +//! `FIXTURE skipped ` lines, which FilmCraft's `cargo xtask fixtures` counts. + +use std::ffi::{OsStr, OsString}; +use std::fs::{File, OpenOptions}; +use std::io::{self, Read}; +use std::path::{Component, Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Default variable that overrides the fixtures root. +pub const ROOT_VAR: &str = "CRAFT_FIXTURES_DIR"; + +/// Default number of bytes [`run_generator`] keeps from each of the child's output streams. +pub const DEFAULT_MAX_OUTPUT: usize = 64 * 1024; + +/// Largest `Cargo.toml` that [`workspace_root`] reads while looking for the workspace manifest. +const MAX_MANIFEST_BYTES: u64 = 1024 * 1024; + +/// Number of names [`temp_path`] tries before it gives up. +const TEMP_ATTEMPTS: u32 = 64; + +/// Suffix of the lock file kept beside each published fixture. +const LOCK_SUFFIX: &str = ".fixture-lock"; + +/// The root of the Cargo workspace that is running the tests. +/// +/// The search starts at the `CARGO_MANIFEST_DIR` that Cargo and nextest set for a test process, which +/// names the package under test. When the package's `Cargo.toml` sets `package.workspace`, it returns +/// that folder, resolved against the package folder. Otherwise it returns the nearest folder at or above +/// the package whose `Cargo.toml` has a `[workspace]` table, or the package folder itself when no +/// workspace manifest is found. The process working directory and `CARGO_TARGET_DIR` are not read. The +/// returned path is canonical. +/// +/// # Errors +/// +/// Returns [`io::ErrorKind::NotFound`] when `CARGO_MANIFEST_DIR` is unset or empty (a test binary run +/// outside Cargo) or no `Cargo.toml` is found, [`io::ErrorKind::InvalidData`] when a manifest is +/// larger than 1 MiB or is not valid TOML, and an error when a manifest is not UTF-8 or the folder +/// cannot be canonicalized. +pub fn workspace_root() -> io::Result { + let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR").filter(|v| !v.is_empty()).ok_or_else(|| { + io::Error::new(io::ErrorKind::NotFound, "CARGO_MANIFEST_DIR is not set; run the tests through Cargo or set the fixtures root variable") + })?; + workspace_root_from(Path::new(&manifest_dir)) +} + +fn workspace_root_from(manifest_dir: &Path) -> io::Result { + let mut package = None; + for dir in manifest_dir.ancestors() { + let path = dir.join("Cargo.toml"); + let Some(text) = read_manifest(&path)? else { continue }; + let keys = scan_manifest(&text) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{} is not a valid TOML manifest: {e}", path.display())))?; + if keys.workspace { + return dir.canonicalize(); + } + if package.is_none() + && let Some(workspace) = keys.package_workspace + { + return dir.join(workspace).canonicalize(); + } + package.get_or_insert(dir); + } + match package { + Some(dir) => dir.canonicalize(), + None => Err(io::Error::new(io::ErrorKind::NotFound, format!("no Cargo.toml in {} or above it", manifest_dir.display()))), + } +} + +/// The keys of a manifest that [`workspace_root`] reads. +#[derive(Debug, Default, PartialEq, Eq)] +struct ManifestKeys { + /// The manifest has a `workspace` table, in any TOML form (`[workspace]`, `["workspace"]` or a + /// top-level `workspace = { ... }`). + workspace: bool, + /// The string value of `package.workspace`. + package_workspace: Option, +} + +/// Parse a manifest as TOML and read its workspace keys. +fn scan_manifest(manifest: &str) -> Result { + let table: toml::Table = manifest.parse()?; + let package_workspace = table.get("package").and_then(|p| p.get("workspace")).and_then(toml::Value::as_str).map(str::to_owned); + Ok(ManifestKeys { workspace: table.get("workspace").is_some_and(toml::Value::is_table), package_workspace }) +} + +fn read_manifest(path: &Path) -> io::Result> { + let meta = match std::fs::metadata(path) { + Ok(meta) if meta.is_file() => meta, + Ok(_) => return Ok(None), + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e), + }; + if meta.len() > MAX_MANIFEST_BYTES { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{} is larger than {MAX_MANIFEST_BYTES} bytes", path.display()))); + } + let mut text = String::new(); + File::open(path)?.take(MAX_MANIFEST_BYTES).read_to_string(&mut text)?; + Ok(Some(text)) +} + +/// The root of all generated fixtures: the nonempty value of `var` (default [`ROOT_VAR`]), or +/// `/target/fixtures`. The folder is not created. +/// +/// # Errors +/// +/// Returns the error of [`workspace_root`] when the variable is unset or empty. +pub fn fixtures_root(var: Option<&str>) -> io::Result { + match std::env::var_os(var.unwrap_or(ROOT_VAR)).filter(|v| !v.is_empty()) { + Some(dir) => Ok(PathBuf::from(dir)), + None => Ok(workspace_root()?.join("target").join("fixtures")), + } +} + +/// `/`, created if missing. `sub` may name nested folders (`"opus/oracle"`). +/// +/// # Errors +/// +/// Returns [`io::ErrorKind::InvalidInput`] when `sub` is absolute, contains `..`, or has a part that +/// is not a plain folder name on its own (on Windows, `group\C:outside`), or when a folder on the way +/// resolves outside the root (a symbolic link or junction that points elsewhere), and the error of +/// [`fixtures_root`] or of creating the folder otherwise. +pub fn fixtures_dir(sub: &str, var: Option<&str>) -> io::Result { + let relative = relative_subdir(sub)?; + create_below(&fixtures_root(var)?, &relative) +} + +/// Create `root/relative` one folder at a time, and return an error before creating the next folder +/// when the one before it resolves outside `root`. Returns `root.join(relative)` as given, not the +/// canonical path. Each folder is checked by path when it is reached, so a folder that another process +/// replaces with a link between that check and the next `create_dir` is not detected; callers then use +/// the returned path by name too ([`temp_path`], [`publish`]). +fn create_below(root: &Path, relative: &Path) -> io::Result { + std::fs::create_dir_all(root)?; + let real_root = root.canonicalize()?; + let mut real = real_root.clone(); + for part in relative.components() { + let next = real.join(part); + match std::fs::create_dir(&next) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + } + real = next.canonicalize()?; + if !real.starts_with(&real_root) || !real.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("fixture folder {} resolves to {}, which is not a folder inside the fixtures root", next.display(), real.display()), + )); + } + } + Ok(root.join(relative)) +} + +fn relative_subdir(sub: &str) -> io::Result { + let outside = || io::Error::new(io::ErrorKind::InvalidInput, format!("fixture folder {sub:?} is not a relative path inside the fixtures root")); + let mut relative = PathBuf::new(); + for component in Path::new(sub).components() { + match component { + Component::Normal(part) => { + // `PathBuf::push` parses the part again, so a part such as `C:outside` would replace the path. + let mut alone = Path::new(part).components(); + if !matches!((alone.next(), alone.next()), (Some(Component::Normal(p)), None) if p == part) { + return Err(outside()); + } + relative.push(part); + } + Component::CurDir => {} + Component::ParentDir | Component::RootDir | Component::Prefix(_) => return Err(outside()), + } + } + Ok(relative) +} + +/// Create a new, empty temporary sibling of `out` and return its path. +/// +/// The name is `.tmp---