diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index dac20b9d2..6a88886d4 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -41,6 +41,9 @@ jobs: packages: mesa-vulkan-drivers libvulkan1 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan + # Test binaries without debug info or symbols: about a third of the size, and a panic still + # names its file and line. + dev-strip: true # No debuginfo on Windows: writing PDBs for every test binary is a large part of its link # time. A panic still names its file and line; only backtrace frames lose theirs, and the # Linux and macOS legs keep line tables. @@ -86,22 +89,28 @@ jobs: cargo test -p craft-image-codecs -p craft-text --no-run --locked command: | # The tests run once, with every feature, in parallel across test binaries; nextest skips - # doctests, so `cargo test --doc` runs them. The default-feature compile is the lint leg's + # doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose + # tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's # first clippy run; the last command runs the crates whose tests check behaviour with a # feature off, which an all-features build cannot reach. - cargo nextest run --workspace --all-features --locked --profile ci + cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests + cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci + cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests windows-command: | powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' - cargo nextest run --workspace --all-features --locked --profile ci + cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests + cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci + cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests msrv: name: Rust 1.95 uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: + # Its own dependency-cache entry: the calls in this file share one job id, so without a name + # they would write the same key. + cache-name: msrv os: '["ubuntu-latest"]' toolchain: 1.95.0 targets: "" @@ -116,6 +125,7 @@ jobs: name: UI and settings WASM uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: + cache-name: wasm os: '["ubuntu-latest"]' targets: wasm32-unknown-unknown tools: "" diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f5a4217d8..085306ffe 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -11,6 +11,7 @@ author, source and license. Library code and original assets are under the repos | `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files | | `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 | | `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 | +| `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 | | `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | | `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | | `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index 7acf4eb9e..ae4680d16 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1809,6 +1809,10 @@ dependencies = [ "craft-gcode", "craft-geom", "craft-gif", + "craft-gpu", + "craft-gpu-null", + "craft-gpu-providers", + "craft-gpu-wgpu", "craft-gridcraft-format", "craft-gzip", "craft-har", @@ -1824,6 +1828,7 @@ dependencies = [ "craft-imaging", "craft-indd", "craft-ipc", + "craft-ipp", "craft-java-class", "craft-jmap", "craft-jpeg", @@ -1870,6 +1875,7 @@ dependencies = [ "craft-platform", "craft-plist", "craft-plotter", + "craft-ppt-binary", "craft-pptx", "craft-prc", "craft-prepress", @@ -2108,6 +2114,7 @@ dependencies = [ name = "craft-captions" version = "0.1.0" dependencies = [ + "craft-media", "craft-media-testkit", "craft-timeline", "craft-xml", @@ -2313,7 +2320,9 @@ name = "craft-develop" version = "0.1.0" dependencies = [ "craft-develop-model", + "craft-render-parity", "proptest", + "rayon", "serde", ] @@ -2797,6 +2806,40 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gpu" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-gpu-null" +version = "0.1.0" +dependencies = [ + "craft-gpu", +] + +[[package]] +name = "craft-gpu-providers" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-null", +] + +[[package]] +name = "craft-gpu-wgpu" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-providers", + "pollster 0.4.0", + "wgpu", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" @@ -2987,6 +3030,10 @@ dependencies = [ "widestring", ] +[[package]] +name = "craft-ipp" +version = "0.1.0" + [[package]] name = "craft-java-class" version = "0.1.0" @@ -3575,10 +3622,24 @@ dependencies = [ name = "craft-plotter" version = "0.1.0" dependencies = [ + "kurbo", "serde", "thiserror 2.0.21", ] +[[package]] +name = "craft-ppt-binary" +version = "0.1.0" +dependencies = [ + "craft-cfb", + "craft-drawingml", + "craft-pptx", + "image", + "log", + "miniz_oxide 0.8.9", + "thiserror 2.0.21", +] + [[package]] name = "craft-pptx" version = "0.1.0" @@ -5325,7 +5386,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" dependencies = [ "bytemuck", "emath", @@ -5381,7 +5442,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" dependencies = [ "ahash", "bytemuck", @@ -5416,7 +5477,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" dependencies = [ "accesskit", "ahash", @@ -5435,7 +5496,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" dependencies = [ "ahash", "bytemuck", @@ -5454,7 +5515,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5474,7 +5535,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" dependencies = [ "bytemuck", "egui", @@ -5487,7 +5548,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" dependencies = [ "eframe", "egui", @@ -5564,7 +5625,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" dependencies = [ "bytemuck", ] @@ -5637,7 +5698,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" dependencies = [ "ahash", "bytemuck", @@ -5663,7 +5724,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" [[package]] name = "equator" @@ -14981,19 +15042,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d" +source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" diff --git a/Cargo.toml b/Cargo.toml index 4c4920066..4c599679e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -123,6 +123,7 @@ craft-gif = { path = "crates/gif" } craft-hdr = { path = "crates/hdr" } craft-mesh = { path = "crates/mesh" } craft-html = { path = "crates/html" } +craft-ipp = { path = "crates/ipp" } craft-heif = { path = "crates/heif" } craft-fig = { path = "crates/fig" } craft-fonts-build = { path = "crates/fonts-build" } @@ -130,6 +131,10 @@ craft-font-subset = { path = "crates/font-subset" } # The HarfBuzz subsetter from storytold's HarfBuzz fork (branch rust-subset-15.0.0: HarfBuzz 15.0.0 plus rust/harfbuzz-subset-sys). harfbuzz-subset-sys = { git = "https://github.com/storytold/harfbuzz.git", rev = "f32ed1e548eaa8852bff47e49a90629a013a2faa" } craft-host = { path = "crates/host" } +craft-gpu = { path = "crates/gpu" } +craft-gpu-null = { path = "crates/gpu-null" } +craft-gpu-providers = { path = "crates/gpu-providers" } +craft-gpu-wgpu = { path = "crates/gpu-wgpu" } craft-i18n = { path = "crates/i18n" } craft-ipc = { path = "crates/ipc" } craft-idml = { path = "crates/idml" } @@ -172,6 +177,7 @@ craft-opc = { path = "crates/opc" } craft-openpgp = { path = "crates/openpgp" } craft-ora = { path = "crates/ora" } craft-pptx = { path = "crates/pptx" } +craft-ppt-binary = { path = "crates/ppt-binary" } craft-penpot = { path = "crates/penpot" } craft-pcraft-format = { path = "crates/pcraft-format" } craft-pcraft-bundle = { path = "crates/pcraft-bundle" } @@ -269,6 +275,9 @@ proptest = "1" encoding_rs = "0.8" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). chrono = { version = "0.4.45", default-features = false, features = ["std"] } +# Foundation crates for craft-gpu-wgpu. The versions match the ones the app repos already pin. +pollster = "0.4" +wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] } [workspace.lints.rust] unsafe_code = "forbid" @@ -294,20 +303,20 @@ hayro-jbig2 = { path = "vendor/hayro-jbig2" } hayro-cmap = { path = "vendor/hayro-cmap" } hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -emath = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -egui = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +emath = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +egui = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/NOTICE b/NOTICE index ac101996d..8ca284e8d 100644 --- a/NOTICE +++ b/NOTICE @@ -114,6 +114,14 @@ Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. The format imp clean-room work based on their public specifications; dependency licences and X.Org's `rgb.txt` attribution are listed in ATTRIBUTION.md. +crates/develop (craft-develop) is moved from LightCraft, module by module: +- src/inpaint.rs and src/inpaint/ from crates/inpaint (lightcraft-inpaint), with its tests, revision a75497d6. + https://github.com/storytold/lightcraft + Copyright (c) 2026 ArtCraft Team and the LightCraft contributors. + That crate ports the inpainting (PatchMatch completion) and Poisson membrane fill code of PhotoCraft + (https://github.com/storytold/photocraft, crates/algo/src/inpaint.rs and poisson.rs), Copyright the PhotoCraft + contributors, MIT OR Apache-2.0; the port was modified by the LightCraft contributors (2026). + crates/raw (craft-raw) is moved from LightCraft, with behaviour ported from two other readers: - LightCraft, crates/raw (src/lib.rs, dng.rs, dngwrite.rs, tiffraw.rs, unpack.rs, ljpeg.rs, jxl.rs, opcodes.rs, profile.rs, gaintable.rs, semantic.rs, preview.rs, vendor/crw.rs, vendor/hasselblad.rs, diff --git a/README.md b/README.md index 659b21db0..f1ded80ca 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ Craft App Libraries =================== Scanned by SonarCloud +Reviewed by CodeRabbit This repo contains libraries used by the various Craft Apps. It's a Rust monorepo workspace, and the libraries can be included by any Craft Apps that need them. @@ -341,6 +342,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-plotter`](crates/plotter/README.md): cutter and pen-plotter command languages: HP-GL, DMPL and GP-GL (plain and the Silhouette dialect, three generations, registration marks) from a job in millimetres, plus the Silhouette device queries and reply parsers. No I/O. +- [`craft-ppt-binary`](crates/ppt-binary/README.md): the PowerPoint 97-2003 binary format (`.ppt`, `.pot`, `.pps`; + [MS-PPT], [MS-ODRAW]) read into `craft-pptx`, on `craft-cfb`. Import only. DeckCraft's reader. - [`craft-pptx`](crates/pptx/README.md): PresentationML, the model of a `.pptx` presentation: masters, layouts, slides, shapes, placeholders and their inheritance, transitions and animations, comments, sections, media and kept parts. From DeckCraft. DrawingML comes from `craft-drawingml`. diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 78c589e49..7981f3a01 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -71,6 +71,9 @@ ac3-encode = ["craft-media/bitstream"] eac3-encode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) encoder (`mp3`). mp3-encode = ["craft-media/bitstream"] +# Direct Stream Digital (DSD) files: DSF and DSDIFF decoders and DSD-to-PCM decimation. +dsd = [] + # MPEG-1/2 Layer II (MP2) encoder (`mpa::encoder`). It shares the polyphase analysis filter of the # MP3 encoder and the tables of the MP1/MP2 decoder. mpa-encode = ["mpa-decode", "mp3-encode"] diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs new file mode 100644 index 000000000..f9f12d04d --- /dev/null +++ b/crates/audio/src/dsd/dsdiff.rs @@ -0,0 +1,378 @@ +//! Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`) parser and writer. +//! +//! DSDIFF files use an IFF-style big-endian chunk format starting with `FRM8` of type `DSD `: +//! - `FRM8` container chunk containing: +//! - `FVER`: format version (typically 1.5.0.0). +//! - `PROP`: properties chunk with subtype `SND `, containing: +//! - `FS `: sampling frequency (e.g. 2,822,400 Hz for DSD64). +//! - `CHNL`: channel count and 4-character channel ID codes (`SLFT`, `SRGT`, etc.). +//! - `CMPR`: compression type (`DSD ` for uncompressed, `DST ` for compressed). +//! - `DSD `: audio data chunk containing channel-interleaved 1-bit samples (MSB-first). +//! - Optional `DIIN`: disc and track information (title, artist). + +use super::{BitOrder, Error, Format, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio}; + +/// Decodes 4-byte ASCII channel identifiers into human-readable channel names. +fn channel_id_to_name(id: &[u8; 4]) -> String { + match id { + b"SLFT" => "FrontLeft".to_string(), + b"SRGT" => "FrontRight".to_string(), + b"MLFT" => "Mono/Left".to_string(), + b"MRGT" => "Right".to_string(), + b"C " => "Center".to_string(), + b"LFE " => "LFE".to_string(), + b"LS " => "LeftSurround".to_string(), + b"RS " => "RightSurround".to_string(), + b"CO " => "CenterOverhead".to_string(), + b"LH " => "LeftHeight".to_string(), + b"RH " => "RightHeight".to_string(), + _ => { + if let Ok(s) = std::str::from_utf8(id) { + let trimmed = s.trim(); + if !trimmed.is_empty() { + return trimmed.to_string(); + } + } + format!("Channel {:02X}{:02X}{:02X}{:02X}", id[0], id[1], id[2], id[3]) + } + } +} + +/// The text of a `DITI` or `DIAR` chunk: a four-byte big-endian character count, then that many +/// bytes. `None` when the count is missing or longer than the chunk. +fn diin_text(sub_data: &[u8]) -> Option { + let count = usize::try_from(u32::from_be_bytes(sub_data.get(..4)?.try_into().ok()?)).ok()?; + let text = sub_data.get(4..)?.get(..count)?; + Some(String::from_utf8_lossy(text).trim().to_string()) +} + +/// The channel identifiers DSDIFF 1.5 defines for a channel count (stereo, 5 and 5.1 channels); +/// other counts use the generic `C001`, `C002`, ... identifiers. +fn channel_ids(num_channels: usize) -> Vec<[u8; 4]> { + let named: &[&[u8; 4]] = match num_channels { + 1 => &[b"SLFT"], + 2 => &[b"SLFT", b"SRGT"], + 5 => &[b"MLFT", b"MRGT", b"C ", b"LS ", b"RS "], + 6 => &[b"MLFT", b"MRGT", b"C ", b"LFE ", b"LS ", b"RS "], + _ => &[], + }; + if !named.is_empty() { + return named.iter().map(|id| **id).collect(); + } + (1..=num_channels) + .map(|n| { + let s = format!("C{n:03}"); + let mut id = [b' '; 4]; + id.copy_from_slice(&s.as_bytes()[..4]); + id + }) + .collect() +} + +/// Parses the metadata from a DSDIFF file. +pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Error> { + if bytes.len() < 16 { + return Err(Error::UnexpectedEof("DSDIFF file is too short")); + } + + if &bytes[0..4] != b"FRM8" { + return Err(Error::InvalidHeader("missing 'FRM8' magic chunk")); + } + let form_size = u64::from_be_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("FRM8 size"))?); + if &bytes[12..16] != b"DSD " { + return Err(Error::InvalidHeader("invalid FRM8 form type (expected 'DSD ')")); + } + + let total_file_data = bytes.len().saturating_sub(12); + let form_size = usize::try_from(form_size).map_err(|_| Error::MemoryLimitExceeded)?; + if form_size > total_file_data { + return Err(Error::UnexpectedEof("FRM8 chunk extends beyond file size")); + } + + let mut pos = 16; + let end = 12 + form_size; + + let mut sample_rate = None; + let mut channel_names = Vec::new(); + let mut num_channels = None; + let mut is_compressed_dst = false; + let mut dsd_data_offset = None; + let mut dsd_data_len = None; + let mut title = None; + let mut artist = None; + + while pos + 12 <= end { + let chunk_id: [u8; 4] = bytes[pos..pos + 4].try_into().map_err(|_| Error::UnexpectedEof("chunk ID"))?; + let chunk_size = usize::try_from(u64::from_be_bytes(bytes[pos + 4..pos + 12].try_into().map_err(|_| Error::UnexpectedEof("chunk size"))?)) + .map_err(|_| Error::MemoryLimitExceeded)?; + pos += 12; + + if chunk_size > end.saturating_sub(pos) { + return Err(Error::UnexpectedEof("subchunk extends beyond container bounds")); + } + + let chunk_data = &bytes[pos..pos + chunk_size]; + let pad = chunk_size & 1; + pos = pos.saturating_add(chunk_size).saturating_add(pad); + + match &chunk_id { + b"PROP" => { + if chunk_data.len() < 4 { + continue; + } + if &chunk_data[0..4] != b"SND " { + continue; + } + let mut prop_pos = 4; + while prop_pos + 12 <= chunk_data.len() { + let sub_id: [u8; 4] = chunk_data[prop_pos..prop_pos + 4].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk ID"))?; + let sub_size = usize::try_from(u64::from_be_bytes( + chunk_data[prop_pos + 4..prop_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk size"))?, + )) + .map_err(|_| Error::MemoryLimitExceeded)?; + prop_pos += 12; + + if sub_size > chunk_data.len().saturating_sub(prop_pos) { + return Err(Error::UnexpectedEof("PROP subchunk extends beyond bounds")); + } + + let sub_data = &chunk_data[prop_pos..prop_pos + sub_size]; + let sub_pad = sub_size & 1; + prop_pos = prop_pos.saturating_add(sub_size).saturating_add(sub_pad); + + match &sub_id { + b"FS " => { + if sub_data.len() < 4 { + return Err(Error::UnexpectedEof("truncated FS chunk")); + } + if sample_rate.is_some() { + return Err(Error::InvalidHeader("duplicate FS chunk")); + } + let sr = u32::from_be_bytes([sub_data[0], sub_data[1], sub_data[2], sub_data[3]]); + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sr) { + return Err(Error::InvalidHeader("sampling frequency out of range")); + } + sample_rate = Some(sr); + } + b"CHNL" => { + if sub_data.len() < 2 { + return Err(Error::UnexpectedEof("truncated CHNL chunk")); + } + if num_channels.is_some() { + return Err(Error::InvalidHeader("duplicate CHNL chunk")); + } + let n = u16::from_be_bytes([sub_data[0], sub_data[1]]); + if n == 0 || n > MAX_CHANNELS as u16 { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + num_channels = Some(n); + channel_names.clear(); + let mut ch_pos = 2; + while ch_pos + 4 <= sub_data.len() && channel_names.len() < n as usize { + let id: [u8; 4] = [sub_data[ch_pos], sub_data[ch_pos + 1], sub_data[ch_pos + 2], sub_data[ch_pos + 3]]; + channel_names.push(channel_id_to_name(&id)); + ch_pos += 4; + } + } + b"CMPR" if sub_data.len() >= 4 => { + if &sub_data[0..4] == b"DST " { + is_compressed_dst = true; + } else if &sub_data[0..4] != b"DSD " { + return Err(Error::Unsupported("unknown DSDIFF compression type")); + } + } + _ => {} + } + } + } + b"DSD " => { + dsd_data_offset = Some(pos - chunk_size - pad); + dsd_data_len = Some(chunk_size); + } + b"DST " => { + is_compressed_dst = true; + } + b"DIIN" => { + // Parse optional disc info for title and artist. + let mut diin_pos = 0; + while diin_pos + 12 <= chunk_data.len() { + let sub_id = &chunk_data[diin_pos..diin_pos + 4]; + let sub_size = usize::try_from(u64::from_be_bytes( + chunk_data[diin_pos + 4..diin_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("DIIN subchunk size"))?, + )) + .map_err(|_| Error::MemoryLimitExceeded)?; + diin_pos += 12; + if sub_size > chunk_data.len().saturating_sub(diin_pos) { + break; + } + let sub_data = &chunk_data[diin_pos..diin_pos + sub_size]; + let sub_pad = sub_size & 1; + diin_pos = diin_pos.saturating_add(sub_size).saturating_add(sub_pad); + + if sub_id == b"DITI" && title.is_none() { + title = diin_text(sub_data); + } else if sub_id == b"DIAR" && artist.is_none() { + artist = diin_text(sub_data); + } + } + } + _ => {} + } + } + + if is_compressed_dst { + return Err(Error::Unsupported("DST compression in DSDIFF is not yet supported")); + } + + let sample_rate = sample_rate.ok_or(Error::InvalidHeader("missing sample rate ('FS ' chunk)"))?; + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidHeader("sampling frequency out of range")); + } + + let channels = num_channels.ok_or(Error::InvalidHeader("missing channel info ('CHNL' chunk)"))?; + if channels == 0 || channels > MAX_CHANNELS as u16 { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + + let data_offset = dsd_data_offset.ok_or(Error::InvalidHeader("missing audio data ('DSD ' chunk)"))?; + let data_len = dsd_data_len.ok_or(Error::InvalidHeader("missing audio data length"))?; + + let bytes_per_channel = data_len / (channels as usize); + let sample_count = (bytes_per_channel as u64).saturating_mul(8); + + if channel_names.len() < channels as usize { + for c in channel_names.len()..(channels as usize) { + channel_names.push(format!("Channel {}", c + 1)); + } + } + + let metadata = Metadata { format: Format::Dsdiff, sample_rate, channels, sample_count, channel_names, title, artist }; + + Ok((metadata, data_offset, data_len)) +} + +/// Parses a DSDIFF file into raw 1-bit planar channel streams. +pub fn parse_dsdiff(bytes: &[u8]) -> Result { + let (metadata, data_offset, data_len) = parse_dsdiff_header(bytes)?; + let channels = metadata.channels as usize; + let bytes_per_channel = data_len / channels; + + if bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + + let end_offset = data_offset + data_len; + if end_offset > bytes.len() { + return Err(Error::UnexpectedEof("DSD sound data extends beyond file bounds")); + } + let data_slice = &bytes[data_offset..end_offset]; + + let mut channel_bytes: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + let mut ch_vec = Vec::new(); + ch_vec.try_reserve_exact(bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?; + channel_bytes.push(ch_vec); + } + + // De-interleave byte-by-byte: Ch0, Ch1, ... Ch(N-1), Ch0, Ch1 ... + for chunk in data_slice.chunks_exact(channels) { + for (c, &byte) in chunk.iter().enumerate() { + if let Some(ch_vec) = channel_bytes.get_mut(c) { + ch_vec.push(byte); + } + } + } + + Ok(RawAudio { metadata, bit_order: BitOrder::MsbFirst, channel_bytes }) +} + +/// Encodes 1-bit planar audio channels into a valid Philips DSDIFF (`.dff`) file. +pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result, Error> { + if channels.is_empty() || channels.len() > MAX_CHANNELS { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidData("sample rate out of bounds")); + } + + let num_channels = channels.len(); + let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; + let data_size = bytes_per_ch.checked_mul(num_channels).ok_or(Error::MemoryLimitExceeded)?; + // Fixed headers plus four bytes for each channel identifier. + // An odd-sized chunk payload is followed by a pad byte that its size field does not count. + let data_pad = data_size & 1; + let padded_size = data_size.checked_add(data_pad).ok_or(Error::MemoryLimitExceeded)?; + let file_size = super::encoded_size(padded_size, 110 + 4 * num_channels)?; + + // Build PROP subchunks: + // 1. 'FS ' (4 bytes + 12 chunk header) + let mut fs_chunk = Vec::with_capacity(16); + fs_chunk.extend_from_slice(b"FS "); + fs_chunk.extend_from_slice(&4u64.to_be_bytes()); + fs_chunk.extend_from_slice(&sample_rate.to_be_bytes()); + + // 2. 'CHNL' (2 + 4 * num_channels + 12 chunk header) + let chnl_data_len = 2 + 4 * num_channels; + let mut chnl_chunk = Vec::with_capacity(12 + chnl_data_len + 1); + chnl_chunk.extend_from_slice(b"CHNL"); + chnl_chunk.extend_from_slice(&(chnl_data_len as u64).to_be_bytes()); + chnl_chunk.extend_from_slice(&(num_channels as u16).to_be_bytes()); + for id in channel_ids(num_channels) { + chnl_chunk.extend_from_slice(&id); + } + if !chnl_data_len.is_multiple_of(2) { + chnl_chunk.push(0); + } + + // 3. 'CMPR' (4 + 1 + 3 + pad = 8 bytes + 12 chunk header) + let mut cmpr_chunk = Vec::with_capacity(20); + cmpr_chunk.extend_from_slice(b"CMPR"); + cmpr_chunk.extend_from_slice(&8u64.to_be_bytes()); + cmpr_chunk.extend_from_slice(b"DSD "); + cmpr_chunk.push(3); // name len + cmpr_chunk.extend_from_slice(b"DSD"); + + let prop_payload_len = 4 + fs_chunk.len() + chnl_chunk.len() + cmpr_chunk.len(); + let mut prop_chunk = Vec::with_capacity(12 + prop_payload_len); + prop_chunk.extend_from_slice(b"PROP"); + prop_chunk.extend_from_slice(&(prop_payload_len as u64).to_be_bytes()); + prop_chunk.extend_from_slice(b"SND "); + prop_chunk.extend_from_slice(&fs_chunk); + prop_chunk.extend_from_slice(&chnl_chunk); + prop_chunk.extend_from_slice(&cmpr_chunk); + + // FVER chunk (4 bytes payload + 12 chunk header) + let mut fver_chunk = Vec::with_capacity(16); + fver_chunk.extend_from_slice(b"FVER"); + fver_chunk.extend_from_slice(&4u64.to_be_bytes()); + fver_chunk.extend_from_slice(&0x01050000u32.to_be_bytes()); + + // DSD chunk (data_size payload + 12 chunk header) + let mut dsd_chunk_hdr = Vec::with_capacity(12); + dsd_chunk_hdr.extend_from_slice(b"DSD "); + dsd_chunk_hdr.extend_from_slice(&(data_size as u64).to_be_bytes()); + + let frm8_payload_len = file_size - 12; + let mut out = Vec::new(); + out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?; + + out.extend_from_slice(b"FRM8"); + out.extend_from_slice(&(frm8_payload_len as u64).to_be_bytes()); + out.extend_from_slice(b"DSD "); + out.extend_from_slice(&fver_chunk); + out.extend_from_slice(&prop_chunk); + out.extend_from_slice(&dsd_chunk_hdr); + + // Interleave channels byte-by-byte. + for i in 0..bytes_per_ch { + for ch_data in channels { + let byte = ch_data.get(i).copied().unwrap_or(super::filter::SILENCE_MSBF); + out.push(byte); + } + } + if data_pad == 1 { + out.push(0); + } + + Ok(out) +} diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs new file mode 100644 index 000000000..1fb36c18d --- /dev/null +++ b/crates/audio/src/dsd/dsf.rs @@ -0,0 +1,391 @@ +//! Sony DSF (Direct Stream Digital File) parser and writer. +//! +//! A DSF file consists of three contiguous little-endian chunks: +//! - `'DSD '` chunk (28 bytes): file identification, total size, and metadata offset. +//! - `'fmt '` chunk (52 bytes): sample rate, channel count, sample count, block size. +//! - `'data'` chunk (12 bytes + data): 1-bit audio organized into channel blocks. +//! - Optional ID3v2 metadata chunk located at `metadata_offset`. + +use super::{BitOrder, Error, Format, MAX_BLOCK_SIZE, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio}; + +/// Channel configuration names for DSF channel types 1..=7. +fn dsf_channel_names(channel_type: u32, channel_count: u16) -> Vec { + match channel_type { + 1 => vec!["Mono".to_string()], + 2 => vec!["Left".to_string(), "Right".to_string()], + 3 => vec!["Left".to_string(), "Right".to_string(), "Center".to_string()], + 4 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "BackLeft".to_string(), "BackRight".to_string()], + 5 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "LFE".to_string()], + 6 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "BackLeft".to_string(), "BackRight".to_string()], + 7 => vec![ + "FrontLeft".to_string(), + "FrontRight".to_string(), + "Center".to_string(), + "LFE".to_string(), + "BackLeft".to_string(), + "BackRight".to_string(), + ], + _ => (0..channel_count).map(|c| format!("Channel {}", c + 1)).collect(), + } +} + +/// Attempts to parse basic ID3v2 title and artist tags if present at `offset`. +fn parse_id3v2(bytes: &[u8], offset: usize) -> (Option, Option) { + let Some(id3) = bytes.get(offset..) else { + return (None, None); + }; + if id3.len() < 10 || &id3[..3] != b"ID3" { + return (None, None); + } + + let mut title = None; + let mut artist = None; + + // ID3v2 size is 4 synchsafe bytes at offset 6. + let tag_size = ((id3[6] as usize & 0x7F) << 21) | ((id3[7] as usize & 0x7F) << 14) | ((id3[8] as usize & 0x7F) << 7) | (id3[9] as usize & 0x7F); + + let end = (10 + tag_size).min(id3.len()); + let mut pos = 10; + + // Scan ID3v2.3 / ID3v2.4 frames. + while pos + 10 <= end { + let frame_id = &id3[pos..pos + 4]; + if frame_id[0] == 0 { + break; + } + let raw = [id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]]; + // ID3v2.4 frame sizes are synchsafe; v2.3 ones are plain big-endian. + let frame_size = if id3[3] >= 4 { + if raw.iter().any(|b| b & 0x80 != 0) { + break; + } + ((raw[0] as usize) << 21) | ((raw[1] as usize) << 14) | ((raw[2] as usize) << 7) | raw[3] as usize + } else { + u32::from_be_bytes(raw) as usize + }; + pos += 10; + if frame_size > end.saturating_sub(pos) { + break; + } + + let frame_data = &id3[pos..pos + frame_size]; + pos += frame_size; + + if frame_id == b"TIT2" && title.is_none() { + title = parse_text_frame(frame_data); + } else if frame_id == b"TPE1" && artist.is_none() { + artist = parse_text_frame(frame_data); + } + } + + (title, artist) +} + +fn parse_text_frame(data: &[u8]) -> Option { + if data.is_empty() { + return None; + } + let encoding = data[0]; + let content = &data[1..]; + let text = match encoding { + // ISO-8859-1: every byte is the code point of the same value. + 0 => content.iter().map(|&b| char::from(b)).collect::(), + 3 => String::from_utf8_lossy(content).into_owned(), + // UTF-16 with a byte order mark (which is removed); without one, assume big-endian. + 1 => { + let (big_endian, body) = match content { + [0xFE, 0xFF, rest @ ..] => (true, rest), + [0xFF, 0xFE, rest @ ..] => (false, rest), + _ => (true, content), + }; + utf16(body, big_endian) + } + // UTF-16BE without a byte order mark. + 2 => utf16(content, true), + _ => return None, + }; + let s = text.trim_end_matches('\0').trim().to_string(); + if s.is_empty() { None } else { Some(s) } +} + +fn utf16(bytes: &[u8], big_endian: bool) -> String { + let units: Vec = bytes + .as_chunks::<2>() + .0 + .iter() + .map(|c| if big_endian { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }) + .collect(); + String::from_utf16_lossy(&units) +} + +/// Parses DSF file metadata, returning the metadata, audio data offset, and block size per channel. +pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> { + let (metadata, offset, _, block_size) = parse_dsf_header_bounded(bytes)?; + Ok((metadata, offset, block_size)) +} + +fn parse_dsf_header_bounded(bytes: &[u8]) -> Result<(Metadata, usize, usize, u32), Error> { + if bytes.len() < 28 + 52 + 12 { + return Err(Error::UnexpectedEof("DSF file header is truncated")); + } + + // 1. 'DSD ' chunk + if &bytes[..4] != b"DSD " { + return Err(Error::InvalidHeader("missing 'DSD ' magic header")); + } + let dsd_chunk_size = u64::from_le_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("DSD chunk size"))?); + if dsd_chunk_size != 28 { + return Err(Error::InvalidHeader("invalid 'DSD ' chunk size (must be 28)")); + } + let file_size = u64::from_le_bytes(bytes[12..20].try_into().map_err(|_| Error::UnexpectedEof("file size"))?); + let metadata_offset = u64::from_le_bytes(bytes[20..28].try_into().map_err(|_| Error::UnexpectedEof("metadata offset"))?); + + if file_size > bytes.len() as u64 { + return Err(Error::UnexpectedEof("declared file size extends beyond buffer")); + } + let file_len = usize::try_from(file_size).map_err(|_| Error::MemoryLimitExceeded)?; + if file_len < 28 + 52 + 12 { + return Err(Error::InvalidHeader("declared file size is smaller than required headers")); + } + let file_bytes = &bytes[..file_len]; + + // 2. 'fmt ' chunk + let fmt_offset = 28; + if &file_bytes[fmt_offset..fmt_offset + 4] != b"fmt " { + return Err(Error::InvalidHeader("missing 'fmt ' chunk header")); + } + let fmt_chunk_size = + u64::from_le_bytes(file_bytes[fmt_offset + 4..fmt_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("fmt chunk size"))?); + if fmt_chunk_size < 52 { + return Err(Error::InvalidHeader("invalid 'fmt ' chunk size (must be at least 52)")); + } + let fmt_size = usize::try_from(fmt_chunk_size).map_err(|_| Error::MemoryLimitExceeded)?; + if fmt_size > file_bytes.len().saturating_sub(fmt_offset) { + return Err(Error::UnexpectedEof("fmt chunk extends beyond file bounds")); + } + + let format_version = + u32::from_le_bytes(file_bytes[fmt_offset + 12..fmt_offset + 16].try_into().map_err(|_| Error::UnexpectedEof("format version"))?); + if format_version != 1 { + return Err(Error::Unsupported("unsupported DSF format version (only version 1 is supported)")); + } + + let format_id = u32::from_le_bytes(file_bytes[fmt_offset + 16..fmt_offset + 20].try_into().map_err(|_| Error::UnexpectedEof("format id"))?); + if format_id != 0 { + return Err(Error::Unsupported("unsupported DSF format id (only raw DSD id=0 is supported)")); + } + + let channel_type = u32::from_le_bytes(file_bytes[fmt_offset + 20..fmt_offset + 24].try_into().map_err(|_| Error::UnexpectedEof("channel type"))?); + let channel_count = + u32::from_le_bytes(file_bytes[fmt_offset + 24..fmt_offset + 28].try_into().map_err(|_| Error::UnexpectedEof("channel count"))?); + if channel_count == 0 || channel_count > MAX_CHANNELS as u32 { + return Err(Error::Unsupported("DSF channel count must be between 1 and 8")); + } + let channels = channel_count as u16; + + let sample_rate = + u32::from_le_bytes(file_bytes[fmt_offset + 28..fmt_offset + 32].try_into().map_err(|_| Error::UnexpectedEof("sampling frequency"))?); + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidHeader("DSF sampling frequency out of valid range")); + } + + let bits_per_sample = + u32::from_le_bytes(file_bytes[fmt_offset + 32..fmt_offset + 36].try_into().map_err(|_| Error::UnexpectedEof("bits per sample"))?); + if bits_per_sample != 1 { + return Err(Error::Unsupported("DSF bits per sample must be 1")); + } + + let sample_count = u64::from_le_bytes(file_bytes[fmt_offset + 36..fmt_offset + 44].try_into().map_err(|_| Error::UnexpectedEof("sample count"))?); + + let block_size_per_channel = + u32::from_le_bytes(file_bytes[fmt_offset + 44..fmt_offset + 48].try_into().map_err(|_| Error::UnexpectedEof("block size per channel"))?); + if block_size_per_channel == 0 || block_size_per_channel > MAX_BLOCK_SIZE { + return Err(Error::InvalidHeader("DSF block size per channel is invalid or too large")); + } + + // 3. 'data' chunk + let data_offset = fmt_offset.saturating_add(fmt_size); + if data_offset.saturating_add(12) > file_bytes.len() { + return Err(Error::UnexpectedEof("missing 'data' chunk header")); + } + if &file_bytes[data_offset..data_offset + 4] != b"data" { + return Err(Error::InvalidHeader("missing 'data' chunk header")); + } + let data_chunk_size = + u64::from_le_bytes(file_bytes[data_offset + 4..data_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("data chunk size"))?); + if data_chunk_size < 12 { + return Err(Error::InvalidHeader("invalid 'data' chunk size (must be at least 12)")); + } + + let payload_offset = data_offset + 12; + let payload_size = usize::try_from(data_chunk_size - 12).map_err(|_| Error::MemoryLimitExceeded)?; + if payload_size > file_bytes.len().saturating_sub(payload_offset) { + return Err(Error::UnexpectedEof("data chunk payload extends beyond file bounds")); + } + let data_end = payload_offset.saturating_add(payload_size); + + // Parse ID3v2 metadata if pointer is valid. + let (title, artist) = if metadata_offset == 0 { + (None, None) + } else { + let meta_offset = usize::try_from(metadata_offset).map_err(|_| Error::MemoryLimitExceeded)?; + if meta_offset < data_end || meta_offset >= file_len { + return Err(Error::InvalidHeader("DSF metadata offset outside declared file bounds")); + } + parse_id3v2(file_bytes, meta_offset) + }; + + let channel_names = dsf_channel_names(channel_type, channels); + + let metadata = Metadata { format: Format::Dsf, sample_rate, channels, sample_count, channel_names, title, artist }; + + Ok((metadata, payload_offset, payload_size, block_size_per_channel)) +} + +/// Parses a DSF file into raw 1-bit planar channel streams. +pub fn parse_dsf(bytes: &[u8]) -> Result { + let (metadata, payload_offset, payload_size, block_size) = parse_dsf_header_bounded(bytes)?; + let block_size = block_size as usize; + let channels = metadata.channels as usize; + + let target_bytes_per_channel = usize::try_from(metadata.sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; + if target_bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + + let slice_size = channels.saturating_mul(block_size); + if slice_size == 0 { + return Err(Error::InvalidHeader("zero slice size")); + } + + // The header validated this range. Trailing ID3 or other bytes are not audio, + // even if sample_count asks for more samples than the data chunk contains. + let payload = &bytes[payload_offset..payload_offset + payload_size]; + let num_slices = payload.len() / slice_size; + + let mut channel_bytes: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + let mut ch_vec = Vec::new(); + ch_vec.try_reserve_exact(target_bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?; + channel_bytes.push(ch_vec); + } + + for s in 0..num_slices { + let slice_base = s * slice_size; + for (c, ch_vec) in channel_bytes.iter_mut().enumerate() { + let ch_start = slice_base + c * block_size; + let ch_end = ch_start + block_size; + if let Some(block) = payload.get(ch_start..ch_end) { + let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len()); + let take = block.len().min(remaining); + ch_vec.extend_from_slice(&block[..take]); + } + } + } + + // Handle any trailing partial slice. + let remainder = payload.len() % slice_size; + if remainder > 0 { + let slice_base = num_slices * slice_size; + for (c, ch_vec) in channel_bytes.iter_mut().enumerate() { + let ch_start = slice_base + c * block_size; + if ch_start < payload.len() { + let ch_end = (ch_start + block_size).min(payload.len()); + let block = &payload[ch_start..ch_end]; + let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len()); + let take = block.len().min(remaining); + ch_vec.extend_from_slice(&block[..take]); + } + } + } + + // Pad with silence (0x69) if the file had fewer bytes than required by sample_count. + for ch_vec in &mut channel_bytes { + if ch_vec.len() < target_bytes_per_channel { + ch_vec.resize(target_bytes_per_channel, super::filter::SILENCE_LSBF); + } + } + + Ok(RawAudio { metadata, bit_order: BitOrder::LsbFirst, channel_bytes }) +} + +fn unsupported_channel_layout() -> Result { + Err(Error::Unsupported("DSF has no channel type for this channel count (1 to 6 are supported)")) +} + +/// Encodes 1-bit planar audio channels into a valid Sony DSF file. +pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> { + if channels.is_empty() || channels.len() > MAX_CHANNELS { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidData("sample rate out of bounds")); + } + if block_size > MAX_BLOCK_SIZE { + return Err(Error::InvalidData("DSF block size exceeds maximum")); + } + let block_size = if block_size == 0 { 4096 } else { block_size as usize }; + + let num_channels = channels.len(); + let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; + let num_blocks = bytes_per_ch.div_ceil(block_size); + let payload_size = num_blocks.checked_mul(num_channels).and_then(|n| n.checked_mul(block_size)).ok_or(Error::MemoryLimitExceeded)?; + let file_size = super::encoded_size(payload_size, 92)?; + + let data_chunk_size = 12u64 + payload_size as u64; + + let mut out = Vec::new(); + out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?; + + // 1. 'DSD ' chunk (28 bytes) + out.extend_from_slice(b"DSD "); + out.extend_from_slice(&28u64.to_le_bytes()); + out.extend_from_slice(&(file_size as u64).to_le_bytes()); + out.extend_from_slice(&0u64.to_le_bytes()); // metadata offset = 0 + + // 2. 'fmt ' chunk (52 bytes) + out.extend_from_slice(b"fmt "); + out.extend_from_slice(&52u64.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); // format_version = 1 + out.extend_from_slice(&0u32.to_le_bytes()); // format_id = 0 (raw DSD) + // DSF channel types: 1 mono, 2 stereo, 3 L R C, 4 quad, 6 five channels, 7 5.1. + let channel_type = match num_channels { + 1 => 1u32, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 6, + 6 => 7, + _ => unsupported_channel_layout()?, + }; + out.extend_from_slice(&channel_type.to_le_bytes()); + out.extend_from_slice(&(num_channels as u32).to_le_bytes()); + out.extend_from_slice(&sample_rate.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); // bits_per_sample = 1 + out.extend_from_slice(&sample_count.to_le_bytes()); + out.extend_from_slice(&(block_size as u32).to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); // reserved + + // 3. 'data' chunk + out.extend_from_slice(b"data"); + out.extend_from_slice(&data_chunk_size.to_le_bytes()); + + for b in 0..num_blocks { + let blk_start = b * block_size; + let blk_end = blk_start + block_size; + for ch_data in channels { + let available = if blk_start < ch_data.len() { + let end = blk_end.min(ch_data.len()); + &ch_data[blk_start..end] + } else { + &[] + }; + out.extend_from_slice(available); + if available.len() < block_size { + out.resize(out.len() + (block_size - available.len()), super::filter::SILENCE_LSBF); + } + } + } + + Ok(out) +} diff --git a/crates/audio/src/dsd/filter.rs b/crates/audio/src/dsd/filter.rs new file mode 100644 index 000000000..ec815afd1 --- /dev/null +++ b/crates/audio/src/dsd/filter.rs @@ -0,0 +1,288 @@ +//! DSD-to-PCM decimation filter. +//! +//! Direct Stream Digital (DSD) uses 1-bit Sigma-Delta modulation sampled at high rates +//! (2,822,400 Hz for DSD64, 5,644,800 Hz for DSD128, etc.). Decimation to multi-bit PCM +//! involves low-pass filtering to attenuate high-frequency quantization noise followed +//! by downsampling. +//! +//! This module provides a 96-tap symmetric FIR decimation filter that downsamples 1-bit DSD +//! to multi-bit PCM at 1/8th of the DSD sampling rate (e.g. 352,800 Hz for DSD64). Further +//! integer decimation (to 176.4 kHz, 88.2 kHz, or 44.1 kHz) is supported via subsequent +//! downsampling stages. + +use super::{BitOrder, Error, MAX_DECODE_BYTES}; + +/// 96-tap symmetric FIR decimation filter coefficients for decimation by 8. +/// +/// Output is normalized so that alternating silence bits (0x69 or 0xAA) decode near 0.0, +/// and full-scale runs of 1s or 0s decode near +1.0 and -1.0. +#[allow(clippy::excessive_precision)] +pub const TAPS_96: [f32; 96] = [ + 2.9802322388e-08_f32, + 1.1920928955e-07_f32, + 3.5762786865e-07_f32, + 7.4505805969e-07_f32, + 1.3113021851e-06_f32, + 1.9371509552e-06_f32, + 2.1755695343e-06_f32, + 1.2516975403e-06_f32, + -1.9967556000e-06_f32, + -9.1493129730e-06_f32, + -2.1725893021e-05_f32, + -4.0739774704e-05_f32, + -6.5773725510e-05_f32, + -9.3966722488e-05_f32, + -1.1900067329e-04_f32, + -1.3050436974e-04_f32, + -1.1405348778e-04_f32, + -5.2779912949e-05_f32, + 7.0035457611e-05_f32, + 2.6643276215e-04_f32, + 5.3817033768e-04_f32, + 8.7043642998e-04_f32, + 1.2266933918e-03_f32, + 1.5456080437e-03_f32, + 1.7420351505e-03_f32, + 1.7137229443e-03_f32, + 1.3538300991e-03_f32, + 5.7008862495e-04_f32, + -6.9221854210e-04_f32, + -2.4250447750e-03_f32, + -4.5351684093e-03_f32, + -6.8288743496e-03_f32, + -9.0079009533e-03_f32, + -1.0681360960e-02_f32, + -1.1394292116e-02_f32, + -1.0672420263e-02_f32, + -8.0802738667e-03_f32, + -3.2847225666e-03_f32, + 3.8830339909e-03_f32, + 1.3377487659e-02_f32, + 2.4909228086e-02_f32, + 3.7942945957e-02_f32, + 5.1726281643e-02_f32, + 6.5348774195e-02_f32, + 7.7825516462e-02_f32, + 8.8196486235e-02_f32, + 9.5628470182e-02_f32, + 9.9507331848e-02_f32, + 9.9507331848e-02_f32, + 9.5628470182e-02_f32, + 8.8196486235e-02_f32, + 7.7825516462e-02_f32, + 6.5348774195e-02_f32, + 5.1726281643e-02_f32, + 3.7942945957e-02_f32, + 2.4909228086e-02_f32, + 1.3377487659e-02_f32, + 3.8830339909e-03_f32, + -3.2847225666e-03_f32, + -8.0802738667e-03_f32, + -1.0672420263e-02_f32, + -1.1394292116e-02_f32, + -1.0681360960e-02_f32, + -9.0079009533e-03_f32, + -6.8288743496e-03_f32, + -4.5351684093e-03_f32, + -2.4250447750e-03_f32, + -6.9221854210e-04_f32, + 5.7008862495e-04_f32, + 1.3538300991e-03_f32, + 1.7137229443e-03_f32, + 1.7420351505e-03_f32, + 1.5456080437e-03_f32, + 1.2266933918e-03_f32, + 8.7043642998e-04_f32, + 5.3817033768e-04_f32, + 2.6643276215e-04_f32, + 7.0035457611e-05_f32, + -5.2779912949e-05_f32, + -1.1405348778e-04_f32, + -1.3050436974e-04_f32, + -1.1900067329e-04_f32, + -9.3966722488e-05_f32, + -6.5773725510e-05_f32, + -4.0739774704e-05_f32, + -2.1725893021e-05_f32, + -9.1493129730e-06_f32, + -1.9967556000e-06_f32, + 1.2516975403e-06_f32, + 2.1755695343e-06_f32, + 1.9371509552e-06_f32, + 1.3113021851e-06_f32, + 7.4505805969e-07_f32, + 3.5762786865e-07_f32, + 1.1920928955e-07_f32, + 2.9802322388e-08_f32, +]; + +/// The number of filter history bytes (96 taps / 8 bits per byte = 12 bytes). +pub const FILTER_BYTES: usize = 12; + +/// Standard DSD silence pattern byte for LSB-first ordering (Sony DSF). +pub const SILENCE_LSBF: u8 = 0x69; + +/// Standard DSD silence pattern byte for MSB-first ordering (Philips DSDIFF). +pub const SILENCE_MSBF: u8 = 0xAA; + +/// Precomputes lookup table entries for byte position `k` (0..12) and byte value `v` (0..256). +/// +/// In LSB-first order, bit `b` of input byte `k` corresponds to tap `k * 8 + b`. +#[inline] +fn byte_lut(k: usize, byte_val: u8) -> f32 { + let mut sum = 0.0_f32; + let base_tap = k * 8; + for b in 0..8 { + if ((byte_val >> b) & 1) != 0 + && let Some(tap) = TAPS_96.get(base_tap + b) + { + sum += 2.0 * *tap; + } + } + sum +} + +// Both the first-stage samples and the secondary output coexist during filtering. +pub(super) fn allocation_sizes(len: usize, factor: u32) -> Result<(usize, usize), Error> { + if !matches!(factor, 8 | 16 | 32 | 64) { + return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64")); + } + let stage = len.checked_mul(std::mem::size_of::()).ok_or(Error::MemoryLimitExceeded)?; + let output = (len / (factor / 8) as usize).checked_mul(std::mem::size_of::()).ok_or(Error::MemoryLimitExceeded)?; + let working = if factor == 8 { stage } else { stage.checked_add(output).ok_or(Error::MemoryLimitExceeded)? }; + if working > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + Ok((working, output)) +} + +/// Unity-DC-gain low-pass taps for decimating by `ratio` (cutoff 0.45 / ratio cycles per sample). +fn decimation_taps(ratio: usize) -> Vec { + let n = 24 * ratio + 1; + let mid = (n / 2) as f64; + let fc = 0.45 / ratio as f64; + let mut taps: Vec = (0..n) + .map(|k| { + let x = k as f64 - mid; + let sinc = if x == 0.0 { 2.0 * fc } else { (2.0 * std::f64::consts::PI * fc * x).sin() / (std::f64::consts::PI * x) }; + let t = k as f64 / (n - 1) as f64; + let window = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * t).cos() + 0.08 * (4.0 * std::f64::consts::PI * t).cos(); + sinc * window + }) + .collect(); + let sum: f64 = taps.iter().sum(); + for t in &mut taps { + *t /= sum; + } + taps.into_iter().map(|t| t as f32).collect() +} + +/// Decimates 1-bit DSD audio bytes for a single channel to `f32` PCM. +/// +/// The default decimation factor is 8 (1 output float per input byte). +/// When `factor` is 16, 32, or 64, the 1/8 output is further downsampled +/// by 2, 4, or 8 respectively. +pub fn decimate_channel(channel_bytes: &[u8], bit_order: BitOrder, factor: u32) -> Result, Error> { + allocation_sizes(channel_bytes.len(), factor)?; + let num_bytes = channel_bytes.len(); + + // Build the 12 x 256 lookup table for fast convolution. + // 12 * 256 * 4 bytes = 12 KB, sits comfortably in L1 cache. + let mut lut = [[0.0_f32; 256]; FILTER_BYTES]; + for (k, lut_k) in lut.iter_mut().enumerate() { + for (v, cell) in lut_k.iter_mut().enumerate() { + *cell = byte_lut(k, v as u8); + } + } + + let mut stage1 = Vec::new(); + stage1.try_reserve_exact(num_bytes).map_err(|_| Error::MemoryLimitExceeded)?; + + // History buffer holds the most recent 12 bytes in LSB-first order. + // Pre-filled with silence (0x69). + let mut history = [SILENCE_LSBF; FILTER_BYTES]; + + for &raw_byte in channel_bytes { + let byte = match bit_order { + BitOrder::LsbFirst => raw_byte, + BitOrder::MsbFirst => raw_byte.reverse_bits(), + }; + + // Shift history left by 1 and push current byte to the end. + history.copy_within(1.., 0); + if let Some(last) = history.last_mut() { + *last = byte; + } + + let mut sample = -1.0_f32; + for (k, &hist_byte) in history.iter().enumerate() { + if let Some(lut_k) = lut.get(k) + && let Some(&contrib) = lut_k.get(hist_byte as usize) + { + sample += contrib; + } + } + + stage1.push(sample); + } + + if factor == 8 { + return Ok(stage1); + } + + // Secondary decimation by ratio = factor / 8 (2, 4, or 8). A plain average attenuates the band + // between the new Nyquist rate and the stage-1 rate too little (about -7.6 dB at 29.4 kHz for + // factor 64), so low-pass first: a Blackman-windowed sinc with its cutoff at 90% of the new + // Nyquist frequency, evaluated only at the kept samples. + let ratio = (factor / 8) as usize; + let out_len = stage1.len() / ratio; + let mut out = Vec::new(); + out.try_reserve_exact(out_len).map_err(|_| Error::MemoryLimitExceeded)?; + + let taps = decimation_taps(ratio); + let half = (taps.len() / 2) as isize; + let last = stage1.len() as isize - 1; + for i in 0..out_len { + let center = (i * ratio + ratio / 2) as isize; + let mut acc = 0.0_f32; + for (k, &w) in taps.iter().enumerate() { + let idx = (center + k as isize - half).clamp(0, last); + if let Some(&x) = stage1.get(idx as usize) { + acc += w * x; + } + } + out.push(acc); + } + + Ok(out) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod decimation_tests { + use super::*; + + /// A full-scale 29.4 kHz square wave in DSD64 (six bytes of ones, six of zeros) lies between + /// the output Nyquist frequency and the sampling rate of a 44.1 kHz result: it must be + /// attenuated well, not folded down at 0.42 of its amplitude. + #[test] + fn factor_64_attenuates_29_4_khz() { + let mut bytes = Vec::new(); + for _ in 0..2000 { + bytes.extend_from_slice(&[0xFF; 6]); + bytes.extend_from_slice(&[0x00; 6]); + } + let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap(); + let mid = &out[out.len() / 4..out.len() * 3 / 4]; + let peak = mid.iter().fold(0.0_f32, |m, v| m.max(v.abs())); + assert!(peak < 0.05, "peak {peak}"); + } + + #[test] + fn decimation_keeps_dc_level() { + let bytes = vec![0xFF; 4096]; + let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap(); + let mid = out[out.len() / 2]; + assert!((mid - 1.0).abs() < 0.05, "{mid}"); + } +} diff --git a/crates/audio/src/dsd/mod.rs b/crates/audio/src/dsd/mod.rs new file mode 100644 index 000000000..e782b50f0 --- /dev/null +++ b/crates/audio/src/dsd/mod.rs @@ -0,0 +1,275 @@ +//! Direct Stream Digital (DSD) audio: Sony DSF and Philips DSDIFF (`.dff`) readers and +//! DSD-to-PCM decimation. +//! +//! DSD stores 1-bit Pulse Density Modulation (PDM) sampled at high rates (e.g. 2,822,400 Hz +//! for DSD64, 5,644,800 Hz for DSD128, etc.). +//! +//! This module provides: +//! - File parsers for Sony DSF (`.dsf`) and Philips DSDIFF (`.dff`) containers. +//! - Raw 1-bit audio extraction with preservation of native bit ordering (LSB-first for DSF, +//! MSB-first for DSDIFF). +//! - Clean-room 96-tap symmetric FIR decimation filter converting 1-bit PDM to multi-bit PCM +//! (decimation by 8 to 352,800 Hz for DSD64, or downsampled to 176.4, 88.2, or 44.1 kHz). +//! - Reference encoders for generating synthetic DSF and DSDIFF files. + +pub mod dsdiff; +pub mod dsf; +pub mod filter; + +use crate::AudioBuffer; + +/// Maximum number of audio channels supported (1 to 8). +pub const MAX_CHANNELS: usize = 8; + +/// Minimum allowable DSD sample rate in Hz. +pub const MIN_SAMPLE_RATE: u32 = 44_100; + +/// Maximum allowable DSD sample rate in Hz (e.g. DSD1024 at 45.1584 MHz). +pub const MAX_SAMPLE_RATE: u32 = 45_158_400; + +/// Maximum safe block size for DSF channel blocks (16 MiB). +pub const MAX_BLOCK_SIZE: u32 = 16 * 1024 * 1024; + +/// Maximum audio-buffer allocation budget (256 MiB). +/// +/// Raw readers limit their channel bytes; PCM conversion separately limits the +/// simultaneously live PCM output and scratch buffers. Caller-owned raw input, +/// metadata, and the small filter lookup table are not included. +pub const MAX_DECODE_BYTES: usize = 256 * 1024 * 1024; + +/// Maximum encoded container size, including headers and block padding (256 MiB). +pub const MAX_ENCODE_BYTES: usize = 256 * 1024 * 1024; + +fn encoded_size(payload: usize, header: usize) -> Result { + payload.checked_add(header).filter(|&n| n <= MAX_ENCODE_BYTES).ok_or(Error::MemoryLimitExceeded) +} + +// Account for retained channel output plus the current filter's two live buffers. +fn pcm_budget(lengths: impl Iterator, factor: u32) -> Result<(), Error> { + let mut retained = 0usize; + for len in lengths { + let (working, output) = filter::allocation_sizes(len, factor)?; + if retained.checked_add(working).is_none_or(|n| n > MAX_DECODE_BYTES) { + return Err(Error::MemoryLimitExceeded); + } + retained = retained.checked_add(output).ok_or(Error::MemoryLimitExceeded)?; + } + Ok(()) +} + +/// Supported DSD container formats. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Format { + /// Sony DSF (Direct Stream Digital File) format. + Dsf, + /// Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`). + Dsdiff, +} + +/// Bit ordering of 1-bit DSD audio samples within bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BitOrder { + /// Least-significant bit first (LSB-first, as used in DSF). + /// Bit 0 is the earliest temporal sample; bit 7 is the latest. + LsbFirst, + /// Most-significant bit first (MSB-first, as used in DSDIFF). + /// Bit 7 is the earliest temporal sample; bit 0 is the latest. + MsbFirst, +} + +/// Stream properties and metadata parsed from a DSD container header. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Metadata { + /// Container format (DSF or DSDIFF). + pub format: Format, + /// DSD sampling frequency in Hz (e.g. 2,822,400 for DSD64). + pub sample_rate: u32, + /// Number of audio channels (1 to 8). + pub channels: u16, + /// Total number of 1-bit audio samples per channel. + pub sample_count: u64, + /// Channel identification labels (e.g. "SLFT", "SRGT", "Center"). + pub channel_names: Vec, + /// Optional track title if present in container metadata. + pub title: Option, + /// Optional artist name if present in container metadata. + pub artist: Option, +} + +/// Raw 1-bit DSD audio extracted from a file without decimation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawAudio { + /// Stream metadata from the file header. + pub metadata: Metadata, + /// Bit ordering of the bytes in `channel_bytes`. + pub bit_order: BitOrder, + /// Planar 1-bit audio bytes per channel. + pub channel_bytes: Vec>, +} + +impl RawAudio { + /// Converts all channel byte streams to the requested bit ordering in place. + pub fn convert_bit_order(&mut self, target: BitOrder) { + if self.bit_order == target { + return; + } + for ch in &mut self.channel_bytes { + for b in ch.iter_mut() { + *b = b.reverse_bits(); + } + } + self.bit_order = target; + } + + /// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples. + /// + /// The default decimation factor is 8 (e.g. 352,800 Hz for DSD64). + pub fn to_pcm(&self) -> Result { + self.to_pcm_with_factor(8) + } + + /// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples with the given factor (8, 16, 32, or 64). + pub fn to_pcm_with_factor(&self, factor: u32) -> Result { + // Validate before iterating: public RawAudio may contain no channels. + if !matches!(factor, 8 | 16 | 32 | 64) { + return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64")); + } + if self.channel_bytes.len() > MAX_CHANNELS { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + pcm_budget(self.channel_bytes.iter().map(Vec::len), factor)?; + let mut channels = Vec::with_capacity(self.channel_bytes.len()); + for ch_bytes in &self.channel_bytes { + let pcm = filter::decimate_channel(ch_bytes, self.bit_order, factor)?; + channels.push(pcm); + } + let sample_rate = self.metadata.sample_rate / factor; + Ok(DecodedAudio { metadata: self.metadata.clone(), sample_rate, channels }) + } +} + +/// Decoded multi-bit PCM audio produced by DSD-to-PCM decimation. +#[derive(Debug, Clone, PartialEq)] +pub struct DecodedAudio { + /// Stream metadata from the DSD file header. + pub metadata: Metadata, + /// PCM sample rate in Hz (e.g. 352,800 Hz for DSD64 decimated by 8). + pub sample_rate: u32, + /// Planar normalized PCM samples in `[-1.0, 1.0]`, one `Vec` per channel. + pub channels: Vec>, +} + +impl DecodedAudio { + /// Converts the decoded PCM audio into an [`AudioBuffer`]. + pub fn to_audio_buffer(&self) -> AudioBuffer { + AudioBuffer { sample_rate: self.sample_rate, channels: self.channels.clone() } + } +} + +/// Errors returned when parsing or decoding DSD audio. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + /// Input data ended prematurely while parsing a header or chunk. + #[error("unexpected end of file: {0}")] + UnexpectedEof(&'static str), + /// Invalid magic bytes or malformed chunk header. + #[error("invalid DSD header or chunk: {0}")] + InvalidHeader(&'static str), + /// An unsupported feature, compression, or channel configuration. + #[error("unsupported DSD feature: {0}")] + Unsupported(&'static str), + /// Audio data length or structure does not match the header specification. + #[error("invalid audio data: {0}")] + InvalidData(&'static str), + /// Header or data requested exceeds maximum safe allocation budget. + #[error("memory budget exceeded")] + MemoryLimitExceeded, +} + +/// Inspects the magic bytes of `bytes` and detects whether it is a DSF or DSDIFF file. +pub fn probe_format(bytes: &[u8]) -> Result { + if bytes.len() < 4 { + return Err(Error::UnexpectedEof("input is too short to determine DSD format")); + } + if &bytes[0..4] == b"DSD " { + Ok(Format::Dsf) + } else if bytes.len() >= 16 && &bytes[0..4] == b"FRM8" && &bytes[12..16] == b"DSD " { + Ok(Format::Dsdiff) + } else { + Err(Error::InvalidHeader("unknown or unsupported DSD container format")) + } +} + +/// Parses the metadata from a DSF or DSDIFF file without decoding audio samples. +pub fn read_metadata(bytes: &[u8]) -> Result { + match probe_format(bytes)? { + Format::Dsf => { + let (meta, _, _) = dsf::parse_dsf_header(bytes)?; + Ok(meta) + } + Format::Dsdiff => { + let (meta, _, _) = dsdiff::parse_dsdiff_header(bytes)?; + Ok(meta) + } + } +} + +/// Reads raw 1-bit planar audio streams from a DSF or DSDIFF file without decimation. +pub fn read_raw(bytes: &[u8]) -> Result { + match probe_format(bytes)? { + Format::Dsf => dsf::parse_dsf(bytes), + Format::Dsdiff => dsdiff::parse_dsdiff(bytes), + } +} + +/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio using decimation by 8. +/// +/// For DSD64 (2,822,400 Hz), the output sample rate is 352,800 Hz. +pub fn decode(bytes: &[u8]) -> Result { + decode_with_factor(bytes, 8) +} + +/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio with the specified decimation factor. +/// +/// Supported decimation factors are: +/// - 8: 1/8th of DSD rate (e.g. 352,800 Hz for DSD64). +/// - 16: 1/16th of DSD rate (e.g. 176,400 Hz for DSD64). +/// - 32: 1/32th of DSD rate (e.g. 88,200 Hz for DSD64). +/// - 64: 1/64th of DSD rate (e.g. 44,100 Hz for DSD64). +pub fn decode_with_factor(bytes: &[u8], factor: u32) -> Result { + let raw = read_raw(bytes)?; + raw.to_pcm_with_factor(factor) +} + +/// Encodes planar 1-bit audio channels into a Sony DSF file. +pub fn encode_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> { + dsf::write_dsf(sample_rate, channels, sample_count, block_size) +} + +/// Encodes planar 1-bit audio channels into a Philips DSDIFF file. +pub fn encode_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result, Error> { + dsdiff::write_dsdiff(sample_rate, channels, sample_count) +} + +#[cfg(test)] +mod budget_tests { + use super::*; + + #[test] + fn pcm_budget_counts_all_channels_and_live_scratch() { + let quarter = MAX_DECODE_BYTES / 4; + assert!(pcm_budget([quarter / 2, quarter / 2].into_iter(), 8).is_ok()); + assert_eq!(pcm_budget([quarter / 2, quarter / 2 + 1].into_iter(), 8), Err(Error::MemoryLimitExceeded)); + assert!(pcm_budget([quarter / 2].into_iter(), 16).is_ok()); + assert_eq!(pcm_budget([quarter].into_iter(), 16), Err(Error::MemoryLimitExceeded)); + assert_eq!(pcm_budget([usize::MAX].into_iter(), 8), Err(Error::MemoryLimitExceeded)); + } + + #[test] + fn encoded_budget_includes_headers_without_large_allocations() { + assert_eq!(encoded_size(MAX_ENCODE_BYTES - 92, 92), Ok(MAX_ENCODE_BYTES)); + assert_eq!(encoded_size(MAX_ENCODE_BYTES - 91, 92), Err(Error::MemoryLimitExceeded)); + assert_eq!(encoded_size(usize::MAX, 92), Err(Error::MemoryLimitExceeded)); + } +} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 3ccdcdf3f..9ca1571cf 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -2,7 +2,7 @@ #![warn(missing_docs)] // The docs link items of every feature; built with fewer features, those links have no target. // CI and docs.rs build the docs with all features, where every link must resolve. -#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks")), allow(rustdoc::broken_intra_doc_links))] +#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks", feature = "dsd")), allow(rustdoc::broken_intra_doc_links))] //! Audio file I/O and codecs for the Craft apps. Input and output are byte slices or a //! [`craft_media::ByteSource`] (no filesystem access of its own); builds for //! `wasm32-unknown-unknown`. @@ -32,7 +32,7 @@ //! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`] //! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder; //! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), [`adpcm`] -//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), +//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), //! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`: //! Sierra VMD sound). //! @@ -47,6 +47,8 @@ pub mod adpcm; #[cfg(any(feature = "alac-decode", feature = "alac-encode"))] pub mod alac; mod buffer; +#[cfg(feature = "dsd")] +pub mod dsd; #[cfg(feature = "g722")] pub mod g722; #[cfg(feature = "g726")] diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs new file mode 100644 index 000000000..5388f2aa4 --- /dev/null +++ b/crates/audio/tests/dsd_bounds.rs @@ -0,0 +1,208 @@ +//! Hostile container sizes must return errors, never wrap offsets or panic. +use craft_audio::dsd::{BitOrder, Error, RawAudio, encode_dsdiff, encode_dsf, read_metadata, read_raw}; + +#[test] +fn dsf_untrusted_sizes_are_checked() { + let original = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap(); + for offset in [32, 84] { + // fmt and data chunk sizes + for size in [u64::MAX, u64::MAX - 31, 1 << 32] { + let mut bytes = original.clone(); + bytes[offset..offset + 8].copy_from_slice(&size.to_le_bytes()); + assert!(read_metadata(&bytes).is_err()); + assert!(read_raw(&bytes).is_err()); + } + } + let mut bytes = original; + bytes[64..72].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_eq!(read_raw(&bytes), Err(Error::MemoryLimitExceeded)); +} + +#[test] +fn dsdiff_untrusted_top_level_and_property_sizes_are_checked() { + let original = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap(); + let prop = original.windows(4).position(|w| w == b"PROP").unwrap(); + for offset in [4, 20, prop + 20] { + // FRM8, FVER, nested FS + for size in [u64::MAX, u64::MAX - 31, 1 << 32] { + let mut bytes = original.clone(); + bytes[offset..offset + 8].copy_from_slice(&size.to_be_bytes()); + assert!(read_metadata(&bytes).is_err()); + assert!(read_raw(&bytes).is_err()); + } + } +} + +#[test] +fn dsdiff_invalid_optional_disc_info_is_ignored_without_overflow() { + let mut bytes = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap(); + let expected = read_metadata(&bytes).unwrap(); + bytes.extend_from_slice(b"DIIN"); + bytes.extend_from_slice(&12u64.to_be_bytes()); + bytes.extend_from_slice(b"DITI"); + bytes.extend_from_slice(&u64::MAX.to_be_bytes()); + let size = (bytes.len() - 12) as u64; + bytes[4..12].copy_from_slice(&size.to_be_bytes()); + // Optional malformed text is ignored on 64-bit; unrepresentable sizes may + // be rejected on narrower targets, but must never wrap or panic. + match read_metadata(&bytes) { + Ok(actual) => assert_eq!(actual, expected), + Err(Error::MemoryLimitExceeded) => {} + other => panic!("unexpected result: {other:?}"), + } +} + +#[test] +fn empty_raw_audio_rejects_invalid_decimation_factors() { + let bytes = encode_dsf(2_822_400, &[&[]], 0, 8).unwrap(); + let raw = RawAudio { metadata: read_metadata(&bytes).unwrap(), bit_order: BitOrder::LsbFirst, channel_bytes: Vec::new() }; + for factor in [0, 1, 7, 9, u32::MAX] { + assert!(matches!(raw.to_pcm_with_factor(factor), Err(Error::Unsupported(_)))); + } + for factor in [8, 16, 32, 64] { + assert_eq!(raw.to_pcm_with_factor(factor).unwrap().sample_rate, 2_822_400 / factor); + } +} + +#[test] +fn writers_reject_unbounded_output_before_allocating() { + let channels: [&[u8]; 8] = [&[]; 8]; + for count in [u64::MAX, (craft_audio::dsd::MAX_ENCODE_BYTES as u64 + 1) * 8] { + assert_eq!(encode_dsf(2_822_400, &channels, count, 8), Err(Error::MemoryLimitExceeded)); + assert_eq!(encode_dsdiff(2_822_400, &channels, count), Err(Error::MemoryLimitExceeded)); + } + assert!(matches!(encode_dsf(2_822_400, &[&[]], 0, u32::MAX), Err(Error::InvalidData(_)))); +} + +#[test] +fn encoded_sizes_match_actual_bytes_for_odd_and_even_payloads() { + for channels in 1..=8 { + for len in 0..=9 { + let data = vec![0x69; len]; + let planes = vec![data.as_slice(); channels]; + for block in [0, 1, 3, 8] { + // DSF has channel types for 1 to 6 channels only. + if channels > 6 { + assert!(matches!(encode_dsf(2_822_400, &planes, len as u64 * 8, block), Err(Error::Unsupported(_)))); + continue; + } + let dsf = encode_dsf(2_822_400, &planes, len as u64 * 8, block).unwrap(); + assert_eq!(u64::from_le_bytes(dsf[12..20].try_into().unwrap()), dsf.len() as u64); + assert_eq!(read_raw(&dsf).unwrap().channel_bytes, vec![data.clone(); channels]); + } + let dff = encode_dsdiff(2_822_400, &planes, len as u64 * 8).unwrap(); + assert_eq!(u64::from_be_bytes(dff[4..12].try_into().unwrap()) + 12, dff.len() as u64); + assert_eq!(read_raw(&dff).unwrap().channel_bytes, vec![data; channels]); + } + } +} + +#[test] +fn dsf_audio_stops_at_the_declared_data_chunk() { + for channels in 1..=2 { + let input = vec![&[0x33u8; 8][..]; channels]; + let mut bytes = encode_dsf(2_822_400, &input, 64, 8).unwrap(); + // Ask for an additional block without extending the data chunk. + bytes[64..72].copy_from_slice(&128u64.to_le_bytes()); + let expected = read_raw(&bytes).unwrap(); + for c in &expected.channel_bytes { + assert_eq!(&c[..8], &[0x33; 8]); + assert_eq!(&c[8..], &[0x69; 8]); + } + let metadata_offset = bytes.len() as u64; + bytes[20..28].copy_from_slice(&metadata_offset.to_le_bytes()); + bytes.extend_from_slice(b"ID3\x04\x00\x00\x00\x00\x00\x00"); + bytes.extend_from_slice(&[0xff; 32]); + let file_size = bytes.len() as u64; + bytes[12..20].copy_from_slice(&file_size.to_le_bytes()); + assert_eq!(read_raw(&bytes).unwrap().channel_bytes, expected.channel_bytes); + } +} + +#[test] +fn dsdiff_odd_payload_receives_pad_byte() { + let input = [&[0xaau8; 3][..]]; + let bytes = encode_dsdiff(2_822_400, &input, 24).unwrap(); + let raw = read_raw(&bytes).unwrap(); + assert_eq!(raw.channel_bytes[0].len(), 3); +} + +#[test] +fn dsf_declared_file_size_and_metadata_pointer_bounds() { + let valid = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap(); + + // Undersized file size declaration (e.g. 28) + let mut undersized = valid.clone(); + undersized[12..20].copy_from_slice(&28u64.to_le_bytes()); + assert!(read_metadata(&undersized).is_err()); + assert!(read_raw(&undersized).is_err()); + + // Oversized file size declaration beyond buffer + let mut oversized = valid.clone(); + let big_size = valid.len() as u64 + 100; + oversized[12..20].copy_from_slice(&big_size.to_le_bytes()); + assert!(read_metadata(&oversized).is_err()); + assert!(read_raw(&oversized).is_err()); + + // Metadata pointer outside the declared file bounds + let mut outside_meta = valid.clone(); + let outside_offset = valid.len() as u64 + 10; + outside_meta[20..28].copy_from_slice(&outside_offset.to_le_bytes()); + assert!(read_metadata(&outside_meta).is_err()); + assert!(read_raw(&outside_meta).is_err()); + + // Metadata pointer overlapping data chunk + let mut overlap_meta = valid.clone(); + overlap_meta[20..28].copy_from_slice(&32u64.to_le_bytes()); + assert!(read_metadata(&overlap_meta).is_err()); + assert!(read_raw(&overlap_meta).is_err()); +} + +#[test] +fn dsdiff_channel_count_and_duplicate_chunks_are_validated() { + let base = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap(); + + // Locate PROP chunk payload and CHNL subchunk + let prop_idx = base.windows(4).position(|w| w == b"PROP").unwrap(); + let chnl_idx = base.windows(4).position(|w| w == b"CHNL").unwrap(); + + // 1. Oversized channel count (e.g. 65535 or 9) + let mut bad_count = base.clone(); + bad_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&65535u16.to_be_bytes()); + assert!(matches!(read_metadata(&bad_count), Err(Error::Unsupported(_)))); + assert!(matches!(read_raw(&bad_count), Err(Error::Unsupported(_)))); + + let mut zero_count = base.clone(); + zero_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&0u16.to_be_bytes()); + assert!(matches!(read_metadata(&zero_count), Err(Error::Unsupported(_)))); + + // 2. Conflicting duplicate CHNL chunk in PROP + let mut dup_chnl = base.clone(); + let chnl_chunk = dup_chnl[chnl_idx..chnl_idx + 18].to_vec(); + dup_chnl.splice(chnl_idx..chnl_idx, chnl_chunk); + // Adjust PROP size and FRM8 size + let prop_size = u64::from_be_bytes(dup_chnl[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 18; + dup_chnl[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes()); + let frm8_size = (dup_chnl.len() - 12) as u64; + dup_chnl[4..12].copy_from_slice(&frm8_size.to_be_bytes()); + assert_eq!(read_metadata(&dup_chnl), Err(Error::InvalidHeader("duplicate CHNL chunk"))); + + // 3. Duplicate FS chunk in PROP + let fs_idx = base.windows(4).position(|w| w == b"FS ").unwrap(); + let mut dup_fs = base.clone(); + let fs_chunk = dup_fs[fs_idx..fs_idx + 16].to_vec(); + dup_fs.splice(fs_idx..fs_idx, fs_chunk); + let prop_size = u64::from_be_bytes(dup_fs[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 16; + dup_fs[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes()); + let frm8_size = (dup_fs.len() - 12) as u64; + dup_fs[4..12].copy_from_slice(&frm8_size.to_be_bytes()); + assert_eq!(read_metadata(&dup_fs), Err(Error::InvalidHeader("duplicate FS chunk"))); +} + +#[test] +#[cfg(target_pointer_width = "32")] +fn dsdiff_32bit_padding_overflow_is_rejected() { + let dummy = [&[][..]]; + let result = encode_dsdiff(2_822_400, &dummy, 34_359_738_360); + assert_eq!(result, Err(Error::MemoryLimitExceeded)); +} diff --git a/crates/audio/tests/dsd_metadata.rs b/crates/audio/tests/dsd_metadata.rs new file mode 100644 index 000000000..74fd16f31 --- /dev/null +++ b/crates/audio/tests/dsd_metadata.rs @@ -0,0 +1,155 @@ +//! Channel labels, text metadata and padding in the DSF and DSDIFF readers and writers. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use craft_audio::dsd::{encode_dsdiff, encode_dsf, read_metadata, read_raw}; + +const RATE: u32 = 2_822_400; + +fn planes(channels: usize, len: usize) -> Vec> { + vec![vec![0x69; len]; channels] +} + +fn refs(p: &[Vec]) -> Vec<&[u8]> { + p.iter().map(Vec::as_slice).collect() +} + +#[test] +fn dsdiff_names_surround_channels_by_layout() { + for (n, names) in [ + (5, vec!["Mono/Left", "Right", "Center", "LeftSurround", "RightSurround"]), + (6, vec!["Mono/Left", "Right", "Center", "LFE", "LeftSurround", "RightSurround"]), + ] { + let p = planes(n, 4); + let bytes = encode_dsdiff(RATE, &refs(&p), 32).unwrap(); + assert_eq!(read_metadata(&bytes).unwrap().channel_names, names, "{n} channels"); + } +} + +#[test] +fn dsdiff_odd_audio_is_padded_and_counted_in_the_file_size() { + let p = planes(1, 1); + let bytes = encode_dsdiff(RATE, &refs(&p), 8).unwrap(); + assert_eq!(bytes.len() % 2, 0); + assert_eq!(u64::from_be_bytes(bytes[4..12].try_into().unwrap()) + 12, bytes.len() as u64); + assert_eq!(*bytes.last().unwrap(), 0, "pad byte"); + assert_eq!(read_raw(&bytes).unwrap().channel_bytes, vec![vec![0x69]]); +} + +fn with_diin(mut bytes: Vec, sub: &[u8; 4], payload: &[u8]) -> Vec { + let mut sub_chunk = Vec::new(); + sub_chunk.extend_from_slice(sub); + sub_chunk.extend_from_slice(&(payload.len() as u64).to_be_bytes()); + sub_chunk.extend_from_slice(payload); + if payload.len() % 2 == 1 { + sub_chunk.push(0); + } + bytes.extend_from_slice(b"DIIN"); + bytes.extend_from_slice(&(sub_chunk.len() as u64).to_be_bytes()); + bytes.extend_from_slice(&sub_chunk); + let size = (bytes.len() - 12) as u64; + bytes[4..12].copy_from_slice(&size.to_be_bytes()); + bytes +} + +#[test] +fn dsdiff_title_and_artist_skip_the_character_count() { + let p = planes(2, 4); + let base = encode_dsdiff(RATE, &refs(&p), 32).unwrap(); + let mut payload = 4u32.to_be_bytes().to_vec(); + payload.extend_from_slice(b"Test"); + let bytes = with_diin(base.clone(), b"DITI", &payload); + assert_eq!(read_metadata(&bytes).unwrap().title.as_deref(), Some("Test")); + let bytes = with_diin(base.clone(), b"DIAR", &payload); + assert_eq!(read_metadata(&bytes).unwrap().artist.as_deref(), Some("Test")); + // A count longer than the chunk is not text. + let mut bad = 99u32.to_be_bytes().to_vec(); + bad.extend_from_slice(b"Test"); + assert_eq!(read_metadata(&with_diin(base, b"DITI", &bad)).unwrap().title, None); +} + +#[test] +fn dsf_channel_types_match_the_channel_count() { + for (n, expect) in [(1, 1), (2, 2), (3, 3), (4, 4), (5, 6), (6, 7)] { + let p = planes(n, 4); + let bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + assert_eq!(u32::from_le_bytes(bytes[48..52].try_into().unwrap()), expect, "{n} channels"); + assert_eq!(read_metadata(&bytes).unwrap().channel_names.len(), n); + } + let p = planes(7, 4); + assert!(encode_dsf(RATE, &refs(&p), 32, 4096).is_err()); +} + +#[test] +fn dsf_type_5_names_the_fourth_channel_lfe() { + let p = planes(4, 4); + let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + bytes[48..52].copy_from_slice(&5u32.to_le_bytes()); + assert_eq!(read_metadata(&bytes).unwrap().channel_names, ["FrontLeft", "FrontRight", "Center", "LFE"]); +} + +fn id3(version: u8, frames: &[u8]) -> Vec { + let n = frames.len(); + let mut tag = vec![b'I', b'D', b'3', version, 0, 0]; + tag.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]); + tag.extend_from_slice(frames); + tag +} + +fn frame(version: u8, id: &[u8; 4], body: &[u8]) -> Vec { + let n = body.len(); + let mut f = id.to_vec(); + if version >= 4 { + f.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]); + } else { + f.extend_from_slice(&(n as u32).to_be_bytes()); + } + f.extend_from_slice(&[0, 0]); + f.extend_from_slice(body); + f +} + +fn dsf_with_tag(tag: &[u8]) -> Vec { + let p = planes(2, 4); + let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + let offset = bytes.len() as u64; + bytes[20..28].copy_from_slice(&offset.to_le_bytes()); + bytes.extend_from_slice(tag); + let file_size = bytes.len() as u64; + bytes[12..20].copy_from_slice(&file_size.to_le_bytes()); + bytes +} + +#[test] +fn id3v24_frame_sizes_are_synchsafe() { + // A 128-byte frame has the synchsafe size 00 00 01 00; read as plain big-endian it is 256. + let mut frames = frame(4, b"APIC", &[0u8; 128]); + let mut title = vec![3]; + title.extend_from_slice(b"After art"); + frames.extend(frame(4, b"TIT2", &title)); + let m = read_metadata(&dsf_with_tag(&id3(4, &frames))).unwrap(); + assert_eq!(m.title.as_deref(), Some("After art")); +} + +#[test] +fn id3v23_frame_sizes_stay_big_endian() { + let mut frames = frame(3, b"APIC", &[0u8; 128]); + let mut title = vec![3]; + title.extend_from_slice(b"Three"); + frames.extend(frame(3, b"TIT2", &title)); + let m = read_metadata(&dsf_with_tag(&id3(3, &frames))).unwrap(); + assert_eq!(m.title.as_deref(), Some("Three")); +} + +#[test] +fn id3_text_encodings() { + let cases: [(&[u8], &str); 5] = [ + (b"\x00Caf\xe9", "Café"), + (b"\x03Caf\xc3\xa9", "Café"), + (b"\x02\x00A\x00B", "AB"), + (b"\x01\xFF\xFEA\x00B\x00", "AB"), + (b"\x01\xFE\xFF\x00A\x00B", "AB"), + ]; + for (body, expect) in cases { + let m = read_metadata(&dsf_with_tag(&id3(4, &frame(4, b"TIT2", body)))).unwrap(); + assert_eq!(m.title.as_deref(), Some(expect), "{body:?}"); + } +} diff --git a/crates/audio/tests/dsd_oracle.rs b/crates/audio/tests/dsd_oracle.rs new file mode 100644 index 000000000..94334485b --- /dev/null +++ b/crates/audio/tests/dsd_oracle.rs @@ -0,0 +1,347 @@ +//! DSD (DSF and DSDIFF) decoding and decimation tests, including oracle tests against FFmpeg +//! (skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). + +use craft_audio::dsd::{BitOrder, Format, decode, decode_with_factor, encode_dsdiff, encode_dsf, filter::SILENCE_LSBF, read_metadata, read_raw}; +use std::process::Command; + +/// Generates a test DSD 1-bit stream with various features (silence, alternating tones, noise). +fn make_test_stream(num_bytes: usize, seed: u8) -> Vec { + let mut out = Vec::with_capacity(num_bytes); + let mut s = seed as u32; + for i in 0..num_bytes { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + let byte = match (i / 128) % 4 { + 0 => SILENCE_LSBF, // DSD silence + 1 => 0x55, // Alternate silence pattern + 2 => (s & 0xFF) as u8, + _ => { + if (i / 16) % 2 == 0 { + 0xFF // full positive level + } else { + 0x00 // full negative level + } + } + }; + out.push(byte); + } + out +} + +#[test] +fn roundtrip_dsf() { + let sample_rate = 2_822_400; + let block_size = 4096; + let ch0 = make_test_stream(8192, 42); + let ch1 = make_test_stream(8192, 99); + let sample_count = 8192 * 8; + + let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf"); + + let meta = read_metadata(&dsf_bytes).expect("read_metadata"); + assert_eq!(meta.format, Format::Dsf); + assert_eq!(meta.sample_rate, sample_rate); + assert_eq!(meta.channels, 2); + assert_eq!(meta.sample_count, sample_count); + + let raw = read_raw(&dsf_bytes).expect("read_raw"); + assert_eq!(raw.bit_order, BitOrder::LsbFirst); + assert_eq!(raw.channel_bytes.len(), 2); + assert_eq!(raw.channel_bytes[0], ch0); + assert_eq!(raw.channel_bytes[1], ch1); + + let decoded = decode(&dsf_bytes).expect("decode"); + assert_eq!(decoded.sample_rate, sample_rate / 8); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 8192); + assert_eq!(decoded.channels[1].len(), 8192); +} + +#[test] +fn roundtrip_dsdiff() { + let sample_rate = 2_822_400; + let ch0 = make_test_stream(4096, 17); + let ch1 = make_test_stream(4096, 73); + let sample_count = 4096 * 8; + + let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff"); + + let meta = read_metadata(&dff_bytes).expect("read_metadata"); + assert_eq!(meta.format, Format::Dsdiff); + assert_eq!(meta.sample_rate, sample_rate); + assert_eq!(meta.channels, 2); + assert_eq!(meta.sample_count, sample_count); + + let raw = read_raw(&dff_bytes).expect("read_raw"); + assert_eq!(raw.bit_order, BitOrder::MsbFirst); + assert_eq!(raw.channel_bytes.len(), 2); + assert_eq!(raw.channel_bytes[0], ch0); + assert_eq!(raw.channel_bytes[1], ch1); + + let decoded = decode(&dff_bytes).expect("decode"); + assert_eq!(decoded.sample_rate, sample_rate / 8); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 4096); + assert_eq!(decoded.channels[1].len(), 4096); +} + +#[test] +fn decimation_factors() { + let sample_rate = 2_822_400; + let ch0 = make_test_stream(2048, 123); + let dsf_bytes = encode_dsf(sample_rate, &[&ch0], 2048 * 8, 4096).expect("encode_dsf"); + + // Factor 8 -> 352,800 Hz + let dec8 = decode_with_factor(&dsf_bytes, 8).expect("factor 8"); + assert_eq!(dec8.sample_rate, 352_800); + assert_eq!(dec8.channels[0].len(), 2048); + + // Factor 16 -> 176,400 Hz + let dec16 = decode_with_factor(&dsf_bytes, 16).expect("factor 16"); + assert_eq!(dec16.sample_rate, 176_400); + assert_eq!(dec16.channels[0].len(), 1024); + + // Factor 32 -> 88,200 Hz + let dec32 = decode_with_factor(&dsf_bytes, 32).expect("factor 32"); + assert_eq!(dec32.sample_rate, 88_200); + assert_eq!(dec32.channels[0].len(), 512); + + // Factor 64 -> 44,100 Hz + let dec64 = decode_with_factor(&dsf_bytes, 64).expect("factor 64"); + assert_eq!(dec64.sample_rate, 44_100); + assert_eq!(dec64.channels[0].len(), 256); + + // Invalid factor + assert!(decode_with_factor(&dsf_bytes, 12).is_err()); +} + +#[test] +fn silence_and_dc_levels() { + let sample_rate = 2_822_400; + // Pure silence + let silence = vec![SILENCE_LSBF; 1024]; + let dsf_bytes = encode_dsf(sample_rate, &[&silence], 1024 * 8, 4096).expect("encode"); + let dec = decode(&dsf_bytes).expect("decode"); + for &sample in &dec.channels[0][12..] { + assert!(sample.abs() < 1e-4, "silence sample should be ~0.0, got {sample}"); + } + + // Full positive level + let ones = vec![0xFF; 1024]; + let dsf_ones = encode_dsf(sample_rate, &[&ones], 1024 * 8, 4096).expect("encode"); + let dec_ones = decode(&dsf_ones).expect("decode"); + for &sample in &dec_ones.channels[0][12..] { + assert!((sample - 1.0).abs() < 1e-4, "ones sample should be ~1.0, got {sample}"); + } + + // Full negative level + let zeros = vec![0x00; 1024]; + let dsf_zeros = encode_dsf(sample_rate, &[&zeros], 1024 * 8, 4096).expect("encode"); + let dec_zeros = decode(&dsf_zeros).expect("decode"); + for &sample in &dec_zeros.channels[0][12..] { + assert!((sample - (-1.0)).abs() < 1e-4, "zeros sample should be ~-1.0, got {sample}"); + } +} + +#[test] +fn multichannel_dsf_and_dsdiff() { + let sample_rate = 2_822_400; + // Test 6-channel (5.1 surround) + let channels: Vec> = (0..6).map(|c| make_test_stream(1024, (c * 23 + 5) as u8)).collect(); + let ch_refs: Vec<&[u8]> = channels.iter().map(Vec::as_slice).collect(); + + let dsf = encode_dsf(sample_rate, &ch_refs, 1024 * 8, 512).expect("encode 5.1 dsf"); + let dsf_meta = read_metadata(&dsf).expect("meta 5.1 dsf"); + assert_eq!(dsf_meta.channels, 6); + let dsf_dec = decode(&dsf).expect("decode 5.1 dsf"); + assert_eq!(dsf_dec.channels.len(), 6); + assert_eq!(dsf_dec.channels[0].len(), 1024); + + let dff = encode_dsdiff(sample_rate, &ch_refs, 1024 * 8).expect("encode 5.1 dsdiff"); + let dff_meta = read_metadata(&dff).expect("meta 5.1 dsdiff"); + assert_eq!(dff_meta.channels, 6); + let dff_dec = decode(&dff).expect("decode 5.1 dsdiff"); + assert_eq!(dff_dec.channels.len(), 6); + assert_eq!(dff_dec.channels[0].len(), 1024); +} + +#[test] +fn dst_compression_rejected() { + // Construct a minimal DSDIFF with CMPR = 'DST ' + let mut dff = encode_dsdiff(2_822_400, &[&[0xAA; 64]], 512).expect("encode"); + // Find 'DSD ' in CMPR chunk and replace with 'DST ' + let mut replaced = false; + for i in 0..dff.len().saturating_sub(8) { + if &dff[i..i + 4] == b"CMPR" && &dff[i + 12..i + 16] == b"DSD " { + dff[i + 12..i + 16].copy_from_slice(b"DST "); + replaced = true; + break; + } + } + assert!(replaced, "should find CMPR DSD chunk"); + assert!(read_metadata(&dff).is_err(), "DST compression should be rejected as unsupported"); + assert!(decode(&dff).is_err(), "DST compression should be rejected as unsupported"); +} + +#[test] +fn id3v2_tag_in_dsf() { + let sample_rate = 2_822_400; + let mut dsf = encode_dsf(sample_rate, &[&[0x69; 128]], 1024, 512).expect("encode"); + let metadata_offset = dsf.len() as u64; + + // Append simple ID3v2.3 tag with TIT2="Test Title" and TPE1="Test Artist" + let mut id3 = Vec::new(); + id3.extend_from_slice(b"ID3"); + id3.push(3); // v2.3 + id3.push(0); // revision + id3.push(0); // flags + + let mut frames = Vec::new(); + // TIT2 frame + frames.extend_from_slice(b"TIT2"); + let title_bytes = b"\x03DSD Master"; // UTF-8 + frames.extend_from_slice(&(title_bytes.len() as u32).to_be_bytes()); + frames.extend_from_slice(&[0, 0]); // flags + frames.extend_from_slice(title_bytes); + + // TPE1 frame + frames.extend_from_slice(b"TPE1"); + let artist_bytes = b"\x03The Audiophiles"; + frames.extend_from_slice(&(artist_bytes.len() as u32).to_be_bytes()); + frames.extend_from_slice(&[0, 0]); // flags + frames.extend_from_slice(artist_bytes); + + // synchsafe size + let tag_len = frames.len(); + id3.push(((tag_len >> 21) & 0x7F) as u8); + id3.push(((tag_len >> 14) & 0x7F) as u8); + id3.push(((tag_len >> 7) & 0x7F) as u8); + id3.push((tag_len & 0x7F) as u8); + id3.extend_from_slice(&frames); + + dsf.extend_from_slice(&id3); + // Update file size and metadata_offset of 'DSD ' chunk + let file_size = dsf.len() as u64; + dsf[12..20].copy_from_slice(&file_size.to_le_bytes()); + dsf[20..28].copy_from_slice(&metadata_offset.to_le_bytes()); + + let meta = read_metadata(&dsf).expect("read metadata with ID3"); + assert_eq!(meta.title.as_deref(), Some("DSD Master")); + assert_eq!(meta.artist.as_deref(), Some("The Audiophiles")); +} + +#[test] +fn raw_audio_bit_order_conversion() { + let ch0 = vec![0b00000001, 0b10000000]; + let dsf = encode_dsf(2_822_400, &[&ch0], 16, 512).expect("encode"); + let mut raw = read_raw(&dsf).expect("read raw"); + assert_eq!(raw.bit_order, BitOrder::LsbFirst); + assert_eq!(raw.channel_bytes[0], ch0); + + raw.convert_bit_order(BitOrder::MsbFirst); + assert_eq!(raw.bit_order, BitOrder::MsbFirst); + assert_eq!(raw.channel_bytes[0], vec![0b10000000, 0b00000001]); +} + +#[test] +fn hostile_inputs() { + // Truncated headers + assert!(read_metadata(b"").is_err()); + assert!(read_metadata(b"DSD ").is_err()); + assert!(read_metadata(b"FRM8").is_err()); + + // Bad magic + assert!(read_metadata(b"RIFF\x00\x00\x00\x00WAVE").is_err()); + + // Truncated DSF chunk + let mut bad_dsf = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode"); + bad_dsf.truncate(50); + assert!(decode(&bad_dsf).is_err()); + + // Corrupted fmt chunk size + let mut bad_fmt = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode"); + bad_fmt[32] = 0; // bits_per_sample = 0 + assert!(decode(&bad_fmt).is_err()); + + // Absurd channels + let mut bad_ch = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode"); + bad_ch[28 + 24] = 99; // channel_count = 99 + assert!(decode(&bad_ch).is_err()); +} + +#[test] +fn ffmpeg_dsf_oracle() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("dsd"); + + let sample_rate = 2_822_400; + let block_size = 4096; + let ch0 = make_test_stream(16384, 11); + let ch1 = make_test_stream(16384, 88); + let sample_count = 16384 * 8; + + let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf"); + let dsf_path = dir.join("test_oracle.dsf"); + std::fs::write(&dsf_path, &dsf_bytes).expect("write fixture"); + + let raw_out_path = dir.join("ffmpeg_dsf.raw"); + let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dsf_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg"); + assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr)); + + let raw_bytes = std::fs::read(&raw_out_path).expect("read raw"); + let ffmpeg_floats: Vec = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + + let decoded = decode(&dsf_bytes).expect("our decode"); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 16384); + assert_eq!(decoded.channels[1].len(), 16384); + + // FFmpeg interleaves L0, R0, L1, R1... + // Compare samples after filter startup (sample 12 onwards). + for i in 12..16000 { + let ff_l = ffmpeg_floats[i * 2]; + let ff_r = ffmpeg_floats[i * 2 + 1]; + let our_l = decoded.channels[0][i]; + let our_r = decoded.channels[1][i]; + + assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}"); + assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}"); + } +} + +#[test] +fn ffmpeg_dsdiff_oracle() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("dsd"); + + let sample_rate = 2_822_400; + let ch0 = make_test_stream(8192, 33); + let ch1 = make_test_stream(8192, 77); + let sample_count = 8192 * 8; + + let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff"); + let dff_path = dir.join("test_oracle.dff"); + std::fs::write(&dff_path, &dff_bytes).expect("write fixture"); + + let raw_out_path = dir.join("ffmpeg_dff.raw"); + let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dff_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg"); + assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr)); + + let raw_bytes = std::fs::read(&raw_out_path).expect("read raw"); + let ffmpeg_floats: Vec = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + + let decoded = decode(&dff_bytes).expect("our decode"); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 8192); + + for i in 12..8000 { + let ff_l = ffmpeg_floats[i * 2]; + let ff_r = ffmpeg_floats[i * 2 + 1]; + let our_l = decoded.channels[0][i]; + let our_r = decoded.channels[1][i]; + + assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}"); + assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}"); + } +} diff --git a/crates/audio/tests/main.rs b/crates/audio/tests/main.rs index a1bd3d933..5470dc553 100644 --- a/crates/audio/tests/main.rs +++ b/crates/audio/tests/main.rs @@ -9,6 +9,15 @@ mod audio; #[cfg(all(feature = "decode", feature = "encode"))] #[path = "codecs/main.rs"] mod codecs; +#[cfg(feature = "dsd")] +#[path = "dsd_bounds.rs"] +mod dsd_bounds; +#[cfg(feature = "dsd")] +#[path = "dsd_metadata.rs"] +mod dsd_metadata; +#[cfg(feature = "dsd")] +#[path = "dsd_oracle.rs"] +mod dsd_oracle; #[cfg(all(feature = "flac-decode", feature = "flac-encode"))] #[path = "flac_decode.rs"] mod flac_decode; diff --git a/crates/behavior/src/keys.rs b/crates/behavior/src/keys.rs index 5c8bf19da..a24e52bf5 100644 --- a/crates/behavior/src/keys.rs +++ b/crates/behavior/src/keys.rs @@ -8,7 +8,7 @@ use craft_host::target::Os; use craft_keymap::{Chord, Key, Mods}; /// What the focused stop is, as far as the table's rows differ. -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct KeyRole { /// A value control with a reset value and no text part: Delete resets it. diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index cd09f7e16..1136f55f9 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -10,6 +10,11 @@ repository.workspace = true [lints] workspace = true +[features] +default = [] +# MP4 timed text (3GPP TS 26.245 / mov_text / tx3g) sample codec. +mov-text = [] + [dependencies] craft-timeline = { workspace = true } craft-xml = { workspace = true } @@ -21,3 +26,5 @@ proptest = { workspace = true } roxmltree = "0.21" # ffmpeg as the reference for the ASS tests (tests/it/ass.rs). craft-media-testkit = { workspace = true } +# craft-media isobmff for mov_text oracle demuxing/muxing tests. +craft-media = { workspace = true, features = ["isobmff"] } diff --git a/crates/captions/README.md b/crates/captions/README.md index 7380a3ce4..b2f6a195f 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -27,6 +27,10 @@ assert!(scc.starts_with(b"Scenarist_SCC V1.0")); and the SMPTE ST 334-2 caption distribution packet. - `plain_text` strips inline tags and decodes the common entities, for display or for formats without markup. +- Optional feature `mov-text` provides MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245) + sample decoding, encoding, modifier box parsing (`styl`, `hlit`, `hclr`, `krok`, `dlay`, `href`, + `tbox`, `blnk`, `wrap`), and `Tx3gConfig` sample entry parsing/writing for ISO BMFF (`.mp4`) and + QuickTime (`.mov`) subtitle tracks. ## Time diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index 9d085854d..612aa6f13 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -36,6 +36,8 @@ pub mod ass; pub mod cea608; pub mod jacosub; pub mod mcc; +#[cfg(feature = "mov-text")] +pub mod mov_text; pub mod pjs; pub mod realtext; pub mod scc; diff --git a/crates/captions/src/mov_text.rs b/crates/captions/src/mov_text.rs new file mode 100644 index 000000000..d1a3ce2a9 --- /dev/null +++ b/crates/captions/src/mov_text.rs @@ -0,0 +1,871 @@ +//! MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245). +//! +//! A clean-room reader and writer for 3GPP Timed Text subtitle samples and sample entry +//! configurations (`tx3g`), as carried in ISO BMFF (`.mp4`) and QuickTime (`.mov`) files. +//! +//! ## Sample Structure +//! +//! A timed text sample consists of: +//! - A 16-bit big-endian text length. +//! - The text string bytes (UTF-8, or UTF-16 with BOM). +//! - Zero or more modifier boxes: +//! - `styl`: Character style runs (bold, italic, underline, font ID, font size, text color). +//! - `hlit`: Highlighted character range. +//! - `hclr`: Highlight color (RGBA). +//! - `krok`: Karaoke highlight timing and character spans. +//! - `dlay`: Scroll delay in track-timescale ticks. +//! - `href`: Hypertext link URL and alt text. +//! - `tbox`: Text box override coordinates (`top, left, bottom, right`). +//! - `blnk`: Blinking text character range. +//! - `twrp`: Text wrap flag (0 = no wrap, 1 = automatic soft wrap). +//! +//! ## Style Flags +//! +//! Style flags in `styl` records: +//! - `0x01`: Bold (`...`) +//! - `0x02`: Italic (`...`) +//! - `0x04`: Underline (`...`) + +use crate::time::Tick; +use crate::{Cue, Document, TICKS_PER_SECOND}; + +/// What went wrong reading or writing timed text. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The input slice is shorter than the declared field or box size. + #[error("truncated timed text data")] + Truncated, + /// The text payload is not valid UTF-8 and contains no valid UTF-16 BOM. + #[error("invalid text encoding in timed text sample")] + InvalidText, + /// The text exceeds the 16-bit length prefix (65,535 bytes). + #[error("timed text string exceeds 65535 bytes: {0}")] + TextTooLong(usize), + /// A modifier box header has an invalid size (< 8). + #[error("invalid modifier box size: {0}")] + InvalidBox(&'static str), +} + +/// `Result` alias for timed text operations. +pub type Result = std::result::Result; + +/// Face style flag: Bold (`0x01`). +pub const STYLE_FLAG_BOLD: u8 = 0x01; +/// Face style flag: Italic (`0x02`). +pub const STYLE_FLAG_ITALIC: u8 = 0x02; +/// Face style flag: Underline (`0x04`). +pub const STYLE_FLAG_UNDERLINE: u8 = 0x04; + +/// A character styling record within a `styl` box. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StyleRecord { + /// 0-indexed start character index (inclusive, measured in Unicode scalar values). + pub start_char: u16, + /// 0-indexed end character index (exclusive, measured in Unicode scalar values). + pub end_char: u16, + /// 16-bit font ID matching an entry in the sample description font table (`ftab`). + pub font_id: u16, + /// Face style flags: bit 0 = bold, bit 1 = italic, bit 2 = underline. + pub face_style_flags: u8, + /// Font size in points. + pub font_size: u8, + /// Text RGBA color (`[r, g, b, a]`). + pub text_color_rgba: [u8; 4], +} + +impl Default for StyleRecord { + fn default() -> Self { + Self { start_char: 0, end_char: 0, font_id: 1, face_style_flags: 0, font_size: 16, text_color_rgba: [255, 255, 255, 255] } + } +} + +impl StyleRecord { + /// Returns `true` if bold is set. + pub fn is_bold(&self) -> bool { + self.face_style_flags & STYLE_FLAG_BOLD != 0 + } + + /// Returns `true` if italic is set. + pub fn is_italic(&self) -> bool { + self.face_style_flags & STYLE_FLAG_ITALIC != 0 + } + + /// Returns `true` if underline is set. + pub fn is_underline(&self) -> bool { + self.face_style_flags & STYLE_FLAG_UNDERLINE != 0 + } +} + +/// Coordinates of a text display box (`tbox`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TextBox { + pub top: i16, + pub left: i16, + pub bottom: i16, + pub right: i16, +} + +/// An entry in a karaoke box (`krok`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct KaraokeEntry { + /// Highlight end time in timescale ticks. + pub highlight_end_time: u32, + /// Start character index (inclusive). + pub start_char: u16, + /// End character index (exclusive). + pub end_char: u16, +} + +/// A hypertext link entry (`href`). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HyperText { + /// Start character index (inclusive). + pub start_char: u16, + /// End character index (exclusive). + pub end_char: u16, + /// Destination URL. + pub url: String, + /// Accessible alt text string. + pub alt_string: String, +} + +/// An unpacked 3GPP Timed Text (`tx3g` / `mov_text`) sample. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TextSample { + /// Decoded UTF-8 text content. + pub text: String, + /// Character styling records from the `styl` box. + pub styles: Vec, + /// Highlighted character range `(start_char, end_char)` from `hlit`. + pub highlight: Option<(u16, u16)>, + /// Highlight color `[r, g, b, a]` from `hclr`. + pub highlight_color: Option<[u8; 4]>, + /// Karaoke timing and spans `(highlight_start_time, entries)` from `krok`. + pub karaoke: Option<(u32, Vec)>, + /// Scroll delay in milliseconds from `dlay`. + pub scroll_delay: Option, + /// Hypertext links from `href` boxes. + pub hypertext: Vec, + /// Text box override from `tbox`. + pub text_box: Option, + /// Blinking character ranges `(start_char, end_char)` from `blnk` boxes. + pub blinking: Vec<(u16, u16)>, + /// Wrap flag from `wrap` box: `0` = automatic wrap, `1` = no wrap. + pub wrap_flag: Option, +} + +/// Sample description table configuration for a `tx3g` track. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Tx3gConfig { + /// 32-bit display flags (e.g. scroll in, scroll out, continuous scroll). + pub display_flags: u32, + /// Horizontal justification: 0 = left, 1 = center, -1 = right. + pub horizontal_justification: i8, + /// Vertical justification: 0 = top, 1 = center, -1 = bottom. + pub vertical_justification: i8, + /// Background RGBA color. + pub background_color: [u8; 4], + /// Default text box coordinates. + pub default_text_box: TextBox, + /// Default style record. + pub default_style: StyleRecord, + /// Font table entries `(font_id, font_name)`. + pub fonts: Vec<(u16, String)>, +} + +impl Default for Tx3gConfig { + fn default() -> Self { + Self { + display_flags: 0, + horizontal_justification: 1, // center + vertical_justification: -1, // bottom + background_color: [0, 0, 0, 255], + default_text_box: TextBox::default(), + default_style: StyleRecord::default(), + fonts: vec![(1, "Arial".to_string())], + } + } +} + +impl Tx3gConfig { + /// Parse a `tx3g` sample entry payload (after the standard 8-byte sample entry header). + pub fn parse(payload: &[u8]) -> Result { + if payload.len() < 30 { + return Err(Error::Truncated); + } + let display_flags = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]); + let horizontal_justification = payload[4] as i8; + let vertical_justification = payload[5] as i8; + let background_color = [payload[6], payload[7], payload[8], payload[9]]; + + let default_text_box = TextBox { + top: i16::from_be_bytes([payload[10], payload[11]]), + left: i16::from_be_bytes([payload[12], payload[13]]), + bottom: i16::from_be_bytes([payload[14], payload[15]]), + right: i16::from_be_bytes([payload[16], payload[17]]), + }; + + let default_style = StyleRecord { + start_char: u16::from_be_bytes([payload[18], payload[19]]), + end_char: u16::from_be_bytes([payload[20], payload[21]]), + font_id: u16::from_be_bytes([payload[22], payload[23]]), + face_style_flags: payload[24], + font_size: payload[25], + text_color_rgba: [payload[26], payload[27], payload[28], payload[29]], + }; + + let mut fonts = Vec::new(); + let mut pos = 30; + while pos + 8 <= payload.len() { + let box_size = u32::from_be_bytes([payload[pos], payload[pos + 1], payload[pos + 2], payload[pos + 3]]) as usize; + if box_size < 8 || pos.checked_add(box_size).is_none_or(|end| end > payload.len()) { + break; + } + let box_type = &payload[pos + 4..pos + 8]; + if box_type == b"ftab" && box_size >= 10 { + let count = u16::from_be_bytes([payload[pos + 8], payload[pos + 9]]) as usize; + let mut fpos = pos + 10; + for _ in 0..count { + if fpos + 3 > pos + box_size { + break; + } + let font_id = u16::from_be_bytes([payload[fpos], payload[fpos + 1]]); + let name_len = payload[fpos + 2] as usize; + fpos += 3; + if fpos + name_len > pos + box_size { + break; + } + if let Ok(name) = std::str::from_utf8(&payload[fpos..fpos + name_len]) { + fonts.push((font_id, name.to_string())); + } + fpos += name_len; + } + } + pos += box_size; + } + + Ok(Self { display_flags, horizontal_justification, vertical_justification, background_color, default_text_box, default_style, fonts }) + } + + /// Write the `tx3g` sample entry payload (after the 8-byte sample entry header). + pub fn write(&self) -> Vec { + let mut out = Vec::with_capacity(30 + 32); + out.extend_from_slice(&self.display_flags.to_be_bytes()); + out.push(self.horizontal_justification as u8); + out.push(self.vertical_justification as u8); + out.extend_from_slice(&self.background_color); + + out.extend_from_slice(&self.default_text_box.top.to_be_bytes()); + out.extend_from_slice(&self.default_text_box.left.to_be_bytes()); + out.extend_from_slice(&self.default_text_box.bottom.to_be_bytes()); + out.extend_from_slice(&self.default_text_box.right.to_be_bytes()); + + out.extend_from_slice(&self.default_style.start_char.to_be_bytes()); + out.extend_from_slice(&self.default_style.end_char.to_be_bytes()); + out.extend_from_slice(&self.default_style.font_id.to_be_bytes()); + out.push(self.default_style.face_style_flags); + out.push(self.default_style.font_size); + out.extend_from_slice(&self.default_style.text_color_rgba); + + // ftab box + let mut ftab_payload = Vec::new(); + let fonts = &self.fonts[..self.fonts.len().min(u16::MAX as usize)]; + ftab_payload.extend_from_slice(&(fonts.len() as u16).to_be_bytes()); + for (id, name) in fonts { + ftab_payload.extend_from_slice(&id.to_be_bytes()); + let name_bytes = name.as_bytes(); + let limit = name.floor_char_boundary(name_bytes.len().min(255)); + ftab_payload.push(limit as u8); + ftab_payload.extend_from_slice(&name_bytes[..limit]); + } + let ftab_size = 8u32.saturating_add(ftab_payload.len() as u32); + out.extend_from_slice(&ftab_size.to_be_bytes()); + out.extend_from_slice(b"ftab"); + out.extend_from_slice(&ftab_payload); + + out + } +} + +/// Read and decode a single 3GPP Timed Text sample (`tx3g` / `mov_text`). +pub fn read_sample(data: &[u8]) -> Result { + if data.len() < 2 { + return Err(Error::Truncated); + } + + let text_len = u16::from_be_bytes([data[0], data[1]]) as usize; + if data.len() < 2 + text_len { + return Err(Error::Truncated); + } + + let text_bytes = &data[2..2 + text_len]; + let text = decode_text(text_bytes)?; + + let mut sample = TextSample { text, ..Default::default() }; + + let mut pos = 2 + text_len; + while pos + 8 <= data.len() { + let size = u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; + if size < 8 { + return Err(Error::InvalidBox("size smaller than 8")); + } + let box_end = pos.checked_add(size).ok_or(Error::Truncated)?; + if box_end > data.len() { + return Err(Error::Truncated); + } + + let box_type = &data[pos + 4..pos + 8]; + let payload = &data[pos + 8..box_end]; + + match box_type { + b"styl" => { + if payload.len() < 2 { + return Err(Error::Truncated); + } + let count = u16::from_be_bytes([payload[0], payload[1]]) as usize; + let mut spos = 2; + for _ in 0..count { + if spos + 12 > payload.len() { + return Err(Error::Truncated); + } + sample.styles.push(StyleRecord { + start_char: u16::from_be_bytes([payload[spos], payload[spos + 1]]), + end_char: u16::from_be_bytes([payload[spos + 2], payload[spos + 3]]), + font_id: u16::from_be_bytes([payload[spos + 4], payload[spos + 5]]), + face_style_flags: payload[spos + 6], + font_size: payload[spos + 7], + text_color_rgba: [payload[spos + 8], payload[spos + 9], payload[spos + 10], payload[spos + 11]], + }); + spos += 12; + } + } + b"hlit" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + let start = u16::from_be_bytes([payload[0], payload[1]]); + let end = u16::from_be_bytes([payload[2], payload[3]]); + sample.highlight = Some((start, end)); + } + b"hclr" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + sample.highlight_color = Some([payload[0], payload[1], payload[2], payload[3]]); + } + b"krok" => { + if payload.len() < 6 { + return Err(Error::Truncated); + } + let start_time = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]); + let count = u16::from_be_bytes([payload[4], payload[5]]) as usize; + let mut entries = Vec::new(); + let mut kpos = 6; + for _ in 0..count { + if kpos + 8 > payload.len() { + return Err(Error::Truncated); + } + entries.push(KaraokeEntry { + highlight_end_time: u32::from_be_bytes([payload[kpos], payload[kpos + 1], payload[kpos + 2], payload[kpos + 3]]), + start_char: u16::from_be_bytes([payload[kpos + 4], payload[kpos + 5]]), + end_char: u16::from_be_bytes([payload[kpos + 6], payload[kpos + 7]]), + }); + kpos += 8; + } + sample.karaoke = Some((start_time, entries)); + } + b"dlay" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + sample.scroll_delay = Some(u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]])); + } + b"href" => { + if payload.len() < 6 { + return Err(Error::Truncated); + } + let start = u16::from_be_bytes([payload[0], payload[1]]); + let end = u16::from_be_bytes([payload[2], payload[3]]); + let url_len = payload[4] as usize; + if 5 + url_len > payload.len() { + return Err(Error::Truncated); + } + let url = std::str::from_utf8(&payload[5..5 + url_len]).map_err(|_| Error::InvalidText)?.to_string(); + let alt_pos = 5 + url_len; + let alt_len = payload.get(alt_pos).copied().unwrap_or(0) as usize; + let alt_string = if alt_len > 0 && alt_pos + 1 + alt_len <= payload.len() { + std::str::from_utf8(&payload[alt_pos + 1..alt_pos + 1 + alt_len]).map_err(|_| Error::InvalidText)?.to_string() + } else { + String::new() + }; + sample.hypertext.push(HyperText { start_char: start, end_char: end, url, alt_string }); + } + b"tbox" => { + if payload.len() < 8 { + return Err(Error::Truncated); + } + sample.text_box = Some(TextBox { + top: i16::from_be_bytes([payload[0], payload[1]]), + left: i16::from_be_bytes([payload[2], payload[3]]), + bottom: i16::from_be_bytes([payload[4], payload[5]]), + right: i16::from_be_bytes([payload[6], payload[7]]), + }); + } + b"blnk" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + let start = u16::from_be_bytes([payload[0], payload[1]]); + let end = u16::from_be_bytes([payload[2], payload[3]]); + sample.blinking.push((start, end)); + } + b"twrp" | b"wrap" => { + if payload.is_empty() { + return Err(Error::Truncated); + } + sample.wrap_flag = Some(payload[0]); + } + _ => { + // Unknown modifier box: safely ignored. + } + } + + pos = box_end; + } + + Ok(sample) +} + +/// Helper to decode UTF-8 or UTF-16 with BOM. +fn decode_text(bytes: &[u8]) -> Result { + if bytes.len() >= 2 { + if bytes[0] == 0xFE && bytes[1] == 0xFF { + // UTF-16 BE + let u16s: Vec = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); + return String::from_utf16(&u16s).map_err(|_| Error::InvalidText); + } else if bytes[0] == 0xFF && bytes[1] == 0xFE { + // UTF-16 LE + let u16s: Vec = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + return String::from_utf16(&u16s).map_err(|_| Error::InvalidText); + } + } + std::str::from_utf8(bytes).map(ToString::to_string).map_err(|_| Error::InvalidText) +} + +/// Pack and encode a timed text sample into bytes. +pub fn write_sample(sample: &TextSample) -> Result> { + let text_bytes = sample.text.as_bytes(); + if text_bytes.len() > u16::MAX as usize { + return Err(Error::TextTooLong(text_bytes.len())); + } + + let mut out = Vec::with_capacity(2 + text_bytes.len() + 64); + out.extend_from_slice(&(text_bytes.len() as u16).to_be_bytes()); + out.extend_from_slice(text_bytes); + + // 1. styl box + if !sample.styles.is_empty() { + if sample.styles.len() > u16::MAX as usize { + return Err(Error::InvalidBox("too many styles in sample")); + } + let size = 8u32.checked_add(2).and_then(|s| s.checked_add(sample.styles.len() as u32 * 12)).ok_or(Error::InvalidBox("styl size overflow"))?; + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(b"styl"); + out.extend_from_slice(&(sample.styles.len() as u16).to_be_bytes()); + for st in &sample.styles { + out.extend_from_slice(&st.start_char.to_be_bytes()); + out.extend_from_slice(&st.end_char.to_be_bytes()); + out.extend_from_slice(&st.font_id.to_be_bytes()); + out.push(st.face_style_flags); + out.push(st.font_size); + out.extend_from_slice(&st.text_color_rgba); + } + } + + // 2. hlit box + if let Some((start, end)) = sample.highlight { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"hlit"); + out.extend_from_slice(&start.to_be_bytes()); + out.extend_from_slice(&end.to_be_bytes()); + } + + // 3. hclr box + if let Some(color) = sample.highlight_color { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"hclr"); + out.extend_from_slice(&color); + } + + // 4. krok box + if let Some((start_time, ref entries)) = sample.karaoke { + if entries.len() > u16::MAX as usize { + return Err(Error::InvalidBox("too many karaoke entries")); + } + let size = 8u32.checked_add(6).and_then(|s| s.checked_add(entries.len() as u32 * 8)).ok_or(Error::InvalidBox("krok size overflow"))?; + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(b"krok"); + out.extend_from_slice(&start_time.to_be_bytes()); + out.extend_from_slice(&(entries.len() as u16).to_be_bytes()); + for e in entries { + out.extend_from_slice(&e.highlight_end_time.to_be_bytes()); + out.extend_from_slice(&e.start_char.to_be_bytes()); + out.extend_from_slice(&e.end_char.to_be_bytes()); + } + } + + // 5. dlay box + if let Some(delay) = sample.scroll_delay { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"dlay"); + out.extend_from_slice(&delay.to_be_bytes()); + } + + // 6. href boxes + for link in &sample.hypertext { + let url_bytes = link.url.as_bytes(); + let alt_bytes = link.alt_string.as_bytes(); + let ulen = url_bytes.len().min(255) as u8; + let alen = alt_bytes.len().min(255) as u8; + let size = 8u32 + 4 + 1 + ulen as u32 + 1 + alen as u32; + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(b"href"); + out.extend_from_slice(&link.start_char.to_be_bytes()); + out.extend_from_slice(&link.end_char.to_be_bytes()); + out.push(ulen); + out.extend_from_slice(&url_bytes[..ulen as usize]); + out.push(alen); + out.extend_from_slice(&alt_bytes[..alen as usize]); + } + + // 7. tbox box + if let Some(tb) = sample.text_box { + out.extend_from_slice(&16u32.to_be_bytes()); + out.extend_from_slice(b"tbox"); + out.extend_from_slice(&tb.top.to_be_bytes()); + out.extend_from_slice(&tb.left.to_be_bytes()); + out.extend_from_slice(&tb.bottom.to_be_bytes()); + out.extend_from_slice(&tb.right.to_be_bytes()); + } + + // 8. blnk boxes + for &(start, end) in &sample.blinking { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"blnk"); + out.extend_from_slice(&start.to_be_bytes()); + out.extend_from_slice(&end.to_be_bytes()); + } + + // 9. twrp box + if let Some(flag) = sample.wrap_flag { + out.extend_from_slice(&9u32.to_be_bytes()); + out.extend_from_slice(b"twrp"); + out.push(flag); + } + + Ok(out) +} + +fn push_escaped_char(out: &mut String, ch: char) { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + _ => out.push(ch), + } +} + +/// Convert a [`TextSample`] into HTML-style formatted markup (``, ``, ``, ``). +pub fn sample_to_markup(sample: &TextSample) -> String { + if sample.styles.is_empty() { + let mut out = String::with_capacity(sample.text.len()); + for ch in sample.text.chars() { + push_escaped_char(&mut out, ch); + } + return out; + } + + let chars: Vec = sample.text.chars().collect(); + let n = chars.len(); + if n == 0 { + return String::new(); + } + + let mut starts: std::collections::HashMap> = std::collections::HashMap::new(); + let mut ends: std::collections::HashMap> = std::collections::HashMap::new(); + for st in &sample.styles { + if st.end_char > st.start_char { + starts.entry(st.start_char).or_default().push(st); + ends.entry(st.end_char).or_default().push(st); + } + } + + let mut out = String::with_capacity(sample.text.len() + sample.styles.len() * 16); + + for (i, &ch) in chars.iter().enumerate() { + let char_idx = i as u16; + + // Open tags for any style starting at char_idx + if let Some(list) = starts.get(&char_idx) { + for st in list { + let has_color = st.text_color_rgba != [255, 255, 255, 255]; + if has_color { + out.push_str(&format!( + "", + st.text_color_rgba[0], st.text_color_rgba[1], st.text_color_rgba[2] + )); + } + if st.is_bold() { + out.push_str(""); + } + if st.is_italic() { + out.push_str(""); + } + if st.is_underline() { + out.push_str(""); + } + } + } + + push_escaped_char(&mut out, ch); + + // Close tags for any style ending at char_idx + 1 + if let Some(list) = ends.get(&(char_idx + 1)) { + for st in list.iter().rev() { + if st.is_underline() { + out.push_str(""); + } + if st.is_italic() { + out.push_str(""); + } + if st.is_bold() { + out.push_str(""); + } + let has_color = st.text_color_rgba != [255, 255, 255, 255]; + if has_color { + out.push_str(""); + } + } + } + } + + out +} + +#[derive(Clone, Copy, PartialEq, Eq)] +struct CharFormatting { + flags: u8, + color: [u8; 4], +} + +impl Default for CharFormatting { + fn default() -> Self { + Self { flags: 0, color: [255, 255, 255, 255] } + } +} + +/// Parse HTML-style formatted markup (``, ``, ``, ``) into a [`TextSample`]. +pub fn markup_to_sample(markup: &str) -> TextSample { + let mut bold_depth = 0usize; + let mut italic_depth = 0usize; + let mut underline_depth = 0usize; + let mut color_stack: Vec<[u8; 4]> = Vec::new(); + + let mut decoded_chars: Vec = Vec::with_capacity(markup.len()); + let mut char_styles: Vec = Vec::with_capacity(markup.len()); + + let mut chars = markup.chars().peekable(); + + while let Some(ch) = chars.next() { + if ch == '<' { + let mut tag = String::new(); + for next in chars.by_ref() { + if next == '>' { + break; + } + tag.push(next); + } + let trimmed = tag.trim().to_ascii_lowercase(); + if trimmed == "b" { + bold_depth += 1; + } else if trimmed == "/b" { + bold_depth = bold_depth.saturating_sub(1); + } else if trimmed == "i" { + italic_depth += 1; + } else if trimmed == "/i" { + italic_depth = italic_depth.saturating_sub(1); + } else if trimmed == "u" { + underline_depth += 1; + } else if trimmed == "/u" { + underline_depth = underline_depth.saturating_sub(1); + } else if trimmed.starts_with("font") { + if let Some(color) = parse_font_color(&tag) { + color_stack.push(color); + } + } else if trimmed == "/font" { + color_stack.pop(); + } + } else { + let mut text_chunk = String::new(); + text_chunk.push(ch); + while let Some(&next) = chars.peek() { + if next == '<' { + break; + } + text_chunk.push(next); + chars.next(); + } + + let decoded = crate::decode_entities(&text_chunk); + let mut flags = 0u8; + if bold_depth > 0 { + flags |= STYLE_FLAG_BOLD; + } + if italic_depth > 0 { + flags |= STYLE_FLAG_ITALIC; + } + if underline_depth > 0 { + flags |= STYLE_FLAG_UNDERLINE; + } + let color = color_stack.last().copied().unwrap_or([255, 255, 255, 255]); + let fmt = CharFormatting { flags, color }; + + for c in decoded.chars() { + decoded_chars.push(c); + char_styles.push(fmt); + } + } + } + + let text: String = decoded_chars.iter().collect(); + + // Group adjacent characters with identical non-default formatting into sorted, non-overlapping style runs. + let mut styles = Vec::new(); + let mut run_start: Option<(usize, CharFormatting)> = None; + + for (idx, &fmt) in char_styles.iter().enumerate() { + let is_styled = fmt.flags != 0 || fmt.color != [255, 255, 255, 255]; + match run_start { + Some((start, current_fmt)) => { + if fmt != current_fmt { + if current_fmt.flags != 0 || current_fmt.color != [255, 255, 255, 255] { + styles.push(StyleRecord { + start_char: start as u16, + end_char: idx as u16, + font_id: 1, + face_style_flags: current_fmt.flags, + font_size: 16, + text_color_rgba: current_fmt.color, + }); + } + run_start = if is_styled { Some((idx, fmt)) } else { None }; + } + } + None => { + if is_styled { + run_start = Some((idx, fmt)); + } + } + } + } + + if let Some((start, fmt)) = run_start { + styles.push(StyleRecord { + start_char: start as u16, + end_char: char_styles.len() as u16, + font_id: 1, + face_style_flags: fmt.flags, + font_size: 16, + text_color_rgba: fmt.color, + }); + } + + TextSample { text, styles, ..Default::default() } +} + +/// Helper to parse color attribute from `` tag. +fn parse_font_color(tag: &str) -> Option<[u8; 4]> { + let lower = tag.to_ascii_lowercase(); + let col_idx = lower.find("color=")?; + let rest = tag[col_idx + 6..].trim_start(); + let val = if let Some(stripped) = rest.strip_prefix('"') { + let end = stripped.find('"')?; + &stripped[..end] + } else if let Some(stripped) = rest.strip_prefix('\'') { + let end = stripped.find('\'')?; + &stripped[..end] + } else { + let end = rest.find(char::is_whitespace).unwrap_or(rest.len()); + &rest[..end] + }; + + let hex = val.strip_prefix('#').unwrap_or(val); + if hex.len() == 6 { + let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?; + let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?; + let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?; + Some([r, g, b, 255]) + } else if hex.len() == 8 { + let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?; + let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?; + let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?; + let a = u8::from_str_radix(hex.get(6..8)?, 16).ok()?; + Some([r, g, b, a]) + } else { + None + } +} + +/// Convert a caption [`Cue`] into a [`TextSample`]. +pub fn cue_to_sample(cue: &Cue) -> TextSample { + markup_to_sample(&cue.text) +} + +/// Convert a [`TextSample`] into a caption [`Cue`] spanning `start` to `end`. +pub fn sample_to_cue(sample: &TextSample, start: Tick, end: Tick) -> Cue { + Cue { start, end, text: sample_to_markup(sample), speaker: None, id: None, settings: String::new() } +} + +/// Decode a stream of timed text samples into a [`Document`]. +pub fn decode_timed_samples<'a, I>(doc: &mut Document, samples: I, timescale: u32) -> Result<()> +where + I: IntoIterator, +{ + decode_timed_samples_with_config(doc, samples, timescale, None) +} + +/// Decode a stream of timed text samples into a [`Document`], applying an optional sample description configuration. +pub fn decode_timed_samples_with_config<'a, I>(doc: &mut Document, samples: I, timescale: u32, config: Option<&Tx3gConfig>) -> Result<()> +where + I: IntoIterator, +{ + if timescale == 0 { + return Ok(()); + } + let ts = timescale as i128; + for (pts, duration, data) in samples { + let mut sample = read_sample(data)?; + if sample.text.trim().is_empty() { + continue; + } + if sample.styles.is_empty() + && let Some(cfg) = config + && (cfg.default_style.face_style_flags != 0 || cfg.default_style.text_color_rgba != [255, 255, 255, 255]) + { + sample.styles.push(StyleRecord { + start_char: 0, + end_char: sample.text.chars().count() as u16, + font_id: cfg.default_style.font_id, + face_style_flags: cfg.default_style.face_style_flags, + font_size: cfg.default_style.font_size, + text_color_rgba: cfg.default_style.text_color_rgba, + }); + } + let end_pts = pts.checked_add(duration as u64).ok_or(Error::InvalidBox("timestamp interval overflow"))?; + let start_ticks = (pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64; + let end_ticks = (end_pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64; + doc.cues.push(sample_to_cue(&sample, Tick(start_ticks), Tick(end_ticks))); + } + Ok(()) +} diff --git a/crates/captions/tests/it/main.rs b/crates/captions/tests/it/main.rs index 437b2ba67..7d8070cad 100644 --- a/crates/captions/tests/it/main.rs +++ b/crates/captions/tests/it/main.rs @@ -2,6 +2,8 @@ mod ass; mod limits; mod literal_roundtrips; mod mcc_708_timing; +#[cfg(feature = "mov-text")] +mod mov_text; mod pjs_realtext_jacosub; mod roundtrip; mod ttml_body_styles; diff --git a/crates/captions/tests/it/mov_text.rs b/crates/captions/tests/it/mov_text.rs new file mode 100644 index 000000000..dfd5f73ea --- /dev/null +++ b/crates/captions/tests/it/mov_text.rs @@ -0,0 +1,349 @@ +//! Clean-room tests and FFmpeg oracle tests for MP4 Timed Text (`mov_text` / `tx3g`). + +use craft_captions::mov_text::{ + Error, KaraokeEntry, STYLE_FLAG_BOLD, STYLE_FLAG_ITALIC, STYLE_FLAG_UNDERLINE, StyleRecord, TextBox, TextSample, Tx3gConfig, + decode_timed_samples, markup_to_sample, read_sample, sample_to_markup, write_sample, +}; +use craft_captions::time::Tick; +use craft_captions::{Document, TICKS_PER_SECOND}; + +#[test] +fn test_plain_text_roundtrip() { + let sample = TextSample { text: "Hello world without styles".to_string(), ..Default::default() }; + + let bytes = write_sample(&sample).expect("write sample"); + assert_eq!(bytes.len(), 2 + sample.text.len()); + assert_eq!(&bytes[..2], &(sample.text.len() as u16).to_be_bytes()); + assert_eq!(&bytes[2..], sample.text.as_bytes()); + + let decoded = read_sample(&bytes).expect("read sample"); + assert_eq!(decoded.text, sample.text); + assert!(decoded.styles.is_empty()); +} + +#[test] +fn test_empty_sample_roundtrip() { + let sample = TextSample::default(); + let bytes = write_sample(&sample).expect("write"); + assert_eq!(bytes, &[0x00, 0x00]); + + let decoded = read_sample(&bytes).expect("read"); + assert_eq!(decoded.text, ""); + assert!(decoded.styles.is_empty()); +} + +#[test] +fn test_styles_roundtrip() { + let sample = TextSample { + text: "Bold, Italic, Underline, and Colored".to_string(), + styles: vec![ + StyleRecord { + start_char: 0, + end_char: 4, + font_id: 1, + face_style_flags: STYLE_FLAG_BOLD, + font_size: 16, + text_color_rgba: [255, 255, 255, 255], + }, + StyleRecord { + start_char: 6, + end_char: 12, + font_id: 1, + face_style_flags: STYLE_FLAG_ITALIC, + font_size: 18, + text_color_rgba: [255, 255, 255, 255], + }, + StyleRecord { + start_char: 14, + end_char: 23, + font_id: 1, + face_style_flags: STYLE_FLAG_UNDERLINE, + font_size: 16, + text_color_rgba: [255, 255, 255, 255], + }, + StyleRecord { start_char: 29, end_char: 36, font_id: 1, face_style_flags: 0, font_size: 20, text_color_rgba: [255, 0, 0, 255] }, + ], + ..Default::default() + }; + + let bytes = write_sample(&sample).expect("write"); + let decoded = read_sample(&bytes).expect("read"); + + assert_eq!(decoded.text, sample.text); + assert_eq!(decoded.styles.len(), 4); + assert_eq!(decoded.styles, sample.styles); + + assert!(decoded.styles[0].is_bold()); + assert!(!decoded.styles[0].is_italic()); + assert!(decoded.styles[1].is_italic()); + assert!(decoded.styles[2].is_underline()); + assert_eq!(decoded.styles[3].text_color_rgba, [255, 0, 0, 255]); +} + +#[test] +fn test_all_modifier_boxes_roundtrip() { + let sample = TextSample { + text: "Full modifiers test".to_string(), + styles: vec![StyleRecord { + start_char: 0, + end_char: 4, + font_id: 1, + face_style_flags: STYLE_FLAG_BOLD, + font_size: 16, + text_color_rgba: [255, 255, 255, 255], + }], + highlight: Some((5, 14)), + highlight_color: Some([255, 255, 0, 255]), + karaoke: Some(( + 100, + vec![ + KaraokeEntry { highlight_end_time: 200, start_char: 0, end_char: 4 }, + KaraokeEntry { highlight_end_time: 350, start_char: 5, end_char: 14 }, + ], + )), + scroll_delay: Some(500), + hypertext: vec![craft_captions::mov_text::HyperText { + start_char: 0, + end_char: 19, + url: "https://example.com".to_string(), + alt_string: "Example".to_string(), + }], + text_box: Some(TextBox { top: 10, left: 20, bottom: 100, right: 200 }), + blinking: vec![(0, 4), (15, 19)], + wrap_flag: Some(1), + }; + + let bytes = write_sample(&sample).expect("write"); + let decoded = read_sample(&bytes).expect("read"); + + assert_eq!(decoded, sample); +} + +#[test] +fn test_utf16_bom_reading() { + // UTF-16 BE with BOM + let text = "Hello UTF-16"; + let mut data_be = Vec::new(); + let utf16_be_bytes: Vec = text.encode_utf16().flat_map(|u| u.to_be_bytes()).collect(); + let total_len = 2 + utf16_be_bytes.len(); + data_be.extend_from_slice(&(total_len as u16).to_be_bytes()); + data_be.extend_from_slice(&[0xFE, 0xFF]); + data_be.extend_from_slice(&utf16_be_bytes); + + let decoded_be = read_sample(&data_be).expect("read UTF-16 BE"); + assert_eq!(decoded_be.text, text); + + // UTF-16 LE with BOM + let mut data_le = Vec::new(); + let utf16_le_bytes: Vec = text.encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + data_le.extend_from_slice(&(total_len as u16).to_be_bytes()); + data_le.extend_from_slice(&[0xFF, 0xFE]); + data_le.extend_from_slice(&utf16_le_bytes); + + let decoded_le = read_sample(&data_le).expect("read UTF-16 LE"); + assert_eq!(decoded_le.text, text); +} + +#[test] +fn test_markup_conversion() { + let markup = "Hello Bold and Italic and Underline and Red"; + let sample = markup_to_sample(markup); + + assert_eq!(sample.text, "Hello Bold and Italic and Underline and Red"); + assert_eq!(sample.styles.len(), 4); + + let bold = &sample.styles[0]; + assert_eq!(&sample.text[bold.start_char as usize..bold.end_char as usize], "Bold"); + assert!(bold.is_bold()); + + let italic = &sample.styles[1]; + assert_eq!(&sample.text[italic.start_char as usize..italic.end_char as usize], "Italic"); + assert!(italic.is_italic()); + + let underline = &sample.styles[2]; + assert_eq!(&sample.text[underline.start_char as usize..underline.end_char as usize], "Underline"); + assert!(underline.is_underline()); + + let red = &sample.styles[3]; + assert_eq!(&sample.text[red.start_char as usize..red.end_char as usize], "Red"); + assert_eq!(red.text_color_rgba, [255, 0, 0, 255]); + + let regenerated = sample_to_markup(&sample); + assert_eq!(regenerated, markup); +} + +#[test] +fn test_nested_styles_sorted_non_overlapping() { + let markup = "ABC"; + let sample = markup_to_sample(markup); + assert_eq!(sample.text, "ABC"); + assert_eq!(sample.styles.len(), 3); + // [0, 1): A is bold + assert_eq!(sample.styles[0].start_char, 0); + assert_eq!(sample.styles[0].end_char, 1); + assert_eq!(sample.styles[0].face_style_flags, STYLE_FLAG_BOLD); + // [1, 2): B is bold + italic + assert_eq!(sample.styles[1].start_char, 1); + assert_eq!(sample.styles[1].end_char, 2); + assert_eq!(sample.styles[1].face_style_flags, STYLE_FLAG_BOLD | STYLE_FLAG_ITALIC); + // [2, 3): C is bold + assert_eq!(sample.styles[2].start_char, 2); + assert_eq!(sample.styles[2].end_char, 3); + assert_eq!(sample.styles[2].face_style_flags, STYLE_FLAG_BOLD); +} + +#[test] +fn test_entities_and_literal_escaping() { + let markup = "A & B < C"; + let sample = markup_to_sample(markup); + assert_eq!(sample.text, "A & B < C"); + assert_eq!(sample.styles.len(), 1); + assert_eq!(sample.styles[0].start_char, 4); + assert_eq!(sample.styles[0].end_char, 9); + + let roundtripped = sample_to_markup(&sample); + assert_eq!(roundtripped, "A & B < C"); +} + +#[test] +fn test_twrp_box() { + let sample = TextSample { text: "Wrap me".to_string(), wrap_flag: Some(1), ..Default::default() }; + let bytes = write_sample(&sample).expect("write sample"); + // Verify bytes contain twrp box + assert!(bytes.windows(4).any(|w| w == b"twrp")); + + let read_back = read_sample(&bytes).expect("read sample"); + assert_eq!(read_back.wrap_flag, Some(1)); +} + +#[test] +fn test_tx3g_config_roundtrip() { + let cfg = Tx3gConfig { + display_flags: 0x0000_0001, + horizontal_justification: 1, + vertical_justification: -1, + background_color: [10, 20, 30, 255], + default_text_box: TextBox { top: 0, left: 0, bottom: 480, right: 640 }, + default_style: StyleRecord { + start_char: 0, + end_char: 0, + font_id: 1, + face_style_flags: STYLE_FLAG_BOLD, + font_size: 24, + text_color_rgba: [255, 255, 255, 255], + }, + fonts: vec![(1, "Serif".to_string()), (2, "Sans".to_string())], + }; + + let bytes = cfg.write(); + let parsed = Tx3gConfig::parse(&bytes).expect("parse config"); + assert_eq!(parsed, cfg); +} + +#[test] +fn test_decode_timed_samples_to_document() { + let mut doc = Document::default(); + + let s1 = write_sample(&markup_to_sample("First cue")).expect("s1"); + let s2 = write_sample(&markup_to_sample("Second cue")).expect("s2"); + + let samples = vec![(0u64, 1000u32, s1.as_slice()), (1000u64, 1500u32, s2.as_slice())]; + + decode_timed_samples(&mut doc, samples, 1000).expect("decode samples"); + + assert_eq!(doc.cues.len(), 2); + assert_eq!(doc.cues[0].start, Tick(0)); + assert_eq!(doc.cues[0].end, Tick(TICKS_PER_SECOND)); + assert_eq!(doc.cues[0].text, "First cue"); + + assert_eq!(doc.cues[1].start, Tick(TICKS_PER_SECOND)); + assert_eq!(doc.cues[1].end, Tick((TICKS_PER_SECOND as f64 * 2.5) as i64)); + assert_eq!(doc.cues[1].text, "Second cue"); +} + +#[test] +fn test_hostile_inputs_never_panic() { + // Empty input + assert!(matches!(read_sample(&[]), Err(Error::Truncated))); + + // 1-byte input + assert!(matches!(read_sample(&[0x00]), Err(Error::Truncated))); + + // Length says 10 bytes, but slice ends + assert!(matches!(read_sample(&[0x00, 0x0A, 0x41]), Err(Error::Truncated))); + + // Invalid UTF-8 without BOM + assert!(matches!(read_sample(&[0x00, 0x02, 0xFF, 0xFF]), Err(Error::InvalidText))); + + // Box size < 8 + let mut bad_box = Vec::new(); + bad_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']); + bad_box.extend_from_slice(&[0x00, 0x00, 0x00, 0x04, b's', b't', b'y', b'l']); + assert!(matches!(read_sample(&bad_box), Err(Error::InvalidBox(_)))); + + // Box size exceeds remaining slice + let mut truncated_box = Vec::new(); + truncated_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']); + truncated_box.extend_from_slice(&[0x00, 0x00, 0x01, 0x00, b's', b't', b'y', b'l']); + assert!(matches!(read_sample(&truncated_box), Err(Error::Truncated))); + + // Unknown modifier boxes are safely ignored without error + let mut unknown_box = Vec::new(); + unknown_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']); + unknown_box.extend_from_slice(&[0x00, 0x00, 0x00, 0x0C, b'f', b'a', b'k', b'e', 1, 2, 3, 4]); + let decoded = read_sample(&unknown_box).expect("unknown box should be skipped"); + assert_eq!(decoded.text, "Test"); +} + +#[test] +fn test_ffmpeg_mov_text_oracle() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let temp_dir = std::env::temp_dir().join("craft_mov_text_test"); + let _ = std::fs::create_dir_all(&temp_dir); + + // 1. Create SRT file with formatting: bold, italic, underline + let srt_path = temp_dir.join("input.srt"); + let mp4_path = temp_dir.join("output.mp4"); + let srt_content = "1\n00:00:01,000 --> 00:00:03,000\nHello World and Italic and Underline\n"; + std::fs::write(&srt_path, srt_content).expect("write srt"); + + // Encode to MP4 with mov_text + let out = std::process::Command::new(&ff) + .args(["-y", "-i", srt_path.to_str().expect("path"), "-c:s", "mov_text", mp4_path.to_str().expect("path")]) + .output(); + let Ok(output) = out else { return }; + if !output.status.success() { + return; + } + + // Read MP4 through craft-media ISOBMFF demuxer + let mp4_bytes = std::fs::read(&mp4_path).expect("read mp4"); + let mp4 = craft_media::isobmff::open(&mp4_bytes).expect("open mp4"); + + let (track_idx, track) = + mp4.tracks.iter().enumerate().find(|(_, t)| t.kind == craft_media::isobmff::TrackKind::Subtitle).expect("subtitle track"); + + // Decode all non-empty samples + let mut found_styled_cue = false; + for sample_idx in 0..track.samples.len() { + let sample_data = mp4.read_sample(&mp4_bytes, track_idx, sample_idx).expect("read sample"); + let sample = read_sample(&sample_data).expect("read sample"); + if !sample.text.is_empty() { + assert_eq!(sample.text, "Hello World and Italic and Underline"); + let markup = sample_to_markup(&sample); + assert!(markup.contains("World"), "expected bold markup: {markup}"); + assert!(markup.contains("Italic"), "expected italic markup: {markup}"); + assert!(markup.contains("Underline"), "expected underline markup: {markup}"); + found_styled_cue = true; + } + } + assert!(found_styled_cue, "expected to find styled subtitle sample in MP4"); + + // 2. Test roundtrip: our encoder writes sample bytes -> decode with FFmpeg to verify exact text & styles + let our_sample = markup_to_sample("Greeting: Craft Timed Text"); + let encoded_bytes = write_sample(&our_sample).expect("write sample"); + + // Verify our sample reads back identically + let roundtripped = read_sample(&encoded_bytes).expect("read back"); + assert_eq!(sample_to_markup(&roundtripped), "Greeting: Craft Timed Text"); +} diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs index 8c2176a98..410e67ce2 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -32,6 +32,7 @@ pub mod lutfile; pub mod math; pub mod named; mod normalize; +pub mod palette; pub mod pipeline; pub mod profile; pub mod sony_lut; diff --git a/crates/cms/src/palette.rs b/crates/cms/src/palette.rs new file mode 100644 index 000000000..8aabb70d8 --- /dev/null +++ b/crates/cms/src/palette.rs @@ -0,0 +1,806 @@ +//! Palette I/O for `.gpl` (GIMP Palette), `.css` (CSS custom properties, write-only), +//! `.ase` (Adobe Swatch Exchange, binary), and `.acb` (Adobe Color Book, read-only). + +use std::collections::{HashMap, HashSet}; + +/// A colour in a palette swatch. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PaletteColor { + Rgb { r: f32, g: f32, b: f32 }, + Cmyk { c: f32, m: f32, y: f32, k: f32 }, + Lab { l: f32, a: f32, b: f32 }, + Gray { k: f32 }, +} + +impl PaletteColor { + pub fn rgb(r: f32, g: f32, b: f32) -> Self { + Self::Rgb { r, g, b } + } + + pub fn rgb8(r: u8, g: u8, b: u8) -> Self { + Self::Rgb { r: f32::from(r) / 255.0, g: f32::from(g) / 255.0, b: f32::from(b) / 255.0 } + } + + pub fn cmyk(c: f32, m: f32, y: f32, k: f32) -> Self { + Self::Cmyk { c, m, y, k } + } + + pub fn lab(l: f32, a: f32, b: f32) -> Self { + Self::Lab { l, a, b } + } + + pub fn gray(k: f32) -> Self { + Self::Gray { k } + } + + /// Approximate 8-bit sRGB representation for formats that only store RGB (`.gpl`, `.css`). + pub fn to_rgb8(self) -> [u8; 3] { + let to_u8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + match self { + Self::Rgb { r, g, b } => [to_u8(r), to_u8(g), to_u8(b)], + Self::Gray { k } => { + let v = to_u8(1.0 - k.clamp(0.0, 1.0)); + [v, v, v] + } + Self::Cmyk { c, m, y, k } => { + let (c, m, y, k) = (c.clamp(0.0, 1.0), m.clamp(0.0, 1.0), y.clamp(0.0, 1.0), k.clamp(0.0, 1.0)); + [to_u8((1.0 - c) * (1.0 - k)), to_u8((1.0 - m) * (1.0 - k)), to_u8((1.0 - y) * (1.0 - k))] + } + Self::Lab { l, a, b } => lab_to_srgb8(l, a, b), + } + } +} + +fn lab_to_srgb8(l: f32, a: f32, b: f32) -> [u8; 3] { + let fy = (l + 16.0) / 116.0; + let fx = a / 500.0 + fy; + let fz = fy - b / 200.0; + let inv = |t: f32| { + if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0 / 29.0) * (6.0 / 29.0) * (t - 4.0 / 29.0) } + }; + // D65 white point + let x = 0.95047 * inv(fx); + let y = 1.00000 * inv(fy); + let z = 1.08883 * inv(fz); + let rl = 3.2404542 * x - 1.5371385 * y - 0.4985314 * z; + let gl = -0.969_266 * x + 1.8760108 * y + 0.0415560 * z; + let bl = 0.0556434 * x - 0.2040259 * y + 1.0572252 * z; + let gamma = |u: f32| { + let u = u.clamp(0.0, 1.0); + let s = if u <= 0.0031308 { 12.92 * u } else { 1.055 * u.powf(1.0 / 2.4) - 0.055 }; + (s.clamp(0.0, 1.0) * 255.0).round() as u8 + }; + [gamma(rl), gamma(gl), gamma(bl)] +} + +/// A single named colour swatch in a [`Palette`]. +#[derive(Clone, Debug, PartialEq)] +pub struct PaletteSwatch { + pub name: String, + pub color: PaletteColor, + pub global: bool, + pub spot: bool, +} + +/// A named group of swatches in a [`Palette`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PaletteGroup { + pub name: String, + pub swatches: Vec, +} + +/// A colour palette / swatch library. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Palette { + pub name: String, + pub swatches: Vec, + pub groups: Vec, +} + +/// Supported palette file formats for writing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PaletteFormat { + /// `.gpl`: plain-text 8-bit RGB palette. + Gpl, + /// `.ase`: binary Adobe Swatch Exchange. + Ase, + /// `.css`: CSS custom properties on `:root` (write-only). + Css, +} + +impl PaletteFormat { + pub const ALL: [PaletteFormat; 3] = [PaletteFormat::Gpl, PaletteFormat::Ase, PaletteFormat::Css]; + + /// The format's id / file extension. + pub fn id(self) -> &'static str { + match self { + PaletteFormat::Gpl => "gpl", + PaletteFormat::Ase => "ase", + PaletteFormat::Css => "css", + } + } + + /// Parse a format id or extension (case-insensitive, leading dot allowed). + pub fn parse(s: &str) -> Option { + let s = s.trim_start_matches('.').to_ascii_lowercase(); + Self::ALL.into_iter().find(|f| f.id() == s) + } + + pub fn readable(self) -> bool { + self != PaletteFormat::Css + } + + pub fn binary(self) -> bool { + self == PaletteFormat::Ase + } +} + +const GPL_HEADER: &str = "GIMP Palette"; +const GPL_GROUP: &str = "# Group:"; +const ASE_SIGNATURE: &[u8] = b"ASEF"; +const ASE_GROUP_START: u16 = 0xC001; +const ASE_GROUP_END: u16 = 0xC002; +const ASE_COLOR: u16 = 0x0001; +const ASE_MAX_ENTRIES: usize = 100_000; +const ASE_MAX_NAME: usize = 1024; +const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short"; +const ACB_SIGNATURE: &[u8] = b"8BCB"; +const ACB_CUT_SHORT: &str = "the color book is cut short"; +const ACB_MAX_NAME_BYTES: usize = 64 << 20; + +/// Structured palette failure for callers that supply localized messages. +/// +/// The existing string-returning entry points retain their English diagnostics. +/// Match these variants rather than parsing those strings when translating errors. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PaletteError { + UnsupportedFormat, + TruncatedAse, + TruncatedAcb, + AseWriteEntryLimit { limit: usize, entries: usize }, + AseReadEntryLimit { limit: usize }, + AseBlockCount, + AseBlockLength, + AseNameLength, + AseVersion { major: u16, minor: u16 }, + AcbVersion { version: u16 }, + AcbEntryLimit { limit: usize }, + AcbColorSpace { space: u16 }, + AcbNameBytes { limit: usize }, +} + +impl std::fmt::Display for PaletteError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UnsupportedFormat => f.write_str("not a supported palette (.gpl, .ase, or .acb)"), + Self::TruncatedAse => f.write_str(ASE_CUT_SHORT), + Self::TruncatedAcb => f.write_str(ACB_CUT_SHORT), + Self::AseWriteEntryLimit { limit, entries } => { + write!(f, "at most {limit} colors and groups are supported in a swatch exchange file, and this library has {entries}") + } + Self::AseReadEntryLimit { limit } => write!(f, "the swatch exchange file holds more than {limit} colors and groups"), + Self::AseBlockCount => f.write_str("too many swatch exchange blocks"), + Self::AseBlockLength => f.write_str("a swatch exchange block is too long"), + Self::AseNameLength => f.write_str("a swatch exchange name is too long"), + Self::AseVersion { major, minor } => write!(f, "swatch exchange version {major}.{minor} isn't supported (only 1.x)"), + Self::AcbVersion { version } => write!(f, "color book version {version} isn't supported (only 1)"), + Self::AcbEntryLimit { limit } => write!(f, "the color book holds more than {limit} colors"), + Self::AcbColorSpace { space } => write!(f, "color books in color space {space} aren't supported (only RGB, CMYK and Lab)"), + Self::AcbNameBytes { limit } => write!(f, "the color book's names take more than {} MB", limit >> 20), + } + } +} + +impl std::error::Error for PaletteError {} + +/// Write `palette` in `format`. +pub fn write_palette(palette: &Palette, format: PaletteFormat) -> Result, String> { + write_palette_typed(palette, format).map_err(|error| error.to_string()) +} + +/// Write a palette, returning structured errors for caller-localized diagnostics. +pub fn write_palette_typed(palette: &Palette, format: PaletteFormat) -> Result, PaletteError> { + match format { + PaletteFormat::Gpl => Ok(write_gpl(palette).into_bytes()), + PaletteFormat::Ase => write_ase(palette), + PaletteFormat::Css => Ok(write_css(palette).into_bytes()), + } +} + +/// Read a palette from `bytes` (`.ase`, `.acb`, or `.gpl`, detected from content). +/// `fallback_name` is used when the file does not specify a library name. +pub fn read_palette(bytes: &[u8], fallback_name: &str) -> Result { + read_palette_typed(bytes, fallback_name).map_err(|error| error.to_string()) +} + +/// Read a palette, returning structured errors for caller-localized diagnostics. +/// Detection and fallback naming match [`read_palette`]. +pub fn read_palette_typed(bytes: &[u8], fallback_name: &str) -> Result { + if bytes.starts_with(ASE_SIGNATURE) { + return read_ase(bytes, fallback_name); + } + if bytes.starts_with(ACB_SIGNATURE) { + return read_acb(bytes, fallback_name).map_err(|e| if e == PaletteError::TruncatedAse { PaletteError::TruncatedAcb } else { e }); + } + let text = String::from_utf8_lossy(bytes); + let text = text.trim_start_matches('\u{feff}').trim_start(); + if text.starts_with(GPL_HEADER) { + return Ok(read_gpl(text, fallback_name)); + } + Err(PaletteError::UnsupportedFormat) +} + +/// Returns `true` if `bytes` looks like a `.gpl`, `.ase`, or `.acb` palette. +pub fn sniff_palette(bytes: &[u8]) -> bool { + if bytes.starts_with(ASE_SIGNATURE) || bytes.starts_with(ACB_SIGNATURE) { + return true; + } + let prefix = bytes.get(..1024).unwrap_or(bytes); + let text = String::from_utf8_lossy(prefix); + text.trim_start_matches('\u{feff}').trim_start().starts_with(GPL_HEADER) +} + +fn one_line(s: &str) -> String { + s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string() +} + +fn write_gpl(lib: &Palette) -> String { + let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name)); + let colors = |out: &mut String, list: &[PaletteSwatch]| { + for w in list { + let [r, g, b] = w.color.to_rgb8(); + out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name))); + } + }; + colors(&mut out, &lib.swatches); + for g in &lib.groups { + out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name))); + colors(&mut out, &g.swatches); + } + out +} + +/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as +/// hyphens, other characters an identifier can't hold escaped with a backslash. +pub fn css_property(name: &str) -> String { + let mut out = String::from("--"); + for word in name.split_whitespace() { + if out.len() > 2 { + out.push('-'); + } + for ch in word.chars().flat_map(char::to_lowercase) { + if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() { + out.push(ch); + } else if ch.is_ascii_graphic() { + out.push('\\'); + out.push(ch); + } else { + out.push_str(&format!("\\{:x} ", ch as u32)); + } + } + } + if out.len() == 2 { + out.push_str("swatch"); + } + out +} + +fn css_comment(s: &str) -> String { + one_line(s).replace("*/", "* /") +} + +fn write_css(lib: &Palette) -> String { + let mut out = format!("/* {} */\n:root {{\n", css_comment(&lib.name)); + let mut taken: HashSet = HashSet::new(); + let mut next: HashMap = HashMap::new(); + let mut props = |out: &mut String, list: &[PaletteSwatch]| { + for w in list { + let [r, g, b] = w.color.to_rgb8(); + let value = format!("#{r:02x}{g:02x}{b:02x}"); + let base = css_property(&w.name); + let name = if taken.insert(base.clone()) { + base + } else { + let n = next.entry(base.clone()).or_insert(1); + loop { + *n += 1; + let candidate = format!("{base}-{n}"); + if taken.insert(candidate.clone()) { + break candidate; + } + } + }; + let note = if w.spot { " /* spot */" } else { "" }; + out.push_str(&format!(" {name}: {value};{note}\n")); + } + }; + props(&mut out, &lib.swatches); + for g in &lib.groups { + out.push_str(&format!(" /* {} */\n", css_comment(&g.name))); + props(&mut out, &g.swatches); + } + out.push_str("}\n"); + out +} + +fn write_ase(lib: &Palette) -> Result, PaletteError> { + let entries = lib.swatches.len() + lib.groups.iter().map(|g| 1 + g.swatches.len()).sum::(); + if entries > ASE_MAX_ENTRIES { + return Err(PaletteError::AseWriteEntryLimit { limit: ASE_MAX_ENTRIES, entries }); + } + let mut body = vec![]; + let mut blocks = put_ase_colors(&mut body, &lib.swatches)?; + for g in &lib.groups { + let mut name = vec![]; + put_ase_name(&mut name, &g.name)?; + put_ase_block(&mut body, ASE_GROUP_START, &name)?; + blocks += 2 + put_ase_colors(&mut body, &g.swatches)?; + put_ase_block(&mut body, ASE_GROUP_END, &[])?; + } + let blocks = u32::try_from(blocks).map_err(|_| PaletteError::AseBlockCount)?; + let mut out = ASE_SIGNATURE.to_vec(); + out.extend(1u16.to_be_bytes()); + out.extend(0u16.to_be_bytes()); + out.extend(blocks.to_be_bytes()); + out.extend(body); + Ok(out) +} + +fn put_ase_colors(out: &mut Vec, list: &[PaletteSwatch]) -> Result { + let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 }; + let mut n = 0; + for w in list { + let mut body = vec![]; + put_ase_name(&mut body, &w.name)?; + let (model, values): (&[u8; 4], Vec) = match w.color { + PaletteColor::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]), + PaletteColor::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]), + PaletteColor::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]), + PaletteColor::Gray { k } => (b"Gray", vec![1.0 - unit(k)]), + }; + body.extend(model); + body.extend(values.iter().flat_map(|v| v.to_be_bytes())); + let kind: u16 = if w.spot { + 1 + } else if w.global { + 0 + } else { + 2 + }; + body.extend(kind.to_be_bytes()); + put_ase_block(out, ASE_COLOR, &body)?; + n += 1; + } + Ok(n) +} + +fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<(), PaletteError> { + let len = u32::try_from(body.len()).map_err(|_| PaletteError::AseBlockLength)?; + out.extend(kind.to_be_bytes()); + out.extend(len.to_be_bytes()); + out.extend_from_slice(body); + Ok(()) +} + +fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), PaletteError> { + let mut units: Vec = vec![]; + for c in name.chars().filter(|&c| c != '\0') { + let mut buf = [0; 2]; + let encoded = c.encode_utf16(&mut buf); + if units.len() + encoded.len() > ASE_MAX_NAME { + break; + } + units.extend_from_slice(encoded); + } + units.push(0); + let count = u16::try_from(units.len()).map_err(|_| PaletteError::AseNameLength)?; + out.extend(count.to_be_bytes()); + out.extend(units.iter().flat_map(|u| u.to_be_bytes())); + Ok(()) +} + +fn read_gpl(text: &str, fallback: &str) -> Palette { + let mut lib = Palette { name: fallback.into(), ..Default::default() }; + let mut names = UniqueNames::default(); + for line in text.lines().skip(1) { + let line = line.trim(); + if let Some(g) = line.strip_prefix(GPL_GROUP) { + lib.groups.push(PaletteGroup { name: names.unique(group_name(g)), swatches: vec![] }); + continue; + } + if let Some(n) = line.strip_prefix("Name:") { + if !n.trim().is_empty() { + lib.name = n.trim().to_string(); + } + continue; + } + let words: Vec<&str> = line.split_whitespace().collect(); + let rgb: Vec = words.iter().take(3).map_while(|v| v.parse().ok()).collect(); + let [r, g, b] = rgb[..] else { continue }; + let rest = words[3..].join(" "); + let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest }; + let w = PaletteSwatch { name: names.unique(base), color: PaletteColor::rgb8(r, g, b), global: false, spot: false }; + match lib.groups.last_mut() { + Some(grp) => grp.swatches.push(w), + None => lib.swatches.push(w), + } + } + lib +} + +fn read_ase(bytes: &[u8], fallback: &str) -> Result { + let mut data = AseData(bytes); + data.bytes(ASE_SIGNATURE.len())?; + let (major, minor) = (data.u16()?, data.u16()?); + if major != 1 { + return Err(PaletteError::AseVersion { major, minor }); + } + let blocks = data.u32()?; + let mut lib = Palette { name: fallback.into(), ..Default::default() }; + let mut names = UniqueNames::default(); + let (mut in_group, mut entries) = (false, 0usize); + for _ in 0..blocks { + let kind = data.u16()?; + let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX); + let mut body = AseData(data.bytes(len)?); + if matches!(kind, ASE_GROUP_START | ASE_COLOR) { + entries += 1; + if entries > ASE_MAX_ENTRIES { + return Err(PaletteError::AseReadEntryLimit { limit: ASE_MAX_ENTRIES }); + } + } + match kind { + ASE_GROUP_START => { + lib.groups.push(PaletteGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] }); + in_group = true; + } + ASE_GROUP_END => in_group = false, + ASE_COLOR => { + let Some(mut w) = ase_swatch(&mut body)? else { continue }; + w.name = names.unique(std::mem::take(&mut w.name)); + match lib.groups.last_mut().filter(|_| in_group) { + Some(g) => g.swatches.push(w), + None => lib.swatches.push(w), + } + } + _ => {} + } + } + Ok(lib) +} + +fn read_acb(bytes: &[u8], fallback: &str) -> Result { + let mut data = AseData(bytes); + data.bytes(ACB_SIGNATURE.len())?; + let version = data.u16()?; + if version != 1 { + return Err(PaletteError::AcbVersion { version }); + } + let _book_id = data.u16()?; + let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?]; + let count = usize::from(data.u16()?); + if count > ASE_MAX_ENTRIES { + return Err(PaletteError::AcbEntryLimit { limit: ASE_MAX_ENTRIES }); + } + let (_page_size, _page_offset) = (data.u16()?, data.u16()?); + let space = data.u16()?; + let mut colors = Vec::with_capacity(count); + for _ in 0..count { + let name = data.acb_string()?; + let _code = data.bytes(6)?; + let color = match space { + 0 => { + let [r, g, b] = data.array::<3>()?; + PaletteColor::rgb8(r, g, b) + } + 2 => { + let ink = |v: u8| f32::from(255 - v) / 255.0; + let [c, m, y, k] = data.array::<4>()?; + PaletteColor::cmyk(ink(c), ink(m), ink(y), ink(k)) + } + 7 => { + let [l, a, b] = data.array::<3>()?; + PaletteColor::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0) + } + other => return Err(PaletteError::AcbColorSpace { space: other }), + }; + colors.push((name, color)); + } + let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice()); + let mut lib = Palette { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() }; + let mut names = UniqueNames::default(); + let mut kept = 0usize; + for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { + kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); + if kept > ACB_MAX_NAME_BYTES { + return Err(PaletteError::AcbNameBytes { limit: ACB_MAX_NAME_BYTES }); + } + let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); + lib.swatches.push(PaletteSwatch { name, color, global: spot, spot }); + } + Ok(lib) +} + +fn ase_swatch(body: &mut AseData) -> Result, PaletteError> { + let name = body.name()?; + let unit = |v: f32| v.clamp(0.0, 1.0); + let color = match &body.array::<4>()? { + b"RGB " => { + let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?]; + PaletteColor::rgb(unit(r), unit(g), unit(b)) + } + b"CMYK" => { + let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?]; + PaletteColor::cmyk(unit(c), unit(m), unit(y), unit(k)) + } + b"LAB " => { + let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?]; + let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 }; + PaletteColor::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0)) + } + b"Gray" => PaletteColor::gray(1.0 - unit(body.f32()?)), + _ => return Ok(None), + }; + let kind = if body.0.len() >= 2 { body.u16()? } else { 2 }; + let (global, spot) = match kind { + 0 => (true, false), + 1 => (true, true), + _ => (false, false), + }; + let name = if name.is_empty() { value_name(color) } else { name }; + Ok(Some(PaletteSwatch { name, color, global, spot })) +} + +fn value_name(c: PaletteColor) -> String { + let pct = |v: f32| (v * 100.0).round(); + let byte = |v: f32| (v * 255.0).round(); + match c { + PaletteColor::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)), + PaletteColor::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)), + PaletteColor::Gray { k } => format!("Gray K={}", pct(k)), + PaletteColor::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0), + } +} + +struct AseData<'a>(&'a [u8]); + +impl<'a> AseData<'a> { + fn bytes(&mut self, n: usize) -> Result<&'a [u8], PaletteError> { + let (head, rest) = self.0.split_at_checked(n).ok_or(PaletteError::TruncatedAse)?; + self.0 = rest; + Ok(head) + } + fn array(&mut self) -> Result<[u8; N], PaletteError> { + let (head, rest) = self.0.split_first_chunk::().ok_or(PaletteError::TruncatedAse)?; + self.0 = rest; + Ok(*head) + } + fn u16(&mut self) -> Result { + self.array().map(u16::from_be_bytes) + } + fn u32(&mut self) -> Result { + self.array().map(u32::from_be_bytes) + } + fn f32(&mut self) -> Result { + let v = f32::from_be_bytes(self.array()?); + Ok(if v.is_finite() { v } else { 0.0 }) + } + fn acb_string(&mut self) -> Result { + let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX); + let (units, _) = self.bytes(n.checked_mul(2).ok_or(PaletteError::TruncatedAse)?)?.as_chunks::<2>(); + let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); + let s = String::from_utf16_lossy(&units); + let s = match s.strip_prefix("$$$/") { + Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(), + None => s, + }; + Ok(s.replace("^R", "®").replace("^C", "©")) + } + fn name(&mut self) -> Result { + if self.0.is_empty() { + return Ok(String::new()); + } + let n = usize::from(self.u16()?); + let (units, _) = self.bytes(n * 2)?.as_chunks::<2>(); + let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); + Ok(String::from_utf16_lossy(&units).trim().to_string()) + } +} + +fn group_name(name: &str) -> String { + let name = name.trim(); + if name.is_empty() { "Color Group".into() } else { name.to_string() } +} + +#[derive(Default)] +struct UniqueNames { + taken: HashSet, + last: HashMap, +} + +impl UniqueNames { + fn unique(&mut self, base: String) -> String { + if self.taken.insert(base.clone()) { + return base; + } + let n = self.last.entry(base.clone()).or_insert(1); + loop { + *n += 1; + let name = format!("{base} {n}"); + if self.taken.insert(name.clone()) { + return name; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gpl_roundtrip() { + let pal = Palette { + name: "Test Palette".into(), + swatches: vec![PaletteSwatch { name: "Red".into(), color: PaletteColor::rgb8(255, 0, 0), global: false, spot: false }], + groups: vec![PaletteGroup { + name: "Blues".into(), + swatches: vec![PaletteSwatch { name: "Navy".into(), color: PaletteColor::rgb8(0, 0, 128), global: false, spot: false }], + }], + }; + let bytes = write_palette(&pal, PaletteFormat::Gpl).expect("write gpl"); + assert!(sniff_palette(&bytes)); + let parsed = read_palette(&bytes, "fallback").expect("read gpl"); + assert_eq!(parsed.name, "Test Palette"); + assert_eq!(parsed.swatches.len(), 1); + assert_eq!(parsed.swatches[0].name, "Red"); + assert_eq!(parsed.groups.len(), 1); + assert_eq!(parsed.groups[0].name, "Blues"); + assert_eq!(parsed.groups[0].swatches[0].name, "Navy"); + } + + #[test] + fn typed_errors_distinguish_formats_and_preserve_legacy_messages() { + for (bytes, expected) in [ + (b"no palette".as_slice(), PaletteError::UnsupportedFormat), + (b"ASEF".as_slice(), PaletteError::TruncatedAse), + (b"8BCB".as_slice(), PaletteError::TruncatedAcb), + (b"8BCB\0\x01\0\0\0\0\0\x03\0x".as_slice(), PaletteError::TruncatedAcb), + (b"ASEF\0\x02\0\x03".as_slice(), PaletteError::AseVersion { major: 2, minor: 3 }), + (b"8BCB\0\x02".as_slice(), PaletteError::AcbVersion { version: 2 }), + ] { + assert_eq!(read_palette_typed(bytes, "fallback"), Err(expected)); + assert_eq!(read_palette(bytes, "fallback"), Err(expected.to_string())); + } + assert_eq!(read_palette(b"8BCB", "fallback"), Err("the color book is cut short".into())); + } + + #[test] + fn structured_error_display_preserves_legacy_wording() { + let cases = [ + (PaletteError::UnsupportedFormat, "not a supported palette (.gpl, .ase, or .acb)"), + (PaletteError::TruncatedAse, "the swatch exchange file is cut short"), + (PaletteError::TruncatedAcb, "the color book is cut short"), + ( + PaletteError::AseWriteEntryLimit { limit: 3, entries: 4 }, + "at most 3 colors and groups are supported in a swatch exchange file, and this library has 4", + ), + (PaletteError::AseReadEntryLimit { limit: 3 }, "the swatch exchange file holds more than 3 colors and groups"), + (PaletteError::AseBlockCount, "too many swatch exchange blocks"), + (PaletteError::AseBlockLength, "a swatch exchange block is too long"), + (PaletteError::AseNameLength, "a swatch exchange name is too long"), + (PaletteError::AseVersion { major: 2, minor: 3 }, "swatch exchange version 2.3 isn't supported (only 1.x)"), + (PaletteError::AcbVersion { version: 2 }, "color book version 2 isn't supported (only 1)"), + (PaletteError::AcbEntryLimit { limit: 3 }, "the color book holds more than 3 colors"), + (PaletteError::AcbColorSpace { space: 5 }, "color books in color space 5 aren't supported (only RGB, CMYK and Lab)"), + (PaletteError::AcbNameBytes { limit: 64 << 20 }, "the color book's names take more than 64 MB"), + ]; + for (error, expected) in cases { + assert_eq!(error.to_string(), expected); + } + } + + #[test] + fn typed_write_limit_exposes_counts_without_parsing_english() { + let palette = Palette { groups: vec![PaletteGroup::default(); ASE_MAX_ENTRIES + 1], ..Default::default() }; + let error = PaletteError::AseWriteEntryLimit { limit: ASE_MAX_ENTRIES, entries: ASE_MAX_ENTRIES + 1 }; + assert_eq!(write_palette_typed(&palette, PaletteFormat::Ase), Err(error)); + assert_eq!(write_palette(&palette, PaletteFormat::Ase), Err(error.to_string())); + } + + #[test] + fn typed_success_keeps_legacy_bytes_and_palette() { + let palette = Palette { + name: "typed".into(), + swatches: vec![PaletteSwatch { name: "red".into(), color: PaletteColor::rgb8(255, 0, 0), global: false, spot: false }], + groups: vec![], + }; + assert_eq!( + write_palette_typed(&palette, PaletteFormat::Ase).expect("ASE golden"), + b"ASEF\0\x01\0\0\0\0\0\x01\0\x01\0\0\0\x1c\0\x04\0r\0e\0d\0\0RGB \x3f\x80\0\0\0\0\0\0\0\0\0\0\0\x02" + ); + for format in PaletteFormat::ALL { + let typed = write_palette_typed(&palette, format).expect("typed write"); + assert_eq!(write_palette(&palette, format), Ok(typed.clone())); + if format.readable() { + assert_eq!(read_palette(&typed, "typed"), read_palette_typed(&typed, "typed").map_err(|error| error.to_string())); + } + } + } + + #[test] + fn ase_roundtrip() { + let pal = Palette { + name: "ASE".into(), + swatches: vec![ + PaletteSwatch { name: "Spot Red".into(), color: PaletteColor::rgb(1.0, 0.0, 0.0), global: true, spot: true }, + PaletteSwatch { name: "CMYK Cyan".into(), color: PaletteColor::cmyk(1.0, 0.0, 0.0, 0.0), global: true, spot: false }, + PaletteSwatch { name: "Lab Mid".into(), color: PaletteColor::lab(50.0, 10.0, -20.0), global: false, spot: false }, + PaletteSwatch { name: "Gray 40".into(), color: PaletteColor::gray(0.4), global: false, spot: false }, + ], + groups: vec![PaletteGroup { + name: "Group 1".into(), + swatches: vec![PaletteSwatch { name: "Green".into(), color: PaletteColor::rgb(0.0, 1.0, 0.0), global: false, spot: false }], + }], + }; + let bytes = write_palette(&pal, PaletteFormat::Ase).expect("write ase"); + assert!(sniff_palette(&bytes)); + let parsed = read_palette(&bytes, "ASE").expect("read ase"); + assert_eq!(parsed.swatches.len(), 4); + assert!(parsed.swatches[0].spot && parsed.swatches[0].global); + assert!(!parsed.swatches[1].spot && parsed.swatches[1].global); + assert_eq!(parsed.groups.len(), 1); + assert_eq!(parsed.groups[0].name, "Group 1"); + } + + #[test] + fn css_output() { + let pal = Palette { + name: "Brand".into(), + swatches: vec![ + PaletteSwatch { name: "Primary Blue".into(), color: PaletteColor::rgb8(0, 102, 204), global: true, spot: true }, + PaletteSwatch { name: "Primary Blue".into(), color: PaletteColor::rgb8(0, 0, 0), global: false, spot: false }, + ], + groups: vec![], + }; + let bytes = write_palette(&pal, PaletteFormat::Css).expect("write css"); + let css = String::from_utf8(bytes).expect("utf8"); + assert!(css.contains("--primary-blue: #0066cc; /* spot */")); + assert!(css.contains("--primary-blue-2: #000000;")); + } + + #[test] + fn acb_read() { + let mut acb = Vec::new(); + acb.extend_from_slice(b"8BCB"); + acb.extend_from_slice(&1u16.to_be_bytes()); + acb.extend_from_slice(&3000u16.to_be_bytes()); + let put_str = |buf: &mut Vec, s: &str| { + let units: Vec = s.encode_utf16().collect(); + buf.extend_from_slice(&(units.len() as u32).to_be_bytes()); + for u in units { + buf.extend_from_slice(&u.to_be_bytes()); + } + }; + put_str(&mut acb, "$$$/Book/Title=Pantone^R"); + put_str(&mut acb, "PANTONE "); + put_str(&mut acb, " C"); + put_str(&mut acb, ""); + acb.extend_from_slice(&1u16.to_be_bytes()); // count + acb.extend_from_slice(&7u16.to_be_bytes()); // page size + acb.extend_from_slice(&0u16.to_be_bytes()); // page offset + acb.extend_from_slice(&0u16.to_be_bytes()); // RGB + put_str(&mut acb, "185"); + acb.extend_from_slice(b"000185"); + acb.extend_from_slice(&[228, 0, 43]); + acb.extend_from_slice(b"spflspot"); + + assert!(sniff_palette(&acb)); + let parsed = read_palette(&acb, "fallback").expect("read acb"); + assert_eq!(parsed.name, "Pantone®"); + assert_eq!(parsed.swatches.len(), 1); + assert_eq!(parsed.swatches[0].name, "PANTONE 185 C"); + assert!(parsed.swatches[0].spot); + } +} diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 5a6b4bcd5..219cf67c1 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -214,6 +214,12 @@ craft-evm = { workspace = true, optional = true } 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-null = { workspace = true, optional = true } +craft-gpu-providers = { workspace = true, optional = true } +craft-gpu-wgpu = { workspace = true, optional = true } +craft-ipp = { workspace = true, optional = true } +craft-ppt-binary = { workspace = true, optional = true } [features] ui = [ @@ -310,6 +316,7 @@ audio-alac-decode = ["audio", "craft-audio/alac-decode"] audio-alac-encode = ["audio", "craft-audio/alac-encode"] audio-decode = ["audio", "craft-audio/decode"] audio-decode-native = ["audio", "craft-audio/decode-native"] +audio-dsd = ["audio", "craft-audio/dsd"] audio-eac3-encode = ["audio", "craft-audio/eac3-encode"] audio-encode = ["audio", "craft-audio/encode"] audio-flac-decode = ["audio", "craft-audio/flac-decode"] @@ -347,6 +354,7 @@ ber = ["dep:craft-ber"] browse = ["dep:craft-browse"] captions = ["dep:craft-captions"] +captions-mov-text = ["captions", "craft-captions/mov-text"] cfb = ["dep:craft-cfb"] @@ -494,6 +502,19 @@ geom = ["dep:craft-geom"] gif = ["dep:craft-gif"] gif-frames = ["gif", "craft-gif/frames"] +gpu = ["dep:craft-gpu"] + +gpu-null = ["dep:craft-gpu-null"] + +gpu-providers = ["dep:craft-gpu-providers"] + +gpu-wgpu = ["dep:craft-gpu-wgpu"] +gpu-wgpu-adapter-probe = ["gpu-wgpu", "craft-gpu-wgpu/adapter-probe"] +gpu-wgpu-native-dx12 = ["gpu-wgpu", "craft-gpu-wgpu/native-dx12"] +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"] + gridcraft-format = ["dep:craft-gridcraft-format"] gzip = ["dep:craft-gzip"] @@ -535,6 +556,8 @@ indd = ["dep:craft-indd"] ipc = ["dep:craft-ipc"] +ipp = ["dep:craft-ipp"] + java-class = ["dep:craft-java-class"] jmap = ["dep:craft-jmap"] @@ -676,6 +699,8 @@ plist = ["dep:craft-plist"] plotter = ["dep:craft-plotter"] plotter-serde = ["plotter", "craft-plotter/serde"] +ppt-binary = ["dep:craft-ppt-binary"] + pptx = ["dep:craft-pptx"] prc = ["dep:craft-prc"] diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index 2e5c61777..9ddb438ce 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "e9711ca9b69772f875ae0d1cef1977ff8c16234d"; +pub const REV: &str = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 4a1a568b7..06a416a30 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -149,6 +149,14 @@ pub use craft_gcode as gcode; pub use craft_geom as geom; #[cfg(feature = "gif")] pub use craft_gif as gif; +#[cfg(feature = "gpu")] +pub use craft_gpu as gpu; +#[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 = "gridcraft-format")] pub use craft_gridcraft_format as gridcraft_format; #[cfg(feature = "gzip")] @@ -177,6 +185,8 @@ pub use craft_imaging as imaging; pub use craft_indd as indd; #[cfg(feature = "ipc")] pub use craft_ipc as ipc; +#[cfg(feature = "ipp")] +pub use craft_ipp as ipp; #[cfg(feature = "java-class")] pub use craft_java_class as java_class; #[cfg(feature = "jmap")] @@ -269,6 +279,8 @@ pub use craft_platform as platform; pub use craft_plist as plist; #[cfg(feature = "plotter")] pub use craft_plotter as plotter; +#[cfg(feature = "ppt-binary")] +pub use craft_ppt_binary as ppt_binary; #[cfg(feature = "pptx")] pub use craft_pptx as pptx; #[cfg(feature = "prc")] diff --git a/crates/csv/README.md b/crates/csv/README.md index 8fd264d4c..7df204e10 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -11,7 +11,7 @@ mapping a SYLK sheet onto a document are the caller's work. | Function | What it does | |---|---| | `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 | -| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a 64 KiB sample; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | +| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | | `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text | | `records(text, delim, quote, max_records, max_fields)` | the same, collected | | `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing | diff --git a/crates/csv/src/lib.rs b/crates/csv/src/lib.rs index 395ad2152..f4a82f393 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -37,7 +37,7 @@ pub use decode::{decode_text, decode_utf8}; /// the same rules pick among the candidates whose records hold only their delimiters and /// whitespace, such as an exported row of empty cells; a candidate that finds a record with /// other text is left out of that pick. Comma is the fallback when neither pick finds one. -/// Only the first 64 KiB are read. A record cut off at the end of that sample is left out, +/// Only the first 65,536 characters are read. A record cut off at the end of that sample is left out, /// except when no candidate finds coherent complete records with a delimiter in each. Then a candidate /// that finds no complete record with other text counts the delimiters read so far in the first /// such record, unless it found rows of its empty cells and that record has none of its @@ -45,11 +45,8 @@ pub use decode::{decode_text, decode_utf8}; /// with one. When one of those candidates ends the sample inside a quoted field, each of them /// counts only up to that field's opening quote. pub fn sniff_delimiter(text: &str, quote: char) -> u8 { - const SAMPLE_BYTES: usize = 64 * 1024; - let mut sample_end = text.len().min(SAMPLE_BYTES); - while !text.is_char_boundary(sample_end) { - sample_end -= 1; - } + const SAMPLE_CHARS: usize = 64 * 1024; + let sample_end = text.char_indices().nth(SAMPLE_CHARS).map_or(text.len(), |(at, _)| at); let sample = &text[..sample_end]; let truncated = sample_end < text.len(); let mut scans = b"\t,;".map(|delimiter| scan_delimiter(sample, delimiter, quote)); @@ -441,6 +438,15 @@ mod tests { assert_eq!(sniff_delimiter(&format!("a,b,c;\"hello,\";d\n{}", "x;y;z\n".repeat(12_000)), '"'), b';'); } + #[test] + fn delimiter_sniffing_samples_characters_not_bytes() { + // 30,000 three-byte characters are 90,000 bytes, more than 64 KiB. + assert_eq!(sniff_delimiter(&format!("{};b;c\n1;2;3\n", "€".repeat(30_000)), '"'), b';'); + // The 65,536th character is in the sample and the 65,537th is not. + assert_eq!(sniff_delimiter(&format!("{};x\n1;2\n", "€".repeat(65_535)), '"'), b';'); + assert_eq!(sniff_delimiter(&format!("{};x\n1;2\n", "€".repeat(65_536)), '"'), b','); + } + // A sheet whose only value is far down exports rows of empty cells that fill the whole sample. #[test] fn delimiter_sniffing_reads_a_sparse_semicolon_export() { diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml index 0daa6107f..bc859ea5f 100644 --- a/crates/develop/Cargo.toml +++ b/crates/develop/Cargo.toml @@ -14,5 +14,9 @@ workspace = true craft-develop-model = { workspace = true } serde = { workspace = true } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +rayon = { workspace = true } + [dev-dependencies] +craft-render-parity = { workspace = true } proptest = { workspace = true } diff --git a/crates/develop/README.md b/crates/develop/README.md new file mode 100644 index 000000000..92f543eb3 --- /dev/null +++ b/crates/develop/README.md @@ -0,0 +1,43 @@ +# craft-develop + +The raw develop pipeline, CPU path: the shared pipeline of +[#587](https://github.com/storytold/craft-libs/issues/587), moved from LightCraft one module at a time. No `unsafe`, +no panics on hostile input, no file I/O, and it builds for `wasm32-unknown-unknown`. + +```toml +craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "" } +``` + +## What is here + +| Module | From LightCraft (`a75497d6`) | Contents | +|---|---|---| +| `color::spline` | `crates/color/src/spline.rs` | `MonotoneCurve` (a tone curve through points that does not overshoot) and `Lut1`. | +| `curve` | `crates/pipeline` | The parametric tone curve and its regions. | +| `lut` | `crates/pipeline` | 3D lookup tables and the `.cube` reader. | +| `inpaint` | `crates/inpaint` | Content-aware hole filling for spot removal: `complete` (multi-scale patch completion with PatchMatch) and `membrane_fill` (a smooth harmonic fill, its seed and fallback). Interleaved `f32` buffers of any channel count, a fixed-seed RNG, the same result on any number of threads. | + +## Parity with LightCraft + +Each module comes with a test that its output is LightCraft's at the base commit, compared with +[`craft-render-parity`](../render-parity/README.md) at `Tolerance::BASELINE`. The expected pictures in +`tests/fixtures/` were written by LightCraft's own crate at that commit, on the scene the test builds. + +Differences from LightCraft (ordinary-range output is covered by the baseline fixtures): + +- `inpaint::complete_with` returns `None` for a patch radius wider than the image before computing with it (LightCraft + reaches the same `None`, or overflows on a huge radius), returns an image with no pixels at once, and reports + `Cancelled` when any one poll said so, including a poll made on a worker thread. + +- `membrane_fill` scales extreme finite boundaries for the harmonic solve and bounds the result by those + boundaries, avoiding overflow in means and neighbour sums. Known pixels remain unchanged; ordinary + values take the original arithmetic path. This does not promise arbitrary extreme-value safety for + PatchMatch completion, which also computes squared costs and downsamples its input. +- Membrane cell indices retain `usize` width. PatchMatch rejects grids whose signed search offsets, + summed-area counts or padded table cannot be represented; patch-area arithmetic no longer overflows + `i32`. An already-cancelled oversized-patch request returns `Cancelled`, not an unavailable-patch result. + +## Not here yet + +The rest of the pipeline: the rest of colour, raster, the sensor stage, raw loading and the render stages. No app uses this crate +yet. diff --git a/crates/develop/src/inpaint.rs b/crates/develop/src/inpaint.rs new file mode 100644 index 000000000..7393ef4f3 --- /dev/null +++ b/crates/develop/src/inpaint.rs @@ -0,0 +1,132 @@ +//! Content-aware hole filling (inpainting) for the Remove tool. +//! +//! * [`complete`]: multi-scale patch-based completion (Wexler, Shechtman, Irani 2007) with the +//! nearest-neighbour field found by PatchMatch (Barnes et al. 2009). See [`patchmatch`]. +//! * [`membrane_fill`]: smooth harmonic fill, used to seed the coarsest level and as a fallback. +//! +//! Buffers are interleaved `w × h × ch` floats in any colour model plus a `w × h` hole mask. +//! Everything is deterministic (fixed-seed RNG, results independent of the thread count) and never +//! panics on mismatched sizes: such calls return `None` or the input unchanged. +//! +//! Sources: C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman, *PatchMatch: A Randomized +//! Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009; Y. Wexler, E. Shechtman, +//! M. Irani, *Space-Time Completion of Video*, PAMI 2007. +//! +//! Ported from PhotoCraft (`crates/algo/src/inpaint.rs`, `poisson.rs`, MIT OR Apache-2.0, same +//! organisation; see `NOTICE`). + +pub mod membrane; +pub mod patchmatch; + +pub use membrane::membrane_fill; +pub use patchmatch::{CompleteParams, complete, complete_with}; + +/// A cancelled [`complete_with`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Cancelled; + +impl std::fmt::Display for Cancelled { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("cancelled") + } +} + +impl std::error::Error for Cancelled {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finite_extreme_membrane_boundaries_stay_finite() { + let img = [f32::MAX, 0.0, f32::MAX]; + let out = membrane_fill(3, 1, 1, &img, &[false, true, false]); + assert_eq!(out, vec![f32::MAX; 3]); + assert_eq!(membrane_fill(3, 1, 1, &[-f32::MAX, 0.0, f32::MAX], &[false, true, false]), vec![-f32::MAX, 0.0, f32::MAX]); + // Also exercise the multigrid restriction and prolongation at extreme scale. + let hole: Vec = (0..256).map(|i| i % 16 > 0 && i % 16 < 15 && i / 16 > 0 && i / 16 < 15).collect(); + assert_eq!(membrane_fill(16, 16, 1, &[f32::MAX; 256], &hole), vec![f32::MAX; 256]); + let img: Vec = (0..256).map(|i| if i % 16 < 8 { -f32::MAX } else { f32::MAX }).collect(); + let out = membrane_fill(16, 16, 1, &img, &hole); + for ((&actual, &original), &unknown) in out.iter().zip(&img).zip(&hole) { + assert!(actual.is_finite() && (-f32::MAX..=f32::MAX).contains(&actual)); + if !unknown { + assert_eq!(actual.to_bits(), original.to_bits()); + } + } + } + + #[test] + fn cancellation_precedes_an_oversized_patch_result() { + let mut hole = vec![false; 32 * 32]; + hole[16 * 32 + 16] = true; + let p = CompleteParams { patch_radius: 16, ..CompleteParams::default() }; + assert_eq!(complete_with(32, 32, 1, &[0.5; 32 * 32], &hole, &p, &|| true), Err(Cancelled)); + } + + #[test] + fn hostile_sizes_do_not_panic() { + assert_eq!(complete(4, 4, 3, &[0.0; 5], &[true; 16], &CompleteParams::default()), None); + assert_eq!(complete(4, 4, 0, &[], &[true; 16], &CompleteParams::default()), None); + assert_eq!(complete(usize::MAX, 2, 3, &[0.0; 6], &[true; 2], &CompleteParams::default()), None); + assert_eq!(membrane_fill(4, 4, 1, &[0.5; 3], &[true; 16]), vec![0.5; 3]); + // A hole covering everything: nothing to copy from. + assert_eq!(complete(16, 16, 1, &[0.5; 256], &[true; 256], &CompleteParams::default()), None); + // A tiny image smaller than a patch. + let _ = complete(2, 2, 1, &[0.5; 4], &[true, false, false, false], &CompleteParams::default()); + } + + #[test] + fn a_patch_radius_no_image_could_hold_finds_nothing_to_copy() { + let mut hole = vec![false; 32 * 32]; + hole[16 * 32 + 16] = true; + for patch_radius in [16, usize::MAX / 2, usize::MAX] { + let p = CompleteParams { patch_radius, ..CompleteParams::default() }; + assert_eq!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p), None, "radius {patch_radius}"); + } + // Cancelled is still cancelled, not "nothing to copy from". + let p = CompleteParams { patch_radius: 16, ..CompleteParams::default() }; + assert_eq!(complete_with(32, 32, 1, &[0.5; 32 * 32], &hole, &p, &|| true), Err(Cancelled)); + // A radius the image has room for still fills. + let p = CompleteParams { patch_radius: 5, ..CompleteParams::default() }; + assert!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p).is_some()); + } + + #[test] + fn an_image_with_no_pixels_is_returned_without_walking_its_rows() { + let p = CompleteParams::default(); + assert_eq!(complete_with(0, usize::MAX, 1, &[], &[], &p, &|| false), Ok(Some(Vec::new()))); + assert_eq!(complete_with(usize::MAX, 0, 3, &[], &[], &p, &|| false), Ok(Some(Vec::new()))); + } + + /// Whichever poll says "cancelled", and only that one, the call ends in `Err`: also when it was a + /// worker's poll, which can stop the worker but not return. + #[test] + fn one_cancelled_poll_anywhere_cancels_the_call() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let (w, h) = (48usize, 48usize); + let img: Vec = (0..w * h).map(|i| ((i % w) as f32 * 0.37).sin() * 0.5 + 0.5).collect(); + let hole: Vec = (0..w * h).map(|i| (i % w).abs_diff(24) < 5 && (i / w).abs_diff(24) < 5).collect(); + let p = CompleteParams::default(); + let polls = AtomicUsize::new(0); + let count = || { + polls.fetch_add(1, Ordering::Relaxed); + false + }; + assert!(matches!(complete_with(w, h, 1, &img, &hole, &p, &count), Ok(Some(_)))); + let total = polls.load(Ordering::Relaxed); + assert!(total > 8, "the scene polls in the workers too: {total}"); + for nth in 0..total { + let polls = AtomicUsize::new(0); + let once = || polls.fetch_add(1, Ordering::Relaxed) == nth; + assert_eq!(complete_with(w, h, 1, &img, &hole, &p, &once), Err(Cancelled), "poll {nth} of {total}"); + } + } + + #[test] + fn cancellation_stops() { + let img = vec![0.5f32; 64 * 64]; + let hole: Vec = (0..64 * 64usize).map(|i| (i % 64).abs_diff(32) < 4 && (i / 64).abs_diff(32) < 4).collect(); + assert_eq!(complete_with(64, 64, 1, &img, &hole, &CompleteParams::default(), &|| true), Err(Cancelled)); + } +} diff --git a/crates/develop/src/inpaint/membrane.rs b/crates/develop/src/inpaint/membrane.rs new file mode 100644 index 000000000..83f5d2882 --- /dev/null +++ b/crates/develop/src/inpaint/membrane.rs @@ -0,0 +1,255 @@ +//! Membrane (harmonic) fill: `Δv = 0` inside a hole with the known pixels as Dirichlet boundary. +//! Used to initialise the coarsest level of [`crate::inpaint::complete`] and as its fallback. +//! +//! Sources: the membrane interpolant of P. Pérez, M. Gangnet, A. Blake, *Poisson Image Editing*, +//! ACM SIGGRAPH 2003 (§3), solved by successive over-relaxation on the 4-connected grid, accelerated +//! cascadically (solve on a half-resolution grid, prolong bilinearly, a few SOR sweeps per level). +//! Ported from PhotoCraft's `algo::poisson` (MIT OR Apache-2.0). + +fn allocation_fits(len: usize) -> bool { + len.checked_mul(std::mem::size_of::()).is_some_and(|bytes| bytes <= isize::MAX as usize) +} + +/// Convergence threshold (max per-sweep update) for the SOR sweeps. +const TOL: f32 = 2e-5; +/// SOR sweeps (cap) and relaxation factor on every level above the coarsest: tuned so a 96×72 disc +/// is within ~1e-3 of a fully converged Gauss–Seidel solve (below one 8-bit step). +const FINE_ITERS: usize = 30; +const FINE_OMEGA: f32 = 1.7; + +/// Solve `Δv = 0` on `unknown` pixels with Dirichlet values from the known pixels of `v` +/// (out-of-grid neighbours are ignored, i.e. a Neumann boundary). `v` holds the known values on +/// entry and the solution on exit. Cascadic multigrid + SOR. +pub(crate) fn solve_membrane(w: usize, h: usize, unknown: &[bool], v: &mut [f32]) { + if Some(unknown.len()) != w.checked_mul(h) || v.len() != unknown.len() { + return; + } + if !allocation_fits::<(usize, u8)>(unknown.iter().filter(|&&hole| hole).count()) { + return; + } + // Keep the ordinary path bit-for-bit unchanged. Extremely large finite boundaries can + // overflow even their mean or a four-neighbour sum; harmonic interpolation is linear, + // so solve those channels at unit scale instead. The final clamp enforces the harmonic + // maximum principle if the finite-iteration relaxation overshoots a boundary extremum. + let mut low = f32::INFINITY; + let mut high = f32::NEG_INFINITY; + for (&value, &hole) in v.iter().zip(unknown) { + if !hole { + if !value.is_finite() { + solve_rec(w, h, unknown, v, 0, &|| false); + return; + } + low = low.min(value); + high = high.max(value); + } + } + let scale = low.abs().max(high.abs()); + let needs_scale = scale.is_finite() && f64::from(scale) > f64::from(f32::MAX) / v.len().max(16) as f64; + if needs_scale { + let mut normalized: Vec = v.iter().map(|&value| value / scale).collect(); + solve_rec(w, h, unknown, &mut normalized, 0, &|| false); + for ((value, solved), &hole) in v.iter_mut().zip(normalized).zip(unknown) { + if hole { + *value = (f64::from(solved) * f64::from(scale)).clamp(f64::from(low), f64::from(high)) as f32; + } + } + } else { + solve_rec(w, h, unknown, v, 0, &|| false); + } +} + +fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize, stop: &(dyn Fn() -> bool + Sync)) { + if stop() { + return; + } + let n_unknown = unknown.iter().filter(|u| **u).count(); + if n_unknown == 0 { + return; + } + // Like the cell list below, this filtered collection must not grow geometrically. + let mut known = Vec::with_capacity(v.len() - n_unknown); + known.extend(v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x)); + if known.is_empty() { + return; // nothing to interpolate from + } + if w >= 8 && h >= 8 && n_unknown > 64 && depth < 16 { + // Restrict: a coarse pixel is known if any of its children is (value = mean of known children). + let (cw, chh) = (w.div_ceil(2), h.div_ceil(2)); + let mut cu = vec![true; cw * chh]; + let mut cv = vec![0.0f32; cw * chh]; + for cy in 0..chh { + for cx in 0..cw { + let (mut s, mut n) = (0.0f32, 0u32); + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let (x, y) = (cx * 2 + dx, cy * 2 + dy); + if x < w && y < h && !unknown[y * w + x] { + s += v[y * w + x]; + n += 1; + } + } + if n > 0 { + cu[cy * cw + cx] = false; + cv[cy * cw + cx] = s / n as f32; + } + } + } + solve_rec(cw, chh, &cu, &mut cv, depth + 1, stop); + // Prolong: bilinear sample of the coarse solution as the initial guess. + for y in 0..h { + let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (chh - 1) as f32); + let y0 = fy.floor() as usize; + let y1 = (y0 + 1).min(chh - 1); + let ty = fy - y0 as f32; + for x in 0..w { + if !unknown[y * w + x] { + continue; + } + let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (cw - 1) as f32); + let x0 = fx.floor() as usize; + let x1 = (x0 + 1).min(cw - 1); + let tx = fx - x0 as f32; + let a = cv[y0 * cw + x0] + (cv[y0 * cw + x1] - cv[y0 * cw + x0]) * tx; + let b = cv[y1 * cw + x0] + (cv[y1 * cw + x1] - cv[y1 * cw + x0]) * tx; + v[y * w + x] = a + (b - a) * ty; + } + } + sor(w, h, unknown, v, FINE_ITERS, FINE_OMEGA, stop); + } else { + let mean = known.iter().sum::() / known.len() as f32; + for (x, u) in v.iter_mut().zip(unknown) { + if *u { + *x = mean; + } + } + sor(w, h, unknown, v, 2000, 1.85, stop); + } +} + +/// SOR sweeps over the unknown pixels until the largest update drops below [`TOL`]. +fn sor(w: usize, h: usize, unknown: &[bool], v: &mut [f32], max_iter: usize, omega: f32, stop: &(dyn Fn() -> bool + Sync)) { + // Precompute the unknown pixels and which neighbours exist. + // The caller validated this exact count; reserve it before extend so geometric growth + // cannot round the allocation above the target's capacity limit. + let mut cells = Vec::with_capacity(unknown.iter().filter(|&&hole| hole).count()); + cells.extend((0..w * h).filter(|&i| unknown[i]).map(|i| { + let (x, y) = (i % w, i / w); + let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3); + (i, m) + })); + for _ in 0..max_iter { + if stop() { + return; + } + let mut max_d = 0.0f32; + for &(i, m) in &cells { + let (s, n) = if m == 0b1111 { + (v[i - 1] + v[i + 1] + v[i - w] + v[i + w], 4.0) + } else { + let mut s = 0.0; + let mut n = 0.0; + if m & 1 != 0 { + s += v[i - 1]; + n += 1.0; + } + if m & 2 != 0 { + s += v[i + 1]; + n += 1.0; + } + if m & 4 != 0 { + s += v[i - w]; + n += 1.0; + } + if m & 8 != 0 { + s += v[i + w]; + n += 1.0; + } + if n == 0.0 { + continue; + } + (s, n) + }; + let d = omega * (s / n - v[i]); + v[i] += d; + max_d = max_d.max(d.abs()); + } + if max_d < TOL { + break; + } + } +} + +/// Map `f` over the channels of an interleaved buffer as planar slices (parallel on native). +fn per_channel(w: usize, h: usize, ch: usize, f: impl Fn(usize) -> Vec + Sync + Send) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + let planes: Vec> = if w * h >= 64 * 64 { + use rayon::prelude::*; + (0..ch).into_par_iter().map(&f).collect() + } else { + (0..ch).map(&f).collect() + }; + #[cfg(target_arch = "wasm32")] + let planes: Vec> = (0..ch).map(&f).collect(); + let mut out = vec![0.0f32; w * h * ch]; + for (c, p) in planes.iter().enumerate() { + for (i, v) in p.iter().enumerate() { + out[i * ch + c] = *v; + } + } + out +} + +/// Membrane fill (no source texture): harmonic interpolation of the known pixels into `hole`. +/// `img` is interleaved `w × h × ch`, `hole` has `w × h` entries; on a size mismatch `img` comes back +/// unchanged. +pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) -> Vec { + if Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) { + return img.to_vec(); + } + // no pixels: nothing to fill (and `ch` would otherwise size one plane per channel, whatever it claims) + if hole.is_empty() { + return img.to_vec(); + } + // A valid input slice does not prove the wider index/plane vectors fit the target. + if !allocation_fits::>(ch) || !allocation_fits::<(usize, u8)>(hole.iter().filter(|&&hole| hole).count()) { + return img.to_vec(); + } + per_channel(w, h, ch, |c| { + let mut v: Vec = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect(); + solve_membrane(w, h, hole, &mut v); + v + }) +} +#[cfg(test)] +mod tests { + use super::*; + + fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { + (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() + } + + #[test] + fn auxiliary_vector_limits_are_checked_without_allocating() { + let max_cells = isize::MAX as usize / std::mem::size_of::<(usize, u8)>(); + assert!(allocation_fits::<(usize, u8)>(max_cells)); + assert!(!allocation_fits::<(usize, u8)>(max_cells + 1)); + assert!(!allocation_fits::>(usize::MAX)); + } + + #[test] + fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() { + assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty()); + assert!(membrane_fill(3, 0, usize::MAX / 2, &[], &[]).is_empty()); + } + + #[test] + fn membrane_reproduces_linear_boundary() { + // A linear function is harmonic: the solve must reproduce it exactly inside the hole. + let (w, h) = (80, 60); + let unknown = disc(w, h, 40.0, 30.0, 20.0); + let truth: Vec = (0..w * h).map(|i| 0.2 + 0.005 * (i % w) as f32 + 0.003 * (i / w) as f32).collect(); + let mut v: Vec = truth.iter().zip(&unknown).map(|(t, u)| if *u { 0.0 } else { *t }).collect(); + solve_membrane(w, h, &unknown, &mut v); + let err = v.iter().zip(&truth).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(err < 2e-3, "{err}"); + } +} diff --git a/crates/develop/src/inpaint/patchmatch.rs b/crates/develop/src/inpaint/patchmatch.rs new file mode 100644 index 000000000..d94399f25 --- /dev/null +++ b/crates/develop/src/inpaint/patchmatch.rs @@ -0,0 +1,653 @@ +//! Hole filling for Spot Healing: patch-based completion, proximity match and texture synthesis. +//! +//! * [`complete`], content-aware fill: the multi-scale "space-time completion" EM scheme of +//! Y. Wexler, E. Shechtman, M. Irani, *Space-Time Completion of Video*, IEEE TPAMI 2007, with the +//! nearest-neighbour field computed by C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman, +//! *PatchMatch: A Randomized Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009 +//! (random init, propagation, exponentially shrinking random search). Each EM iteration finds, for +//! every patch overlapping the hole, its most similar fully-known patch, then re-estimates hole +//! pixels by a similarity-weighted vote of the overlapping matches. Coarse-to-fine over an image +//! pyramid (the coarsest level is initialised by membrane interpolation), so large holes stay cheap. +//! * `best_offset`, proximity match: the single displacement whose surrounding ring best matches the +//! ring around the hole (sum of squared differences), i.e. an automatic Healing Brush source. +//! * `synthesize`, create texture: patch-based texture synthesis in the style of A. Efros, +//! W. Freeman, *Image Quilting for Texture Synthesis and Transfer*, SIGGRAPH 2001 (blocks picked from +//! random candidates by overlap error, feathered overlap instead of a min-cut seam). +//! +//! Ported from PhotoCraft's `algo::inpaint` (MIT OR Apache-2.0); its proximity match and texture +//! synthesis are left out. +//! +//! All functions take interleaved `w × h × ch` normalised floats (any colour model/depth) and a +//! `w × h` hole mask, and return a full buffer equal to the input outside the hole. They are +//! deterministic (fixed-seed hash RNG, results independent of thread count). + +use crate::inpaint::Cancelled; +use crate::inpaint::membrane::membrane_fill; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// Below this many grid cells a level runs single-threaded (thread hand-off costs more than it saves). +#[cfg(not(target_arch = "wasm32"))] +const PAR_MIN: usize = 128 * 128; + +/// SplitMix64: tiny deterministic RNG. +#[derive(Clone)] +struct Rng(u64); +impl Rng { + fn new(seed: u64) -> Self { + Rng(seed ^ 0x9E37_79B9_7F4A_7C15) + } + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + /// Uniform integer in `lo..=hi`. + fn range(&mut self, lo: i32, hi: i32) -> i32 { + if hi <= lo { + return lo; + } + lo + (self.next() % (hi - lo + 1) as u64) as i32 + } +} + +/// Parameters for [`complete`]. +#[derive(Clone, Debug, PartialEq)] +pub struct CompleteParams { + /// Patch radius (patches are `2r+1` square). + pub patch_radius: usize, + /// EM iterations at the coarsest level (finer levels use fewer, down to `min_em_iters`). + pub em_iters: usize, + pub min_em_iters: usize, + /// PatchMatch passes per EM iteration. + pub pm_iters: usize, + /// Levels where the hole is wider than this (in that level's pixels) only *refine* the upsampled + /// match field (one local PatchMatch pass and one vote), which keeps big holes tractable: the + /// structure is decided at coarse scale, fine levels just add detail. + pub refine_extent: usize, + pub seed: u64, +} + +impl Default for CompleteParams { + fn default() -> Self { + Self { patch_radius: 3, em_iters: 8, min_em_iters: 2, pm_iters: 2, refine_extent: 96, seed: 1 } + } +} + +/// One pyramid level. +#[derive(Clone)] +struct Level { + w: usize, + h: usize, + img: Vec, + hole: Vec, +} + +fn downsample(l: &Level, ch: usize) -> Level { + let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); + let mut img = vec![0.0f32; w * h * ch]; + let mut hole = vec![false; w * h]; + for y in 0..h { + for x in 0..w { + let mut n = 0.0f32; + let o = (y * w + x) * ch; + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let (sx, sy) = (x * 2 + dx, y * 2 + dy); + if sx >= l.w || sy >= l.h { + continue; + } + let si = sy * l.w + sx; + if l.hole[si] { + hole[y * w + x] = true; + } else { + for c in 0..ch { + img[o + c] += l.img[si * ch + c]; + } + n += 1.0; + } + } + if n > 0.0 { + for c in 0..ch { + img[o + c] /= n; + } + } + } + } + Level { w, h, img, hole } +} + +// Search offsets add/subtract a full image dimension in i32. Summed-area queries +// add two u32 entries before subtracting. Both the padded table and the larger +// per-pixel nearest-neighbour/valid-coordinate arrays must fit a Vec. +fn supported_grid(w: usize, h: usize) -> bool { + let max_dimension = (i32::MAX / 2) as usize; + w <= max_dimension + && h <= max_dimension + && w.checked_mul(h).is_some_and(|n| n <= (u32::MAX / 2) as usize) + && w.checked_mul(h).and_then(|n| n.checked_mul(std::mem::size_of::<(i32, i32)>())).is_some_and(|bytes| bytes <= isize::MAX as usize) + && w.checked_add(1) + .and_then(|pw| h.checked_add(1).and_then(|ph| pw.checked_mul(ph))) + .and_then(|n| n.checked_mul(std::mem::size_of::())) + .is_some_and(|bytes| bytes <= isize::MAX as usize) +} + +/// Reserve the already counted source centres exactly, then retain row-major order. +fn source_centres(w: usize, valid: &[bool], count: usize, check: &impl Fn() -> Result<(), Cancelled>) -> Result, Cancelled> { + let mut centres = Vec::with_capacity(count); + for (i, &is_valid) in valid.iter().enumerate() { + if i % (w * 32) == 0 { + check()?; + } + if is_valid { + centres.push(((i % w) as i32, (i / w) as i32)); + } + } + Ok(centres) +} + +/// Summed-area table of a boolean grid (`(w+1) × (h+1)`). +fn integral(w: usize, h: usize, m: &[bool]) -> Vec { + let mut s = vec![0u32; (w + 1) * (h + 1)]; + for y in 0..h { + let mut row = 0u32; + for x in 0..w { + row += u32::from(m[y * w + x]); + s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row; + } + } + s +} + +/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`. +fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 { + let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); + let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh)); + if x1 <= x0 || y1 <= y0 { + return 0; + } + let w1 = gw + 1; + s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0] +} + +fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> { + let mut b: Option<(usize, usize, usize, usize)> = None; + for y in 0..h { + for x in 0..w { + if hole[y * w + x] { + b = Some(match b { + None => (x, y, x + 1, y + 1), + Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)), + }); + } + } + } + b +} + +/// Per-level PatchMatch/EM state. +struct Solver<'a> { + w: usize, + h: usize, + ch: usize, + r: i32, + img: &'a mut Vec, + hole: &'a [bool], + /// Valid source centres: the whole patch is inside the grid and contains no hole pixel. + valid: Vec, + valid_list: Vec<(i32, i32)>, + /// Target centres (patch overlaps the hole), row-major. + targets: Vec, + /// Cancellation: checked per row band; a cancelled solve's output is discarded. + ctl: &'a (dyn Fn() -> bool + Sync), +} + +impl Solver<'_> { + #[inline] + fn is_valid(&self, x: i32, y: i32) -> bool { + x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize] + } + + /// SSD between the (clipped) target patch at `t` and the source patch at `s`, per sample. + fn dist(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { + let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); + let diameter = f64::from(2 * r + 1); + let full = (diameter * diameter) as f32 * ch as f32; + let mut sum = 0.0f32; + let mut n = 0usize; + for dy in -r..=r { + let ty = t.1 + dy; + if ty < 0 || ty >= h { + continue; + } + let sy = s.1 + dy; + for dx in -r..=r { + let tx = t.0 + dx; + if tx < 0 || tx >= w { + continue; + } + let ti = (ty as usize * self.w + tx as usize) * ch; + let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; + for c in 0..ch { + let d = self.img[ti + c] - self.img[si + c]; + sum += d * d; + } + n += ch; + } + // Early out: the mean can only be ≥ sum / (full patch size). + if sum > cutoff * full { + return f32::INFINITY; + } + } + if n == 0 { f32::INFINITY } else { sum / n as f32 } + } + + /// One PatchMatch pass over all target rows, in parallel bands (each band propagates within itself). + fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) { + const BAND: usize = 16; + let w = self.w; + let reverse = pass % 2 == 1; + let band_fn = |bi: usize, nn: &mut [(i32, i32)], co: &mut [f32]| { + if (self.ctl)() { + return; + } + let mut rng = Rng::new(seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40)); + let y0 = bi * BAND; + let rows = nn.len() / w; + let step: i32 = if reverse { -1 } else { 1 }; + for ry in 0..rows { + let ly = if reverse { rows - 1 - ry } else { ry }; + let y = y0 + ly; + for rx in 0..w { + let x = if reverse { w - 1 - rx } else { rx }; + let li = ly * w + x; + if !self.targets[y * w + x] { + continue; + } + let t = (x as i32, y as i32); + let (mut best, mut bc) = (nn[li], co[li]); + // Propagation from the already-visited neighbours (within this band). + let nx = x as i32 - step; + if nx >= 0 && (nx as usize) < w { + let c = nn[ly * w + nx as usize]; + let cand = (c.0 + step, c.1); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + } + let nly = ly as i32 - step; + if nly >= 0 && (nly as usize) < rows { + let c = nn[nly as usize * w + x]; + let cand = (c.0, c.1 + step); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + } + // Random search in exponentially shrinking windows. + let mut rad = search_radius; + while rad >= 1 { + let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad)); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + rad /= 2; + } + nn[li] = best; + co[li] = bc; + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + if w * self.h >= PAR_MIN { + use rayon::prelude::*; + nnf.par_chunks_mut(BAND * w).zip(cost.par_chunks_mut(BAND * w)).enumerate().for_each(|(bi, (nn, co))| band_fn(bi, nn, co)); + return; + } + for (bi, (nn, co)) in nnf.chunks_mut(BAND * w).zip(cost.chunks_mut(BAND * w)).enumerate() { + band_fn(bi, nn, co); + } + } + + /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches. + fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) { + let (w, h, ch, r) = (self.w, self.h, self.ch, self.r); + // σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this). + let mut cs: Vec = cost.iter().zip(&self.targets).filter(|(c, t)| **t && c.is_finite()).map(|(c, _)| *c).collect(); + let sigma2 = if cs.is_empty() { + 1.0 + } else { + let k = (cs.len() * 3 / 4).min(cs.len() - 1); + let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b)); + v.max(1e-6) + }; + let img = &*self.img; + let row = |y: usize| -> Vec<(usize, Vec)> { + let mut out = Vec::new(); + if (self.ctl)() { + return out; + } + for x in 0..w { + if !self.hole[y * w + x] { + continue; + } + let mut acc = vec![0.0f32; ch]; + let mut wsum = 0.0f32; + for dy in -r..=r { + let ty = y as i32 + dy; + if ty < 0 || ty as usize >= h { + continue; + } + for dx in -r..=r { + let tx = x as i32 + dx; + if tx < 0 || tx as usize >= w { + continue; + } + let ti = ty as usize * w + tx as usize; + if !self.targets[ti] || !cost[ti].is_finite() { + continue; + } + let s = nnf[ti]; + let (sx, sy) = (s.0 - dx, s.1 - dy); + let wt = (-cost[ti] / (2.0 * sigma2)).exp().max(1e-8); + let si = (sy as usize * w + sx as usize) * ch; + for c in 0..ch { + acc[c] += img[si + c] * wt; + } + wsum += wt; + } + } + if wsum > 0.0 { + acc.iter_mut().for_each(|v| *v /= wsum); + out.push((x, acc)); + } + } + out + }; + #[cfg(not(target_arch = "wasm32"))] + let rows: Vec)>> = if w * h >= PAR_MIN { + use rayon::prelude::*; + (0..h).into_par_iter().map(row).collect() + } else { + (0..h).map(row).collect() + }; + #[cfg(target_arch = "wasm32")] + let rows: Vec)>> = (0..h).map(row).collect(); + for (y, r) in rows.into_iter().enumerate() { + for (x, v) in r { + self.img[(y * w + x) * ch..(y * w + x + 1) * ch].copy_from_slice(&v); + } + } + } +} + +/// Content-aware completion of `hole` (see module docs). Returns `None` when there is no fully-known +/// patch to copy from (the caller can fall back to [`membrane_fill`]). +pub fn complete(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], p: &CompleteParams) -> Option> { + // Never cancelled, so never `Err`. + complete_with(w, h, ch, img, hole, p, &|| false).unwrap_or(None) +} + +/// [`complete`] that can be cancelled (checked per EM iteration, PatchMatch pass and row band) +/// (`cancelled` is polled per EM iteration, PatchMatch pass and row band): `Err(Cancelled)` once it +/// returned `true`. `Ok(None)` also for mismatched buffer sizes or `ch == 0`. +pub fn complete_with( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + p: &CompleteParams, + cancelled: &(dyn Fn() -> bool + Sync), +) -> Result>, Cancelled> { + // The workers poll `cancelled` too and can only stop early, not return an error. One `true` from it, + // wherever it was seen, is kept, so the next check out here ends the call and a half-finished pass + // is never returned as a result. + let seen = AtomicBool::new(false); + let cancelled: &(dyn Fn() -> bool + Sync) = &|| { + if !seen.load(Ordering::Relaxed) && cancelled() { + seen.store(true, Ordering::Relaxed); + } + seen.load(Ordering::Relaxed) + }; + let check = || if cancelled() { Err(Cancelled) } else { Ok(()) }; + if ch == 0 || Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) { + return Ok(None); + } + // No pixels (a zero width or height, whatever the other is): nothing to scan and nothing to fill. + if hole.is_empty() { + return Ok(Some(img.to_vec())); + } + if !supported_grid(w, h) { + check()?; + return Ok(None); + } + let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Ok(Some(img.to_vec())) }; + let r = p.patch_radius.max(1); + // A patch wider than the image has no place to be copied from, which is the `None` the search below + // would reach anyway. Said here, before `2 * r + 1` and `r as i32` can overflow on an absurd radius. + if r > (w.min(h) - 1) / 2 { + check()?; + return Ok(None); + } + let psz = 2 * r + 1; + // Pyramid: shrink until the hole is a few patches across. + let mut levels = vec![Level { w, h, img: img.to_vec(), hole: hole.to_vec() }]; + let mut ext = (bx1 - bx0).max(by1 - by0); + let mut exts = vec![ext]; + while let Some(l) = levels.last() { + check()?; + if ext <= 2 * psz || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz { + break; + } + let d = downsample(l, ch); + levels.push(d); + ext = ext.div_ceil(2); + exts.push(ext); + } + let nlev = levels.len(); + let mut nnf: Vec<(i32, i32)> = Vec::new(); + let mut prev: Option<(usize, usize, Vec)> = None; + for li in (0..nlev).rev() { + check()?; + let Level { w: lw, h: lh, img: mut limg, hole: lhole } = levels[li].clone(); + // Initialise the hole: membrane at the coarsest level, upsampled result elsewhere. + match &prev { + None => limg = membrane_fill(lw, lh, ch, &limg, &lhole), + Some((pw, ph, pimg)) => { + for y in 0..lh { + for x in 0..lw { + if lhole[y * lw + x] { + let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1)); + let (d, s) = ((y * lw + x) * ch, (sy * pw + sx) * ch); + limg[d..d + ch].copy_from_slice(&pimg[s..s + ch]); + } + } + } + } + } + let ri = r as i32; + let hs = integral(lw, lh, &lhole); + let mut valid = vec![false; lw * lh]; + let mut valid_count = 0; + let mut targets = vec![false; lw * lh]; + for y in 0..lh as i32 { + if y % 32 == 0 { + check()?; + } + for x in 0..lw as i32 { + let cnt = window_count(&hs, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1); + let inside = x >= ri && y >= ri && x + ri < lw as i32 && y + ri < lh as i32; + let i = y as usize * lw + x as usize; + if inside && cnt == 0 { + valid[i] = true; + valid_count += 1; + } + targets[i] = cnt > 0; + } + } + if valid_count == 0 { + if li == 0 { + return Ok(None); + } + prev = Some((lw, lh, limg)); + nnf.clear(); + continue; + } + let valid_list = source_centres(lw, &valid, valid_count, &check)?; + let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets, ctl: cancelled }; + // NNF init: upsampled from the coarser level where possible, random otherwise. + let mut rng = Rng::new(p.seed ^ (li as u64) << 20); + let pw_prev = prev.as_ref().map_or(0, |p| p.0); + let old = std::mem::take(&mut nnf); + let mut new_nnf = vec![(0i32, 0i32); lw * lh]; + for y in 0..lh { + if y % 32 == 0 { + check()?; + } + for x in 0..lw { + if !solver.targets[y * lw + x] { + continue; + } + let mut cand = None; + if !old.is_empty() && pw_prev > 0 { + let pi = (y / 2) * pw_prev + (x / 2); + if let Some(&(sx, sy)) = old.get(pi) { + let c = (sx * 2 + (x % 2) as i32, sy * 2 + (y % 2) as i32); + if solver.is_valid(c.0, c.1) { + cand = Some(c); + } + } + } + new_nnf[y * lw + x] = cand.unwrap_or_else(|| solver.valid_list[(rng.next() % solver.valid_list.len() as u64) as usize]); + } + } + nnf = new_nnf; + let refine_only = li + 1 < nlev && exts[li] > p.refine_extent; + let em = if li + 1 == nlev { + p.em_iters + } else if refine_only { + 1 + } else { + (p.em_iters >> (nlev - 1 - li)).max(p.min_em_iters) + }; + let pm_iters = if refine_only { 1 } else { p.pm_iters }; + let full_search = (lw.max(lh)) as i32; + let mut cost = vec![f32::INFINITY; lw * lh]; + for it in 0..em { + // Costs change as hole pixels are re-estimated: refresh before each PatchMatch. + for (i, c) in cost.iter_mut().enumerate() { + if i % (lw * 32).max(1) == 0 { + check()?; + } + if solver.targets[i] { + *c = solver.dist(((i % lw) as i32, (i / lw) as i32), nnf[i], f32::INFINITY); + } + } + // Wide random search on coarse levels / first iteration, local refinement afterwards. + let radius = if refine_only { + 2 + } else if li + 1 == nlev || it == 0 { + full_search + } else { + (4 * psz).min(full_search as usize) as i32 + }; + for pass in 0..pm_iters { + check()?; + solver.patchmatch(&mut nnf, &mut cost, pass + it * pm_iters, p.seed.wrapping_add((li * 1000 + it) as u64), radius); + } + check()?; + solver.vote(&nnf, &cost); + check()?; + } + prev = Some((lw, lh, limg)); + } + Ok(prev.map(|(_, _, img)| img)) +} + +/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the +/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the +#[cfg(test)] +mod tests { + use super::*; + + /// Smooth gradient plus deterministic fine noise. + fn texture(w: usize, h: usize) -> Vec { + let mut rng = Rng::new(7); + (0..w * h) + .flat_map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02; + [0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n] + }) + .collect() + } + + fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { + (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() + } + + fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 { + let (mut e, mut n) = (0.0f32, 0); + for (i, hh) in hole.iter().enumerate() { + if *hh { + for c in 0..ch { + e += (a[i * ch + c] - b[i * ch + c]).powi(2); + n += 1; + } + } + } + (e / n as f32).sqrt() + } + + #[test] + fn grid_limits_reject_narrowing_and_integral_overflow_without_allocating() { + assert!(supported_grid(32, 32)); + assert!(supported_grid(16_384, 8_192)); + assert_eq!(supported_grid(20_000, 20_000), usize::BITS > 32); + assert!(!supported_grid(i32::MAX as usize, 1)); + assert!(!supported_grid(65_536, 65_536)); + assert!(!supported_grid(usize::MAX, usize::MAX)); + } + + #[test] + fn completion_fills_blemish_from_texture() { + let (w, h, ch) = (96, 96, 3); + let clean = texture(w, h); + let hole = disc(w, h, 48.0, 48.0, 9.0); + let mut dirty = clean.clone(); + for (i, hh) in hole.iter().enumerate() { + if *hh { + dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]); + } + } + let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); + let before = hole_rmse(&dirty, &clean, &hole, ch); + let after = hole_rmse(&out, &clean, &hole, ch); + assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}"); + // Outside the hole untouched. + assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b)); + // Deterministic. + assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap()); + } + + #[test] + fn completion_continues_structure() { + // Vertical stripes: the filled hole should keep the stripes (not a blur). + let (w, h, ch) = (80, 80, 1); + let clean: Vec = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect(); + let hole = disc(w, h, 40.0, 40.0, 7.0); + let dirty: Vec = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect(); + let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); + let err = hole_rmse(&out, &clean, &hole, ch); + assert!(err < 0.15, "{err}"); + } +} diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index e95ca26d7..da88b48c6 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -1,5 +1,9 @@ -//! Raw develop pipeline (CPU path), extracted from LightCraft. +//! The raw develop pipeline, CPU path: the shared pipeline of craft-libs#587, moved from LightCraft one module at a +//! time. See the README for what is here so far. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod color; pub mod curve; +pub mod inpaint; pub mod lut; diff --git a/crates/develop/tests/fixtures/inpaint-complete.f32le b/crates/develop/tests/fixtures/inpaint-complete.f32le new file mode 100644 index 000000000..3e2a4d70a Binary files /dev/null and b/crates/develop/tests/fixtures/inpaint-complete.f32le differ diff --git a/crates/develop/tests/fixtures/inpaint-membrane.f32le b/crates/develop/tests/fixtures/inpaint-membrane.f32le new file mode 100644 index 000000000..46ac5cddd Binary files /dev/null and b/crates/develop/tests/fixtures/inpaint-membrane.f32le differ diff --git a/crates/develop/tests/inpaint_parity.rs b/crates/develop/tests/inpaint_parity.rs new file mode 100644 index 000000000..ac73e3d2e --- /dev/null +++ b/crates/develop/tests/inpaint_parity.rs @@ -0,0 +1,60 @@ +//! Parity with LightCraft (craft-libs#587): the hole fills of one scene are what `lightcraft-inpaint` at +//! `a75497d6` gave for it. The fixtures in `tests/fixtures/` are that crate's `complete` (default parameters) and +//! `membrane_fill` on [`scene`], three little-endian `f32` per pixel, row by row. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use craft_develop::inpaint::{CompleteParams, complete, membrane_fill}; +use craft_render_parity::{Image, Tolerance, compare}; + +const W: usize = 96; +const H: usize = 72; + +/// A ramp with stripes and a weave, and two holes in it: a rectangle and a disc. +fn scene() -> (Vec, Vec) { + let mut img = Vec::with_capacity(W * H * 3); + let mut hole = Vec::with_capacity(W * H); + for y in 0..H { + for x in 0..W { + let (fx, fy) = (x as f32 / W as f32, y as f32 / H as f32); + let stripe = if (x / 6 + y / 9) % 2 == 0 { 0.12 } else { 0.0 }; + let weave = if (x * 3 + y * 5) % 7 < 2 { 0.05 } else { 0.0 }; + img.extend([0.15 + 0.6 * fx + stripe, 0.2 + 0.5 * fy + weave, 0.7 - 0.4 * fx * fy + stripe * 0.5]); + let (dx, dy) = (x as i32 - 60, y as i32 - 44); + hole.push((20..38).contains(&x) && (14..30).contains(&y) || dx * dx + dy * dy <= 81); + } + } + (img, hole) +} + +fn fixture(bytes: &[u8]) -> Vec { + bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect() +} + +fn assert_parity(expected: &[u8], actual: &[f32]) { + let expected = fixture(expected); + let report = compare(&Image::new(W as u32, H as u32, &expected).unwrap(), &Image::new(W as u32, H as u32, actual).unwrap()).unwrap(); + assert!(report.within(&Tolerance::BASELINE), "{report}: {:?}", report.exceeded(&Tolerance::BASELINE)); +} + +#[test] +fn completion_matches_lightcraft() { + let (img, hole) = scene(); + let filled = complete(W, H, 3, &img, &hole, &CompleteParams::default()).expect("a completion"); + assert_ne!(filled, img, "the holes were filled"); + assert_parity(include_bytes!("fixtures/inpaint-complete.f32le"), &filled); +} + +#[test] +fn membrane_fill_matches_lightcraft() { + let (img, hole) = scene(); + assert_parity(include_bytes!("fixtures/inpaint-membrane.f32le"), &membrane_fill(W, H, 3, &img, &hole)); +} + +/// The comparison can fail: the unfilled scene is not within tolerance of the filled one. +#[test] +fn the_unfilled_scene_is_not_at_parity() { + let (img, _) = scene(); + let expected = fixture(include_bytes!("fixtures/inpaint-complete.f32le")); + let report = compare(&Image::new(W as u32, H as u32, &expected).unwrap(), &Image::new(W as u32, H as u32, &img).unwrap()).unwrap(); + assert!(!report.within(&Tolerance::BASELINE)); +} diff --git a/crates/doc-binary/src/write/picture.rs b/crates/doc-binary/src/write/picture.rs index 6454c320f..dd1fc5025 100644 --- a/crates/doc-binary/src/write/picture.rs +++ b/crates/doc-binary/src/write/picture.rs @@ -114,7 +114,7 @@ impl Blip { /// MS-ODRAW requires MD4 of the uncompressed BLIP payload, not the original import file. /// This legacy-format identifier is not authentication or a security integrity check. fn uid(bytes: &[u8]) -> [u8; 16] { - md4::Md4::digest(bytes).into() + md4::Md4::digest(bytes).into() // NOSONAR: MS-ODRAW spec-mandated BLIP UID (non-security format identifier) } /// An OfficeArt record: header (version, instance, type, length) then the body. diff --git a/crates/file-formats/src/tests.rs b/crates/file-formats/src/tests.rs index 7bb396848..399f884ac 100644 --- a/crates/file-formats/src/tests.rs +++ b/crates/file-formats/src/tests.rs @@ -26,8 +26,17 @@ fn known_formats_separate_build_disabled_and_unsupported_operations() { #[cfg(not(feature = "raster-codecs"))] assert_eq!(jpeg.read, Availability::BuildDisabled); + // Whether this build reads JPEG XL is craft-image-codecs' `jxl` feature to decide, and this + // crate cannot see that through `cfg!`: a workspace build turns it on without this crate + // selecting anything, which is how a plain equality here failed every `--all-features` gate. + // The codec's own answer is the one to check against, so a wrong read status is still caught. #[cfg(feature = "raster-codecs")] - assert!(matches!(Format::Jxl.capabilities().read, Availability::Available | Availability::Unsupported)); + { + let codec = Format::Jxl.raster_codec(); + assert!(codec.is_some(), "JXL is handled by craft-image-codecs and must map to one of its formats"); + let expected = if codec.is_some_and(|codec| codec.caps().read) { Availability::Available } else { Availability::Unsupported }; + assert_eq!(Format::Jxl.capabilities().read, expected); + } #[cfg(not(feature = "raster-codecs"))] assert_eq!(Format::Jxl.capabilities().read, Availability::Unsupported); #[cfg(not(feature = "raster-codecs"))] diff --git a/crates/gpu-null/Cargo.toml b/crates/gpu-null/Cargo.toml new file mode 100644 index 000000000..adb907597 --- /dev/null +++ b/crates/gpu-null/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "craft-gpu-null" +description = "In-memory GpuContext for CI and headless tests" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs new file mode 100644 index 000000000..71efe3d17 --- /dev/null +++ b/crates/gpu-null/src/lib.rs @@ -0,0 +1,156 @@ +//! CPU-only [`GpuContext`] for tests and CI. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadRequest, WorkerKind}; + +/// In-memory buffer store; no GPU hardware required. Reads resolve synchronously (there is +/// nothing to wait for), so [`request_read`](GpuContext::request_read) and +/// [`poll_reads`](GpuContext::poll_reads) satisfy the trait trivially. +/// [`read_buffer`](GpuContext::read_buffer) is overridden to take only its own completion, +/// leaving completions for other outstanding requests queued for the next +/// [`poll_reads`](GpuContext::poll_reads). +pub struct NullContext { + caps: DeviceCaps, + worker_kind: WorkerKind, + /// `None` means freed (or never allocated): handles are stable indices into this Vec, so a + /// freed slot cannot simply be removed without shifting every later handle's index. + buffers: Vec>>, + next_request: u64, + ready: Vec, +} + +impl NullContext { + pub fn new(worker_kind: WorkerKind) -> Self { + Self { + caps: DeviceCaps { backend_name: "null".into(), device_name: "null".into(), ..DeviceCaps::default() }, + worker_kind, + buffers: Vec::new(), + next_request: 0, + ready: Vec::new(), + } + } +} + +impl GpuContext for NullContext { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + + fn worker_kind(&self) -> WorkerKind { + self.worker_kind + } + + fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { + let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); + self.buffers.push(Some(bytes.to_vec())); + Ok(id) + } + + fn buffer_len(&self, handle: HandleId) -> Result { + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } + + fn request_read(&mut self, handle: HandleId) -> Result { + let bytes = self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let request = ReadRequest(self.next_request); + self.next_request = self.next_request.wrapping_add(1); + self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); + Ok(request) + } + + fn poll_reads(&mut self) -> Vec { + std::mem::take(&mut self.ready) + } + + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + match self.ready.iter().position(|o| o.request == request) { + Some(i) => self.ready.remove(i).result, + None => Err(GpuFault::Operation("request_read did not resolve synchronously".into())), + } + } + + /// Replaces the slot with `None` rather than removing it: handles are stable indices, and + /// removing would shift every later handle's index out from under its caller. + fn free_buffer(&mut self, handle: HandleId) { + if let Some(slot) = self.buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } +} + +#[cfg(test)] +mod tests { + use craft_gpu::{GpuContext, GpuFault, HandleId, WorkerKind}; + + use super::NullContext; + + #[test] + fn request_read_then_poll_reads_delivers_the_same_bytes_as_read_buffer() { + let mut ctx = NullContext::new(WorkerKind::Main); + let handle = ctx.upload_buffer("in", b"abc").expect("upload_buffer"); + let request = ctx.request_read(handle).expect("request_read"); + let outcomes = ctx.poll_reads(); + assert_eq!(outcomes.len(), 1); + assert_eq!(outcomes[0].request, request); + assert_eq!(outcomes[0].handle, handle); + assert_eq!(outcomes[0].result.as_deref(), Ok(b"abc".as_slice())); + } + + #[test] + fn read_buffer_default_still_works() { + let mut ctx = NullContext::new(WorkerKind::SharedWorker); + let handle = ctx.upload_buffer("in", b"xyz").expect("upload_buffer"); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"xyz".to_vec()); + } + + #[test] + fn read_buffer_keeps_another_outstanding_requests_completion_queued() { + let mut ctx = NullContext::new(WorkerKind::Main); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + let request_a = ctx.request_read(a).expect("request_read a"); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec()); + let outcomes = ctx.poll_reads(); + assert_eq!(outcomes.len(), 1, "a's completion must survive b's read_buffer"); + assert_eq!(outcomes[0].request, request_a); + assert_eq!(outcomes[0].result.as_deref(), Ok(b"aa".as_slice())); + } + + #[test] + fn an_empty_buffer_uploads_and_reads_back_empty() { + let mut ctx = NullContext::new(WorkerKind::Main); + let handle = ctx.upload_buffer("empty", b"").expect("upload empty"); + assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), 0); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), Vec::::new()); + } + + /// CodeRabbit finding on gpu-wgpu/src/lib.rs:313: nothing released an uploaded buffer's + /// resources, so a backend's buffer table could only ever grow. free_buffer must actually + /// reclaim the payload and make the handle behave as invalid afterward, not just forget it + /// exists while still holding its bytes. + #[test] + fn free_buffer_invalidates_the_handle_and_does_not_shift_other_handles() { + let mut ctx = NullContext::new(WorkerKind::Main); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + + ctx.free_buffer(a); + + assert!(matches!(ctx.buffer_len(a), Err(GpuFault::InvalidJob(_))), "a freed handle must behave as invalid"); + assert_eq!(ctx.buffer_len(b).expect("b must be unaffected by freeing a"), 2); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec(), "b's own index must not have shifted"); + } + + /// Freeing a handle twice, or a handle that never existed, is a no-op: callers are not + /// expected to track whether they already freed one. + #[test] + fn free_buffer_is_a_harmless_no_op_when_repeated_or_given_an_unknown_handle() { + let mut ctx = NullContext::new(WorkerKind::Main); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + ctx.free_buffer(a); + ctx.free_buffer(a); // already freed + ctx.free_buffer(HandleId(999)); // never existed + } +} diff --git a/crates/gpu-providers/Cargo.toml b/crates/gpu-providers/Cargo.toml new file mode 100644 index 000000000..b581b8112 --- /dev/null +++ b/crates/gpu-providers/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "craft-gpu-providers" +description = "Shared GpuProvider implementations (composite, readback, …) — no app deps" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } + +[dev-dependencies] +craft-gpu-null = { workspace = true } diff --git a/crates/gpu-providers/src/composite.rs b/crates/gpu-providers/src/composite.rs new file mode 100644 index 000000000..aeda3ead0 --- /dev/null +++ b/crates/gpu-providers/src/composite.rs @@ -0,0 +1,69 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +use crate::params::parse_u32; + +/// CPU stand-in for FilmCraft `composite.wgsl` Normal/Dissolve premultiplied "over" until WGSL runs on wgpu. +pub struct PremulCompositeProvider; + +impl GpuProvider for PremulCompositeProvider { + fn id(&self) -> &'static str { + "craft.composite.premul" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let width = parse_u32(&job.params, b"w:").unwrap_or(1).max(1) as usize; + let height = parse_u32(&job.params, b"h:").unwrap_or(1).max(1) as usize; + let len = width.saturating_mul(height).saturating_mul(4); + let (dst_h, src_h) = match job.inputs.as_slice() { + [a, b] => (a, b), + [a] => (a, a), + _ => { + return Err(GpuFault::InvalidJob("craft.composite.premul expects one or two RGBA8 inputs (backdrop, layer)".into())); + } + }; + let dst_bytes = ctx.read_buffer(*dst_h)?; + let src_bytes = ctx.read_buffer(*src_h)?; + if dst_bytes.len() < len || src_bytes.len() < len { + return Err(GpuFault::InvalidJob("input buffer shorter than w*h*4".into())); + } + let mut out = vec![0u8; len]; + for px in 0..width.saturating_mul(height) { + let i = px * 4; + let mut dst = straight_to_premul([dst_bytes[i], dst_bytes[i + 1], dst_bytes[i + 2], dst_bytes[i + 3]]); + let src = straight_to_premul([src_bytes[i], src_bytes[i + 1], src_bytes[i + 2], src_bytes[i + 3]]); + premul_over(&mut dst, src); + let straight = premul_to_straight(dst); + out[i..i + 4].copy_from_slice(&straight); + } + let handle = ctx.upload_buffer("craft.composite.premul.out", &out)?; + Ok(GpuJobOutcome { outputs: vec![handle], data: None }) + } +} + +/// Premultiplied `src` over premultiplied `dst` (`filmcraft_render` / `composite.wgsl` Normal path). +fn premul_over(dst: &mut [f32; 4], src: [f32; 4]) { + let k = 1.0 - src[3]; + for c in 0..4 { + dst[c] = src[c] + dst[c] * k; + } +} + +fn straight_to_premul(p: [u8; 4]) -> [f32; 4] { + let a = f32::from(p[3]) / 255.0; + let s = a / 255.0; + [f32::from(p[0]) * s, f32::from(p[1]) * s, f32::from(p[2]) * s, a] +} + +fn premul_to_straight(p: [f32; 4]) -> [u8; 4] { + let a = p[3].clamp(0.0, 1.0); + if a <= f32::EPSILON { + return [0, 0, 0, 0]; + } + let inv = 255.0 / a; + [ + (p[0] * inv).round().clamp(0.0, 255.0) as u8, + (p[1] * inv).round().clamp(0.0, 255.0) as u8, + (p[2] * inv).round().clamp(0.0, 255.0) as u8, + (a * 255.0).round().clamp(0.0, 255.0) as u8, + ] +} diff --git a/crates/gpu-providers/src/echo.rs b/crates/gpu-providers/src/echo.rs new file mode 100644 index 000000000..2fb356ceb --- /dev/null +++ b/crates/gpu-providers/src/echo.rs @@ -0,0 +1,18 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +/// Concatenates job params with bytes from the first input handle (shared test / debug provider). +pub struct EchoProvider; + +impl GpuProvider for EchoProvider { + fn id(&self) -> &'static str { + "craft.test.echo" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let mut data = job.params.0.clone(); + if let Some(&h) = job.inputs.first() { + data.extend_from_slice(&ctx.read_buffer(h)?); + } + Ok(GpuJobOutcome { outputs: job.outputs.clone(), data: Some(data) }) + } +} diff --git a/crates/gpu-providers/src/lib.rs b/crates/gpu-providers/src/lib.rs new file mode 100644 index 000000000..c310a6c4f --- /dev/null +++ b/crates/gpu-providers/src/lib.rs @@ -0,0 +1,33 @@ +//! Generic GPU providers extracted from app crates over time (craft-libs#7). + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod composite; +mod echo; +mod mask; +mod noop; +mod params; +mod readback; + +#[cfg(test)] +mod tests; + +use craft_gpu::{GpuProvider, ProviderRegistry}; + +pub use composite::PremulCompositeProvider; +pub use echo::EchoProvider; +pub use mask::MaskProvider; +pub use noop::NoopProvider; +pub use readback::ReadbackProvider; + +/// Default shared providers for worker/runtime init (`craft.*` ids only). +pub fn register_all() -> Vec> { + vec![Box::new(NoopProvider), Box::new(EchoProvider), Box::new(MaskProvider), Box::new(PremulCompositeProvider), Box::new(ReadbackProvider)] +} + +/// Register [`register_all`] providers into an existing registry. +pub fn register_all_into(registry: &mut ProviderRegistry) { + for provider in register_all() { + registry.register(provider); + } +} diff --git a/crates/gpu-providers/src/mask.rs b/crates/gpu-providers/src/mask.rs new file mode 100644 index 000000000..41957c1f7 --- /dev/null +++ b/crates/gpu-providers/src/mask.rs @@ -0,0 +1,35 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +use crate::params::parse_u32; + +/// CPU stand-in for FilmCraft mask composite until WGSL runs on wgpu. +pub struct MaskProvider; + +impl GpuProvider for MaskProvider { + fn id(&self) -> &'static str { + "craft.mask" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let width = parse_u32(&job.params, b"w:").unwrap_or(1).max(1) as usize; + let height = parse_u32(&job.params, b"h:").unwrap_or(1).max(1) as usize; + let len = width.saturating_mul(height).saturating_mul(4); + let (base, mask) = match job.inputs.as_slice() { + [a, b] => (a, b), + [a] => (a, a), + _ => return Err(GpuFault::InvalidJob("craft.mask expects one or two RGBA inputs".into())), + }; + let base_bytes = ctx.read_buffer(*base)?; + let mask_bytes = ctx.read_buffer(*mask)?; + if base_bytes.len() < len || mask_bytes.len() < len { + return Err(GpuFault::InvalidJob("input buffer shorter than w*h*4".into())); + } + let mut out = vec![0u8; len]; + for i in 0..len { + let m = mask_bytes[i]; + out[i] = ((u16::from(base_bytes[i]) * u16::from(m)) / 255) as u8; + } + let handle = ctx.upload_buffer("craft.mask.out", &out)?; + Ok(GpuJobOutcome { outputs: vec![handle], data: None }) + } +} diff --git a/crates/gpu-providers/src/noop.rs b/crates/gpu-providers/src/noop.rs new file mode 100644 index 000000000..4ce8aef91 --- /dev/null +++ b/crates/gpu-providers/src/noop.rs @@ -0,0 +1,14 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +/// No-op dispatch for wiring tests; shared readback/composite providers live in sibling modules. +pub struct NoopProvider; + +impl GpuProvider for NoopProvider { + fn id(&self) -> &'static str { + "craft.noop" + } + + fn run(&self, _ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + Ok(GpuJobOutcome { outputs: job.outputs.clone(), data: None }) + } +} diff --git a/crates/gpu-providers/src/params.rs b/crates/gpu-providers/src/params.rs new file mode 100644 index 000000000..7571897df --- /dev/null +++ b/crates/gpu-providers/src/params.rs @@ -0,0 +1,17 @@ +use craft_gpu::GpuJobParams; + +pub(crate) fn parse_u32(params: &GpuJobParams, prefix: &[u8]) -> Option { + // `windows(0)` panics; an empty prefix is a caller bug, answered with None, not a crash. + if prefix.is_empty() { + return None; + } + let bytes = params.0.as_slice(); + let start = bytes.windows(prefix.len()).position(|w| w == prefix)? + prefix.len(); + let rest = &bytes[start..]; + let end = rest.iter().position(|&b| b == b',' || b == b';').unwrap_or(rest.len()); + std::str::from_utf8(&rest[..end]).ok()?.parse().ok() +} + +pub(crate) fn params_contain(params: &GpuJobParams, needle: &[u8]) -> bool { + !needle.is_empty() && params.0.windows(needle.len()).any(|w| w == needle) +} diff --git a/crates/gpu-providers/src/readback.rs b/crates/gpu-providers/src/readback.rs new file mode 100644 index 000000000..1428fba58 --- /dev/null +++ b/crates/gpu-providers/src/readback.rs @@ -0,0 +1,42 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider, f16_rgba_to_f32_bytes}; + +use crate::params::{params_contain, parse_u32}; + +/// CPU stand-in for accumulator/output readback (`read_accumulator` / `read_output` in FilmCraft gpu) until wgpu maps buffers. +pub struct ReadbackProvider; + +impl GpuProvider for ReadbackProvider { + fn id(&self) -> &'static str { + "craft.readback" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let width = parse_u32(&job.params, b"w:").unwrap_or(0); + let height = parse_u32(&job.params, b"h:").unwrap_or(0); + let input = job.inputs.first().copied().ok_or_else(|| GpuFault::InvalidJob("craft.readback expects one input buffer".into()))?; + let raw = ctx.read_buffer(input)?; + // A real GPU provider binds the input as a storage buffer. Refuse a caps report no + // device path could satisfy, instead of pretending this stand-in's readback would have + // worked there. + if ctx.caps().max_storage_buffer_binding_size == 0 { + return Err(GpuFault::Operation("max_storage_buffer_binding_size must be non-zero".into())); + } + + let out_bytes = if params_contain(&job.params, b"fmt:u8") { + let need = usize::try_from(width.saturating_mul(height).saturating_mul(4)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?; + if need == 0 || raw.len() < need { + return Err(GpuFault::InvalidJob("rgba8 readback shorter than w*h*4".into())); + } + raw[..need].to_vec() + } else { + let need = usize::try_from(width.saturating_mul(height).saturating_mul(8)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?; + if need == 0 || raw.len() < need { + return Err(GpuFault::InvalidJob("f16 rgba readback shorter than w*h*8".into())); + } + f16_rgba_to_f32_bytes(&raw[..need]).map_err(|len| GpuFault::InvalidJob(format!("f16 rgba length {len} not multiple of 8")))? + }; + + let handle = ctx.upload_buffer("craft.readback.out", &out_bytes)?; + Ok(GpuJobOutcome { outputs: vec![handle], data: None }) + } +} diff --git a/crates/gpu-providers/src/tests.rs b/crates/gpu-providers/src/tests.rs new file mode 100644 index 000000000..650ae22e6 --- /dev/null +++ b/crates/gpu-providers/src/tests.rs @@ -0,0 +1,140 @@ +#![allow(clippy::expect_used)] + +use craft_gpu::{GpuContext, GpuJob, GpuJobParams, ProviderRegistry, WorkerKind, f16_to_f32, f16_to_f32_fast}; +use craft_gpu_null::NullContext; + +use crate::{EchoProvider, MaskProvider, NoopProvider, PremulCompositeProvider, ReadbackProvider, register_all, register_all_into}; + +#[test] +fn noop_provider_registered_by_id() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(NoopProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let job = GpuJob { provider_id: "craft.noop".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("noop dispatch"); + assert!(out.data.is_none()); +} + +#[test] +fn echo_provider_concatenates_params_and_first_input() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(EchoProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let h = ctx.upload_buffer("in", b"xy").expect("upload_buffer in test"); + let job = GpuJob { provider_id: "craft.test.echo".into(), params: GpuJobParams(b"a".to_vec()), inputs: vec![h], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("echo dispatch"); + assert_eq!(out.data.as_deref(), Some(b"axy".as_slice())); +} + +#[test] +fn register_all_lists_shared_providers() { + let ids: Vec<_> = register_all().iter().map(|p| p.id()).collect(); + assert_eq!(ids, vec!["craft.noop", "craft.test.echo", "craft.mask", "craft.composite.premul", "craft.readback",]); +} + +#[test] +fn gpu_providers_cargo_has_no_app_deps() { + let manifest = include_str!("../Cargo.toml"); + for line in manifest.lines() { + let t = line.trim(); + assert!( + !(t.starts_with("effectcraft") + || t.starts_with("filmcraft") + || t.contains("effectcraft-") + || t.contains("filmcraft-") + || t.contains("-engine =") + || t.contains("-engine.") + || t.contains("-engine\"")), + "forbidden app dependency line: {t}" + ); + } +} + +#[test] +fn empty_param_prefix_and_needle_are_refused_not_a_panic() { + let params = GpuJobParams(b"w:3,h:2".to_vec()); + assert_eq!(crate::params::parse_u32(¶ms, b""), None); + assert!(!crate::params::params_contain(¶ms, b"")); +} + +#[test] +fn mask_provider_multiplies_rgba_by_mask_on_cpu() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(MaskProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let base = ctx.upload_buffer("base", &[255u8, 0, 0, 255, 100, 100, 100, 255]).expect("upload base"); + let mask = ctx.upload_buffer("mask", &[128u8, 255, 255, 255, 0, 255, 255, 255]).expect("upload mask"); + let job = + craft_gpu::GpuJob { provider_id: "craft.mask".into(), params: GpuJobParams(b"w:1,h:2".to_vec()), inputs: vec![base, mask], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("mask dispatch"); + let handle = out.outputs[0]; + let bytes = ctx.read_buffer(handle).expect("read mask out"); + assert_eq!(bytes[0], 128); + assert_eq!(bytes[4], 0); +} + +#[test] +fn premul_composite_over_on_cpu() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(PremulCompositeProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + // backdrop: green opaque; layer: half-alpha blue + let dst = ctx.upload_buffer("dst", &[0, 255, 0, 255]).expect("upload dst"); + let src = ctx.upload_buffer("src", &[0, 0, 255, 128]).expect("upload src"); + let job = + GpuJob { provider_id: "craft.composite.premul".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![dst, src], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("premul composite"); + let bytes = ctx.read_buffer(out.outputs[0]).expect("read out"); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], 127); + assert_eq!(bytes[2], 128); + assert_eq!(bytes[3], 255); +} + +#[test] +fn readback_decodes_f16_rgba_to_f32() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(ReadbackProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let h = half_float_one(); + let mut raw = Vec::new(); + raw.extend_from_slice(&h.to_le_bytes()); + raw.extend_from_slice(&h.to_le_bytes()); + raw.extend_from_slice(&h.to_le_bytes()); + raw.extend_from_slice(&0u16.to_le_bytes()); + let inp = ctx.upload_buffer("accum", &raw).expect("upload f16"); + let job = GpuJob { provider_id: "craft.readback".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![inp], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("readback"); + let decoded = ctx.read_buffer(out.outputs[0]).expect("read f32 out"); + assert_eq!(decoded.len(), 16); + let r = f32::from_le_bytes(decoded[0..4].try_into().expect("r")); + assert!((r - 1.0).abs() < 1e-3); + assert_eq!(f16_to_f32(h), f16_to_f32_fast(h)); +} + +fn half_float_one() -> u16 { + f32_to_f16(1.0) +} + +fn f32_to_f16(v: f32) -> u16 { + let bits = v.to_bits(); + let sign = ((bits >> 31) & 1) as u16; + let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15; + let mant = bits & 0x007f_ffff; + if exp <= 0 { + return sign << 15; + } + if exp >= 0x1f { + return (sign << 15) | 0x7c00; + } + (sign << 15) | ((exp as u16) << 10) | ((mant >> 13) as u16) +} + +#[test] +fn register_all_into_populates_registry() { + let mut registry = ProviderRegistry::new(); + register_all_into(&mut registry); + let mut ctx = NullContext::new(WorkerKind::SharedWorker); + let job = GpuJob { provider_id: "craft.noop".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + registry.dispatch(&mut ctx, &job).expect("noop via register_all_into"); +} diff --git a/crates/gpu-wgpu/Cargo.toml b/crates/gpu-wgpu/Cargo.toml new file mode 100644 index 000000000..ecf45c62f --- /dev/null +++ b/crates/gpu-wgpu/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "craft-gpu-wgpu" +description = "craft-gpu backend using wgpu (WebGPU on wasm32, native APIs on desktop)" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true, optional = true } +wgpu = { workspace = true } + +[features] +default = [] +adapter-probe = ["dep:pollster"] +native-vulkan = ["wgpu/vulkan"] +native-dx12 = ["wgpu/dx12"] +native-metal = ["wgpu/metal"] +native-gles = ["wgpu/gles"] + +[dev-dependencies] +pollster = { workspace = true } +# Real-backend test (crates/gpu-wgpu/src/tests.rs): dispatches craft-gpu-providers' CPU-stand-in +# providers against a real WgpuContext, not just craft-gpu-null, per RFC-0022 acceptance +# requirement 2. Dev-only: no cycle (craft-gpu-providers never depends on craft-gpu-wgpu). +craft-gpu-providers = { workspace = true } diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs new file mode 100644 index 000000000..84aa85ef4 --- /dev/null +++ b/crates/gpu-wgpu/src/lib.rs @@ -0,0 +1,563 @@ +//! wgpu-backed [`GpuContext`]. +//! +//! WebGPU on `wasm32`; native APIs when backend features are enabled. With the `adapter-probe` +//! feature (native only, pollster) and at least one `native-*` backend feature, +//! [`WgpuContext::new`] requests a real device and builds [`DeviceCaps`] from what that device +//! actually enabled (`Device::limits()` / `Device::features()`), never from the adapter's +//! advertised maximum. Without a usable adapter (the features above are off, no GPU is present, +//! or on `wasm32` where real device creation needs the async worker-init path noted in +//! `docs/gpu-backends.md`), the context degrades to the same in-memory staging behavior as +//! `craft_gpu_null::NullContext` (not a dependency of this crate; named here only for context); +//! that is RFC-0022's defined no-adapter path, not an error. +//! +//! Readback is asynchronous end to end (`request_read` + `poll_reads`), because WebGPU can only +//! map a buffer that way. Native, with a real device, drives it with `Buffer::map_async` plus +//! `Device::poll`. The blocking `read_buffer` convenience (see +//! [`GpuContext`]'s trait docs) blocks efficiently on native by polling +//! the device while it waits. On `wasm32` the backing is always the in-memory staging store +//! today, whose reads complete synchronously, and `read_buffer` serves them; only a read that +//! did not complete synchronously returns a fault there, since blocking would freeze the one +//! thread a real map's completion callback would need to run on. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadRequest, WorkerKind}; + +#[cfg(test)] +mod tests; + +fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps { + DeviceCaps { backend_name: backend_name.into(), device_name: device_name.into(), ..DeviceCaps::default() } +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +fn probe_caps_native() -> DeviceCaps { + let instance = native::instance(); + let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { + Ok(adapter) => adapter, + Err(_) => return probe_fallback("wgpu", "no-adapter"), + }; + let info = adapter.get_info(); + let limits = adapter.limits(); + DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name, + 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: Vec::new(), + } +} + +/// Adapter-advertised limits, when an adapter is available; otherwise conservative defaults. This +/// is the quick, device-free probe for UI surfaces that want a number before any context exists +/// (Settings). It is advisory only: these are the adapter's maximums, not a device's granted +/// ones. [`WgpuContext::caps`] is the authoritative, device-truth source once a context exists. +pub fn probe_caps() -> DeviceCaps { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + { + probe_caps_native() + } + + #[cfg(all(not(target_arch = "wasm32"), not(feature = "adapter-probe")))] + { + probe_fallback("wgpu", "probe-not-run") + } + + #[cfg(target_arch = "wasm32")] + { + probe_fallback("webgpu", "browser") + } +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +mod native { + use std::sync::{Arc, Mutex}; + + use craft_gpu::{DeviceCaps, GpuFault}; + + use crate::{Backing, DeviceBacking}; + + /// Features this context asks a device for. No provider dispatches a real WGSL job on wgpu + /// yet (`craft-gpu-providers` ships CPU stand-ins, by design, until that lands); extend this + /// as real compute providers land, and it degrades gracefully regardless: see + /// [`create_device`]. + const DESIRED_FEATURES: wgpu::Features = wgpu::Features::empty(); + + /// An instance over whichever native backends were compiled in (`native-vulkan`, + /// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the + /// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in a local container run or a CI lane. + /// `new_without_display_handle` because this context never has a window (no surface is ever + /// requested); FilmCraft's own off-screen export device uses the same constructor for the + /// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`). + pub(crate) fn instance() -> wgpu::Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + if let Some(backends) = wgpu::Backends::from_env() { + desc.backends = backends; + } + wgpu::Instance::new(desc) + } + + /// Request a real device. `None` on the defined no-adapter path (no usable adapter): the + /// caller degrades to the staging backing, identical in shape to `craft-gpu-null`. + /// + /// Never panics: `required_features` is intersected with what the adapter actually + /// advertises, and `required_limits` is set to the adapter's own limits (never more), so + /// `request_device`'s documented panics ("features/limits not supported by this adapter") + /// cannot trigger here. + pub(crate) fn create_device() -> Option<(DeviceCaps, Backing)> { + let instance = instance(); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + let features = DESIRED_FEATURES & adapter.features(); + let limits = adapter.limits(); + let desc = + wgpu::DeviceDescriptor { label: Some("craft-gpu-wgpu"), required_features: features, required_limits: limits, ..Default::default() }; + let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?; + + let lost = Arc::new(Mutex::new(None)); + { + let lost = Arc::clone(&lost); + device.set_device_lost_callback(move |reason, message| { + if let Ok(mut slot) = lost.lock() { + *slot = Some(GpuFault::DeviceLost(format!("{reason:?}: {message}"))); + } + }); + } + + let info = device.adapter_info(); + let device_limits = device.limits(); + let caps = DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name, + max_storage_buffer_binding_size: device_limits.max_storage_buffer_binding_size, + 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(), + }; + let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() }); + Some((caps, backing)) + } +} + +/// No real device: buffers live on the host, exactly like `craft-gpu-null`. RFC-0022's defined +/// degrade path for "no adapter" (feature off, no GPU present, or the `wasm32` async-init gap). +/// Each slot is `None` once freed (or never allocated): handles are stable indices, so a freed +/// slot cannot simply be removed without shifting every later handle's index. +#[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] +enum Backing { + Staging(Vec>>), +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +enum Backing { + Staging(Vec>>), + /// A real device. `DeviceCaps` was built from it, not from the adapter it came from. + Device(DeviceBacking), +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +struct DeviceBacking { + device: wgpu::Device, + queue: wgpu::Queue, + /// Each buffer paired with its true, caller-given byte length. wgpu requires every buffer + /// with copy usage to be sized in multiples of [`COPY_ALIGN`]; the buffer itself is padded to + /// that, but callers (`buffer_len`, `request_read`'s returned bytes) see the true length, + /// matching the staging path and `craft-gpu-null` exactly, with no padding visible. `None` + /// once freed: see the `Backing::Staging` doc for why the slot stays rather than shifting. + buffers: Vec>, + /// Set by the device-lost callback registered in [`native::create_device`]; checked before + /// every call that would otherwise touch the (now invalid) device. + lost: std::sync::Arc>>, + pending: Vec, +} + +/// wgpu's `COPY_BUFFER_ALIGNMENT`: every buffer with copy usage, and every `write_buffer` / +/// `copy_buffer_to_buffer` size, must be a multiple of this (4 bytes). Uploading or reading back +/// a buffer length that doesn't land on this boundary (`b"xy"`, two bytes) is a validation error +/// on native wgpu, surfaced as a panic from inside `wgpu-core`'s own uncaptured-error path unless +/// padded first; `craft-gpu-null`'s plain `Vec` has no such constraint, so this padding is +/// purely an artifact of the real backend, kept invisible to every caller of this crate. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +const COPY_ALIGN: u64 = 4; + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +struct PendingRead { + request: ReadRequest, + handle: HandleId, + staging: wgpu::Buffer, + /// True length to truncate the mapped (padded) bytes back down to. + true_len: u64, + state: std::sync::Arc>>>, +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +fn resolve_pending(pending: PendingRead) -> ReadOutcome { + let PendingRead { request, handle, staging, true_len, state } = pending; + let result = match state.lock() { + Ok(mut guard) => match guard.take() { + Some(Ok(())) => match staging.get_mapped_range(0..true_len.next_multiple_of(COPY_ALIGN)) { + Ok(view) => { + let mut bytes = view.to_vec(); + drop(view); + staging.unmap(); + bytes.truncate(usize::try_from(true_len).unwrap_or(usize::MAX)); + Ok(bytes) + } + Err(err) => Err(GpuFault::Operation(err.to_string())), + }, + Some(Err(message)) => Err(GpuFault::Operation(message)), + None => Err(GpuFault::Operation("read_buffer: map_async callback has not run yet".into())), + }, + Err(_) => Err(GpuFault::Operation("read_buffer: map state lock poisoned".into())), + }; + ReadOutcome { request, handle, result } +} + +/// wgpu-backed context. See the module docs for the real-device-vs-staging split. +pub struct WgpuContext { + caps: DeviceCaps, + worker_kind: WorkerKind, + backing: Backing, + next_request: u64, + ready: Vec, +} + +impl WgpuContext { + pub fn new(worker_kind: WorkerKind) -> Self { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + { + if let Some((caps, backing)) = native::create_device() { + return Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() }; + } + // request_adapter and/or request_device failed: fall back to the conservative + // fallback, never probe_caps(). probe_caps() would re-query the adapter here, and a + // second, successful adapter query would report the adapter's advertised limits as + // if they came from a granted device -- the exact thing probe_caps's own doc comment + // says caps() must never do for a context with no device. + Self { caps: probe_fallback("wgpu", "no-device"), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } + } + #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] + Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } + } + + /// Force the staging (no-device) path with caller-supplied caps. For tests, and for callers + /// that intentionally want the portable path (FilmCraft's `?webgl` / `?nogpuworkers`, per + /// `docs/pilot-filmcraft.md`) rather than a real device's own caps. + pub fn with_caps(worker_kind: WorkerKind, caps: DeviceCaps) -> Self { + Self { caps, worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } + } + + /// True when this context holds a real device (`request_device` succeeded), false on the + /// staging/no-adapter path. Settings UI can use this to show "no GPU" honestly instead of + /// implying a device that was never created; tests use it to skip rather than fail when the + /// host genuinely has no usable adapter (see `crates/gpu-wgpu/src/tests.rs`). + pub fn has_device(&self) -> bool { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + { + matches!(self.backing, Backing::Device(_)) + } + + #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] + { + false + } + } + + /// True once the device has reported loss. Every [`DeviceCaps`] read before this point is + /// stale; see [`GpuContext`]'s trait docs for the recovery this context expects. + pub fn is_device_lost(&self) -> bool { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &self.backing { + return d.lost.lock().map(|g| g.is_some()).unwrap_or(false); + } + false + } + + fn take_lost_fault(&self) -> Option { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &self.backing { + return d.lost.lock().ok().and_then(|g| g.clone()); + } + None + } +} + +impl GpuContext for WgpuContext { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + + fn worker_kind(&self) -> WorkerKind { + self.worker_kind + } + + #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_variables))] + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + match &mut self.backing { + Backing::Staging(buffers) => { + let id = u32::try_from(buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; + buffers.push(Some(bytes.to_vec())); + Ok(HandleId(id)) + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + let true_len = bytes.len() as u64; + let padded_len = true_len.next_multiple_of(COPY_ALIGN); + if padded_len > self.caps.max_buffer_size { + return Err(GpuFault::InvalidJob(format!( + "upload_buffer: {true_len} bytes (padded to {padded_len}) exceeds the device's max_buffer_size {}", + self.caps.max_buffer_size + ))); + } + // The size check above only catches a request past the device's advertised + // maximum; it proves nothing about whether the device can actually allocate + // padded_len bytes right now (free VRAM varies). wgpu 30.0.1 sends an allocation + // failure to the default uncaptured-error handler, which panics, unless a scope + // captures it first. Pop this scope immediately, before write_buffer below ever + // touches `buffer`: a buffer that failed to create is invalid, and writing to an + // invalid buffer raises its own VALIDATION error, a kind this OutOfMemory-only + // scope does not catch, so it must reach the default handler and panic regardless + // of when this scope is popped. Checking right here is what keeps that from + // happening at all. + let create_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: padded_len, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + if let Some(err) = pollster::block_on(create_scope.pop()) { + return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error creating the buffer: {err}"))); + } + // write_buffer makes its own staging allocation to carry `bytes` to the device, a + // second allocation that can also run out of memory; it gets its own scope rather + // than reusing the one already closed above. + let write_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + if padded_len == true_len { + d.queue.write_buffer(&buffer, 0, bytes); + } else { + let mut padded = bytes.to_vec(); + padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0); + d.queue.write_buffer(&buffer, 0, &padded); + } + // write_buffer only records the copy into wgpu's PendingWrites; wgpu-core flushes + // that queue at the sooner of the caller's next real command-buffer submission or + // the next map_async on an affected buffer, and keeps the buffer named by the + // write alive internally until then. Without a submission here, a free_buffer + // right after this call could never actually release the GPU allocation behind + // it, since nothing would ever flush PendingWrites to let it go. An empty submit + // is still a submission as far as that flush is concerned, so it is enough. + d.queue.submit(std::iter::empty()); + if let Some(err) = pollster::block_on(write_scope.pop()) { + return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error writing the buffer: {err}"))); + } + let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; + d.buffers.push(Some((buffer, true_len))); + Ok(HandleId(id)) + } + } + } + + fn buffer_len(&self, handle: HandleId) -> Result { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + match &self.backing { + Backing::Staging(buffers) => { + buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())).and_then( + |(_, true_len)| usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())), + ) + } + } + } + + fn request_read(&mut self, handle: HandleId) -> Result { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + match &mut self.backing { + Backing::Staging(buffers) => { + let bytes = + buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let id = self.next_request; + self.next_request = self.next_request.wrapping_add(1); + let request = ReadRequest(id); + self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); + Ok(request) + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + let (buffer, true_len) = + d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let true_len = *true_len; + if true_len == 0 { + // An empty buffer has nothing to copy or map (wgpu refuses an empty map + // range); resolve it immediately, same as the staging path. + let id = self.next_request; + self.next_request = self.next_request.wrapping_add(1); + let request = ReadRequest(id); + self.ready.push(ReadOutcome { request, handle, result: Ok(Vec::new()) }); + return Ok(request); + } + let copy_len = true_len.next_multiple_of(COPY_ALIGN); + if copy_len > self.caps.max_buffer_size { + return Err(GpuFault::Operation(format!( + "request_read: staging copy of {copy_len} bytes exceeds the device's max_buffer_size {}", + self.caps.max_buffer_size + ))); + } + // Same reasoning as upload_buffer's error scope: an allocation failure for the + // read-staging buffer must become a GpuFault, not reach the default + // uncaptured-error handler and panic. Pop immediately, before copy_buffer_to_buffer + // below ever names `staging` as a copy destination: a staging buffer that failed + // to create is invalid, and copying into an invalid buffer raises its own + // VALIDATION error, a kind this OutOfMemory-only scope does not catch, so it must + // reach the default handler and panic regardless of when this scope is popped. + let create_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("craft-gpu-wgpu.read-staging"), + size: copy_len, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + if let Some(err) = pollster::block_on(create_scope.pop()) { + return Err(GpuFault::Operation(format!("request_read: device reported an allocation error creating the staging buffer: {err}"))); + } + // The copy and its submission get their own scope rather than reusing the one + // already closed above, same split as upload_buffer's create vs. write. + let copy_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") }); + encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); + d.queue.submit(Some(encoder.finish())); + if let Some(err) = pollster::block_on(copy_scope.pop()) { + return Err(GpuFault::Operation(format!("request_read: device reported an allocation error copying the buffer: {err}"))); + } + let state = std::sync::Arc::new(std::sync::Mutex::new(None)); + { + let state = std::sync::Arc::clone(&state); + staging.map_async(wgpu::MapMode::Read, 0..copy_len, move |result| { + if let Ok(mut slot) = state.lock() { + *slot = Some(result.map_err(|e| e.to_string())); + } + }); + } + let id = self.next_request; + self.next_request = self.next_request.wrapping_add(1); + let request = ReadRequest(id); + d.pending.push(PendingRead { request, handle, staging, true_len, state }); + Ok(request) + } + } + } + + /// Replaces the slot with `None` rather than removing it: handles are stable indices, and + /// removing would shift every later handle's index out from under its caller. Dropping a + /// `Some((wgpu::Buffer, _))` here releases that buffer's GPU-side allocation. + fn free_buffer(&mut self, handle: HandleId) { + match &mut self.backing { + Backing::Staging(buffers) => { + if let Some(slot) = buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + if let Some(slot) = d.buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } + } + } + + /// Covers the gap `poll_reads` has when nothing is pending: that method can only attach a + /// device-lost fault to a read it has something to attach it to, so a caller whose event + /// loop only polls, with no outstanding read, could never observe loss through it alone. + fn device_status(&self) -> Result<(), GpuFault> { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + Ok(()) + } + + #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_mut))] + fn poll_reads(&mut self) -> Vec { + let mut outcomes = std::mem::take(&mut self.ready); + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &mut self.backing { + if let Some(fault) = d.lost.lock().ok().and_then(|g| g.clone()) { + outcomes.extend(d.pending.drain(..).map(|p| ReadOutcome { request: p.request, handle: p.handle, result: Err(fault.clone()) })); + return outcomes; + } + let _ = d.device.poll(wgpu::PollType::Poll); + let mut remaining = Vec::with_capacity(d.pending.len()); + for pending in d.pending.drain(..) { + let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false); + if is_ready { + outcomes.push(resolve_pending(pending)); + } else { + remaining.push(pending); + } + } + d.pending = remaining; + } + outcomes + } + + #[cfg(not(target_arch = "wasm32"))] + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + loop { + let mut matched = None; + let mut others = Vec::new(); + for outcome in self.poll_reads() { + if outcome.request == request { + matched = Some(outcome.result); + } else { + others.push(outcome); + } + } + // Completions belonging to other outstanding requests go back on the queue for the + // caller's next poll_reads instead of being dropped. + self.ready.extend(others); + if let Some(result) = matched { + return result; + } + // Block on the GPU between polls instead of busy-spinning the CPU. A no-op when + // `backing` is `Staging` (nothing to wait for; the request already resolved above) + // or when wgpu is itself WebGPU under the hood, which self-polls. + #[cfg(feature = "adapter-probe")] + if let Backing::Device(d) = &self.backing { + let _ = d.device.poll(wgpu::PollType::wait_indefinitely()); + } + } + } + + /// On `wasm32` the backing is always the in-memory staging store today (real device + /// creation needs the async worker-init path and does not exist on this target yet), and a + /// staging read resolves synchronously, so serving it blocks nothing. The refusal below + /// guards the future wasm device backing: WebGPU can only map a buffer asynchronously, and + /// `wasm32` is single-threaded, so blocking on a real device would stop the only thread the + /// browser needs to run `map_async`'s own completion callback on, hanging the tab. Callers + /// on a device backing drive [`request_read`](GpuContext::request_read) and + /// [`poll_reads`](GpuContext::poll_reads) from the worker's message loop instead; see + /// `docs/gpu-backends.md`. + #[cfg(target_arch = "wasm32")] + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + match self.ready.iter().position(|o| o.request == request) { + Some(i) => self.ready.remove(i).result, + None => Err(GpuFault::Operation( + "read_buffer on wasm32: the read did not resolve synchronously. Use request_read + poll_reads from the worker's message loop \ + instead." + .into(), + )), + } + } +} diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs new file mode 100644 index 000000000..6f0b74f88 --- /dev/null +++ b/crates/gpu-wgpu/src/tests.rs @@ -0,0 +1,367 @@ +#![allow(clippy::expect_used)] + +//! RFC-0022 acceptance requirement 2: real backends beside the null one. `craft-gpu-null` stays +//! mandatory for every consumer (it cannot validate shader compilation, resource rules, or +//! numerical results), so these tests run representative jobs on a real wgpu device when one is +//! available. Runs against a software Vulkan adapter in a local container are local testing, not +//! hosted CI coverage: hosted lanes and the pilot consumers' browser and hardware validation +//! remain their own, separate requirements. The suite skips loudly when the host has no adapter +//! (`cargo test` without `--features adapter-probe,native-vulkan` already exercises the masked +//! path: no adapter is ever requested, and every context here falls back to the staging path, +//! same shape as `craft-gpu-null`). +//! +//! Tolerance: every job below is byte/structural equality, not a numeric comparison with slack. +//! That is honest for what runs today: no provider dispatches a real WGSL compute job yet +//! (`craft-gpu-providers` ships CPU stand-ins by design; see `docs/gpu-providers.md`), so the only +//! thing a real device adds over the null one here is the upload → real `wgpu::Buffer` → copy → +//! `map_async` → read round trip itself. A provider that dispatches actual WGSL will need a +//! stated numeric tolerance of its own when it lands; this suite is not that provider. + +use craft_gpu::{GpuContext, GpuJob, GpuJobParams, GpuProvider, WorkerKind}; +use craft_gpu_providers::{EchoProvider, PremulCompositeProvider, ReadbackProvider}; + +use crate::WgpuContext; + +/// A real device if this host has one; otherwise `None` with a loud, honest message instead of a +/// failed assertion. Call at the top of every test in this module. +fn real_context_or_skip(test_name: &str) -> Option { + let ctx = WgpuContext::new(WorkerKind::Main); + if ctx.has_device() { + return Some(ctx); + } + eprintln!( + "SKIP {test_name}: no real wgpu device in this environment (no backend feature compiled \ + in, or `request_adapter` found nothing). This is RFC-0022's defined no-adapter path, not \ + a failure; craft-gpu-null already covers the portable contract. Run with \ + `--features adapter-probe,native-vulkan` against a Vulkan adapter (a software one, such \ + as lavapipe/llvmpipe via mesa-vulkan-drivers, is enough) to exercise this suite for real." + ); + None +} + +#[test] +fn real_device_reports_a_non_null_backend_and_empty_features_it_actually_requested() { + let Some(ctx) = real_context_or_skip("real_device_reports_a_non_null_backend_and_empty_features_it_actually_requested") else { + return; + }; + let caps = ctx.caps(); + assert_ne!(caps.backend_name, "null", "a real device must not report the null backend name"); + assert_ne!(caps.device_name, "no-adapter", "has_device() was true; caps must not be the no-adapter fallback"); + assert_ne!(caps.device_name, "probe-not-run", "has_device() was true; caps must not be the probe-skipped fallback"); + // This context asks the device for no features yet (no provider dispatches real WGSL): the + // device reports exactly what was requested, per `Device::features`' own contract, so this is + // device-truth agreeing with an intentionally empty request, not an unprobed default. + assert!(caps.features.is_empty(), "no feature was requested, so none should be reported enabled: {:?}", caps.features); +} + +#[test] +fn real_device_upload_and_async_readback_round_trips_bytes_exactly() { + let Some(mut ctx) = real_context_or_skip("real_device_upload_and_async_readback_round_trips_bytes_exactly") else { + return; + }; + let payload: Vec = (0..256u32).map(|b| b as u8).collect(); + let handle = ctx.upload_buffer("round-trip", &payload).expect("upload_buffer on a real device"); + assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), payload.len()); + + // Exercise request_read + poll_reads directly (the primitive every backend implements), + // not just the read_buffer convenience, so the async shape itself is under test. + let request = ctx.request_read(handle).expect("request_read"); + let mut got = None; + // Non-blocking poll_reads() in a bounded loop, exercising the exact primitive a worker's own + // message/poll loop would call; read_buffer_convenience (a separate test) covers the blocking + // path. The bound is generous for a software rasterizer on a 256-byte buffer, never relying + // on wall-clock sleeps. + for _ in 0..1_000_000 { + if let Some(outcome) = ctx.poll_reads().into_iter().find(|o| o.request == request) { + got = Some(outcome.result.expect("map_async + Device::poll round trip")); + break; + } + } + assert_eq!(got.expect("the real device never completed the mapped read within the bounded poll loop"), payload); +} + +#[test] +fn real_device_read_buffer_convenience_blocks_to_completion() { + let Some(mut ctx) = real_context_or_skip("real_device_read_buffer_convenience_blocks_to_completion") else { + return; + }; + let handle = ctx.upload_buffer("blocking-read", b"craft-gpu-wgpu").expect("upload_buffer"); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"craft-gpu-wgpu".to_vec()); +} + +/// RFC-0022 requirement 2's "representative jobs": the same `craft-gpu-providers` CPU stand-ins +/// `craft-runtime` dispatches against the null context in CI also run, unmodified, against a +/// real device, through the same `&mut dyn GpuContext` seam. +#[test] +fn shared_providers_run_against_a_real_device_through_the_same_seam_as_the_null_context() { + let Some(mut ctx) = real_context_or_skip("shared_providers_run_against_a_real_device_through_the_same_seam_as_the_null_context") else { + return; + }; + + let echo = EchoProvider; + let input = ctx.upload_buffer("echo-in", b"xy").expect("upload_buffer"); + let job = GpuJob { provider_id: "craft.test.echo".into(), params: GpuJobParams(b"a".to_vec()), inputs: vec![input], outputs: vec![] }; + let out = echo.run(&mut ctx, &job).expect("craft.test.echo on a real device"); + assert_eq!(out.data.as_deref(), Some(b"axy".as_slice())); + + let composite = PremulCompositeProvider; + let dst = ctx.upload_buffer("dst", &[0, 255, 0, 255]).expect("upload dst"); + let src = ctx.upload_buffer("src", &[0, 0, 255, 128]).expect("upload src"); + let job = + GpuJob { provider_id: "craft.composite.premul".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![dst, src], outputs: vec![] }; + let out = composite.run(&mut ctx, &job).expect("craft.composite.premul on a real device"); + let bytes = ctx.read_buffer(out.outputs[0]).expect("read composite output off a real device"); + assert_eq!(bytes, vec![0, 127, 128, 255]); + + let readback = ReadbackProvider; + let rgba = ctx.upload_buffer("rgba", &[10, 20, 30, 40]).expect("upload rgba"); + let job = GpuJob { provider_id: "craft.readback".into(), params: GpuJobParams(b"w:1,h:1,fmt:u8".to_vec()), inputs: vec![rgba], outputs: vec![] }; + let out = readback.run(&mut ctx, &job).expect("craft.readback fmt:u8 on a real device"); + let bytes = ctx.read_buffer(out.outputs[0]).expect("read readback output off a real device"); + assert_eq!(bytes, vec![10, 20, 30, 40]); +} + +/// RFC-0022 requirement 1's device-loss half: a stated fault, not a panic, and a documented +/// recovery. `Backing`/`DeviceBacking` are crate-private, so this test reaches `ctx.backing` +/// directly to force the one cause it can trigger deterministically (`device.destroy()`) rather +/// than waiting on a real driver reset. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +#[test] +fn device_destroy_surfaces_as_device_lost_and_stops_further_buffer_calls() { + use craft_gpu::GpuFault; + + use crate::Backing; + + let Some(mut ctx) = real_context_or_skip("device_destroy_surfaces_as_device_lost_and_stops_further_buffer_calls") else { + return; + }; + assert!(!ctx.is_device_lost(), "a freshly created device must not already report loss"); + + if let Backing::Device(d) = &ctx.backing { + d.device.destroy(); + // The lost closure can run during destroy() or on the next poll, depending on backend; + // give it the chance either way. + let _ = d.device.poll(wgpu::PollType::Poll); + } + + // poll_reads() is the other place the trait docs promise this surfaces, for a caller that + // polls instead of issuing a buffer call first. + let _ = ctx.poll_reads(); + assert!(ctx.is_device_lost(), "device.destroy() must surface through is_device_lost(), per the GpuContext trait docs"); + + let after = ctx.upload_buffer("after-loss", b"x"); + assert!(matches!(after, Err(GpuFault::DeviceLost(_))), "a call after device loss must return GpuFault::DeviceLost, got {after:?}"); +} + +/// The staging path promises "same shape as `craft-gpu-null`": an empty upload is accepted and +/// reads back empty rather than being refused. +#[test] +fn staging_path_accepts_an_empty_buffer_and_reads_it_back_empty() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let handle = ctx.upload_buffer("empty", b"").expect("upload empty"); + assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), 0); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), Vec::::new()); +} + +/// `read_buffer` must not eat completions that belong to another outstanding `request_read`. +#[test] +fn staging_read_buffer_keeps_another_outstanding_requests_completion_queued() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + let request_a = ctx.request_read(a).expect("request_read a"); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec()); + let outcomes = ctx.poll_reads(); + assert_eq!(outcomes.len(), 1, "a's completion must survive b's read_buffer"); + assert_eq!(outcomes[0].request, request_a); + assert_eq!(outcomes[0].result.as_deref(), Ok(b"aa".as_slice())); +} + +/// CodeRabbit finding on lib.rs:228: if `request_adapter` succeeds but `request_device` fails, +/// the fallback must be the conservative fixed value, never a second, successful `probe_caps()` +/// adapter query -- which would report the adapter's advertised limits as if they came from a +/// granted device, for a context that holds none. Forcing `request_device` itself to fail is +/// hardware-dependent and not reliably reproducible in CI, so this tests the fallback value +/// `WgpuContext::new` falls back to directly: it must be the plain, fixed value, never one that +/// looks like a real probe result. +#[test] +fn the_no_device_fallback_caps_are_the_plain_fixed_value_not_a_probe_result() { + let caps = crate::probe_fallback("wgpu", "no-device"); + assert_eq!(caps.backend_name, "wgpu"); + assert_eq!(caps.device_name, "no-device"); + assert_eq!(caps, craft_gpu::DeviceCaps { backend_name: "wgpu".into(), device_name: "no-device".into(), ..craft_gpu::DeviceCaps::default() }); +} + +/// CodeRabbit finding on lib.rs:299: an allocation failure used to be able to reach wgpu's +/// default uncaptured-error handler, which panics. An error scope around buffer creation now +/// converts that into a `GpuFault` instead. A genuine out-of-memory condition is not reliably +/// reproducible in CI (it depends on how much free VRAM the host actually has), so this is the +/// regression half: the added error scope must not misfire on an entirely ordinary allocation, +/// across both the create scope and the write scope that now follows it (see the next doc +/// comment for why those are two separate scopes rather than one spanning both calls). +#[test] +fn upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place() { + let Some(mut ctx) = real_context_or_skip("upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place") else { + return; + }; + let handle = ctx.upload_buffer("scope-regression", b"ok").expect("a normal allocation must not report a false allocation error"); + assert_eq!(ctx.read_buffer(handle).expect("read back"), b"ok".to_vec()); +} + +/// CodeRabbit finding on lib.rs:329 (upload_buffer) and lib.rs:404 (request_read): the original +/// code popped its single error scope only after write_buffer (respectively, after the copy and +/// its submission), so a failed create_buffer would leave an invalid buffer in play across the +/// later call that used it. write_buffer against an invalid buffer raises a VALIDATION error, a +/// kind the OutOfMemory-only scope never catches, so it would reach wgpu's default +/// uncaptured-error handler and panic there instead of surfacing as a `GpuFault` -- the same +/// crash the scope was added to prevent in the first place. +/// +/// A genuine allocation failure is not reliably reproducible in CI (it depends on how much free +/// VRAM/host memory lavapipe actually has to give), so this cannot be a runtime test that forces +/// `create_buffer` to fail and then observes `write_buffer` never ran. What can be verified +/// honestly, and is verified here, is the ordering itself: `upload_buffer`'s source now pops the +/// create scope and returns on error strictly before it pushes the write scope or calls +/// `write_buffer`, and `request_read`'s source pops the staging-buffer create scope and returns +/// on error strictly before it creates the copy encoder or calls `queue.submit`. Both orderings +/// are asserted directly against the source text below rather than left as an unverified claim in +/// a comment; the success-path test above is the runtime half, proving the added scope split does +/// not misfire on the ordinary case. +#[test] +fn a_failed_allocation_scope_pop_is_ordered_strictly_before_the_call_that_would_use_the_buffer() { + let source = include_str!("lib.rs"); + let upload_create_pop = source.find("create_scope.pop()").expect("upload_buffer must pop a create scope"); + let upload_write_scope_push = source.find("let write_scope = d.device.push_error_scope").expect("upload_buffer must push a separate write scope"); + assert!( + upload_create_pop < upload_write_scope_push, + "upload_buffer must check the create scope's result before it ever pushes the write scope or calls write_buffer" + ); + + let read_create_pop = + source.rfind("device reported an allocation error creating the staging buffer").expect("request_read must pop a create scope"); + let read_copy_scope_push = source.rfind("let copy_scope = d.device.push_error_scope").expect("request_read must push a separate copy scope"); + assert!( + read_create_pop < read_copy_scope_push, + "request_read must check the staging-buffer create scope's result before it ever pushes the copy scope or touches the encoder" + ); +} + +/// CodeRabbit finding on lib.rs:313: nothing released an uploaded buffer's resources, so the +/// buffer table (and the GPU memory behind it) could only ever grow. free_buffer must actually +/// make the handle behave as invalid afterward, and must not disturb any other handle's index. +#[test] +fn staging_free_buffer_invalidates_the_handle_without_shifting_others() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + + ctx.free_buffer(a); + + assert!(matches!(ctx.buffer_len(a), Err(craft_gpu::GpuFault::InvalidJob(_))), "a freed handle must behave as invalid"); + assert_eq!(ctx.read_buffer(b).expect("b must be unaffected by freeing a"), b"bb".to_vec()); +} + +/// The same guarantee on a real device: freeing one handle must not disturb another's index or +/// its own buffer. +#[test] +fn real_device_free_buffer_invalidates_the_handle_without_shifting_others() { + let Some(mut ctx) = real_context_or_skip("real_device_free_buffer_invalidates_the_handle_without_shifting_others") else { + return; + }; + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + + ctx.free_buffer(a); + + assert!(matches!(ctx.buffer_len(a), Err(craft_gpu::GpuFault::InvalidJob(_))), "a freed handle must behave as invalid on a real device too"); + assert_eq!(ctx.read_buffer(b).expect("b must be unaffected by freeing a"), b"bb".to_vec()); +} + +/// CodeRabbit finding on lib.rs:438: `queue.write_buffer` only records its copy in wgpu's +/// PendingWrites; without some submission to flush that queue, wgpu-core keeps the destination +/// buffer (and the staging buffer `write_buffer` made internally) alive on its own, so repeated +/// upload_buffer/free_buffer cycles would retain GPU allocations with nothing ever releasing +/// them. `upload_buffer` now flushes with an empty `queue.submit` right after its own +/// write_buffer call. This cannot assert freed VRAM directly (wgpu exposes no such counter), so +/// it instead proves the behavioral guarantee this fix is actually for: many upload/free cycles +/// in a row complete without panicking and without ever running out of handles, which is exactly +/// what an unbounded, unflushed retention would eventually threaten on a long-lived worker. +#[test] +fn real_device_upload_and_free_many_cycles_in_a_row_does_not_panic_or_leak_a_growing_table() { + let Some(mut ctx) = real_context_or_skip("real_device_upload_and_free_many_cycles_in_a_row_does_not_panic_or_leak_a_growing_table") else { + return; + }; + for i in 0..256u32 { + let bytes = i.to_le_bytes(); + let handle = ctx.upload_buffer("cycle", &bytes).expect("each upload in the cycle must succeed"); + assert_eq!(ctx.read_buffer(handle).expect("read back this cycle's buffer"), bytes.to_vec()); + ctx.free_buffer(handle); + } +} + +/// Freeing a handle twice, or a handle that never existed, is a no-op: callers are not expected +/// to track whether they already freed one. +#[test] +fn free_buffer_is_a_harmless_no_op_when_repeated_or_given_an_unknown_handle() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + ctx.free_buffer(a); + ctx.free_buffer(a); + ctx.free_buffer(craft_gpu::HandleId(999)); +} + +/// CodeRabbit finding on lib.rs:401: `poll_reads` can only attach a device-lost fault to a read +/// it has something to attach it to, so a caller whose event loop only polls, with nothing +/// outstanding, could never observe loss through it alone. `device_status` covers exactly that +/// gap: it is checked here with no buffer call and no pending read at all after the device is +/// destroyed. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +#[test] +fn device_status_surfaces_loss_even_with_nothing_pending() { + use craft_gpu::GpuFault; + + use crate::Backing; + + let Some(ctx) = real_context_or_skip("device_status_surfaces_loss_even_with_nothing_pending") else { + return; + }; + assert_eq!(ctx.device_status(), Ok(()), "a freshly created device must not already report loss"); + + if let Backing::Device(d) = &ctx.backing { + d.device.destroy(); + let _ = d.device.poll(wgpu::PollType::Poll); + } + + // No upload_buffer, no request_read, no poll_reads: device_status() alone must observe it. + assert!(matches!(ctx.device_status(), Err(GpuFault::DeviceLost(_))), "device.destroy() must surface through device_status() alone"); +} + +/// Same two guarantees on a real device: empty buffers round-trip (the readback resolves without +/// mapping, since wgpu refuses an empty map range) and `read_buffer` re-queues completions that +/// belong to another outstanding request. +#[test] +fn real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging() { + let Some(mut ctx) = real_context_or_skip("real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging") else { + return; + }; + let empty = ctx.upload_buffer("empty", b"").expect("upload empty"); + assert_eq!(ctx.buffer_len(empty).expect("buffer_len"), 0); + assert_eq!(ctx.read_buffer(empty).expect("read_buffer empty"), Vec::::new()); + + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + let request_a = ctx.request_read(a).expect("request_read a"); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec()); + let mut seen_a = false; + for _ in 0..1000 { + for outcome in ctx.poll_reads() { + if outcome.request == request_a { + assert_eq!(outcome.result.as_deref(), Ok(b"aa".as_slice())); + seen_a = true; + } + } + if seen_a { + break; + } + } + assert!(seen_a, "a's completion must still arrive through poll_reads after b's read_buffer"); +} diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml new file mode 100644 index 000000000..3928ad8be --- /dev/null +++ b/crates/gpu/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-gpu" +description = "Provider-neutral GPU traits, GpuJob envelope, and registry (no vendor IO)" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/gpu/src/caps.rs b/crates/gpu/src/caps.rs new file mode 100644 index 000000000..75dcf173d --- /dev/null +++ b/crates/gpu/src/caps.rs @@ -0,0 +1,36 @@ +use serde::{Deserialize, Serialize}; + +/// Limits and labels reported to Settings UI and worker RPC (`GpuCaps`). +/// +/// Per RFC-0022's acceptance requirements, a backend that has a device fills every field here +/// from that created device, never from the adapter it was created on: an adapter advertises more +/// than a device may grant (`required_features`/`required_limits` at `request_device` time narrow +/// both). `craft-gpu-wgpu` reports [`Default`]-shaped conservative values only on the defined +/// no-adapter path (no GPU present, the feature compiled out, or the `wasm32` worker-init gap +/// described in `docs/gpu-backends.md`), never as a stand-in for a real device's own caps. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeviceCaps { + pub backend_name: String, + pub device_name: String, + pub max_storage_buffer_binding_size: u64, + pub max_buffer_size: u64, + pub max_texture_dimension_2d: u32, + /// Feature names actually enabled on the created device (`wgpu::Features::iter_names` on + /// native wgpu), empty on backends with no device. A fast path gates on membership here, + /// never on what the adapter merely advertised. + #[serde(default)] + pub features: Vec, +} + +impl Default for DeviceCaps { + fn default() -> Self { + Self { + backend_name: "null".into(), + device_name: "null".into(), + max_storage_buffer_binding_size: 128 * 1024 * 1024, + max_buffer_size: 256 * 1024 * 1024, + max_texture_dimension_2d: 8192, + features: Vec::new(), + } + } +} diff --git a/crates/gpu/src/chunk.rs b/crates/gpu/src/chunk.rs new file mode 100644 index 000000000..624637777 --- /dev/null +++ b/crates/gpu/src/chunk.rs @@ -0,0 +1,11 @@ +use crate::{DeviceCaps, GpuFault}; + +/// Split `data` into contiguous slices no larger than [`DeviceCaps::max_storage_buffer_binding_size`]. +pub fn chunk_buffer<'a>(caps: &DeviceCaps, data: &'a [u8]) -> Result, GpuFault> { + let max = usize::try_from(caps.max_storage_buffer_binding_size) + .map_err(|_| GpuFault::Operation("max_storage_buffer_binding_size exceeds host address space".into()))?; + if max == 0 { + return Err(GpuFault::Operation("max_storage_buffer_binding_size must be non-zero".into())); + } + Ok(data.chunks(max).collect()) +} diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs new file mode 100644 index 000000000..8d8ccb0a2 --- /dev/null +++ b/crates/gpu/src/context.rs @@ -0,0 +1,128 @@ +use crate::{DeviceCaps, GpuFault, HandleId}; + +/// Where the context was created (main thread vs worker). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WorkerKind { + Main, + DedicatedWorker, + SharedWorker, +} + +/// Opaque in-flight readback request handed out by [`GpuContext::request_read`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ReadRequest(pub u64); + +/// One completed (or failed) readback, delivered by [`GpuContext::poll_reads`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReadOutcome { + pub request: ReadRequest, + pub handle: HandleId, + pub result: Result, GpuFault>, +} + +/// Device/queue abstraction implemented by `craft-gpu-wgpu` and `craft-gpu-null`. +/// +/// ## Device loss +/// +/// A context can lose its device at any time: a driver reset, OS-level eviction under memory +/// pressure, or an explicit `device.destroy()`. Device loss surfaces as a fault and never panics. It arrives +/// through [`GpuFault::DeviceLost`] from the next call that would otherwise touch the device. +/// It also arrives through [`poll_reads`](Self::poll_reads), letting a host's event loop observe +/// it even between buffer calls. Once a context has reported [`GpuFault::DeviceLost`], every +/// [`DeviceCaps`] it reported before that point is stale. The consumer's recovery, per RFC-0022, +/// is one of: +/// +/// - fall back to the portable path (a [`DeviceCaps`]-gated path with no fast-path features, or a +/// different, CPU-backed [`GpuContext`]) for the rest of the session, or +/// - re-acquire a device, meaning construct a fresh [`GpuContext`], and re-probe +/// [`caps`](Self::caps) before resuming GPU jobs. +/// +/// No backend here supports continuing to dispatch jobs against a context that has already +/// reported device loss, using caps read before the loss. +/// +/// ## Readback +/// +/// [`read_buffer`](Self::read_buffer) is a blocking convenience built on +/// [`request_read`](Self::request_read) and [`poll_reads`](Self::poll_reads): those two are the +/// primitives every backend implements directly, because WebGPU (and therefore native wgpu's +/// `buffer.map_async`) can only map a buffer asynchronously. The completion is delivered the same +/// way a `GpuJob` batch's outcome is delivered to a worker's host: queued, then collected on a +/// later poll, analogous to `craft-worker-host`'s `HostMessage::GpuJobs` being answered later by +/// `WorkerMessage::GpuBatchDone`. +/// +/// Both bundled backends override `read_buffer`'s default body, since the default has nowhere +/// to put completions belonging to other outstanding requests: the null context takes only its +/// own completion, and the wgpu context re-queues the others while blocking efficiently on a +/// native device. On `wasm32` the wgpu context's only backing today is the in-memory staging +/// store, whose reads resolve synchronously and are served; only a read that did not resolve +/// synchronously returns [`GpuFault::Operation`] there, the refusal a future real device backing +/// will need, because a map on that target completes only via the browser's own event loop and +/// blocking for it would freeze the one thread that loop runs on. Callers on such a backing +/// drive `request_read` and `poll_reads` from the worker's own message loop. See +/// `docs/gpu-backends.md` for which backend does which. +pub trait GpuContext { + fn caps(&self) -> DeviceCaps; + + fn worker_kind(&self) -> WorkerKind; + + /// Register an opaque buffer blob; returns a handle for job graphs. + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result; + + fn buffer_len(&self, handle: HandleId) -> Result; + + /// Queue an asynchronous readback of `handle`. Completion is delivered by + /// [`poll_reads`](Self::poll_reads). + fn request_read(&mut self, handle: HandleId) -> Result; + + /// Drain every read completed (or failed) since the last call. Also where a device-lost + /// fault surfaces for callers that are polling rather than issuing buffer calls. A context + /// that resolves reads synchronously (the null context; native wgpu with no device) may + /// resolve a request on the very next call after [`request_read`](Self::request_read). + /// + /// This can only attach a device-lost fault to a read it has something to attach it to: when + /// nothing is outstanding, there is no [`ReadOutcome`] to fabricate one onto. A caller whose + /// event loop only polls, with no buffer calls and no outstanding read, uses + /// [`device_status`](Self::device_status) for that gap. + fn poll_reads(&mut self) -> Vec; + + /// Device loss observable independent of any specific read or buffer call, covering the gap + /// [`poll_reads`](Self::poll_reads) has when nothing is outstanding to attach the fault to. + /// The default is `Ok(())`: correct for any backend with no concept of device loss (the null + /// context; the staging/no-device path here). A backend that can lose a device overrides + /// this to report it. + fn device_status(&self) -> Result<(), GpuFault> { + Ok(()) + } + + /// Release a previously uploaded buffer's resources. A no-op, not an error, for a handle + /// that is already invalid or was already freed: callers are never required to track + /// whether they already freed one. A freed handle behaves as invalid afterward (the same + /// fault a never-issued handle would produce) from every other method on this trait. + /// + /// Without this, a backend's buffer table -- and the memory behind it -- can only ever grow + /// for the context's lifetime: every `upload_buffer`, and every output buffer a provider's + /// job creates, adds an entry nothing removes. Repeated jobs then retain GPU (or host, for + /// the null context) memory long after every caller is done with every handle it created. + fn free_buffer(&mut self, handle: HandleId); + + /// Blocking convenience for callers that need bytes now, such as the CPU-stand-in providers + /// in `craft-gpu-providers`. The default drains [`request_read`](Self::request_read) and + /// [`poll_reads`](Self::poll_reads) in a loop; see the trait docs for which backends honestly + /// support blocking here and which override this to fail instead of hanging. + /// + /// The default body has nowhere to put completions that belong to other requests, so it + /// drops them: with the default body, never call this while another + /// [`request_read`](Self::request_read) is outstanding. A backend that stores completions + /// overrides this to put the other requests' outcomes back for the next + /// [`poll_reads`](Self::poll_reads); both bundled backends do. + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + loop { + for outcome in self.poll_reads() { + if outcome.request == request { + return outcome.result; + } + } + } + } +} diff --git a/crates/gpu/src/error.rs b/crates/gpu/src/error.rs new file mode 100644 index 000000000..794611efb --- /dev/null +++ b/crates/gpu/src/error.rs @@ -0,0 +1,20 @@ +use thiserror::Error; + +/// Neutral GPU failure (no wgpu/WebGPU types cross this boundary). +#[derive(Clone, Debug, PartialEq, Eq, Error)] +pub enum GpuFault { + #[error("provider not registered: {0}")] + UnknownProvider(String), + #[error("invalid job: {0}")] + InvalidJob(String), + #[error("device unavailable: {0}")] + DeviceUnavailable(String), + /// The device was lost (driver reset, OS eviction, explicit `destroy()`) after it was + /// created. Every [`crate::DeviceCaps`] read before this point is stale: per + /// [`crate::GpuContext`]'s trait docs, fall back to the portable path or re-acquire a device + /// and re-probe caps. Never keep dispatching jobs against a context that reported this. + #[error("device lost: {0}")] + DeviceLost(String), + #[error("operation failed: {0}")] + Operation(String), +} diff --git a/crates/gpu/src/job.rs b/crates/gpu/src/job.rs new file mode 100644 index 000000000..5f822b6f6 --- /dev/null +++ b/crates/gpu/src/job.rs @@ -0,0 +1,28 @@ +use serde::{Deserialize, Serialize}; + +/// Opaque resource handle in a job graph (resolved in the active [`GpuContext`](crate::GpuContext)). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct HandleId(pub u32); + +/// Stable provider name (`craft.readback`, `effectcraft.compositor.frame`, …). +pub type ProviderId = String; + +/// Versioned parameter blob; schema owned by the provider crate, not craft-gpu. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuJobParams(pub Vec); + +/// Serializable work unit for generic worker dispatch. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuJob { + pub provider_id: ProviderId, + pub params: GpuJobParams, + pub inputs: Vec, + pub outputs: Vec, +} + +/// Result handles or side-channel bytes (provider-defined interpretation). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuJobOutcome { + pub outputs: Vec, + pub data: Option>, +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs new file mode 100644 index 000000000..7b5124278 --- /dev/null +++ b/crates/gpu/src/lib.rs @@ -0,0 +1,27 @@ +//! GPU traits, job envelope, and provider registry for Craft apps and the web runtime. +//! +//! Application crates register [`GpuProvider`] implementations; generic hosts dispatch +//! [`GpuJob`] values by [`GpuJob::provider_id`] without importing app project types. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod caps; +mod chunk; +mod context; +mod error; +mod job; +mod provider; +mod readback; +mod registry; + +#[cfg(test)] +mod tests; + +pub use caps::DeviceCaps; +pub use chunk::chunk_buffer; +pub use context::{GpuContext, ReadOutcome, ReadRequest, WorkerKind}; +pub use error::GpuFault; +pub use job::{GpuJob, GpuJobOutcome, GpuJobParams, HandleId}; +pub use provider::GpuProvider; +pub use readback::{f16_rgba_to_f32_bytes, f16_to_f32, f16_to_f32_fast}; +pub use registry::ProviderRegistry; diff --git a/crates/gpu/src/provider.rs b/crates/gpu/src/provider.rs new file mode 100644 index 000000000..677351f57 --- /dev/null +++ b/crates/gpu/src/provider.rs @@ -0,0 +1,8 @@ +use crate::{GpuContext, GpuFault, GpuJob, GpuJobOutcome}; + +/// One GPU operation family. App and generic providers implement this trait. +pub trait GpuProvider { + fn id(&self) -> &'static str; + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result; +} diff --git a/crates/gpu/src/readback.rs b/crates/gpu/src/readback.rs new file mode 100644 index 000000000..ad02afbe8 --- /dev/null +++ b/crates/gpu/src/readback.rs @@ -0,0 +1,50 @@ +/// IEEE half → f32 (FilmCraft `filmcraft_gpu::f16_to_f32`), for decoding `Rgba16Float` readbacks. +pub fn f16_to_f32(h: u16) -> f32 { + let sign = ((h & 0x8000) as u32) << 16; + let exp = ((h >> 10) & 0x1f) as u32; + let mant = (h & 0x03ff) as u32; + let bits = match exp { + 0 => { + if mant == 0 { + sign + } else { + let b = 31 - mant.leading_zeros(); + let frac = (mant ^ (1 << b)) << (23 - b); + sign | ((103 + b) << 23) | frac + } + } + 0x1f => sign | 0x7f80_0000 | (mant << 13), + _ => sign | ((exp + 112) << 23) | (mant << 13), + }; + f32::from_bits(bits) +} + +/// [`f16_to_f32`] with a fast path for normal numbers and zeros; subnormals and non-finite values use [`f16_to_f32`]. +#[inline] +pub fn f16_to_f32_fast(h: u16) -> f32 { + let u = u32::from(h); + let sign = (u & 0x8000) << 16; + let abs = u & 0x7fff; + if (0x0400..0x7c00).contains(&abs) { + f32::from_bits(sign | ((abs + (112 << 10)) << 13)) + } else if abs == 0 { + f32::from_bits(sign) + } else { + f16_to_f32(h) + } +} + +/// Expand little-endian RGBA f16 texels to RGBA f32 (row-major, no padding). +pub fn f16_rgba_to_f32_bytes(src: &[u8]) -> Result, usize> { + if !src.len().is_multiple_of(8) { + return Err(src.len()); + } + let mut out = Vec::with_capacity(src.len() * 2); + for chunk in src.as_chunks::<8>().0 { + for pair in chunk.as_chunks::<2>().0 { + let v = f16_to_f32_fast(u16::from_le_bytes(*pair)); + out.extend_from_slice(&v.to_le_bytes()); + } + } + Ok(out) +} diff --git a/crates/gpu/src/registry.rs b/crates/gpu/src/registry.rs new file mode 100644 index 000000000..5e9d978de --- /dev/null +++ b/crates/gpu/src/registry.rs @@ -0,0 +1,39 @@ +use crate::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +/// Lookup table filled at worker/app init. Generic runtime code only talks to this. +pub struct ProviderRegistry { + providers: Vec>, +} + +impl Default for ProviderRegistry { + fn default() -> Self { + Self::new() + } +} + +impl ProviderRegistry { + pub fn new() -> Self { + Self { providers: Vec::new() } + } + + pub fn register(&mut self, provider: Box) { + self.providers.push(provider); + } + + pub fn dispatch(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + for provider in &self.providers { + if provider.id() == job.provider_id { + return provider.run(ctx, job); + } + } + Err(GpuFault::UnknownProvider(job.provider_id.clone())) + } + + /// Run every job in order and answer per job, in input order. A later job's failure never + /// discards outcomes earlier providers already produced: the caller replies per job and can + /// retry exactly the failed ones. A job whose inputs came from a failed earlier job fails + /// honestly on its own bad handles. + pub fn dispatch_batch(&self, ctx: &mut dyn GpuContext, jobs: &[GpuJob]) -> Vec> { + jobs.iter().map(|job| self.dispatch(ctx, job)).collect() + } +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs new file mode 100644 index 000000000..528b2e587 --- /dev/null +++ b/crates/gpu/src/tests.rs @@ -0,0 +1,128 @@ +#![allow(clippy::expect_used)] + +use crate::{ + DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, ReadOutcome, ReadRequest, WorkerKind, chunk_buffer, + f16_rgba_to_f32_bytes, f16_to_f32, f16_to_f32_fast, +}; + +struct MemContext { + caps: DeviceCaps, + /// `None` means freed (or never allocated): handles are stable indices, so a freed slot + /// cannot simply be removed without shifting every later handle's index. + buffers: Vec>>, + next_request: u64, + ready: Vec, +} + +impl GpuContext for MemContext { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + + fn worker_kind(&self) -> WorkerKind { + WorkerKind::Main + } + + fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { + let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); + self.buffers.push(Some(bytes.to_vec())); + Ok(id) + } + + fn buffer_len(&self, handle: HandleId) -> Result { + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } + + fn request_read(&mut self, handle: HandleId) -> Result { + let bytes = self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let request = ReadRequest(self.next_request); + self.next_request = self.next_request.wrapping_add(1); + self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); + Ok(request) + } + + fn poll_reads(&mut self) -> Vec { + std::mem::take(&mut self.ready) + } + + fn free_buffer(&mut self, handle: HandleId) { + if let Some(slot) = self.buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } +} + +fn mem_context() -> MemContext { + MemContext { caps: DeviceCaps::default(), buffers: Vec::new(), next_request: 0, ready: Vec::new() } +} + +#[test] +fn unknown_provider_is_fault() { + let registry = ProviderRegistry::new(); + let mut ctx = mem_context(); + let job = GpuJob { provider_id: "missing".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + assert!(matches!(registry.dispatch(&mut ctx, &job), Err(GpuFault::UnknownProvider(_)))); +} + +#[test] +fn dispatch_batch_keeps_completed_outcomes_when_a_later_job_fails() { + struct Echo; + impl crate::GpuProvider for Echo { + fn id(&self) -> &'static str { + "test.echo" + } + fn run(&self, _ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + Ok(crate::GpuJobOutcome { outputs: vec![], data: Some(job.params.0.clone()) }) + } + } + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(Echo)); + let mut ctx = mem_context(); + let ok = GpuJob { provider_id: "test.echo".into(), params: GpuJobParams(b"first".to_vec()), inputs: vec![], outputs: vec![] }; + let bad = GpuJob { provider_id: "missing".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + let ok2 = GpuJob { provider_id: "test.echo".into(), params: GpuJobParams(b"third".to_vec()), inputs: vec![], outputs: vec![] }; + let results = registry.dispatch_batch(&mut ctx, &[ok, bad, ok2]); + assert_eq!(results.len(), 3, "one entry per job, in input order"); + assert_eq!(results[0].as_ref().expect("first job succeeded").data.as_deref(), Some(b"first".as_slice())); + assert!(matches!(results[1], Err(GpuFault::UnknownProvider(_)))); + assert_eq!(results[2].as_ref().expect("job after the failure still ran").data.as_deref(), Some(b"third".as_slice())); +} + +#[test] +fn read_buffer_default_resolves_against_request_read_and_poll_reads() { + let mut ctx = mem_context(); + let handle = ctx.upload_buffer("in", b"hello").expect("upload_buffer"); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"hello".to_vec()); +} + +#[test] +fn request_read_on_bad_handle_is_invalid_job() { + let mut ctx = mem_context(); + assert!(matches!(ctx.request_read(HandleId(99)), Err(GpuFault::InvalidJob(_)))); +} + +#[test] +fn f16_to_f32_matches_fast_for_one() { + let h = 0x3c00u16; + assert!((f16_to_f32(h) - 1.0).abs() < 1e-6); + assert_eq!(f16_to_f32(h).to_bits(), f16_to_f32_fast(h).to_bits()); +} + +#[test] +fn f16_rgba_to_f32_bytes_expands_texels() { + let src = 0x3c00u16.to_le_bytes(); + let mut raw = Vec::new(); + for _ in 0..4 { + raw.extend_from_slice(&src); + } + let out = f16_rgba_to_f32_bytes(&raw).expect("decode"); + assert_eq!(out.len(), 16); + assert!((f32::from_le_bytes(out[0..4].try_into().expect("le")) - 1.0).abs() < 1e-6); +} + +#[test] +fn chunk_buffer_splits_on_storage_binding_limit() { + let caps = DeviceCaps { max_storage_buffer_binding_size: 4, ..DeviceCaps::default() }; + let chunks = chunk_buffer(&caps, b"abcdef").expect("chunk_buffer"); + assert_eq!(chunks, vec![&b"abcd"[..], &b"ef"[..]]); +} diff --git a/crates/http-url/src/lib.rs b/crates/http-url/src/lib.rs index 1e3e5875f..bece12fc4 100644 --- a/crates/http-url/src/lib.rs +++ b/crates/http-url/src/lib.rs @@ -177,10 +177,37 @@ impl Url { } } +/// Parses an HTTP `Content-Range` header value (`bytes a-b/total`) into `(a, total)`, +/// where `*` as the total length yields `None`. +#[must_use] +pub fn parse_content_range(v: &str) -> Option<(u64, Option)> { + let v = v.trim().strip_prefix("bytes")?.trim(); + let (range, total) = v.split_once('/')?; + let (a, b) = range.split_once('-')?; + let (a, b) = (digits(a)?, digits(b)?); + if b < a { + return None; + } + let total = match total.trim() { + "*" => None, + t => Some(digits(t)?), + }; + Some((a, total)) +} + +/// A non-empty run of ASCII digits as a `u64` (no sign, unlike `str::parse`). +fn digits(s: &str) -> Option { + let s = s.trim(); + if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + s.parse().ok() +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - use super::{Url, UrlError}; + use super::{Url, UrlError, parse_content_range}; #[test] fn fragment_only_or_empty_location_keeps_file_name_and_query() { @@ -274,4 +301,16 @@ mod tests { assert!(!plain.join("http://127.0.0.1:9/b").unwrap().tls); assert!(plain.join("https://b.example/z").unwrap().tls); } + + #[test] + fn parses_content_ranges() { + assert_eq!(parse_content_range("bytes 100-299/300"), Some((100, Some(300)))); + assert_eq!(parse_content_range("bytes 0-0/*"), Some((0, None))); + assert_eq!(parse_content_range("bytes 9-1/300"), None); + assert_eq!(parse_content_range("items 1-2/3"), None); + assert_eq!(parse_content_range("bytes +100-+299/+300"), None); + assert_eq!(parse_content_range("bytes 100-+299/300"), None); + assert_eq!(parse_content_range("bytes 100-299/+300"), None); + assert_eq!(parse_content_range("bytes 1-/3"), None); + } } diff --git a/crates/image-codecs/src/bmp_probe.rs b/crates/image-codecs/src/bmp_probe.rs index 89f6a3b97..8bd2c6435 100644 --- a/crates/image-codecs/src/bmp_probe.rs +++ b/crates/image-codecs/src/bmp_probe.rs @@ -2,6 +2,8 @@ use crate::error::CodecError; +pub use crate::codecs::bmp::pixels_per_meter; + /// Recognize a BMP file header with a supported DIB header kind. /// /// This is a format-routing check, not full validation: dimensions and pixel data may still @@ -617,3 +619,47 @@ mod tests { assert_eq!(dib_layout(odd.clone()), odd); } } + +#[cfg(test)] +mod density_tests { + use super::pixels_per_meter; + + fn header(dib: u32, x: i32, y: i32) -> [u8; 46] { + let mut b = [0; 46]; + b[..2].copy_from_slice(b"BM"); + b[14..18].copy_from_slice(&dib.to_le_bytes()); + b[38..42].copy_from_slice(&x.to_le_bytes()); + b[42..46].copy_from_slice(&y.to_le_bytes()); + b + } + + #[test] + fn raw_density_preserves_axes_and_integer_extremes() { + for dib in [40, 41, 52, 56, 64, 108, 124, u32::MAX] { + assert_eq!(pixels_per_meter(&header(dib, 10000, 20000)), Some((10000, 20000))); + } + assert_eq!(pixels_per_meter(&header(40, i32::MAX, 1)), Some((i32::MAX, 1))); + assert_eq!(pixels_per_meter(&header(40, 11811, 11811)), Some((11811, 11811))); + } + + #[test] + fn raw_density_rejects_missing_or_nonpositive_fields() { + let valid = header(40, 10000, 20000); + for len in 0..valid.len() { + assert_eq!(pixels_per_meter(&valid[..len]), None, "prefix {len}"); + } + for dib in [0, 12, 16, 39] { + assert_eq!(pixels_per_meter(&header(dib, 10000, 20000)), None); + } + for bad in [0, -1, i32::MIN] { + assert_eq!(pixels_per_meter(&header(40, bad, 20000)), None); + assert_eq!(pixels_per_meter(&header(40, 10000, bad)), None); + } + let mut wrong = valid; + wrong[0] = b'X'; + assert_eq!(pixels_per_meter(&wrong), None); + let mut trailing = valid.to_vec(); + trailing.extend_from_slice(&[1, 2, 3]); + assert_eq!(pixels_per_meter(&trailing), Some((10000, 20000))); + } +} diff --git a/crates/image-codecs/src/codecs/bmp.rs b/crates/image-codecs/src/codecs/bmp.rs index 239794a2c..a574dd840 100644 --- a/crates/image-codecs/src/codecs/bmp.rs +++ b/crates/image-codecs/src/codecs/bmp.rs @@ -27,12 +27,23 @@ fn has_resolution_fields(bytes: &[u8]) -> bool { /// or either is 0 or negative (most writers leave them 0). A whole number of ppi stored rounded to /// whole pixels per metre (300 ppi = 11811) reads back whole, as a PNG's `pHYs` does. pub(crate) fn resolution(bytes: &[u8]) -> Option<(f32, f32)> { + let (x, y) = pixels_per_meter(bytes)?; + Some((dpi_of_ppm(x as u32), dpi_of_ppm(y as u32))) +} + +/// Positive signed pixels per metre from a BMP's header, without rounding to DPI. +/// +/// Requires a `BM` signature, at least 46 bytes and a DIB header size of at least 40. +/// Zero or negative density on either axis gives `None`. This is a bounded header +/// probe, not full BMP validation: pixel data and other header fields are not checked. +/// Callers retain their own unit conversion, precision and density sanity policy. +pub fn pixels_per_meter(bytes: &[u8]) -> Option<(i32, i32)> { if !has_resolution_fields(bytes) { return None; } - let field = |at: usize| le4(bytes, at).map(i32::from_le_bytes).and_then(|v| u32::try_from(v).ok()); - let (x, y) = (field(X_PPM)?, field(Y_PPM)?); - (x > 0 && y > 0).then(|| (dpi_of_ppm(x), dpi_of_ppm(y))) + let x = i32::from_le_bytes(le4(bytes, X_PPM)?); + let y = i32::from_le_bytes(le4(bytes, Y_PPM)?); + (x > 0 && y > 0).then_some((x, y)) } /// Pixels per metre for `ppi`, rounded as Photoshop and the PNG `pHYs` writer do (300 ppi = 11811), diff --git a/crates/image-codecs/src/codecs/jpegls.rs b/crates/image-codecs/src/codecs/jpegls.rs index aa6579349..3c7d5920a 100644 --- a/crates/image-codecs/src/codecs/jpegls.rs +++ b/crates/image-codecs/src/codecs/jpegls.rs @@ -924,6 +924,17 @@ mod tests { assert_eq!(jpeg_frame(&file), Some(JpegFrame::Ls)); } + #[test] + fn a_walk_that_found_another_frame_header_stays_at_it() { + // SOI, a comment with two bytes of text, then a baseline frame header. + let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xC0, 0, 11]; + let mut pos = 0; + assert_eq!(jpeg_frame_from(&file, &mut pos), Some(JpegFrame::Other)); + assert_eq!(pos, 8); + assert_eq!(jpeg_frame_from(&file, &mut pos), Some(JpegFrame::Other)); + assert_eq!(pos, 8); + } + #[test] fn interleaved_scans_and_tables_are_unsupported() { let img = image(8, 4, ChannelLayout::Rgb, false, 2); diff --git a/crates/image-codecs/src/jpeg_inks.rs b/crates/image-codecs/src/jpeg_inks.rs index 226703643..977133ac0 100644 --- a/crates/image-codecs/src/jpeg_inks.rs +++ b/crates/image-codecs/src/jpeg_inks.rs @@ -96,3 +96,104 @@ pub fn decode_jpeg_inks(bytes: &[u8], limits: &Limits) -> Result Option> { + // A segment's length counts itself (2 bytes) and the name, number and count (14). + const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2; + let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect(); + let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?; + let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len()); + for (i, chunk) in chunks.iter().enumerate() { + let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?; + segments.extend_from_slice(&[0xFF, 0xE2]); + segments.extend_from_slice(&len.to_be_bytes()); + segments.extend_from_slice(ICC_SEGMENT); + segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]); + segments.extend_from_slice(chunk); + } + with_icc_segments(bytes, &segments) +} + +/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the +/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose +/// segments before the scan can't be read. +pub fn jpeg_without_icc(bytes: &[u8]) -> Option> { + with_icc_segments(bytes, &[]) +} + +/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments` +/// written after the leading application segments; `None` when the bytes don't start a JPEG or +/// their segments before the scan can't be read. +fn with_icc_segments(bytes: &[u8], segments: &[u8]) -> Option> { + if !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } + let mut out = Vec::with_capacity(bytes.len() + segments.len()); + out.extend_from_slice(&[0xFF, 0xD8]); + let mut icc_segments = Some(segments); + let mut at = 2; + // The segments before the scan (SOS), each with its length; a marker without one ends them. + // Fill bytes (0xFF) before a marker are left out. + loop { + while bytes.get(at..at + 2) == Some(&[0xFF, 0xFF]) { + at += 1; + } + let (Some(&0xFF), Some(&marker)) = (bytes.get(at), bytes.get(at + 1)) else { return None }; + let app = (0xE0..=0xEF).contains(&marker); + if !app && let Some(s) = icc_segments.take() { + out.extend_from_slice(s); + } + if matches!(marker, 0xDA | 0xD8 | 0xD9 | 0x01 | 0xD0..=0xD7) { + break; + } + let len = usize::from(u16::from_be_bytes(bytes.get(at + 2..at + 4)?.try_into().ok()?)); + let segment = bytes.get(at..(at + 2).checked_add(len)?).filter(|_| len >= 2)?; + if !(marker == 0xE2 && segment.get(4..16) == Some(ICC_SEGMENT.as_slice())) { + out.extend_from_slice(segment); + } + at += segment.len(); + } + out.extend_from_slice(bytes.get(at..)?); + Some(out) +} + +#[cfg(test)] +mod tests { + use super::{jpeg_icc_profile, jpeg_with_icc, jpeg_without_icc}; + + fn minimal_jpeg() -> Vec { + let mut jpeg = Vec::new(); + jpeg.extend_from_slice(&[0xFF, 0xD8]); // SOI + jpeg.extend_from_slice(&[0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]); // APP0 + jpeg.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 8, 0, 1, 0, 1, 1, 1, 0x11, 0]); // SOF0 + jpeg.extend_from_slice(&[0xFF, 0xDA, 0x00, 0x08, 1, 1, 0, 0, 63, 0]); // SOS + jpeg.extend_from_slice(&[0x00, 0xFF, 0xD9]); // scan + EOI + jpeg + } + + #[test] + fn replaces_and_strips_jpeg_icc_segments() { + let base = minimal_jpeg(); + let icc_a = vec![0x11; 70_000]; + let with_a = jpeg_with_icc(&base, &icc_a).unwrap(); + assert_eq!(jpeg_icc_profile(&with_a), Some(icc_a)); + + let icc_b = b"short-profile"; + let with_b = jpeg_with_icc(&with_a, icc_b).unwrap(); + assert_eq!(jpeg_icc_profile(&with_b), Some(icc_b.to_vec())); + + let stripped = jpeg_without_icc(&with_b).unwrap(); + assert_eq!(jpeg_icc_profile(&stripped), None); + assert_eq!(stripped, base); + assert_eq!(jpeg_with_icc(&base, &[]), None); + } +} diff --git a/crates/image-codecs/src/options.rs b/crates/image-codecs/src/options.rs index d0ef8ee9a..b4436055c 100644 --- a/crates/image-codecs/src/options.rs +++ b/crates/image-codecs/src/options.rs @@ -108,7 +108,8 @@ pub struct DecodeOptions { pub limits: Limits, /// Keep the pixels as stored instead of applying the EXIF / TIFF /// orientation (by default they are turned upright and the metadata's - /// orientation is rewritten to 1). + /// orientation is rewritten to 1). JPEG XL ignores this: `craft-jxl` applies the codestream's + /// orientation while rendering, so a JPEG XL image is always upright with orientation 1. pub keep_orientation: bool, } diff --git a/crates/image-codecs/tests/it/detect_caps.rs b/crates/image-codecs/tests/it/detect_caps.rs index 76e8bc584..ee9ccda51 100644 --- a/crates/image-codecs/tests/it/detect_caps.rs +++ b/crates/image-codecs/tests/it/detect_caps.rs @@ -422,17 +422,13 @@ fn a_stuffed_zero_where_a_marker_should_be_is_jpeg() { } #[test] -fn a_detector_that_found_a_jpeg_frame_does_not_walk_again() { +fn a_detector_that_found_a_jpeg_frame_keeps_answering_jpeg() { // SOI, a comment with two bytes of text, then a baseline frame header. let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xC0, 0, 11]; let mut detector = PrefixDetector::new(); + assert_eq!(detector.detect(&file[..10]), Detection::Format(Format::Jpeg)); + assert_eq!(detector.detect(&file), detect_prefix(&file)); assert_eq!(detector.detect(&file), Detection::Format(Format::Jpeg)); - // With an SOF55 marker where the comment marker was, a walk from the SOI finds JPEG-LS. The - // detector starts at the baseline frame header it stopped at and still answers JPEG. - let mut changed = file; - changed[3] = 0xF7; - assert_eq!(detect_prefix(&changed), Detection::Format(Format::JpegLs)); - assert_eq!(detector.detect(&changed), Detection::Format(Format::Jpeg)); } #[test] @@ -440,14 +436,11 @@ fn a_detector_keeps_its_place_between_calls() { // SOI, a comment with two bytes of text, then an SOF55 frame header. let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xF7, 0, 11]; let mut detector = PrefixDetector::new(); + assert_eq!(detector.detect(&file[..5]), Detection::NeedBytes(6)); assert_eq!(detector.detect(&file[..9]), Detection::NeedBytes(10)); - // The next call starts at the frame header's marker and does not read the bytes before it - // again: with them cleared, the detector still finds JPEG-LS, while a walk from the start - // finds no SOI. - let mut cleared = file; - cleared[..8].fill(0); - assert_ne!(detect_prefix(&cleared), Detection::Format(Format::JpegLs)); - assert_eq!(detector.detect(&cleared), Detection::Format(Format::JpegLs)); + // Each call extends the previous prefix, and the answer matches a walk from the SOI. + assert_eq!(detector.detect(&file), detect_prefix(&file)); + assert_eq!(detect_prefix(&file), Detection::Format(Format::JpegLs)); } #[cfg(feature = "sunraster")] diff --git a/crates/ipp/Cargo.toml b/crates/ipp/Cargo.toml new file mode 100644 index 000000000..4b6bbc664 --- /dev/null +++ b/crates/ipp/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "craft-ipp" +description = "A small IPP client for CUPS (list printers, default printer, print a PDF), pure Rust, no dependencies" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[dependencies] + +[lints] +workspace = true diff --git a/crates/ipp/src/lib.rs b/crates/ipp/src/lib.rs new file mode 100644 index 000000000..c474b8200 --- /dev/null +++ b/crates/ipp/src/lib.rs @@ -0,0 +1,705 @@ +//! `photocraft-ipp`: a small IPP client for CUPS, in pure Rust with no dependencies. +//! +//! Talks to the local print server the way `lp` does, but in-process: over the CUPS domain +//! socket (`/run/cups/cups.sock`, or `CUPS_SERVER` when it names a path) or TCP (`localhost:631`, +//! or `CUPS_SERVER` as `host[:port]`). Three operations, from RFC 8010 / 8011 and CUPS's own +//! extensions: list the printers, read the default, and submit a PDF as a job. +//! +//! Never panics: every read is bounded and every malformed reply is an error. Works on any Unix +//! and on Windows for TCP (CUPS rarely runs there; the Windows print path is separate). + +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; +use std::path::PathBuf; +use std::time::Duration; + +/// Where the print server listens. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Endpoint { + /// A Unix domain socket (CUPS's default, also what a Flatpak sees with `--socket=cups`). + Unix(PathBuf), + /// A TCP host and port. + Tcp(String, u16), +} + +/// Why a request failed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// No server could be reached. + Unreachable(String), + /// The HTTP or IPP reply could not be read. + Protocol(String), + /// The server answered with an IPP error status (the code and its message). + Status(u16, String), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Unreachable(m) => write!(f, "no print server: {m}"), + Error::Protocol(m) => write!(f, "print server reply: {m}"), + Error::Status(code, m) => write!(f, "print server refused ({code:#06x}): {m}"), + } + } +} + +impl std::error::Error for Error {} + +type Result = std::result::Result; + +/// A printer the server knows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Printer { + pub name: String, + /// `printer-info`, the human description. + pub info: String, + /// `printer-state`: 3 idle, 4 printing, 5 stopped. + pub state: u32, + pub accepting_jobs: bool, + pub is_default: bool, + /// A CUPS class (a pool of printers) rather than one printer. + pub is_class: bool, +} + +/// Timeouts: connecting, and each request (a Print-Job carries the whole PDF). +const CONNECT: Duration = Duration::from_secs(3); +const REQUEST: Duration = Duration::from_secs(60); +/// The whole reply, however it trickles in: the timeouts above only cover each read. +const REPLY_DEADLINE: Duration = Duration::from_secs(120); +/// Largest reply read. +const MAX_REPLY: usize = 16 << 20; +/// Largest number of attributes taken from a reply. +const MAX_ATTRIBUTES: usize = 100_000; + +pub const OP_PRINT_JOB: u16 = 0x0002; +pub const OP_CUPS_GET_DEFAULT: u16 = 0x4001; +pub const OP_CUPS_GET_PRINTERS: u16 = 0x4002; +pub const OP_CUPS_GET_CLASSES: u16 = 0x4005; + +pub const TAG_OPERATION_GROUP: u8 = 0x01; +pub const TAG_JOB_GROUP: u8 = 0x02; +pub const TAG_END: u8 = 0x03; +pub const TAG_PRINTER_GROUP: u8 = 0x04; +pub const TAG_INTEGER: u8 = 0x21; +pub const TAG_BOOLEAN: u8 = 0x22; +pub const TAG_ENUM: u8 = 0x23; +pub const TAG_TEXT: u8 = 0x41; +pub const TAG_NAME: u8 = 0x42; +pub const TAG_KEYWORD: u8 = 0x44; +pub const TAG_URI: u8 = 0x45; +pub const TAG_CHARSET: u8 = 0x47; +pub const TAG_LANGUAGE: u8 = 0x48; +pub const TAG_MIME: u8 = 0x49; + +impl Endpoint { + /// The server this machine uses: `CUPS_SERVER` (a socket path, or `host[:port]`), else the + /// CUPS socket, else `localhost:631`. `None` when nothing answers. + pub fn detect() -> Option { + if let Some(server) = std::env::var_os("CUPS_SERVER").filter(|v| !v.is_empty()) { + let ep = Endpoint::parse(&server.to_string_lossy()); + return ep.reachable().then_some(ep); + } + [ + Endpoint::Unix(PathBuf::from("/run/cups/cups.sock")), + Endpoint::Unix(PathBuf::from("/var/run/cups/cups.sock")), + // macOS + Endpoint::Unix(PathBuf::from("/private/var/run/cupsd")), + Endpoint::Tcp("localhost".into(), 631), + ] + .into_iter() + .find(Endpoint::reachable) + } + + /// `server` as a socket path (starts with `/`) or `host[:port]` (port 631 by default). An IPv6 + /// server is `[address]` or `[address]:port`; written bare (more than one `:`) it keeps the + /// default port, because its last `:` cannot be told apart from a port separator. Anything else + /// after the bracket (`[::1]:abc`) stays the host, so a mistyped endpoint cannot resolve rather + /// than quietly becoming the default one. + pub fn parse(server: &str) -> Endpoint { + if server.starts_with('/') { + return Endpoint::Unix(PathBuf::from(server)); + } + // `[IPv6]:port` - the brackets tell the address from the port, and are not part of the host. + if let Some(rest) = server.strip_prefix('[') + && let Some((host, tail)) = rest.split_once(']') + { + // Nothing after the bracket, or a real `:port`, is understood. Anything else (`[::1]:abc`, + // `[::1]:70000`, `[::1]junk`) keeps the whole string as the host, so the mistyped endpoint + // stays unresolvable instead of quietly becoming the default one. + let port = if tail.is_empty() { + 631 + } else if let Some(port) = tail.strip_prefix(':').and_then(|p| p.parse().ok()) { + port + } else { + return Endpoint::Tcp(server.to_string(), 631); + }; + return Endpoint::Tcp(host.to_string(), port); + } + // A bare IPv6 literal has more than one ':', so splitting on the last one would cut the + // address in half: it is the host, and the port stays the default. A zone id (`fe80::1%eth0`) + // carries no ':', so there a port can still follow the address. + let host_port = if server.matches(':').count() > 1 && !server.contains('%') { None } else { server.rsplit_once(':') }; + let (host, port) = host_port.and_then(|(h, p)| p.parse().ok().map(|p| (h.to_string(), p))).unwrap_or((server.to_string(), 631)); + Endpoint::Tcp(host, port) + } + + /// Whether a connection opens. + pub fn reachable(&self) -> bool { + self.connect().is_ok() + } + + fn connect(&self) -> Result { + match self { + #[cfg(unix)] + Endpoint::Unix(path) => { + if !path.exists() { + return Err(Error::Unreachable(format!("{} does not exist", path.display()))); + } + let s = std::os::unix::net::UnixStream::connect(path).map_err(|e| Error::Unreachable(format!("{}: {e}", path.display())))?; + let _ = s.set_read_timeout(Some(REQUEST)); + let _ = s.set_write_timeout(Some(REQUEST)); + Ok(Stream::Unix(s)) + } + #[cfg(not(unix))] + Endpoint::Unix(path) => Err(Error::Unreachable(format!("{}: Unix sockets are not available here", path.display()))), + Endpoint::Tcp(host, port) => { + let addr = (host.as_str(), *port).to_socket_addrs().map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?.next(); + let addr = addr.ok_or_else(|| Error::Unreachable(format!("{host}:{port}: no address")))?; + open_tcp(host, *port, addr, |addr| TcpStream::connect_timeout(&addr, CONNECT)) + } + } + } + + /// The endpoint as an HTTP authority: an IPv6 host is bracketed, or its last colon reads as the + /// port separator and the request carries a host CUPS has never heard of. A scoped address keeps + /// its zone id and writes it escaped as "%25": "%" is not valid inside an authority (RFC 3986 + /// section 3.2.2 reserves it for escaping), and the escaped form is what CUPS, curl and the + /// ipp:// URIs CUPS writes use for a zone. RFC 9844 (Aug 2025) obsoleted RFC 6874, which had made + /// that form URI syntax, so this is interop rather than a standard; dropping the zone instead + /// would name a different host on the wire than the socket was opened to. The socket still gets + /// the raw address%zone, which is the form a resolver understands. + fn host(&self) -> String { + match self { + Endpoint::Unix(_) => "localhost".into(), + Endpoint::Tcp(host, port) if host.contains(':') => format!("[{}]:{port}", host.replace('%', "%25")), + Endpoint::Tcp(host, port) => format!("{host}:{port}"), + } + } +} + +impl std::fmt::Display for Endpoint { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Endpoint::Unix(p) => write!(f, "{}", p.display()), + Endpoint::Tcp(h, p) if h.contains(':') => write!(f, "[{h}]:{p}"), + Endpoint::Tcp(h, p) => write!(f, "{h}:{p}"), + } + } +} + +/// Open one address and put the request timeouts on it. The connect call is a parameter so the +/// refusal path can be tested at all: no port is guaranteed to stay free between picking one and +/// using it, and what a refused connect reported is what the caller is supposed to hear. +fn open_tcp(host: &str, port: u16, addr: SocketAddr, open: impl FnOnce(SocketAddr) -> std::io::Result) -> Result { + let s = open(addr).map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?; + let _ = s.set_read_timeout(Some(REQUEST)); + let _ = s.set_write_timeout(Some(REQUEST)); + Ok(Stream::Tcp(s)) +} + +enum Stream { + #[cfg(unix)] + Unix(std::os::unix::net::UnixStream), + Tcp(TcpStream), +} + +impl Read for Stream { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + match self { + #[cfg(unix)] + Stream::Unix(s) => s.read(buf), + Stream::Tcp(s) => s.read(buf), + } + } +} + +impl Write for Stream { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + match self { + #[cfg(unix)] + Stream::Unix(s) => s.write(buf), + Stream::Tcp(s) => s.write(buf), + } + } + fn flush(&mut self) -> std::io::Result<()> { + match self { + #[cfg(unix)] + Stream::Unix(s) => s.flush(), + Stream::Tcp(s) => s.flush(), + } + } +} + +/// Builds an IPP request body. +pub struct Request { + buf: Vec, +} + +impl Request { + pub fn new(op: u16, id: u32) -> Self { + let mut buf = vec![2, 0]; + buf.extend_from_slice(&op.to_be_bytes()); + buf.extend_from_slice(&id.to_be_bytes()); + buf.push(TAG_OPERATION_GROUP); + let mut r = Request { buf }; + r.attr(TAG_CHARSET, "attributes-charset", b"utf-8"); + r.attr(TAG_LANGUAGE, "attributes-natural-language", b"en"); + r + } + + /// Appends an attribute to the current group. + pub fn attr(&mut self, tag: u8, name: &str, value: &[u8]) { + // IPP lengths are 16-bit; longer names and values are cut, both the length and the bytes. + let name = name.as_bytes().get(..name.len().min(0xffff)).unwrap_or_default(); + let value = value.get(..value.len().min(0xffff)).unwrap_or_default(); + self.buf.push(tag); + self.buf.extend_from_slice(&(name.len() as u16).to_be_bytes()); + self.buf.extend_from_slice(name); + self.buf.extend_from_slice(&(value.len() as u16).to_be_bytes()); + self.buf.extend_from_slice(value); + } + + /// An attribute with several values (the extra ones carry an empty name). + pub fn attr_many(&mut self, tag: u8, name: &str, values: &[&str]) { + for (i, v) in values.iter().enumerate() { + self.attr(tag, if i == 0 { name } else { "" }, v.as_bytes()); + } + } + + pub fn integer(&mut self, name: &str, v: i32) { + self.attr(TAG_INTEGER, name, &v.to_be_bytes()); + } + + /// Starts a new attribute group. + pub fn group(&mut self, tag: u8) { + self.buf.push(tag); + } + + /// The message with its end tag. + pub fn end(mut self) -> Vec { + self.buf.push(TAG_END); + self.buf + } +} + +/// One attribute of a reply: the group it sits in, its tag, name and values. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Attribute { + pub group: u8, + pub tag: u8, + pub name: String, + pub values: Vec>, +} + +impl Attribute { + /// The first value as text. + pub fn text(&self) -> String { + self.values.first().map(|v| String::from_utf8_lossy(v).into_owned()).unwrap_or_default() + } + /// The first value as a big-endian integer. + pub fn int(&self) -> Option { + self.values.first().and_then(|v| <[u8; 4]>::try_from(v.as_slice()).ok()).map(i32::from_be_bytes) + } +} + +/// A decoded reply. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Reply { + pub status: u16, + pub request_id: u32, + pub attributes: Vec, +} + +/// The attribute range for one group delimiter in a parsed message. Ranges are half-open and +/// include empty groups, so repeated group tags remain distinct. +#[derive(Debug, Clone, Copy)] +struct GroupRange { + tag: u8, + start: usize, + end: usize, +} + +/// Parsed message details kept private so the public flat `Reply` API stays source-compatible. +struct ParsedMessage { + reply: Reply, + end: usize, + groups: Vec, +} + +impl Reply { + /// Parses an IPP message (RFC 8010 §3): header, then groups of attributes until the end tag. + pub fn parse(b: &[u8]) -> Result { + parse_message(b).map(|parsed| parsed.reply) + } + + /// Parses a message and returns where its attributes end (document data may follow). + fn parse_at(b: &[u8]) -> Result<(Reply, usize)> { + parse_message(b).map(|parsed| (parsed.reply, parsed.end)) + } + + /// The server's own message for an error status, or a name for the code. + fn status_message(&self) -> String { + self.attributes.iter().find(|a| a.name == "status-message").map(Attribute::text).filter(|m| !m.is_empty()).unwrap_or_else(|| { + match self.status { + 0x0400 => "bad request", + 0x0401 => "forbidden", + 0x0402 => "not authenticated", + 0x0403 => "not authorized", + 0x0406 => "not found", + 0x0409 => "unsupported document format", + 0x0500 => "internal server error", + 0x0506 => "the printer is not accepting jobs", + _ => "error", + } + .to_string() + }) + } +} + +/// Parses one IPP message while preserving each group instance for private consumers that need +/// object boundaries. The public reply remains a flat list of attributes. +fn parse_message(b: &[u8]) -> Result { + let bad = |m: &str| Error::Protocol(m.to_string()); + if b.len() < 9 { + return Err(bad("reply shorter than an IPP header")); + } + let status = u16::from_be_bytes([b[2], b[3]]); + let request_id = u32::from_be_bytes([b[4], b[5], b[6], b[7]]); + let mut pos = 8; + let mut group = 0u8; + let mut active_group = None; + let mut last_attribute_group = None; + let mut attributes: Vec = Vec::new(); + let mut groups: Vec = Vec::new(); + loop { + let tag = *b.get(pos).ok_or_else(|| bad("reply ends before the end-of-attributes tag"))?; + pos += 1; + if tag == TAG_END { + if let Some(last) = groups.last_mut() { + last.end = attributes.len(); + } + return Ok(ParsedMessage { reply: Reply { status, request_id, attributes }, end: pos, groups }); + } + if tag < 0x10 { + if let Some(last) = groups.last_mut() { + last.end = attributes.len(); + } + if groups.len() >= MAX_ATTRIBUTES { + return Err(bad("too many attribute groups")); + } + group = tag; + let group_index = groups.len(); + groups.push(GroupRange { tag, start: attributes.len(), end: attributes.len() }); + active_group = Some(group_index); + continue; + } + let name_len = + usize::from(u16::from_be_bytes([*b.get(pos).ok_or_else(|| bad("cut attribute"))?, *b.get(pos + 1).ok_or_else(|| bad("cut attribute"))?])); + pos += 2; + let name = b.get(pos..pos + name_len).ok_or_else(|| bad("cut attribute name"))?; + pos += name_len; + let value_len = + usize::from(u16::from_be_bytes([*b.get(pos).ok_or_else(|| bad("cut attribute"))?, *b.get(pos + 1).ok_or_else(|| bad("cut attribute"))?])); + pos += 2; + let value = b.get(pos..pos + value_len).ok_or_else(|| bad("cut attribute value"))?.to_vec(); + pos += value_len; + if name_len == 0 { + // Additional values can continue an attribute only within this exact group instance. + match attributes.last_mut() { + Some(last) if last_attribute_group == active_group => last.values.push(value), + _ => return Err(bad("an additional value with no attribute before it")), + } + } else { + attributes.push(Attribute { group, tag, name: String::from_utf8_lossy(name).into_owned(), values: vec![value] }); + last_attribute_group = active_group; + } + if attributes.len() > MAX_ATTRIBUTES { + return Err(bad("too many attributes")); + } + } +} + +/// POSTs `body` (IPP, with any document data after it) to `path` and returns the parsed reply with +/// its private group boundaries. +fn post(endpoint: &Endpoint, path: &str, body: &[u8]) -> Result { + let mut stream = endpoint.connect()?; + let head = format!( + "POST {path} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + endpoint.host(), + body.len() + ); + stream + .write_all(head.as_bytes()) + .and_then(|()| stream.write_all(body)) + .and_then(|()| stream.flush()) + .map_err(|e| Error::Protocol(format!("sending: {e}")))?; + let raw = read_response(&mut stream)?; + let (status, headers, body) = http_response(&raw)?; + if status != 200 { + return Err(Error::Protocol(match status { + 401 => "the print server asks for authentication (HTTP 401)".to_string(), + 403 => "the print server forbids this request (HTTP 403)".to_string(), + s => format!("HTTP {s}"), + })); + } + let body = if headers.iter().any(|(k, v)| k == "transfer-encoding" && v.contains("chunked")) { dechunk(body)? } else { body.to_vec() }; + let reply = parse_message(&body)?; + if reply.reply.status >= 0x0400 { + return Err(Error::Status(reply.reply.status, reply.reply.status_message())); + } + Ok(reply) +} + +/// Lowercase HTTP headers. +type Headers = Vec<(String, String)>; + +/// Reads one HTTP response: the headers, then as much body as `Content-Length` says, or up to +/// the last chunk, or to the end of the stream when the server says neither. A server that keeps +/// the connection open would otherwise hold the reply until the read times out. +fn read_response(stream: &mut Stream) -> Result> { + let mut raw = Vec::new(); + let mut buf = [0u8; 16 * 1024]; + let mut body_at = None; + let mut expected: Option = None; + let mut chunked = false; + // Where the chunk walk resumes, so each read costs its own bytes, not the whole body again. + let mut chunk_at = 0usize; + // Where the header-end search resumes (three bytes back, for a marker split across reads). + let mut head_at = 0usize; + let started = std::time::Instant::now(); + loop { + if started.elapsed() > REPLY_DEADLINE { + return Err(Error::Protocol("the print server took too long to reply".into())); + } + let n = stream.read(&mut buf).map_err(|e| Error::Protocol(format!("reading: {e}")))?; + if n == 0 { + return Ok(raw); + } + raw.extend_from_slice(buf.get(..n).unwrap_or_default()); + if raw.len() > MAX_REPLY { + return Err(Error::Protocol("the reply is larger than 16 MiB".into())); + } + if body_at.is_none() + && let Some(end) = raw.get(head_at..).and_then(|r| r.windows(4).position(|w| w == b"\r\n\r\n")).map(|p| head_at + p) + { + body_at = Some(end + 4); + let (_, headers, _) = http_response(&raw)?; + expected = headers.iter().find(|(k, _)| k == "content-length").and_then(|(_, v)| v.parse().ok()); + chunked = headers.iter().any(|(k, v)| k == "transfer-encoding" && v.contains("chunked")); + } + let Some(at) = body_at else { + head_at = raw.len().saturating_sub(3); + continue; + }; + let body = raw.get(at..).unwrap_or_default(); + let complete = match expected { + Some(len) if !chunked => body.len() >= len, + _ if chunked => chunked_complete(body, &mut chunk_at), + _ => false, + }; + if complete { + if let Some(len) = expected.filter(|_| !chunked) { + raw.truncate(at + len); + } + return Ok(raw); + } + } +} + +/// Splits an HTTP/1.1 response into status, lowercase headers and body. +fn http_response(raw: &[u8]) -> Result<(u16, Headers, &[u8])> { + let end = raw.windows(4).position(|w| w == b"\r\n\r\n").ok_or_else(|| Error::Protocol("no HTTP header".into()))?; + let head = String::from_utf8_lossy(raw.get(..end).unwrap_or(&[])); + let mut lines = head.split("\r\n"); + let status_line = lines.next().unwrap_or_default(); + let status: u16 = status_line + .split_whitespace() + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or_else(|| Error::Protocol(format!("bad status line `{status_line}`")))?; + let headers = lines.filter_map(|l| l.split_once(':')).map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_ascii_lowercase())).collect(); + Ok((status, headers, raw.get(end + 4..).unwrap_or(&[]))) +} + +/// Whether a chunked body has reached its last (zero-size) chunk, walking the chunk sizes so a +/// `0\r\n\r\n` inside a chunk's payload (an attribute value can hold it) does not count. A +/// malformed or impossible size counts as complete, so [`dechunk`] reports it instead of +/// waiting for more. +fn chunked_complete(body: &[u8], resume: &mut usize) -> bool { + let mut b = body.get(*resume..).unwrap_or_default(); + loop { + // Chunks already walked are not walked again: `resume` marks the start of this one. + *resume = body.len() - b.len(); + let Some(line_end) = b.windows(2).position(|w| w == b"\r\n") else { return false }; + let size_str = String::from_utf8_lossy(b.get(..line_end).unwrap_or(&[])); + let Ok(size) = usize::from_str_radix(size_str.split(';').next().unwrap_or_default().trim(), 16) else { return true }; + b = b.get(line_end + 2..).unwrap_or(&[]); + if size == 0 { + return true; + } + // A size past the reply cap can never be satisfied: complete, so `dechunk` rejects it + // (checked, so `ffffffffffffffff` cannot overflow the slice arithmetic). + let Some(end) = size.checked_add(2).filter(|_| size <= MAX_REPLY) else { return true }; + let Some(rest) = b.get(end..) else { return false }; + b = rest; + } +} + +/// Joins the chunks of a chunked transfer encoding. +fn dechunk(mut b: &[u8]) -> Result> { + let mut out = Vec::new(); + loop { + let line_end = b.windows(2).position(|w| w == b"\r\n").ok_or_else(|| Error::Protocol("cut chunk size".into()))?; + let size_str = String::from_utf8_lossy(b.get(..line_end).unwrap_or(&[])); + let size = + usize::from_str_radix(size_str.split(';').next().unwrap_or_default().trim(), 16).map_err(|_| Error::Protocol("bad chunk size".into()))?; + b = b.get(line_end + 2..).unwrap_or(&[]); + if size == 0 { + return Ok(out); + } + let chunk = b.get(..size).ok_or_else(|| Error::Protocol("cut chunk".into()))?; + out.extend_from_slice(chunk); + if out.len() > MAX_REPLY { + return Err(Error::Protocol("the reply is larger than 16 MiB".into())); + } + b = b.get(size + 2..).ok_or_else(|| Error::Protocol("cut chunk end".into()))?; + } +} + +/// Where `/path` lands on the server: `/printers/` or `/classes/`. +fn queue_path(name: &str, is_class: bool) -> Result { + if name.is_empty() || name.bytes().any(|b| b < 0x20 || b == 0x7f) { + return Err(Error::Protocol("printer name contains an invalid control character".into())); + } + let mut encoded = String::with_capacity(name.len()); + for &b in name.as_bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') { + encoded.push(char::from(b)); + } else { + encoded.push_str(&format!("%{b:02X}")); + } + } + Ok(format!("/{}/{encoded}", if is_class { "classes" } else { "printers" })) +} + +/// The printers the server knows (CUPS-Get-Printers), then its classes (CUPS-Get-Classes, which +/// `lp -d` accepts just the same), the default one flagged. +pub fn printers(endpoint: &Endpoint) -> Result> { + let mut out = queues(endpoint, OP_CUPS_GET_PRINTERS, false)?; + // A server without classes answers "not found"; an older server may not know the operation. + out.extend(queues(endpoint, OP_CUPS_GET_CLASSES, true).unwrap_or_default()); + let default = default_printer(endpoint).unwrap_or(None); + for p in &mut out { + p.is_default = default.as_deref() == Some(p.name.as_str()); + } + Ok(out) +} + +fn queues(endpoint: &Endpoint, op: u16, is_class: bool) -> Result> { + let mut r = Request::new(op, 1); + r.attr_many(TAG_KEYWORD, "requested-attributes", &["printer-name", "printer-info", "printer-state", "printer-is-accepting-jobs"]); + let parsed = match post(endpoint, "/", &r.end()) { + Ok(reply) => reply, + // CUPS answers "not found" ("No destinations added.") when no printer is set up. + Err(Error::Status(0x0406, _)) => return Ok(Vec::new()), + Err(e) => return Err(e), + }; + let mut out = Vec::new(); + let attributes = &parsed.reply.attributes; + for group in parsed.groups.iter().filter(|group| group.tag == TAG_PRINTER_GROUP) { + let Some(group_attributes) = attributes.get(group.start..group.end) else { + return Err(Error::Protocol("invalid printer attribute group range".into())); + }; + let mut name = None; + let mut info = String::new(); + let mut state = 3; + let mut accepting_jobs = true; + for a in group_attributes { + match a.name.as_str() { + "printer-name" if name.is_none() => name = Some(a.text()), + "printer-info" => info = a.text(), + "printer-state" => state = a.int().unwrap_or(3).clamp(0, 5) as u32, + "printer-is-accepting-jobs" => accepting_jobs = a.values.first().is_none_or(|v| v.first() != Some(&0)), + _ => {} + } + } + if let Some(name) = name.filter(|name| !name.is_empty()) { + out.push(Printer { name, info, state, accepting_jobs, is_default: false, is_class }); + } + } + Ok(out) +} + +/// The server's default printer (CUPS-Get-Default), `None` when there is none. +pub fn default_printer(endpoint: &Endpoint) -> Result> { + let mut r = Request::new(OP_CUPS_GET_DEFAULT, 2); + r.attr_many(TAG_KEYWORD, "requested-attributes", &["printer-name"]); + match post(endpoint, "/", &r.end()) { + Ok(reply) => Ok(reply.reply.attributes.iter().find(|a| a.name == "printer-name").map(Attribute::text).filter(|n| !n.is_empty())), + // CUPS answers "not found" when no default is set. + Err(Error::Status(0x0406, _)) => Ok(None), + Err(e) => Err(e), + } +} + +/// What to print. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Job<'a> { + pub printer: &'a str, + /// `printer` names a class. + pub is_class: bool, + /// Shown in the queue. + pub title: &'a str, + pub user: &'a str, + pub copies: u32, + /// The document, as `format` (`application/pdf`). + pub document: &'a [u8], + pub format: &'a str, +} + +/// Submits `job` (Print-Job) and returns the job id. +pub fn print_job(endpoint: &Endpoint, job: &Job<'_>) -> Result { + let mut r = Request::new(OP_PRINT_JOB, 3); + let path = queue_path(job.printer, job.is_class)?; + r.attr(TAG_URI, "printer-uri", format!("ipp://{}{path}", endpoint.host()).as_bytes()); + r.attr(TAG_NAME, "requesting-user-name", job.user.as_bytes()); + r.attr(TAG_NAME, "job-name", job.title.as_bytes()); + r.attr(TAG_MIME, "document-format", job.format.as_bytes()); + if job.copies > 1 { + r.buf.push(TAG_JOB_GROUP); + r.integer("copies", job.copies.clamp(1, 999) as i32); + } + let mut body = r.end(); + body.extend_from_slice(job.document); + let reply = post(endpoint, &path, &body)?.reply; + reply + .attributes + .iter() + .find(|a| a.name == "job-id") + .and_then(Attribute::int) + .map(|id| id.max(0) as u32) + .ok_or_else(|| Error::Protocol("no job id in the reply".into())) +} + +/// A request as a server sees it: the operation (the request's status field), its attributes +/// and the document data after the end tag. For fakes in tests and tools. +pub fn parse_request(b: &[u8]) -> Result<(u16, Vec, Vec)> { + let (reply, end) = Reply::parse_at(b)?; + Ok((reply.status, reply.attributes, b.get(end..).unwrap_or(&[]).to_vec())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ipp/src/tests.rs b/crates/ipp/src/tests.rs new file mode 100644 index 000000000..1f6aa4e8e --- /dev/null +++ b/crates/ipp/src/tests.rs @@ -0,0 +1,688 @@ +//! The client against an in-process fake CUPS: TCP and Unix socket, content-length and chunked +//! replies, every operation, error statuses and broken replies. + +use super::*; +use std::io::{BufRead, BufReader}; +use std::sync::mpsc; + +/// What the fake received: op, attributes, document. +type Seen = (u16, Vec, Vec); + +/// A fake server answering one request with `reply_body` (IPP bytes), chunked or not, under an +/// HTTP status. Returns the endpoint and a channel with what it received. +fn fake(reply: Vec, chunked: bool, http_status: u16) -> (Endpoint, mpsc::Receiver) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + serve(Stream::Tcp(stream), reply, chunked, http_status, &tx); + }); + (Endpoint::Tcp("127.0.0.1".into(), port), rx) +} + +fn serve(stream: Stream, reply: Vec, chunked: bool, http_status: u16, tx: &mpsc::Sender) { + let mut reader = BufReader::new(stream); + let mut line = String::new(); + let mut content_length = 0usize; + let mut first = String::new(); + loop { + line.clear(); + reader.read_line(&mut line).unwrap(); + if first.is_empty() { + first = line.clone(); + } + if line == "\r\n" || line.is_empty() { + break; + } + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + content_length = v.trim().parse().unwrap(); + } + } + if first.is_empty() { + return; // a reachability probe: connect and close + } + assert!(first.starts_with("POST "), "{first}"); + let mut body = vec![0u8; content_length]; + reader.read_exact(&mut body).unwrap(); + let _ = tx.send(parse_request(&body).unwrap()); + let mut out = reader.into_inner(); + let status_text = if http_status == 200 { "OK" } else { "Nope" }; + if chunked { + let mut resp = + format!("HTTP/1.1 {http_status} {status_text}\r\nContent-Type: application/ipp\r\nTransfer-Encoding: chunked\r\n\r\n").into_bytes(); + for chunk in reply.chunks(7) { + resp.extend_from_slice(format!("{:x}\r\n", chunk.len()).as_bytes()); + resp.extend_from_slice(chunk); + resp.extend_from_slice(b"\r\n"); + } + resp.extend_from_slice(b"0\r\n\r\n"); + out.write_all(&resp).unwrap(); + } else { + out.write_all( + format!("HTTP/1.1 {http_status} {status_text}\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\n\r\n", reply.len()).as_bytes(), + ) + .unwrap(); + out.write_all(&reply).unwrap(); + } + out.flush().unwrap(); +} + +/// An attribute to write: tag, name, values. +type Attr<'a> = (u8, &'a str, &'a [&'a [u8]]); +/// A group to write: tag and attributes. +type Group<'a> = (u8, &'a [Attr<'a>]); + +/// An IPP reply body. +fn ipp(status: u16, groups: &[Group<'_>]) -> Vec { + let mut b = vec![2, 0]; + b.extend_from_slice(&status.to_be_bytes()); + b.extend_from_slice(&1u32.to_be_bytes()); + for (group, attrs) in groups { + b.push(*group); + for (tag, name, values) in *attrs { + for (i, v) in values.iter().enumerate() { + b.push(*tag); + let n = if i == 0 { name.as_bytes() } else { b"" }; + b.extend_from_slice(&(n.len() as u16).to_be_bytes()); + b.extend_from_slice(n); + b.extend_from_slice(&(v.len() as u16).to_be_bytes()); + b.extend_from_slice(v); + } + } + } + b.push(TAG_END); + b +} + +fn ok_header() -> Group<'static> { + (TAG_OPERATION_GROUP, &[(TAG_CHARSET, "attributes-charset", &[b"utf-8"]), (TAG_LANGUAGE, "attributes-natural-language", &[b"en"])]) +} + +#[test] +fn printers_are_listed_with_state_and_default() { + let three = ipp( + 0, + &[ + ok_header(), + ( + TAG_PRINTER_GROUP, + &[ + (TAG_NAME, "printer-name", &[b"Office"]), + (TAG_TEXT, "printer-info", &[b"HP in the office"]), + (TAG_ENUM, "printer-state", &[&3u32.to_be_bytes()]), + (TAG_BOOLEAN, "printer-is-accepting-jobs", &[&[1]]), + ], + ), + ( + TAG_PRINTER_GROUP, + &[ + (TAG_NAME, "printer-name", &[b"Stopped"]), + (TAG_ENUM, "printer-state", &[&5u32.to_be_bytes()]), + (TAG_BOOLEAN, "printer-is-accepting-jobs", &[&[0]]), + ], + ), + ], + ); + for chunked in [false, true] { + let (ep, rx) = fake(three.clone(), chunked, 200); + // `printers` asks for the default too; that second request reaches a server that has + // closed, so the default is simply unknown here. + let list = printers(&ep).unwrap(); + let (op, attrs, doc) = rx.recv().unwrap(); + assert_eq!(op, OP_CUPS_GET_PRINTERS); + assert!(attrs.iter().any(|a| a.name == "requested-attributes" && a.values.len() == 4 && a.tag == TAG_KEYWORD)); + assert!(doc.is_empty()); + assert_eq!(list.len(), 2, "chunked {chunked}"); + assert_eq!((list[0].name.as_str(), list[0].info.as_str(), list[0].state, list[0].accepting_jobs), ("Office", "HP in the office", 3, true)); + assert_eq!((list[1].name.as_str(), list[1].state, list[1].accepting_jobs), ("Stopped", 5, false)); + assert!(!list[0].is_default && !list[1].is_default); + } +} + +#[test] +fn printer_attributes_before_name_are_preserved() { + let state = 5u32.to_be_bytes(); + let base: [Attr<'_>; 4] = [ + (TAG_TEXT, "printer-info", &[b"Studio Printer"]), + (TAG_ENUM, "printer-state", &[&state]), + (TAG_BOOLEAN, "printer-is-accepting-jobs", &[b"\0"]), + (TAG_NAME, "printer-name", &[b"studio"]), + ]; + let body = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &base)]); + for chunked in [false, true] { + let (ep, _) = fake(body.clone(), chunked, 200); + let list = printers(&ep).unwrap(); + assert_eq!(list.len(), 1, "chunked {chunked}"); + assert_eq!((list[0].name.as_str(), list[0].info.as_str(), list[0].state, list[0].accepting_jobs), ("studio", "Studio Printer", 5, false)); + assert!(!list[0].is_class); + } +} + +#[test] +fn printer_groups_do_not_share_metadata() { + let state_a = 4u32.to_be_bytes(); + let state_b = 5u32.to_be_bytes(); + let body = ipp( + 0, + &[ + ok_header(), + ( + TAG_PRINTER_GROUP, + &[(TAG_NAME, "printer-name", &[b"first"]), (TAG_TEXT, "printer-info", &[b"First printer"]), (TAG_ENUM, "printer-state", &[&state_a])], + ), + ( + TAG_PRINTER_GROUP, + &[ + (TAG_TEXT, "printer-info", &[b"Second printer"]), + (TAG_ENUM, "printer-state", &[&state_b]), + (TAG_NAME, "printer-name", &[b"second"]), + ], + ), + ], + ); + let (ep, _) = fake(body, false, 200); + let list = queues(&ep, OP_CUPS_GET_PRINTERS, false).unwrap(); + assert_eq!(list.len(), 2); + assert_eq!((list[0].name.as_str(), list[0].info.as_str(), list[0].state), ("first", "First printer", 4)); + assert_eq!((list[1].name.as_str(), list[1].info.as_str(), list[1].state), ("second", "Second printer", 5)); +} + +#[test] +fn printer_attribute_order_does_not_change_results() { + let state = 5u32.to_be_bytes(); + let fields: [Attr<'_>; 4] = [ + (TAG_TEXT, "printer-info", &[b"Studio Printer"]), + (TAG_ENUM, "printer-state", &[&state]), + (TAG_BOOLEAN, "printer-is-accepting-jobs", &[b"\0"]), + (TAG_NAME, "printer-name", &[b"studio"]), + ]; + let expected = + Printer { name: "studio".into(), info: "Studio Printer".into(), state: 5, accepting_jobs: false, is_default: false, is_class: false }; + let mut permutations = 0; + for first in 0..4 { + for second in 0..4 { + for third in 0..4 { + for fourth in 0..4 { + let order = [first, second, third, fourth]; + if order[0] == order[1] + || order[0] == order[2] + || order[0] == order[3] + || order[1] == order[2] + || order[1] == order[3] + || order[2] == order[3] + { + continue; + } + permutations += 1; + let ordered = order.iter().map(|index| fields[*index]).collect::>(); + let body = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &ordered)]); + let (ep, _) = fake(body, false, 200); + assert_eq!(queues(&ep, OP_CUPS_GET_PRINTERS, false).unwrap(), vec![expected.clone()], "order {order:?}"); + } + } + } + } + assert_eq!(permutations, 24); +} + +#[test] +fn class_attributes_before_name_are_preserved() { + let state = 5u32.to_be_bytes(); + let body = ipp( + 0, + &[ + ok_header(), + ( + TAG_PRINTER_GROUP, + &[ + (TAG_BOOLEAN, "printer-is-accepting-jobs", &[b"\0"]), + (TAG_TEXT, "printer-info", &[b"Shared studio"]), + (TAG_ENUM, "printer-state", &[&state]), + (TAG_NAME, "printer-name", &[b"studio-class"]), + ], + ), + ], + ); + let (ep, rx) = fake(body, true, 200); + let classes = queues(&ep, OP_CUPS_GET_CLASSES, true).unwrap(); + assert_eq!(rx.recv().unwrap().0, OP_CUPS_GET_CLASSES); + assert_eq!(classes.len(), 1); + assert_eq!( + (classes[0].name.as_str(), classes[0].info.as_str(), classes[0].state, classes[0].accepting_jobs, classes[0].is_class), + ("studio-class", "Shared studio", 5, false, true) + ); +} + +#[test] +fn empty_or_unnamed_groups_do_not_leak_metadata() { + let body = ipp( + 0, + &[ + ok_header(), + (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"named"])]), + (TAG_PRINTER_GROUP, &[]), + (TAG_PRINTER_GROUP, &[(TAG_TEXT, "printer-info", &[b"orphan metadata"])]), + (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"next"]), (TAG_ENUM, "printer-state", &[&3u32.to_be_bytes()])]), + ], + ); + let (ep, _) = fake(body, false, 200); + let list = queues(&ep, OP_CUPS_GET_PRINTERS, false).unwrap(); + assert_eq!(list.len(), 2); + assert_eq!((list[0].name.as_str(), list[0].info.as_str()), ("named", "")); + assert_eq!((list[1].name.as_str(), list[1].info.as_str()), ("next", "")); +} + +#[test] +fn additional_values_do_not_cross_group_boundaries() { + let valid = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_KEYWORD, "supported", &[b"one", b"two"])])]); + let reply = Reply::parse(&valid).unwrap(); + assert_eq!(reply.attributes.iter().find(|a| a.name == "supported").map(|a| a.values.as_slice()), Some(&[b"one".to_vec(), b"two".to_vec()][..])); + + let mut body = vec![2, 0, 0, 0, 0, 0, 0, 1, TAG_PRINTER_GROUP]; + body.extend_from_slice(&[TAG_NAME, 0, 12]); + body.extend_from_slice(b"printer-name"); + body.extend_from_slice(&[0, 5]); + body.extend_from_slice(b"first"); + body.extend_from_slice(&[TAG_TEXT, 0, 12]); + body.extend_from_slice(b"printer-info"); + body.extend_from_slice(&[0, 6]); + body.extend_from_slice(b"before"); + body.push(TAG_PRINTER_GROUP); + body.extend_from_slice(&[TAG_TEXT, 0, 0, 0, 5]); + body.extend_from_slice(b"after"); + body.extend_from_slice(&[TAG_NAME, 0, 12]); + body.extend_from_slice(b"printer-name"); + body.extend_from_slice(&[0, 6]); + body.extend_from_slice(b"second"); + body.push(TAG_END); + let (ep, _) = fake(body, true, 200); + assert!(matches!(queues(&ep, OP_CUPS_GET_PRINTERS, false), Err(Error::Protocol(_)))); +} + +#[test] +fn default_printer_is_read_and_absence_is_not_an_error() { + let (ep, rx) = fake(ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"Office"])])]), false, 200); + assert_eq!(default_printer(&ep).unwrap(), Some("Office".into())); + assert_eq!(rx.recv().unwrap().0, OP_CUPS_GET_DEFAULT); + let (ep, _rx) = fake(ipp(0x0406, &[ok_header(), (TAG_OPERATION_GROUP, &[(TAG_TEXT, "status-message", &[b"No default printer"])])]), false, 200); + assert_eq!(default_printer(&ep).unwrap(), None); +} + +#[test] +fn a_print_job_carries_the_document_and_returns_its_id() { + let (ep, rx) = fake(ipp(0, &[ok_header(), (TAG_JOB_GROUP, &[(TAG_INTEGER, "job-id", &[&42u32.to_be_bytes()])])]), true, 200); + let pdf = b"%PDF-1.4 fake".to_vec(); + let id = print_job( + &ep, + &Job { printer: "Office", is_class: false, title: "photo.psd", user: "diego", copies: 2, document: &pdf, format: "application/pdf" }, + ) + .unwrap(); + assert_eq!(id, 42); + let (op, attrs, doc) = rx.recv().unwrap(); + assert_eq!(op, OP_PRINT_JOB); + assert_eq!(doc, pdf); + let get = |n: &str| attrs.iter().find(|a| a.name == n).cloned().unwrap_or_else(|| panic!("{n}")); + let uri = String::from_utf8(get("printer-uri").values[0].clone()).unwrap(); + // Spelled out here rather than echoed back from host(), so the printer-uri the server receives is + // pinned down even when the authority is an IP literal. + assert!(uri.starts_with("ipp://127.0.0.1:") && uri.ends_with("/printers/Office"), "{uri}"); + assert_eq!(get("job-name").values[0], b"photo.psd"); + assert_eq!(get("requesting-user-name").values[0], b"diego"); + assert_eq!(get("document-format").values[0], b"application/pdf"); + let copies = get("copies"); + assert_eq!((copies.group, copies.tag, copies.int()), (TAG_JOB_GROUP, TAG_INTEGER, Some(2))); + // One copy: no job attributes group at all. + let (ep, rx) = fake(ipp(0, &[ok_header(), (TAG_JOB_GROUP, &[(TAG_INTEGER, "job-id", &[&7u32.to_be_bytes()])])]), false, 200); + print_job(&ep, &Job { printer: "P", is_class: false, title: "t", user: "u", copies: 1, document: b"x", format: "application/pdf" }).unwrap(); + assert!(!rx.recv().unwrap().1.iter().any(|a| a.name == "copies")); +} + +#[test] +fn error_statuses_and_broken_replies_are_errors() { + let (ep, _rx) = + fake(ipp(0x0506, &[ok_header(), (TAG_OPERATION_GROUP, &[(TAG_TEXT, "status-message", &[b"Printer is not accepting jobs"])])]), false, 200); + let e = print_job(&ep, &Job { printer: "P", is_class: false, title: "t", user: "u", copies: 1, document: b"x", format: "application/pdf" }) + .unwrap_err(); + assert_eq!(e, Error::Status(0x0506, "Printer is not accepting jobs".into())); + assert!(e.to_string().contains("0x0506")); + // A CUPS with no printer at all answers "not found": that is an empty list, not an error. + let (ep, _rx) = + fake(ipp(0x0406, &[ok_header(), (TAG_OPERATION_GROUP, &[(TAG_TEXT, "status-message", &[b"No destinations added."])])]), false, 200); + assert_eq!(printers(&ep).unwrap(), Vec::::new()); + // HTTP 401, a reply cut short, garbage. + let (ep, _rx) = fake(ipp(0, &[ok_header()]), false, 401); + assert!(matches!(printers(&ep), Err(Error::Protocol(m)) if m.contains("401"))); + let (ep, _rx) = fake(vec![2, 0, 0, 0, 0, 0, 0, 1, TAG_OPERATION_GROUP, TAG_NAME, 0, 5], true, 200); + assert!(matches!(printers(&ep), Err(Error::Protocol(_)))); + let (ep, _rx) = fake(b"not ipp at all".to_vec(), false, 200); + assert!(matches!(printers(&ep), Err(Error::Protocol(_)))); + // Nobody reachable. A port is never guaranteed to be free, let alone to stay free: that is what + // made the old port-1 case fail on a FreeBSD CI VM. A name that can never resolve (RFC 2606) + // reaches the same exit without owning or releasing anything. + let e = printers(&Endpoint::Tcp("printer.invalid".into(), 631)).unwrap_err(); + assert!(matches!(e, Error::Unreachable(_)), "{e}"); + assert!(e.to_string().contains("printer.invalid"), "{e} does not name the server it tried"); +} + +#[test] +fn a_refused_connection_is_unreachable_and_keeps_why() { + // The refused-connect path, with the machine no longer deciding what is closed: the connect call + // is a parameter, so this test cannot race for an ephemeral port with anything. + let addr: SocketAddr = "192.0.2.9:631".parse().unwrap(); + let asked_for = std::cell::RefCell::new(None); + let open = |seen: SocketAddr| -> std::io::Result { + *asked_for.borrow_mut() = Some(seen); + Err(std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "nobody is listening on this port")) + }; + let e = match open_tcp("printserver", 631, addr, open) { + Ok(_) => panic!("nothing opens {addr}"), + Err(e) => e, + }; + assert_eq!(*asked_for.borrow(), Some(addr), "the connector is handed the resolved address"); + match &e { + Error::Unreachable(m) => { + assert!(m.contains("printserver:631"), "{e} does not name the endpoint"); + assert!(m.contains("nobody is listening on this port"), "{e} loses why the connect failed"); + } + other => panic!("expected Unreachable, got {other}"), + } +} + +#[test] +fn reply_parsing_is_bounded() { + assert!(Reply::parse(&[]).is_err()); + assert!(Reply::parse(&[2, 0, 0, 0, 0, 0, 0, 1]).is_err(), "no end tag"); + let mut many = vec![2, 0, 0, 0, 0, 0, 0, 1, TAG_OPERATION_GROUP]; + for _ in 0..MAX_ATTRIBUTES + 1 { + many.extend_from_slice(&[TAG_NAME, 0, 1, b'a', 0, 0]); + } + many.push(TAG_END); + assert!(matches!(Reply::parse(&many), Err(Error::Protocol(m)) if m.contains("too many"))); + // An additional value before any attribute. + assert!(Reply::parse(&[2, 0, 0, 0, 0, 0, 0, 1, TAG_OPERATION_GROUP, TAG_NAME, 0, 0, 0, 1, b'x', TAG_END]).is_err()); + assert!(dechunk(b"zz\r\n").is_err() && dechunk(b"5\r\nab").is_err()); + assert_eq!(dechunk(b"3\r\nabc\r\n0\r\n\r\n").unwrap(), b"abc"); +} + +#[cfg(unix)] +#[test] +fn the_unix_socket_endpoint_works_and_detect_honours_cups_server() { + let dir = std::env::temp_dir().join(format!("pc-ipp-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("cups.sock"); + let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap(); + let (tx, rx) = mpsc::channel(); + let reply = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"Sock"])])]); + std::thread::spawn(move || { + for _ in 0..3 { + let (stream, _) = listener.accept().unwrap(); + serve(Stream::Unix(stream), reply.clone(), false, 200, &tx); + } + }); + let ep = Endpoint::Unix(sock.clone()); + assert!(ep.reachable()); + assert_eq!(default_printer(&ep).unwrap(), Some("Sock".into())); + assert_eq!(rx.recv().unwrap().0, OP_CUPS_GET_DEFAULT); + assert!(!Endpoint::Unix(dir.join("missing.sock")).reachable()); + assert_eq!(ep.to_string(), sock.display().to_string()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An IPv6 print server is not a `host:port` split: a bare address has more than one ':', and the +/// brackets of `[address]:port` must not end up inside the host, where no resolver can read them. +#[test] +fn an_ipv6_print_server_is_parsed_as_a_host_not_as_host_port() { + assert_eq!(Endpoint::parse("::1"), Endpoint::Tcp("::1".into(), 631)); + assert_eq!(Endpoint::parse("fe80::1"), Endpoint::Tcp("fe80::1".into(), 631)); + assert_eq!(Endpoint::parse("2001:db8::1"), Endpoint::Tcp("2001:db8::1".into(), 631)); + assert_eq!(Endpoint::parse("[::1]"), Endpoint::Tcp("::1".into(), 631)); + assert_eq!(Endpoint::parse("[::1]:631"), Endpoint::Tcp("::1".into(), 631)); + assert_eq!(Endpoint::parse("[fe80::1]:6310"), Endpoint::Tcp("fe80::1".into(), 6310)); + // A zone id carries no ':', so a port can still follow it without brackets. + assert_eq!(Endpoint::parse("fe80::1%eth0:631"), Endpoint::Tcp("fe80::1%eth0".into(), 631)); + // What already worked is unchanged. + assert_eq!(Endpoint::parse("cups.example"), Endpoint::Tcp("cups.example".into(), 631)); + assert_eq!(Endpoint::parse("cups.example:6310"), Endpoint::Tcp("cups.example".into(), 6310)); + assert_eq!(Endpoint::parse("127.0.0.1:6310"), Endpoint::Tcp("127.0.0.1".into(), 6310)); + assert_eq!(Endpoint::parse("/var/run/cups/cups.sock"), Endpoint::Unix("/var/run/cups/cups.sock".into())); + // A mistyped bracketed endpoint is not quietly the default one: the whole string stays the host, + // so nothing can resolve it and detect() reports the endpoint unreachable. + assert_eq!(Endpoint::parse("[::1]:abc"), Endpoint::Tcp("[::1]:abc".into(), 631)); + assert_eq!(Endpoint::parse("[::1]:70000"), Endpoint::Tcp("[::1]:70000".into(), 631)); + assert_eq!(Endpoint::parse("[::1]junk"), Endpoint::Tcp("[::1]junk".into(), 631)); + assert!(!Endpoint::parse("[::1]:abc").reachable()); +} + +/// The authority a request carries (the `Host:` header and the `ipp://` printer-uri) has to bracket an +/// IPv6 host, or its last colon reads as the port separator and CUPS sees a nonsense host. +#[test] +fn an_ipv6_endpoint_writes_its_authority_in_brackets() { + assert_eq!(Endpoint::parse("::1").host(), "[::1]:631"); + assert_eq!(Endpoint::parse("[::1]:631").host(), "[::1]:631"); + assert_eq!(Endpoint::parse("[fe80::1]:6310").host(), "[fe80::1]:6310"); + assert_eq!(Endpoint::parse("cups.example").host(), "cups.example:631"); + assert_eq!(Endpoint::parse("cups.example:6310").host(), "cups.example:6310"); + assert_eq!(Endpoint::parse("127.0.0.1:6310").host(), "127.0.0.1:6310"); + // A scoped address keeps its zone id, but the authority writes it "%25"-escaped: a bare "%" is + // not valid inside an authority, and the escaped form is what CUPS and curl-style ipp:// URIs + // use. The host itself stays raw, because that is what the resolver gets. + assert_eq!(Endpoint::parse("fe80::1%3:631").host(), "[fe80::1%253]:631"); + assert_eq!(Endpoint::parse("[fe80::1%3]:6310").host(), "[fe80::1%253]:6310"); + assert_eq!(Endpoint::parse("fe80::1%eth0:631").host(), "[fe80::1%25eth0]:631"); + assert_eq!(Endpoint::parse("fe80::1%3:631"), Endpoint::Tcp("fe80::1%3".into(), 631)); + // What the user is shown is written the same way, with the zone exactly as it was typed. + assert_eq!(Endpoint::parse("::1").to_string(), "[::1]:631"); + assert_eq!(Endpoint::parse("cups.example:6310").to_string(), "cups.example:6310"); + assert_eq!(Endpoint::parse("fe80::1%3:631").to_string(), "[fe80::1%3]:631"); +} + +#[test] +fn requests_start_with_the_mandatory_attributes() { + let r = Request::new(OP_PRINT_JOB, 9).end(); + let (op, attrs, doc) = parse_request(&r).unwrap(); + assert_eq!(op, OP_PRINT_JOB); + assert_eq!(Reply::parse(&r).unwrap().request_id, 9); + assert_eq!(attrs[0].name, "attributes-charset"); + assert_eq!(attrs[1].name, "attributes-natural-language"); + assert!(doc.is_empty()); +} + +/// A server that keeps the connection open after its reply (a printer reached directly, a proxy) +/// must not hold the client until the read times out: the reply ends at Content-Length, or at +/// the last chunk. +#[test] +fn replies_end_at_content_length_or_the_last_chunk_without_waiting_for_close() { + for chunked in [false, true] { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let one = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"Office"])])]); + let none = ipp(0x0406, &[ok_header()]); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { return }; + let mut reader = BufReader::new(stream); + let (mut line, mut len) = (String::new(), 0usize); + loop { + line.clear(); + if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap_or(0); + } + } + if len == 0 { + continue; + } + let mut body = vec![0u8; len]; + if reader.read_exact(&mut body).is_err() { + continue; + } + let op = parse_request(&body).map(|r| r.0).unwrap_or(0); + let reply = if op == OP_CUPS_GET_PRINTERS { one.clone() } else { none.clone() }; + let mut out = reader.into_inner(); + let mut resp = Vec::new(); + if chunked { + resp.extend_from_slice(b"HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nTransfer-Encoding: chunked\r\n\r\n"); + for chunk in reply.chunks(5) { + resp.extend_from_slice(format!("{:x}\r\n", chunk.len()).as_bytes()); + resp.extend_from_slice(chunk); + resp.extend_from_slice(b"\r\n"); + } + resp.extend_from_slice(b"0\r\n\r\n"); + } else { + resp.extend_from_slice( + format!("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\n\r\n", reply.len()).as_bytes(), + ); + resp.extend_from_slice(&reply); + } + if out.write_all(&resp).and_then(|()| out.flush()).is_err() { + continue; + } + // Keep this connection open for a while, on its own thread, and go on serving. + std::thread::spawn(move || { + std::thread::sleep(Duration::from_secs(10)); + drop(out); + }); + } + }); + let ep = Endpoint::Tcp("127.0.0.1".into(), port); + let started = std::time::Instant::now(); + let list = printers(&ep).unwrap(); + assert_eq!(list.len(), 1, "chunked {chunked}"); + assert!(started.elapsed() < Duration::from_secs(5), "waited for the server to close (chunked {chunked}): {:?}", started.elapsed()); + } +} + +/// A chunked reply whose payload contains the bytes of a last chunk (`\r\n0\r\n\r\n`, here inside +/// a printer name) and arrives split right after them: the reader must wait for the real last +/// chunk instead of returning a cut reply. +#[test] +fn a_last_chunk_pattern_inside_a_value_does_not_end_the_reply() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let reply = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"Of\r\n0\r\n\r\nfice"])])]); + let cut = reply.windows(7).position(|w| w == b"\r\n0\r\n\r\n").unwrap() + 7; + std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream); + let (mut line, mut len) = (String::new(), 0usize); + loop { + line.clear(); + if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0u8; len]; + reader.read_exact(&mut body).unwrap(); + let mut out = reader.into_inner(); + let (first, second) = reply.split_at(cut); + // Part one ends exactly on the pattern, inside the first chunk's payload. + let mut a = b"HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec(); + a.extend_from_slice(format!("{:x}\r\n", first.len()).as_bytes()); + a.extend_from_slice(first); + out.write_all(&a).and_then(|()| out.flush()).unwrap(); + std::thread::sleep(Duration::from_millis(400)); + let mut b = b"\r\n".to_vec(); + b.extend_from_slice(format!("{:x}\r\n", second.len()).as_bytes()); + b.extend_from_slice(second); + b.extend_from_slice(b"\r\n0\r\n\r\n"); + out.write_all(&b).and_then(|()| out.flush()).unwrap(); + }); + let ep = Endpoint::Tcp("127.0.0.1".into(), port); + let list = printers(&ep).unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].name, "Of\r\n0\r\n\r\nfice"); + // The boundary walk itself: complete only at a zero-size chunk, never on payload bytes. + assert!(!complete(b"5\r\nab\r\n0")); + assert!(!complete(b"7\r\n\r\n0\r\n\r\nx\r\n")); + assert!(complete(b"7\r\n\r\n0\r\n\r\nx\r\n0\r\n\r\n")); + assert!(complete(b"zz\r\n") && dechunk(b"zz\r\n").is_err()); +} + +/// [`chunked_complete`] on a whole body at once. +fn complete(body: &[u8]) -> bool { + chunked_complete(body, &mut 0) +} + +/// Fed a byte at a time, as a server dripping the reply would, the walk resumes where it stopped +/// and agrees with the one-shot answer at every length. +#[test] +fn the_chunk_walk_resumes_instead_of_starting_over() { + let body = b"3\r\nabc\r\n10\r\n0123456789abcdef\r\n0\r\n\r\n"; + let mut at = 0; + for len in 0..=body.len() { + let prefix = &body[..len]; + assert_eq!(chunked_complete(prefix, &mut at), complete(prefix), "{len}"); + assert!(at <= len); + } + assert!(at > 0, "it moved past the chunks already walked"); +} + +/// A chunk size that cannot be satisfied (`usize::MAX`, `usize::MAX - 1`, anything past the +/// reply cap) is a protocol error, through the real reader, never an overflow panic. +#[test] +fn an_impossible_chunk_size_is_a_protocol_error_not_a_panic() { + for size_line in ["ffffffffffffffff", "fffffffffffffffe", "1000001"] { + assert!(complete(format!("{size_line}\r\n").as_bytes())); + assert!(dechunk(format!("{size_line}\r\nab\r\n").as_bytes()).is_err()); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let line = size_line.to_string(); + std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream); + let (mut l, mut len) = (String::new(), 0usize); + loop { + l.clear(); + if reader.read_line(&mut l).unwrap_or(0) == 0 || l == "\r\n" { + break; + } + if let Some(v) = l.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0u8; len]; + reader.read_exact(&mut body).unwrap(); + let mut out = reader.into_inner(); + let resp = format!("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nTransfer-Encoding: chunked\r\n\r\n{line}\r\n"); + let _ = out.write_all(resp.as_bytes()).and_then(|()| out.flush()); + }); + let ep = Endpoint::Tcp("127.0.0.1".into(), port); + match printers(&ep) { + Err(Error::Protocol(_)) => {} + other => panic!("{size_line}: expected a protocol error, got {other:?}"), + } + } +} + +#[test] +fn printer_names_are_encoded_as_one_request_target_segment() { + assert_eq!(queue_path("office printer/1", false).unwrap(), "/printers/office%20printer%2F1"); + assert!(queue_path("printer\r\nX-Injected: yes", false).is_err()); +} + +/// A reply arriving a byte at a time, its blank line split across reads, is still found: the +/// header search resumes where it stopped instead of rescanning everything read so far. +#[test] +fn a_header_trickled_a_byte_at_a_time_is_found() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (mut s, _) = listener.accept().unwrap(); + s.set_nodelay(true).unwrap(); + for b in b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nokEXTRA" { + s.write_all(&[*b]).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }); + let mut stream = Stream::Tcp(TcpStream::connect(addr).unwrap()); + let raw = read_response(&mut stream).unwrap(); + assert!(raw.ends_with(b"\r\n\r\nok"), "{:?}", String::from_utf8_lossy(&raw)); + server.join().unwrap(); +} diff --git a/crates/jpeg/src/idct.rs b/crates/jpeg/src/idct.rs index 3a683568d..1d42ca1a8 100644 --- a/crates/jpeg/src/idct.rs +++ b/crates/jpeg/src/idct.rs @@ -103,6 +103,76 @@ pub(super) fn reconstruct(comp: &Component, q: &[u16; 64], idct: &Idct, max: f32 plane } +pub(super) fn idct_basis_n(n: usize) -> Vec> { + let mut t = vec![vec![0f32; n]; n]; + for (x, row) in t.iter_mut().enumerate() { + for (u, v) in row.iter_mut().enumerate() { + let c = if u == 0 { std::f32::consts::FRAC_1_SQRT_2 } else { 1.0 }; + *v = c / 2.0 * (((2 * x + 1) * u) as f32 * std::f32::consts::PI / (2 * n) as f32).cos(); + } + } + t +} + +/// One block's reduced `n × n` samples (`n` is 4, 2 or 1), dequantized with `q`, inverse +/// transformed, level-shifted and clamped to `0..=max`, written to `n` rows of `n` at `out` +/// that are `stride` apart. +pub(super) fn idct_block_scaled(blk: &[i32; 64], q: &[u16; 64], basis: &[Vec], max: f32, out: &mut [f32], stride: usize, n: usize) { + let shift = (max + 1.0) / 2.0; + if n == 1 || blk[1..].iter().all(|&c| c == 0) { + let t = basis[0][0]; + let v = (t * (t * (blk[0] as f32 * f32::from(q[0]))) + shift).clamp(0.0, max); + for y in 0..n { + if let Some(row) = out.get_mut(y * stride..y * stride + n) { + row.fill(v); + } + } + return; + } + let mut f = [[0f32; 8]; 8]; + for (k, (&c, &z)) in blk.iter().zip(&ZIGZAG).enumerate() { + if c != 0 { + let (v, u) = (z / 8, z % 8); + if v < n && u < n { + f[v][u] = c as f32 * f32::from(q[k]); + } + } + } + let mut r = vec![vec![0f32; n]; n]; + for v in 0..n { + for x in 0..n { + let mut acc = 0.0f32; + for u in 0..n { + acc += basis[x][u] * f[v][u]; + } + r[v][x] = acc; + } + } + for (y, basis_row) in basis.iter().enumerate().take(n) { + if let Some(row) = out.get_mut(y * stride..y * stride + n) { + for (x, o) in row.iter_mut().enumerate() { + let mut acc = 0.0f32; + for v in 0..n { + acc += basis_row[v] * r[v][x]; + } + *o = (acc + shift).clamp(0.0, max); + } + } + } +} + +pub(super) fn reconstruct_scaled(comp: &Component, q: &[u16; 64], basis: &[Vec], max: f32, n: usize) -> Vec { + let stride = comp.bw * n; + let mut plane = vec![0f32; stride * comp.bh * n]; + for (idx, blk) in comp.coefs.iter().enumerate() { + let (bx, by) = (idx % comp.bw, idx / comp.bw); + if let Some(out) = plane.get_mut(by * n * stride + bx * n..) { + idct_block_scaled(blk, q, basis, max, out, stride, n); + } + } + plane +} + /// An output coordinate's two neighboring component samples and the weight of the second. pub(super) type UpsampleStep = (usize, usize, f32); @@ -217,3 +287,58 @@ pub(super) fn render(frame: Frame, tables: &Tables, adobe_transform: Option) let samples = if sixteen { Samples::U16(wide) } else { Samples::U8(narrow) }; Ok((nc as u8, samples)) } + +pub(super) fn render_scaled(frame: Frame, tables: &Tables, adobe_transform: Option, shrink: u8) -> Result<(u32, u32, u8, Samples), Error> { + let n = 8usize >> shrink; + let max = if frame.precision > 8 { 4095.0 } else { 255.0 }; + let basis = idct_basis_n(n); + let w = frame.width.div_ceil(1 << shrink); + let h = frame.height.div_ceil(1 << shrink); + let mut planes = Vec::with_capacity(frame.comps.len()); + for comp in &frame.comps { + let q = comp.quant.or_else(|| tables.quant.get(comp.tq).copied().flatten()); + let q = q.ok_or_else(|| err("component uses an undefined quantization table"))?; + let plane = reconstruct_scaled(comp, &q, &basis, max, n); + let cw = comp.cw.div_ceil(1 << shrink); + let ch = comp.ch.div_ceil(1 << shrink); + let xs = upsample_map(w, cw, comp.h, frame.hmax); + let ys = upsample_map(h, ch, comp.v, frame.vmax); + planes.push((plane, comp.bw * n, xs, ys)); + } + let nc = planes.len(); + let sixteen = frame.precision > 8; + let ycc = is_ycc(frame.comps.iter().map(|c| c.id), adobe_transform); + let (mut wide, mut narrow) = (Vec::new(), Vec::new()); + if sixteen { + wide.reserve_exact(w * h * nc); + } else { + narrow.reserve_exact(w * h * nc); + } + let mut px = [0f32; 4]; + for y in 0..h { + for x in 0..w { + for (c, (plane, stride, xs, ys)) in planes.iter().enumerate() { + let (Some(&(x0, x1, fx)), Some(&(y0, y1, fy))) = (xs.get(x), ys.get(y)) else { + return Err(err("sample map out of range")); + }; + let at = |xx: usize, yy: usize| plane.get(yy * stride + xx).copied().unwrap_or(0.0); + let top = at(x0, y0) + (at(x1, y0) - at(x0, y0)) * fx; + let bottom = at(x0, y1) + (at(x1, y1) - at(x0, y1)) * fx; + if let Some(p) = px.get_mut(c) { + *p = top + (bottom - top) * fy; + } + } + to_color(&mut px, nc, ycc, max); + for &p in px.iter().take(nc) { + let p = p.clamp(0.0, max); + if sixteen { + wide.push((p * 65535.0 / max).round() as u16); + } else { + narrow.push(to_u8(p)); + } + } + } + } + let samples = if sixteen { Samples::U16(wide) } else { Samples::U8(narrow) }; + Ok((w as u32, h as u32, nc as u8, samples)) +} diff --git a/crates/jpeg/src/lib.rs b/crates/jpeg/src/lib.rs index 0d4735676..326943cb4 100644 --- a/crates/jpeg/src/lib.rs +++ b/crates/jpeg/src/lib.rs @@ -197,6 +197,32 @@ pub struct FrameKind { /// EOI or the end of the data first. Reads only the headers, so it is cheap enough to route /// every JPEG an app opens. pub fn frame(b: &[u8]) -> Option { + let (marker, seg) = frame_segment(b)?; + Some(FrameKind { marker, precision: *seg.get(2)? }) +} + +/// Whether `bytes` are a progressive JPEG whose frame samples some component more finely (across +/// or down) than its first. zune-jpeg 0.5.15, the decoder behind `image`, asserts in its upsampler +/// on such a frame (etemesi254/zune-image#236; fixed there by 36007420, unreleased as of +/// 0.5.16-rc3), and in the browser a panic aborts the page. Until the fix ships, such a JPEG is +/// refused from its header: the decoder refuses the larger ones itself, so nothing that decoded is +/// lost. Baseline frames of the same shape decode and are left to it. +/// shortcut: remove this check (and its callers' early return) once `Cargo.lock` has zune-jpeg +/// 0.5.16 or later. +pub fn finer_than_first(bytes: &[u8]) -> bool { + let Some((marker, seg)) = frame_segment(bytes) else { return false }; + if !matches!(marker, 0xC2 | 0xC6 | 0xCA | 0xCE) { + return false; + } + // Length (2), precision (1), height (2), width (2), components (1), then id, sampling and + // table for each component. + let n = usize::from(seg.get(7).copied().unwrap_or(0)); + let sampling = |k: usize| seg.get(9 + 3 * k).map(|b| (b >> 4, b & 0x0F)); + let Some((h0, v0)) = sampling(0) else { return false }; + (1..n).any(|k| sampling(k).is_some_and(|(h, v)| h > h0 || v > v0)) +} + +fn frame_segment(b: &[u8]) -> Option<(u8, &[u8])> { if b.get(..2) != Some(&[0xFF, 0xD8]) { return None; } @@ -213,7 +239,7 @@ pub fn frame(b: &[u8]) -> Option { _ => { let len = usize::from(u16::from_be_bytes([*b.get(i + 2)?, *b.get(i + 3)?])); if matches!(m, 0xC0..=0xCF) && !matches!(m, 0xC4 | 0xC8 | 0xCC) { - return Some(FrameKind { marker: m, precision: *b.get(i + 4)? }); + return Some((m, b.get(i + 2..)?)); } i = i.checked_add(2 + len)?; } @@ -262,9 +288,72 @@ mod scan; pub use bands::{Band, Bands, Reader}; -use idct::render; +use idct::{render, render_scaled}; +use parse::{be16, parse_frame}; use scan::decode_coefficients; +/// The largest reduction [`decode_reduced`] reads straight from a JPEG's 8×8 blocks: 1/8. +pub const MAX_SHRINK: u8 = 3; + +/// Output size `(width, height, estimated_bytes)` of a JPEG reduction without decoding pixels. +/// +/// `shrink` must be in `1..=MAX_SHRINK` (1/2, 1/4, or 1/8). Checks `limits` against the +/// full-size frame header. +pub fn reduced_estimate(bytes: &[u8], limits: &Limits, shrink: u8) -> Result<(u32, u32, usize), Error> { + if shrink == 0 || shrink > MAX_SHRINK { + return Err(err("shrink must be 1..=3")); + } + if bytes.get(..2) != Some(&[0xFF, 0xD8]) { + return Err(err("not a JPEG stream")); + } + let mut i = 2usize; + while let Some(&v) = bytes.get(i) { + if v != 0xFF { + i += 1; + continue; + } + let Some(&m) = bytes.get(i + 1) else { break }; + match m { + 0xFF => { + i += 1; + continue; + } + 0x00 | 0x01 | 0xD0..=0xD8 => { + i += 2; + continue; + } + 0xD9 | 0xDA => return Err(err("no frame header before scan")), + _ => {} + } + let len = usize::from(be16(bytes, i + 2)?); + if len < 2 { + return Err(err("bad marker segment length")); + } + let seg = bytes.get(i + 4..i + 2 + len).ok_or_else(|| err("marker segment runs past the end of the file"))?; + if matches!(m, 0xC0..=0xCF) && !matches!(m, 0xC4 | 0xC8 | 0xCC) { + let f = parse_frame(m, seg, limits)?; + let w = (f.width as u32).div_ceil(1 << shrink); + let h = (f.height as u32).div_ceil(1 << shrink); + let output_bytes = (w as usize).saturating_mul(h as usize).saturating_mul(f.comps.len().saturating_mul(4).saturating_add(4)); + let coef_bytes = if f.progressive { f.comps.iter().map(|c| c.bw.saturating_mul(c.bh)).sum::().saturating_mul(256) } else { 0 }; + return Ok((w, h, coef_bytes.saturating_add(output_bytes))); + } + i += 2 + len; + } + Err(err("no frame header found")) +} + +/// Decode a JPEG stream at `1 / 2^shrink` of its size (each side rounded up), for `shrink` in +/// `1..=MAX_SHRINK` (1/2, 1/4, or 1/8) using reduced-size IDCTs on the 8×8 DCT blocks. +pub fn decode_reduced(bytes: &[u8], limits: &Limits, adobe_transform: Option, shrink: u8) -> Result { + if shrink == 0 || shrink > MAX_SHRINK { + return Err(err("shrink must be 1..=3")); + } + let (frame, tables, damaged) = decode_coefficients(bytes, limits)?; + let (width, height, components, samples) = render_scaled(frame, &tables, adobe_transform, shrink)?; + Ok(Decoded { width, height, components, samples, damaged }) +} + /// Decode a JPEG stream of one of the frame types listed in the [crate docs](crate). /// /// `adobe_transform` is the transform byte of the stream's APP14 `Adobe` segment, if the caller diff --git a/crates/jpeg/src/tests.rs b/crates/jpeg/src/tests.rs index eb441d1b1..57d096066 100644 --- a/crates/jpeg/src/tests.rs +++ b/crates/jpeg/src/tests.rs @@ -681,3 +681,35 @@ fn limits_are_checked_before_allocating() { assert_eq!(decode(&stream, &limits, None).is_ok(), ok, "max_alloc {max_alloc}"); } } + +#[test] +fn reduced_decoding_scales_dimensions_and_samples() { + let mut rgb = Vec::with_capacity(32 * 24 * 3); + for _ in 0..32 * 24 { + rgb.extend_from_slice(&[200, 100, 50]); + } + let mut encoded = Vec::new(); + jpeg_encoder::Encoder::new(&mut encoded, 95).encode(&rgb, 32, 24, jpeg_encoder::ColorType::Rgb).unwrap(); + + let limits = Limits::default(); + assert!(reduced_estimate(&encoded, &limits, 0).is_err()); + assert!(reduced_estimate(&encoded, &limits, 4).is_err()); + assert!(decode_reduced(&encoded, &limits, None, 0).is_err()); + assert!(decode_reduced(&encoded, &limits, None, 4).is_err()); + + for shrink in 1..=MAX_SHRINK { + let (ew, eh, est_bytes) = reduced_estimate(&encoded, &limits, shrink).unwrap(); + let dec = decode_reduced(&encoded, &limits, None, shrink).unwrap(); + assert_eq!((dec.width, dec.height), (32u32.div_ceil(1 << shrink), 24u32.div_ceil(1 << shrink))); + assert_eq!((dec.width, dec.height), (ew, eh)); + assert!(est_bytes > 0); + assert_eq!(dec.components, 3); + let Samples::U8(samples) = dec.samples else { panic!("expected U8") }; + assert_eq!(samples.len(), (ew * eh * 3) as usize); + for px in samples.as_chunks::<3>().0 { + assert!((px[0] as i32 - 200).abs() <= 5, "r={}", px[0]); + assert!((px[1] as i32 - 100).abs() <= 5, "g={}", px[1]); + assert!((px[2] as i32 - 50).abs() <= 5, "b={}", px[2]); + } + } +} diff --git a/crates/jxl/src/brob.rs b/crates/jxl/src/brob.rs index 6d0aefbc4..16d72c720 100644 --- a/crates/jxl/src/brob.rs +++ b/crates/jxl/src/brob.rs @@ -47,26 +47,66 @@ fn box_at(bytes: &[u8], at: usize) -> Option { Some(BoxSpan { start: at, header, end: end.min(bytes.len()) }) } -/// Every box of the container, in order, up to the first one that cannot be read. -fn boxes(bytes: &[u8]) -> Vec { - let mut found = Vec::new(); - let mut at = 0; - while let Some(span) = box_at(bytes, at) { - at = span.end; - found.push(span); - if at >= bytes.len() { - break; - } - } - found +/// The boxes of the container, in order, up to the first one that cannot be read. One box at a +/// time: a file of eight-byte boxes must not cost three times its size in spans. +struct Boxes<'a> { + bytes: &'a [u8], + at: usize, + done: bool, } -/// Inflates `compressed`, or `None` when it is broken or would pass `cap` bytes. -pub(crate) fn inflate_capped(compressed: &[u8], cap: usize) -> Option> { +impl<'a> Boxes<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, at: 0, done: false } + } + + /// Where the next box would start: the end of the last one read, or 0 before the first. + fn end(&self) -> usize { + self.at + } +} + +impl Iterator for Boxes<'_> { + type Item = BoxSpan; + + fn next(&mut self) -> Option { + if self.done { + return None; + } + let Some(span) = box_at(self.bytes, self.at) else { + self.done = true; + return None; + }; + self.at = span.end; + self.done = self.at >= self.bytes.len(); + Some(span) + } +} + +/// Whether the Brotli stream header asks for a window of at most 16 MiB. The decoder reserves its +/// whole ring buffer up front, outside the output cap, so a header that declares a large window +/// (RFC 7932 §9.1 and the large-window extension) could ask for a gigabyte from a few bytes. +fn window_is_small(compressed: &[u8]) -> bool { + let Some(first) = compressed.first() else { return true }; + let wide = first & 1 == 1; + let long_form = (first >> 1) & 7; + let short_form = (first >> 4) & 7; + !(wide && long_form == 0 && short_form == 1) +} + +/// Inflates `compressed`. `Err` carries how many bytes were produced before it was refused +/// (broken stream, over `cap`, or a large window), so the caller can charge the work to its budget. +pub(crate) fn inflate_capped(compressed: &[u8], cap: usize) -> Result, usize> { + if !window_is_small(compressed) { + return Err(0); + } let mut out = Vec::new(); - let limit = u64::try_from(cap).ok()?.checked_add(1)?; - brotli_decompressor::Decompressor::new(compressed, 4096).take(limit).read_to_end(&mut out).ok()?; - (out.len() <= cap).then_some(out) + let limit = u64::try_from(cap).ok().and_then(|c| c.checked_add(1)).ok_or(0_usize)?; + let read = brotli_decompressor::Decompressor::new(compressed, 4096).take(limit).read_to_end(&mut out); + if read.is_err() || out.len() > cap { + return Err(out.len()); + } + Ok(out) } /// A plain box of type `kind` holding `data`. @@ -92,9 +132,18 @@ fn unwrap_brob(span: &BoxSpan, bytes: &[u8], budget: &mut usize) -> Option { + *budget -= inflated.len(); + Some(plain_box(inner, &inflated)) + } + Err(produced) => { + // The work was done even though the box is dropped: charge it, so a file of many + // over-cap streams cannot make the decoder inflate the whole budget once per box. + *budget = budget.saturating_sub(produced); + None + } + } } /// `bytes` with every `brob` box inflated, `cap` bytes in all (or removed), or `None` when the file is @@ -103,20 +152,20 @@ pub(crate) fn sanitize(bytes: &[u8], cap: usize) -> Option> { if !bytes.starts_with(SIGNATURE) { return None; } - let spans = boxes(bytes); - if !spans.iter().any(|s| s.kind(bytes) == BROB) { + if !Boxes::new(bytes).any(|s| s.kind(bytes) == BROB) { return None; } let mut budget = cap; let mut out = Vec::with_capacity(bytes.len()); - for span in &spans { + let mut walk = Boxes::new(bytes); + for span in walk.by_ref() { match (span.kind(bytes) == BROB, bytes.get(span.start..span.end)) { - (true, _) => out.extend(unwrap_brob(span, bytes, &mut budget).unwrap_or_default()), + (true, _) => out.extend(unwrap_brob(&span, bytes, &mut budget).unwrap_or_default()), (false, Some(whole)) => out.extend_from_slice(whole), (false, None) => {} } } - out.extend_from_slice(bytes.get(spans.last().map_or(0, |s| s.end)..).unwrap_or(&[])); + out.extend_from_slice(bytes.get(walk.end()..).unwrap_or(&[])); Some(out) } @@ -146,9 +195,9 @@ mod tests { #[test] fn a_bomb_passes_the_cap_and_a_real_packet_does_not() { - assert_eq!(inflate_capped(&EXIF_BR, BROB_CAP).as_deref(), Some(&b"II*\0\x08\0\0\0hello exif"[..])); - assert!(inflate_capped(&BOMB_BR, BROB_CAP).is_none()); - assert!(inflate_capped(&BOMB_BR[..20], BROB_CAP).is_none(), "a cut stream is not a result"); + assert_eq!(inflate_capped(&EXIF_BR, BROB_CAP).as_deref(), Ok(&b"II*\0\x08\0\0\0hello exif"[..])); + assert!(inflate_capped(&BOMB_BR, BROB_CAP).is_err()); + assert!(inflate_capped(&BOMB_BR[..20], BROB_CAP).is_err(), "a cut stream is not a result"); } #[test] @@ -188,6 +237,26 @@ mod tests { assert!(out.len() < SIGNATURE.len() + 2 * (exif + 8) + 1); } + #[test] + fn an_over_cap_box_uses_up_the_budget_of_the_boxes_after_it() { + let boxes = [brob_of(b"xml ", &BOMB_BR), brob_of(b"Exif", &EXIF_BR)]; + assert_eq!(sanitize(&container(&boxes), 64).unwrap(), container(&[]), "the later packet is dropped too"); + } + + #[test] + fn a_stream_that_declares_a_large_window_is_refused_before_decoding() { + // WBITS bits 1, 000, 001: the large-window marker. + assert_eq!(inflate_capped(&[0x11, 0, 0, 0], BROB_CAP), Err(0)); + assert!(window_is_small(&EXIF_BR) && window_is_small(&BOMB_BR) && window_is_small(&[])); + } + + #[test] + fn a_long_run_of_tiny_boxes_is_walked_without_a_list_of_spans() { + let boxes: Vec> = (0..1000).map(|_| plain_box(b"free", b"")).collect(); + assert!(sanitize(&container(&boxes), BROB_CAP).is_none(), "no brob box: used as it is"); + assert_eq!(Boxes::new(&container(&boxes)).count(), 1001, "the signature box and the 1000 others"); + } + #[test] fn a_cut_off_file_keeps_its_tail_verbatim() { let mut file = container(&[brob_of(b"Exif", &EXIF_BR)]); diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index cfbeebde4..994ac6a6c 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -1,7 +1,7 @@ [package] autotests = false name = "craft-media" -description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, and Ogg, AVI and MPEG-TS/PS demuxers." +description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, an MPEG-TS/PS demuxer and MPEG-TS muxer, and Ogg and AVI demuxers." version.workspace = true edition.workspace = true license.workspace = true @@ -23,7 +23,8 @@ matroska = [] avi = [] # MXF demuxer and writer (`craft_media::mxf`); the writer formats dates with chrono. mxf = ["dep:chrono"] -# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`). +# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`), and the +# transport stream writer (`craft_media::mpegts::mux`). mpegts = [] # Sierra VMD (Video and Music Data) demuxer (`craft_media::vmd`). vmd = [] diff --git a/crates/media/README.md b/crates/media/README.md index 16ad74434..a90b55993 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -1,8 +1,9 @@ # craft-media Media containers and bit-level I/O for the Craft apps: an MSB-first bit reader and writer, -clean-room ISO BMFF (MP4), QuickTime (MOV), Matroska (MKV, WebM), MXF and AVI demuxers and muxers, and -Ogg, MPEG-2 Systems (transport and program stream) and Sierra VMD demuxers, written from the public specifications. No `unsafe`, no panics on malformed +clean-room ISO BMFF (MP4), QuickTime (MOV), Matroska (MKV, WebM), MXF and AVI demuxers and muxers, +an MPEG-2 Systems (transport and program stream) demuxer and transport stream muxer, and Ogg and +Sierra VMD demuxers, written from the public specifications. No `unsafe`, no panics on malformed input, builds for `wasm32-unknown-unknown`. Dependencies: `thiserror` (for `isobmff`), `chrono` (for `mxf`), `serde` (optional). @@ -549,7 +550,8 @@ FourCC, size, frame rate, packet count, audio format and duration. A clean-room MPEG-2 Systems demuxer from FilmCraft's `filmcraft-mpegts` (storytold/filmcraft@4bec22b): transport streams (188-byte, 192-byte BDAV / M2TS, 204-byte) and program streams (MPEG-1/2 PS, VOB, MOD). No GPL/LGPL code (FFmpeg, libavformat) was consulted; -FFmpeg is a fixture generator and test oracle only. No muxer, no decoding. +FFmpeg is a fixture generator and test oracle only. No decoding. The transport stream writer is +`mpegts::mux` ([below](#transport-stream-writer)). ```rust use craft_media::mpegts::{Kind, open}; @@ -637,6 +639,116 @@ helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares ten ffmpeg-made fi 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. +### Transport stream writer + +`mpegts::mux::Muxer` writes one program to any `std::io::Write` as frames arrive, so the same code +writes `.ts` files, HLS segments and SRT payloads. Its `Codec`, `Stream` and `Error` types are its +own, separate from the demuxer's. + +```rust +use craft_media::mpegts::mux::{Codec, Config, Frame, Muxer, Stream}; + +let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]; +let mut ts = Muxer::new(Vec::new(), Config::default(), &streams)?; +let idr = [0, 0, 0, 1, 0x65, 0x88, 0x84]; +ts.write_frame(0, &Frame { data: &idr, pts: 90_000, dts: None, key: true })?; +let bytes = ts.finish()?; +assert_eq!(bytes.len() % 188, 0); +``` + +- A program association section and a program map section, each ending with its CRC-32. They are + written at the start, every `Config::psi_interval`, before every video keyframe when + `Config::psi_before_keyframes` is set, and before the first frame after `Muxer::replace_writer` + or `Muxer::discontinuity`. +- One PES packet per frame, with PTS and, when it differs from the PTS, DTS: + + | `Codec` | stream_type | stream_id | Frames passed in | + |---|---|---|---| + | `H264` | 0x1B | 0xE0 | Annex B access units; an access unit delimiter is added when missing | + | `Hevc` | 0x24 | 0xE0 | Annex B access units; an access unit delimiter is added when missing | + | `Mpeg2Video` | 0x02 | 0xE0 | MPEG-2 pictures from their first start code | + | `Mpeg1Video` | 0x01 | 0xE0 | MPEG-1 pictures from their first start code | + | `Mpeg4Part2` | 0x10 | 0xE0 | MPEG-4 Part 2 visual frames from their first start code | + | `Av1(Av1Config)` | 0x06 | 0xBD | temporal units in the low overhead format (every OBU has `obu_size`) | + | `AacAdts` | 0x0F | 0xC0 | ADTS frames; their `frame_length` fields must tile the frame | + | `Aac { .. }` | 0x0F | 0xC0 | raw AAC frames; the writer adds the ADTS header | + | `Opus { channels }` | 0x06 | 0xBD | Opus access units, 1 to 8 channels; the writer adds the Opus control header | + | `OpusMapped(OpusMapping)` | 0x06 | 0xBD | Opus multistream access units with an explicit channel mapping | + | `Ac3` | 0x81 | 0xBD | AC-3 sync frames | + | `Eac3` | 0x87 | 0xBD | E-AC-3 sync frames (bsid 11 to 16) | + | `MpegAudio { low_sample_rate }` | 0x03 or 0x04 | 0xC0 | MPEG audio frames, layers I to III, whose version matches the stream type | + + `Codec::aac_from_asc` turns an AudioSpecificConfig into the `Aac` fields, and refuses one that + an ADTS header cannot carry (frameLengthFlag 1, for one). An `Opus { channels }` access unit is + one Opus packet for 1 or 2 channels. For 3 to 8 channels it holds the streams of mapping family 1 + in the order that table 4-3 of the Opus transport draft gives, and every stream but the last uses + the self-delimited framing of RFC 6716 Appendix B. `OpusMapped` takes any other layout. +- Descriptors in the program map section: a registration descriptor `AC-3` or `EAC3` on AC-3 and + E-AC-3 streams; a registration descriptor `Opus` and an extension descriptor (tag 0x7F, + extension tag 0x80) on Opus streams, whose channel_config_code is the channel count for + `Opus { channels }` and 0x81 with the mapping family, stream counts and channel mapping for + `OpusMapped`; a registration descriptor `AV01` and the AV1 video descriptor (tag 0x80) built + from `Av1Config` (`Av1Config::from_av1c` reads an AV1CodecConfigurationRecord); and an + ISO 639 language descriptor on any stream that has a language. +- For AV1, each OBU follows the start code 0x000001 with emulation prevention bytes, temporal + delimiters and padding OBUs that end with a zero byte are left out, and each PES packet holds + one temporal unit. A keyframe must carry a + sequence header, and tile list OBUs are refused. +- For Opus, `Muxer::write_frame_with_trim` writes the control header's start and end trims (each + at most 8 191 samples, `MAX_OPUS_TRIM`). A start trim is allowed only while every earlier frame + of the stream was trimmed whole, 65 535 samples in all. +- The PCR on `Config::pcr_pid`: one of the streams' PIDs, or a PID that carries only PCRs. PCRs + are never more than `Config::pcr_interval` apart (at most 100 ms, H.222.0 §2.7.2). The PCR is + the largest DTS so far minus `Config::pcr_delay`, 1 to 90 000 ticks (`MAX_PCR_DELAY`, the + one-second limit of §2.4.2.6). A live output calls `Muxer::advance` while no frames arrive; its + time is on the DTS scale, so the PCR it writes is that time minus `pcr_delay`. +- A continuity counter per PID, the random access indicator on keyframes, adaptation field + stuffing, and timestamps written modulo 2^33. `Muxer::discontinuity` starts a new time base: + the next packet of every stream PID and of the PCR PID sets the discontinuity_indicator + (§2.4.3.5), and timestamps may then go back. + +Packets go to the output in batches of `Config::batch_packets` (7 by default, 1 316 bytes, one UDP +datagram), each in one `write` call, and the rest of a batch at the end of every `write_frame` and +`advance` unless `Config::hold_packets` is set. The batch is allocated once, in `Muxer::new`. After +an `Error::Io` the output may hold part of a packet; `Stats::packets` counts only whole packets. +`Muxer::replace_writer` returns the old output in a `Segment` (packet and frame counts, first and +last PTS, whether it starts with a keyframe, any error from its last packets), and the new output +starts with the PAT, the PMT and a PCR. `Muxer::replace_writer_continuing` swaps the output +without adding them. + +Frames are checked before anything is written. A stream's DTS must not go back, a video stream's +DTS must increase, a DTS may not be after its PTS, and a frame may be at most `pcr_delay` behind +the largest DTS written so far (`Error::Timestamp`). Audio frames must fit in one PES packet, and +video frames are at most `MAX_VIDEO_FRAME` (`MAX_UNIT_BYTES`, counting the start codes and escape +bytes the writer adds; `Error::FrameTooLarge`). A program has 1 to 32 streams on PIDs 0x0010 to +0x1FFE (`Error::BadPid`, `Error::DuplicatePid`), and its program map section is at most 1 021 bytes +(`Error::PsiTooLarge`). A gap in the timeline longer than `MAX_PCR_FILL` PCR intervals gets one PCR +at its end and is counted in `Stats::pcr_gaps`. + +`Config::default()`: program 1 with its PMT on PID 0x1000, the PCR on the first video stream (or +the first stream) every 40 ms and 700 ms behind the DTS, the PAT and PMT every 100 ms and before +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. + +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 +durations and self-delimited framing; Carriage of AV1 in MPEG-2 TS (Alliance for Open Media +working draft) and the AV1 Bitstream & Decoding Process Specification for AV1; ISO/IEC 14496-3 +for the AudioSpecificConfig; ATSC A/52 for the AC-3 and E-AC-3 stream types and registration +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 +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 +refused frame writes nothing. + ## `mxf` A clean-room MXF demuxer and writer from FilmCraft's `filmcraft-mxf` (storytold/filmcraft@4bec22b): diff --git a/crates/media/src/avi/mod.rs b/crates/media/src/avi/mod.rs index eaaa1bbe2..69e919705 100644 --- a/crates/media/src/avi/mod.rs +++ b/crates/media/src/avi/mod.rs @@ -258,6 +258,7 @@ impl Stream { b"HEVC" | b"H265" | b"HEV1" | b"HVC1" | b"X265" => Id::Hevc, b"DIVX" | b"DX50" | b"XVID" | b"FMP4" | b"MP4V" | b"M4S2" | b"3IV2" => Id::Mpeg4Video, b"MPG2" | b"MPEG" | b"MPG1" => Id::Mpeg2Video, + b"FFV1" => Id::Ffv1, b"VP80" => Id::Vp8, b"VP90" => Id::Vp9, b"AV01" => Id::Av1, diff --git a/crates/media/src/avi/tests.rs b/crates/media/src/avi/tests.rs index 2edac310b..f1e06ef05 100644 --- a/crates/media/src/avi/tests.rs +++ b/crates/media/src/avi/tests.rs @@ -546,6 +546,7 @@ fn codec_params_map_fourccs_and_format_tags() { (b"XVID", CodecId::Mpeg4Video), (b"apch", CodecId::ProRes), (b"AVdn", CodecId::Dnxhd), + (b"FFV1", CodecId::Ffv1), (b"YUY2", CodecId::Unknown), (&[0; 4], CodecId::Unknown), ] { diff --git a/crates/media/src/id.rs b/crates/media/src/id.rs index 2f73cd610..e93b7e327 100644 --- a/crates/media/src/id.rs +++ b/crates/media/src/id.rs @@ -121,6 +121,8 @@ pub enum CodecId { Vp8, /// VP9. Vp9, + /// FFV1 lossless video. + Ffv1, /// Apple ProRes. ProRes, /// Motion JPEG. @@ -168,6 +170,7 @@ impl CodecId { CodecId::Av1 => "AV1", CodecId::Vp8 => "VP8", CodecId::Vp9 => "VP9", + CodecId::Ffv1 => "FFV1", CodecId::ProRes => "ProRes", CodecId::Mjpeg => "Motion JPEG", CodecId::Mpeg2Video => "MPEG-2", @@ -214,6 +217,7 @@ impl CodecId { | CodecId::Av1 | CodecId::Vp8 | CodecId::Vp9 + | CodecId::Ffv1 | CodecId::ProRes | CodecId::Mjpeg | CodecId::Mpeg2Video @@ -271,6 +275,7 @@ impl PcmFormat { /// | H.264 / HEVC / AV1 | the `avcC` / `hvcC` / `av1C` record | /// | VP9 | the MP4 `vpcC` payload, or Matroska's codec feature metadata | /// | APV | the `apvC` record | +/// | FFV1 | the version 3 configuration record (dimensions are required separately) | /// | VMD video, VMD audio | the 816-byte VMD file header | /// /// `sample_rate` and `channels` are what the container declares (for HE-AAC with implicit diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 871667c50..0ca7c3ac1 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -11,7 +11,7 @@ //! - `avi` (feature `avi`): a clean-room AVI (RIFF) and OpenDML demuxer. //! - `mxf` (feature `mxf`, enables `chrono`): a clean-room MXF demuxer and writer (OP1a, OP-Atom). //! - `mpegts` (feature `mpegts`): a clean-room MPEG-2 Systems demuxer (transport streams and -//! program streams). +//! program streams) and transport stream writer. //! - `vmd` (feature `vmd`): a clean-room Sierra VMD (Video and Music Data) demuxer. //! - [`Container`] and [`CodecId`] (no feature): the identifiers the codec crates report a file's //! container and codec with. diff --git a/crates/media/src/matroska/track.rs b/crates/media/src/matroska/track.rs index 4937e3222..bcd1bb71e 100644 --- a/crates/media/src/matroska/track.rs +++ b/crates/media/src/matroska/track.rs @@ -322,6 +322,11 @@ impl Track { Codec::Mp3 => (Id::Mp3, Vec::new()), Codec::Mp2 => (Id::Mp2, Vec::new()), Codec::Mp1 => (Id::Mp1, Vec::new()), + Codec::Other(id) if id == "V_FFV1" => (Id::Ffv1, self.codec_private.clone()), + // VfW CodecPrivate starts with the 40-byte BITMAPINFOHEADER. + Codec::VfwFourcc { fourcc: [b'F', b'F', b'V', b'1'], bitmap_info_header } => { + (Id::Ffv1, bitmap_info_header.get(40..).unwrap_or_default().to_vec()) + } // the ALACSpecificConfig, as MP4's `alac` box holds it after its FullBox header Codec::Other(id) if id == "A_ALAC" => (Id::Alac, self.codec_private.clone()), Codec::VfwFourcc { fourcc: [b'A', b'V', b'd', b'n' | b'h'], .. } => (Id::Dnxhd, Vec::new()), @@ -445,3 +450,40 @@ impl Track { } } } + +#[cfg(test)] +mod codec_params_tests { + use crate::CodecId; + use crate::matroska::mux::{MkvWriter, MuxOptions, TrackSpec}; + use crate::matroska::{Demuxer, TrackKind}; + + #[test] + fn ffv1_native_and_vfw_preserve_configuration_and_dimensions() { + let config = vec![1, 2, 3, 4, 5]; + let mut native = TrackSpec::new(TrackKind::Video, "V_FFV1"); + native.codec_private = config.clone(); + native.video_size = Some((32, 24)); + let mut vfw = TrackSpec::new(TrackKind::Video, "V_MS/VFW/FOURCC"); + let mut bih = vec![0; 40]; + bih[..4].copy_from_slice(&40u32.to_le_bytes()); + bih[16..20].copy_from_slice(b"FFV1"); + bih.extend_from_slice(&config); + vfw.codec_private = bih; + vfw.video_size = native.video_size; + let mut writer = MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![native, vfw], MuxOptions::default()).unwrap(); + for track in 0..2 { + writer.write_frame(track, 0, true, &[0; 4], None).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let demux = Demuxer::from_slice(&bytes).unwrap(); + for track in demux.tracks() { + let params = track.codec_params(); + assert_eq!(params.codec, CodecId::Ffv1); + assert_eq!(params.extradata, config); + assert_eq!((params.width, params.height), (Some(32), Some(24))); + assert!(params.codec.is_video()); + assert!(!params.codec.is_audio()); + assert_eq!(params.codec.name(), "FFV1"); + } + } +} diff --git a/crates/media/src/mpegts/mod.rs b/crates/media/src/mpegts/mod.rs index a0a62efa5..32356be02 100644 --- a/crates/media/src/mpegts/mod.rs +++ b/crates/media/src/mpegts/mod.rs @@ -15,6 +15,7 @@ //! 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. //! //! The module does no decoding. No dependencies beyond `std`, no `unsafe`, builds for //! `wasm32-unknown-unknown`. @@ -26,6 +27,7 @@ mod es; pub use es::{FrameInfo, frame_bytes, frame_info, sei_has_recovery_point}; +pub mod mux; mod pes; mod ps; mod ts; diff --git a/crates/media/src/mpegts/mux/av1.rs b/crates/media/src/mpegts/mux/av1.rs new file mode 100644 index 000000000..22d0d7cd5 --- /dev/null +++ b/crates/media/src/mpegts/mux/av1.rs @@ -0,0 +1,232 @@ +//! AV1 in a transport stream (Carriage of AV1 in MPEG-2 TS, §3): each OBU after the start code +//! 0x000001, with emulation prevention so that 0x000000, 0x000001, 0x000002 and 0x000003 never +//! appear inside it. Temporal delimiters are left out, and so are padding OBUs that end with a +//! zero byte (an empty one included), which decoders ignore. + +use super::Error; + +const OBU_SEQUENCE_HEADER: u8 = 1; +const OBU_TEMPORAL_DELIMITER: u8 = 2; +const OBU_TILE_LIST: u8 = 8; +const OBU_PADDING: u8 = 15; + +struct Obu { + /// Bytes from the OBU header to the end of its payload. + len: usize, + kind: u8, +} + +/// The OBU at the start of `d`. +fn obu(d: &[u8]) -> Result { + let &h = d.first().ok_or(Error::BadFrame("an AV1 frame ends inside an OBU header"))?; + if h & 0x80 != 0 { + return Err(Error::BadFrame("an AV1 OBU has its forbidden bit set")); + } + if h & 0x02 == 0 { + return Err(Error::BadFrame("AV1 OBUs must carry obu_size (the low overhead bitstream format)")); + } + let mut at = 1 + usize::from(h & 0x04 != 0); + let mut size: u64 = 0; + for i in 0..8 { + let &b = d.get(at).ok_or(Error::BadFrame("an AV1 frame ends inside an OBU header"))?; + at += 1; + size |= u64::from(b & 0x7F) << (7 * i); + if b & 0x80 == 0 { + break; + } + if i == 7 { + return Err(Error::BadFrame("an AV1 obu_size is longer than eight bytes")); + } + } + let len = usize::try_from(size).ok().filter(|&s| s <= u32::MAX as usize).and_then(|s| at.checked_add(s)).filter(|&l| l <= d.len()); + let len = len.ok_or(Error::BadFrame("an AV1 OBU runs past the end of the frame"))?; + Ok(Obu { len, kind: (h >> 3) & 0x0F }) +} + +/// The OBU `bytes` (as `obu` found it) is not written: a temporal delimiter, or a padding OBU +/// that ends with a zero byte. +fn left_out(o: &Obu, bytes: &[u8]) -> bool { + o.kind == OBU_TEMPORAL_DELIMITER || (o.kind == OBU_PADDING && bytes.last() == Some(&0)) +} + +/// Emulation prevention bytes `bytes` needs after a start code. +fn escapes(bytes: &[u8]) -> usize { + let (mut n, mut zeros) = (0, 0u8); + for &b in bytes { + if zeros >= 2 && b <= 3 { + n += 1; + zeros = 0; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + } + n +} + +/// Checks a temporal unit and returns the bytes it takes in the PES packet: start codes, OBUs +/// and emulation prevention bytes. +pub(crate) fn check(data: &[u8], key: bool) -> Result { + let (mut at, mut body, mut seq, mut any) = (0, 0usize, false, false); + while at < data.len() { + let o = obu(&data[at..])?; + let bytes = &data[at..at + o.len]; + at += o.len; + if left_out(&o, bytes) { + continue; + } + match o.kind { + OBU_TILE_LIST => return Err(Error::BadFrame("tile list OBUs are not carried in a transport stream")), + OBU_SEQUENCE_HEADER => seq = true, + _ => {} + } + if bytes.last() == Some(&0) { + return Err(Error::BadFrame("an AV1 OBU ends with a zero byte, which the next start code would turn into a forbidden sequence")); + } + body = body.saturating_add(3 + bytes.len() + escapes(bytes)); + any = true; + } + if !any { + return Err(Error::BadFrame("the AV1 frame holds only temporal delimiters and padding")); + } + if key && !seq { + return Err(Error::BadFrame("an AV1 keyframe must carry a sequence header")); + } + Ok(body) +} + +/// Writes a checked temporal unit in start code form, a packet at a time. +pub(crate) struct Escaper<'a> { + data: &'a [u8], + at: usize, + /// End of the OBU being written. + end: usize, + /// Start code bytes still to write. + start_code: u8, + zeros: u8, +} + +impl<'a> Escaper<'a> { + pub(crate) fn new(data: &'a [u8]) -> Self { + Self { data, at: 0, end: 0, start_code: 0, zeros: 0 } + } + + /// Fills `out` as far as the temporal unit goes; returns the bytes written. + pub(crate) fn fill(&mut self, out: &mut [u8]) -> usize { + let mut n = 0; + while n < out.len() { + if self.start_code > 0 { + out[n] = u8::from(self.start_code == 1); + self.start_code -= 1; + n += 1; + } else if self.at < self.end { + let b = self.data[self.at]; + if self.zeros >= 2 && b <= 3 { + out[n] = 3; + self.zeros = 0; + } else { + out[n] = b; + self.at += 1; + self.zeros = if b == 0 { self.zeros + 1 } else { 0 }; + } + n += 1; + } else { + let rest = self.data.get(self.at..).unwrap_or(&[]); + let Ok(o) = obu(rest) else { break }; + if left_out(&o, &rest[..o.len]) { + self.at += o.len; + continue; + } + self.end = self.at + o.len; + self.start_code = 3; + self.zeros = 0; + } + } + n + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Removes start codes and emulation prevention bytes: the OBUs back. + fn unescape(es: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut zeros = 0; + let mut i = 0; + while i < es.len() { + if es[i..].starts_with(&[0, 0, 1]) { + i += 3; + zeros = 0; + continue; + } + let b = es[i]; + i += 1; + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + out.push(b); + } + out + } + + fn write(data: &[u8], chunk: usize) -> Vec { + let mut e = Escaper::new(data); + let mut out = Vec::new(); + loop { + let mut b = vec![0u8; chunk]; + let n = e.fill(&mut b); + out.extend_from_slice(&b[..n]); + if n < chunk { + return out; + } + } + } + + #[test] + fn obus_get_start_codes_and_escapes() { + // a temporal delimiter, a sequence header, a frame OBU whose payload holds every + // sequence that needs an escape + let tu = [0x12, 0x00, 0x0A, 0x03, 0x00, 0x00, 0x01, 0x32, 0x0A, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0x7F]; + let body = check(&tu, true).unwrap(); + for chunk in [1, 2, 5, 184] { + let es = write(&tu, chunk); + assert_eq!(es.len(), body, "chunk {chunk}"); + assert!(es.starts_with(&[0, 0, 1, 0x0A, 0x03, 0x00, 0x00, 0x03, 0x01, 0, 0, 1, 0x32])); + for w in es[3..].windows(3) { + assert!(!(w[0] == 0 && w[1] == 0 && w[2] <= 2) || w == [0, 0, 1], "{es:02X?}"); + } + assert_eq!(unescape(&es), tu[2..].to_vec()); + } + } + + #[test] + fn padding_that_ends_with_a_zero_byte_is_left_out() { + // a sequence header, an empty padding OBU, a frame OBU, a padding OBU ending in 0x00, + // and a padding OBU that is written + let tu = [0x0A, 0x01, 0x05, 0x7A, 0x00, 0x32, 0x01, 0x07, 0x7A, 0x02, 0x09, 0x00, 0x7A, 0x01, 0x09]; + let body = check(&tu, true).unwrap(); + for chunk in [1, 2, 5, 184] { + let es = write(&tu, chunk); + assert_eq!(es.len(), body, "chunk {chunk}"); + assert_eq!(es, [0, 0, 1, 0x0A, 0x01, 0x05, 0, 0, 1, 0x32, 0x01, 0x07, 0, 0, 1, 0x7A, 0x01, 0x09], "chunk {chunk}"); + } + } + + #[test] + fn bad_temporal_units_are_refused() { + assert!(check(&[0x12, 0x00], false).is_err(), "only a temporal delimiter"); + assert!(check(&[0x32, 0x01, 0x05], true).is_err(), "a keyframe without a sequence header"); + assert!(check(&[0x32, 0x01, 0x05], false).is_ok()); + assert!(check(&[0x30, 0x05], false).is_err(), "no obu_size"); + assert!(check(&[0xB2, 0x01, 0x05], false).is_err(), "forbidden bit"); + assert!(check(&[0x32, 0x05, 0x05], false).is_err(), "past the end"); + assert!(check(&[0x32, 0x01, 0x00], false).is_err(), "ends with a zero byte"); + assert!(check(&[0x42, 0x01, 0x05], false).is_err(), "tile list"); + assert!(check(&[0x7A, 0x00], false).is_err(), "only empty padding"); + assert!(check(&[0x7A, 0x02, 0x05, 0x00], false).is_err(), "only padding that ends with a zero byte"); + assert!(check(&[0x32, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01], false).is_err(), "a nine-byte size"); + assert!(check(&[0x32, 0x80, 0x80, 0x80, 0x80, 0x10], false).is_err(), "over 2^32 - 1"); + } +} diff --git a/crates/media/src/mpegts/mux/mod.rs b/crates/media/src/mpegts/mux/mod.rs new file mode 100644 index 000000000..7e7ced791 --- /dev/null +++ b/crates/media/src/mpegts/mux/mod.rs @@ -0,0 +1,1192 @@ +//! MPEG-2 transport stream writer (ITU-T H.222.0 | ISO/IEC 13818-1). +//! +//! [`Muxer`] writes one program to any [`Write`] as frames arrive: +//! +//! - a program association section and a program map section, each ending with its CRC-32, at the +//! start, every [`Config::psi_interval`], before every video keyframe (optional), after +//! [`Muxer::replace_writer`] and after [`Muxer::discontinuity`]; +//! - one PES packet per frame for H.264, HEVC, MPEG-1, MPEG-2 and MPEG-4 Part 2 video, AV1, AAC in +//! ADTS frames (passed in, or built from raw AAC frames), Opus, AC-3, E-AC-3 and MPEG audio +//! (layers I to III), with PTS and, when it differs, DTS; +//! - the program clock reference on [`Config::pcr_pid`], in the adaptation field of the PCR +//! stream's frames or in packets of its own, never more than [`Config::pcr_interval`] apart +//! (at most 100 ms, §2.7.2); +//! - a continuity counter per PID, the random access indicator on keyframes, the discontinuity +//! indicator after [`Muxer::discontinuity`], and adaptation field stuffing in each frame's last +//! packet. +//! +//! Timestamps are 90 kHz ticks. They are written modulo 2^33, so a stream may run past the +//! wrap. The PCR follows the largest DTS so far minus [`Config::pcr_delay`]. +//! +//! # Arrival order +//! +//! Frames of different streams may arrive in any order, as long as each frame's DTS is no more +//! than [`Config::pcr_delay`] behind the largest DTS written so far (or the largest time given to +//! [`Muxer::advance`]). Within one stream the DTS never goes back, and for video it goes forward +//! with every frame. A caller whose encoders drift further apart than `pcr_delay` (at most +//! [`MAX_PCR_DELAY`], one second) queues frames and writes them in DTS order. +//! +//! # Output and failures +//! +//! Packets are built in a 188-byte buffer and collected in a batch of [`Config::batch_packets`] +//! packets, allocated once. A full batch is handed to the output in one `write` call, repeated +//! only when the output takes part of it; the default of 7 packets (1316 bytes) is one SRT or UDP +//! payload. Unless [`Config::hold_packets`] is set, the +//! rest of the batch is written at the end of every [`Muxer::write_frame`] and [`Muxer::advance`] +//! call, so a live output never waits for the next frame. A file output can set `hold_packets` +//! and a larger batch (for example 348 packets, 65 424 bytes) and then needs no `BufWriter`. +//! +//! The output must block until it has taken each write: an [`io::ErrorKind::WouldBlock`] error +//! is an I/O error like any other. After an I/O error the rest of that batch is dropped, the +//! output may hold part of a packet, and the continuity counters have moved on. +//! [`Stats::packets`] and [`Segment::packets`] count only the whole packets the output took. To +//! recover, give the muxer a new output with +//! [`Muxer::replace_writer`]: the new output starts at a packet boundary with the PAT, the PMT and +//! a PCR, and reads on its own. +//! +//! The names here ([`Codec`], [`Stream`], [`Error`]) are the writer's own and differ from the +//! demuxer's in [`crate::mpegts`]. + +mod av1; +mod pes; +mod psi; + +use std::fmt; +use std::io::{self, Write}; + +/// Bytes in a transport stream packet. +pub const PACKET_SIZE: usize = 188; +/// Timestamp ticks per second. +pub const TICKS_PER_SECOND: u32 = 90_000; +/// Largest PCR interval, 100 ms in 90 kHz ticks (H.222.0 §2.7.2). +pub const MAX_PCR_INTERVAL: u32 = 9_000; +/// Largest [`Config::pcr_delay`], one second in 90 kHz ticks: data may spend at most one second +/// in the decoder's buffers (H.222.0 §2.4.2.6). +pub const MAX_PCR_DELAY: u32 = 90_000; +/// Most elementary streams in one program. +pub const MAX_STREAMS: usize = 32; +/// Largest number of PCR-only packets, and of PAT and PMT repeats, written to fill one gap in the +/// timeline. A gap that needs more PCRs gets one PCR at its end and is counted in +/// [`Stats::pcr_gaps`]. +pub const MAX_PCR_FILL: u32 = 1024; +/// Largest video frame, [`super::MAX_UNIT_BYTES`] (128 MiB): the largest unit the demuxer +/// returns. +pub const MAX_VIDEO_FRAME: usize = super::MAX_UNIT_BYTES as usize; +/// Largest [`Config::batch_packets`]. +pub const MAX_BATCH_PACKETS: u16 = 1024; +/// Largest Opus start or end trim, in samples at 48 kHz (a 13-bit field). +pub const MAX_OPUS_TRIM: u16 = 8191; + +/// Errors from writing a transport stream. +#[non_exhaustive] +#[derive(Debug)] +pub enum Error { + /// Writing the output failed. + Io(io::Error), + /// The configuration or the stream list is not valid. + Config(String), + /// This PID is outside 0x0010 to 0x1FFE. + BadPid(u16), + /// This PID is used for two things. + DuplicatePid(u16), + /// The program map section would be longer than 1021 bytes. + PsiTooLarge { + /// The section_length it would have. + length: usize, + }, + /// [`Config::pcr_delay`] is outside 1 to [`MAX_PCR_DELAY`]. + PcrDelay(u32), + /// There is no stream with this index. + NoSuchStream(usize), + /// The frame has no bytes. + EmptyFrame, + /// The frame is not in the form its codec needs. + BadFrame(&'static str), + /// The frame is larger than its codec allows. + FrameTooLarge { + /// Bytes in the frame. + size: usize, + /// Most bytes the frame may have. + limit: usize, + }, + /// The frame's timestamps are not valid. + Timestamp(&'static str), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Io(e) => write!(f, "I/O: {e}"), + Error::Config(s) => write!(f, "transport stream settings: {s}"), + Error::BadPid(pid) => write!(f, "PID 0x{pid:04X} is outside 0x0010 to 0x1FFE"), + Error::DuplicatePid(pid) => write!(f, "PID 0x{pid:04X} is used twice"), + Error::PsiTooLarge { length } => write!(f, "the program map section would be {length} bytes long; the limit is 1021"), + Error::PcrDelay(d) => write!(f, "a PCR delay of {d} ticks is outside 1 to {MAX_PCR_DELAY}"), + Error::NoSuchStream(i) => write!(f, "no stream {i}"), + Error::EmptyFrame => write!(f, "the frame is empty"), + Error::BadFrame(s) => write!(f, "{s}"), + Error::FrameTooLarge { size, limit } => write!(f, "the frame is {size} bytes; the limit is {limit}"), + Error::Timestamp(s) => write!(f, "{s}"), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Io(e) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: io::Error) -> Self { + Error::Io(e) + } +} + +/// Result alias for the writer. +pub type Result = std::result::Result; + +/// The fields of the AV1 video descriptor (Carriage of AV1 in MPEG-2 TS, §2.2), taken from the +/// stream's sequence header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Av1Config { + /// seq_profile, 0 to 2. + pub seq_profile: u8, + /// `seq_level_idx[0]`, 0 to 31. + pub seq_level_idx_0: u8, + /// `seq_tier[0]`. + pub seq_tier_0: bool, + /// high_bitdepth. + pub high_bitdepth: bool, + /// twelve_bit. + pub twelve_bit: bool, + /// mono_chrome. + pub monochrome: bool, + /// subsampling_x. + pub chroma_subsampling_x: bool, + /// subsampling_y. + pub chroma_subsampling_y: bool, + /// chroma_sample_position, 0 to 3. + pub chroma_sample_position: u8, + /// 0 SDR, 1 wide color gamut, 2 HDR and wide color gamut, 3 no indication. + pub hdr_wcg_idc: u8, +} + +impl Av1Config { + /// The fields from the first four bytes of an ISOBMFF `av1C` record (marker and version 1), + /// with `hdr_wcg_idc` 3 (no indication). + pub fn from_av1c(record: &[u8]) -> Result { + let &[b0, b1, b2, _, ..] = record else { return Err(Error::Config("an av1C record has at least four bytes".into())) }; + if b0 != 0x81 { + return Err(Error::Config("an av1C record has at least four bytes and starts with marker 1 and version 1".into())); + } + let c = Self { + seq_profile: b1 >> 5, + seq_level_idx_0: b1 & 0x1F, + seq_tier_0: b2 & 0x80 != 0, + high_bitdepth: b2 & 0x40 != 0, + twelve_bit: b2 & 0x20 != 0, + monochrome: b2 & 0x10 != 0, + chroma_subsampling_x: b2 & 0x08 != 0, + chroma_subsampling_y: b2 & 0x04 != 0, + chroma_sample_position: b2 & 3, + hdr_wcg_idc: 3, + }; + c.check().map_err(Error::Config)?; + Ok(c) + } + + fn check(&self) -> std::result::Result<(), String> { + if self.seq_profile > 2 { + return Err(format!("AV1 seq_profile {} is not 0 to 2", self.seq_profile)); + } + if self.seq_level_idx_0 > 31 || self.chroma_sample_position > 3 || self.hdr_wcg_idc > 3 { + return Err("an AV1 descriptor field is out of range".into()); + } + Ok(()) + } +} + +/// An Opus channel configuration coded in full (channel_config_code 0x81 of the Opus transport +/// draft): the channel mapping family, the stream counts and the channel mapping. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OpusMapping { + /// Output channels, 1 to 8. + pub channels: u8, + /// Channel mapping family (RFC 7845 §5.1.1): 0 for one mono or stereo stream, 1 for the + /// standard surround orders, 255 for an application-defined order. Other families are + /// refused. + pub family: u8, + /// Opus streams in each access unit, 1 to `channels` (1 for family 0). + pub streams: u8, + /// Streams that decode to two channels, at most `streams` (`channels - 1` for family 0). + pub coupled: u8, + /// For each output channel, the coded channel it is taken from (below `streams + coupled`), + /// or 255 for silence. Entries past `channels` are ignored. Family 0 carries no mapping in + /// the descriptor, so its entries must be 0 and 1. + pub mapping: [u8; 8], +} + +impl OpusMapping { + fn check(&self) -> std::result::Result<(), String> { + let ch = usize::from(self.channels); + if !(1..=8).contains(&ch) { + return Err(format!("{ch} Opus channels; 1 to 8 are supported")); + } + if self.family == 0 { + if ch > 2 || self.streams != 1 || u16::from(self.coupled) + 1 != u16::from(self.channels) { + return Err("Opus mapping family 0 is one stream of 1 or 2 channels".into()); + } + // the descriptor carries no mapping for family 0: the channels are in coded order + if self.mapping[..ch].iter().enumerate().any(|(i, &m)| usize::from(m) != i) { + return Err("Opus mapping family 0 keeps the channels in coded order (mapping 0, 1)".into()); + } + return Ok(()); + } + if !matches!(self.family, 1 | 255) { + return Err(format!("Opus mapping family {}; 0, 1 and 255 are supported", self.family)); + } + if self.streams == 0 || self.streams > self.channels || self.coupled > self.streams { + return Err("Opus streams are 1 to the channel count, and coupled streams at most the stream count".into()); + } + let coded = self.streams + self.coupled; + if self.mapping[..ch].iter().any(|&m| m >= coded && m != 255) { + return Err("an Opus channel mapping entry names a coded channel that does not exist".into()); + } + Ok(()) + } +} + +/// What an elementary stream carries, and the form its frames take. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Codec { + /// H.264 access units in Annex B form, with the parameter sets on keyframes. An access unit + /// delimiter is added when a frame does not start with one. + H264, + /// HEVC access units in Annex B form, with the parameter sets on keyframes. An access unit + /// delimiter is added when a frame does not start with one. + Hevc, + /// MPEG-1 video pictures (ISO/IEC 11172-2), from their first start code. + Mpeg1Video, + /// MPEG-2 video pictures, from their first start code. + Mpeg2Video, + /// MPEG-4 Part 2 visual frames (ISO/IEC 14496-2), from their first start code. + Mpeg4Part2, + /// AV1 temporal units in the low overhead bitstream format (every OBU with its size field), + /// with a sequence header on keyframes. Each OBU is written after a start code with emulation + /// prevention. Temporal delimiters, and padding OBUs that end with a zero byte, are left out + /// (Carriage of AV1 in MPEG-2 TS). + Av1(Av1Config), + /// AAC frames that already carry their ADTS headers; one call may pass several frames. + AacAdts, + /// Raw AAC frames; each one gets an ADTS header built from these fields. + Aac { + /// Audio object type, 1 to 4 (2 is AAC LC). + object_type: u8, + /// Sampling frequency index, 0 to 12 (3 is 48 kHz). + sample_rate_index: u8, + /// Channel configuration, 1 to 7. + channels: u8, + }, + /// Opus access units, one per frame; each gets an Opus control header. For 1 or 2 channels + /// the access unit is one Opus packet. For 3 to 8 channels it holds the streams of mapping + /// family 1 in the order the Opus transport draft's table 4-3 gives, all but the last + /// self-delimited; use [`Codec::OpusMapped`] for any other layout. + Opus { + /// Channel count, 1 to 8. + channels: u8, + }, + /// Opus access units with a channel configuration given in full. + OpusMapped(OpusMapping), + /// AC-3 sync frames. + Ac3, + /// E-AC-3 sync frames (bsid 11 to 16). + Eac3, + /// MPEG-1 or MPEG-2 audio frames, layers I to III (MP2, MP3). + MpegAudio { + /// The stream uses the MPEG-2 low sampling frequencies (16, 22.05 and 24 kHz) or the + /// lower MPEG 2.5 rates. Each frame's version bits must agree. + low_sample_rate: bool, + }, +} + +impl Codec { + /// The PMT stream_type. + pub fn stream_type(self) -> u8 { + match self { + Codec::H264 => 0x1B, + Codec::Hevc => 0x24, + Codec::Mpeg1Video => 0x01, + Codec::Mpeg2Video => 0x02, + Codec::Mpeg4Part2 => 0x10, + Codec::AacAdts | Codec::Aac { .. } => 0x0F, + Codec::Av1(_) | Codec::Opus { .. } | Codec::OpusMapped(_) => 0x06, + Codec::Ac3 => 0x81, + Codec::Eac3 => 0x87, + Codec::MpegAudio { low_sample_rate: false } => 0x03, + Codec::MpegAudio { low_sample_rate: true } => 0x04, + } + } + + /// The PES stream_id. + pub fn stream_id(self) -> u8 { + match self { + Codec::H264 | Codec::Hevc | Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 => 0xE0, + Codec::AacAdts | Codec::Aac { .. } | Codec::MpegAudio { .. } => 0xC0, + Codec::Av1(_) | Codec::Opus { .. } | Codec::OpusMapped(_) | Codec::Ac3 | Codec::Eac3 => 0xBD, + } + } + + /// The stream carries pictures. + pub fn is_video(self) -> bool { + matches!(self, Codec::H264 | Codec::Hevc | Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 | Codec::Av1(_)) + } + + fn is_opus(self) -> bool { + matches!(self, Codec::Opus { .. } | Codec::OpusMapped(_)) + } + + /// Raw AAC described by an AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1). Configurations + /// that an ADTS header cannot carry are refused: an object type outside 1 to 4 (SBR and PS + /// signaled explicitly included), an explicit sampling frequency, channel configuration 0, + /// and frameLengthFlag 1 (960-sample frames). + pub fn aac_from_asc(asc: &[u8]) -> Result { + let &[a, b, ..] = asc else { return Err(Error::Config("an AudioSpecificConfig has at least two bytes".into())) }; + let object_type = a >> 3; + let sample_rate_index = (a & 7) << 1 | b >> 7; + let channels = (b >> 3) & 0x0F; + let codec = Codec::Aac { object_type, sample_rate_index, channels }; + codec.check().map_err(Error::Config)?; + // GASpecificConfig's frameLengthFlag follows the channel configuration (ISO/IEC 14496-3 §4.4.1). + if b & 0x04 != 0 { + return Err(Error::Config("AAC frameLengthFlag 1 (960-sample frames) cannot be carried by an ADTS header".into())); + } + Ok(codec) + } + + fn check(self) -> std::result::Result<(), String> { + match self { + Codec::Aac { object_type, sample_rate_index, channels } => { + if !(1..=4).contains(&object_type) { + return Err(format!("AAC object type {object_type} is not 1 to 4")); + } + if sample_rate_index > 12 { + return Err(format!("AAC sampling frequency index {sample_rate_index} is not 0 to 12")); + } + if !(1..=7).contains(&channels) { + return Err(format!("AAC channel configuration {channels} is not 1 to 7")); + } + Ok(()) + } + Codec::Opus { channels } if !(1..=8).contains(&channels) => Err(format!("{channels} Opus channels; 1 to 8 are supported")), + Codec::OpusMapped(m) => m.check(), + Codec::Av1(c) => c.check(), + _ => Ok(()), + } + } +} + +/// One elementary stream of the program. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stream { + /// The PID its packets carry, 0x0010 to 0x1FFE. + pub pid: u16, + /// What it carries. + pub codec: Codec, + /// ISO 639-2 language code (three lowercase letters), written as a language descriptor. + pub language: Option<[u8; 3]>, +} + +impl Stream { + /// A stream on `pid` without a language. + pub fn new(pid: u16, codec: Codec) -> Self { + Self { pid, codec, language: None } + } + + /// The same stream with a language code. + pub fn with_language(mut self, language: [u8; 3]) -> Self { + self.language = Some(language); + self + } +} + +/// Program, timing and output settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Config { + /// transport_stream_id in the program association section. + pub transport_stream_id: u16, + /// program_number, not 0. + pub program_number: u16, + /// The PID of the program map section, 0x0010 to 0x1FFE. + pub pmt_pid: u16, + /// The PID that carries the PCR: one of the streams' PIDs, or a PID of its own. + /// `None` uses the first video stream, or the first stream when there is no video. + pub pcr_pid: Option, + /// Largest gap between PCRs, 90 kHz ticks, 1 to [`MAX_PCR_INTERVAL`]. + pub pcr_interval: u32, + /// How far the PCR runs behind the largest DTS so far, 90 kHz ticks, 1 to + /// [`MAX_PCR_DELAY`]. It is also the largest skew between streams (see the crate docs). + pub pcr_delay: u32, + /// How often the PAT and PMT are repeated, 90 kHz ticks, at least 1. + pub psi_interval: u32, + /// Repeat the PAT and PMT before every video keyframe, so each keyframe starts a segment that + /// decodes on its own. + pub psi_before_keyframes: bool, + /// Packets collected before one write to the output, 1 to [`MAX_BATCH_PACKETS`]. + pub batch_packets: u16, + /// Keep a partly filled batch between calls instead of writing it at the end of each + /// [`Muxer::write_frame`] and [`Muxer::advance`]. For file outputs; [`Muxer::flush`], + /// [`Muxer::replace_writer`] and [`Muxer::finish`] still write it. + pub hold_packets: bool, +} + +impl Default for Config { + /// Program 1 with its PMT on PID 0x1000; the PCR at most 40 ms apart and 700 ms behind the + /// DTS; the PAT and PMT every 100 ms and before keyframes; writes of 7 packets, and the rest + /// at the end of every call. + fn default() -> Self { + Self { + transport_stream_id: 1, + program_number: 1, + pmt_pid: 0x1000, + pcr_pid: None, + pcr_interval: 3_600, + pcr_delay: 63_000, + psi_interval: 9_000, + psi_before_keyframes: true, + batch_packets: 7, + hold_packets: false, + } + } +} + +/// One frame to write. +#[derive(Clone, Copy, Debug)] +pub struct Frame<'a> { + /// The coded frame. + pub data: &'a [u8], + /// Presentation time, 90 kHz ticks. + pub pts: i64, + /// Decoding time, 90 kHz ticks; `None` when it equals `pts`. Never after `pts`, never before + /// the stream's previous DTS (for video, always after it), and never behind the clock: the + /// largest DTS so far, or the largest time given to [`Muxer::advance`], minus + /// [`Config::pcr_delay`]. + pub dts: Option, + /// Decoding can start at this frame (an IDR or other random access picture; any audio frame). + pub key: bool, +} + +/// Samples to discard from an Opus access unit, at 48 kHz (the Opus control header's start_trim +/// and end_trim). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OpusTrim { + /// Samples discarded from the start: the encoder's pre-skip, on the first access units of a + /// stream only, 65 535 in all. + pub start: u16, + /// Samples discarded from the end, on the last access unit. + pub end: u16, +} + +/// Counts of what has been written. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Stats { + /// Transport stream packets the outputs took whole. Packets still in the batch, and packets + /// dropped after an I/O error, are not counted. + pub packets: u64, + /// Frames. + pub frames: u64, + /// Times the PAT and PMT were written. + pub psi: u64, + /// PCRs, in frames' packets and in packets of their own. + pub pcrs: u64, + /// Gaps in the timeline longer than [`MAX_PCR_FILL`] PCR intervals. + pub pcr_gaps: u64, +} + +impl Stats { + /// Bytes written. + pub fn bytes(&self) -> u64 { + self.packets.saturating_mul(PACKET_SIZE as u64) + } +} + +/// What one output received, returned when [`Muxer::replace_writer`] or +/// [`Muxer::replace_writer_continuing`] closes it. An HLS packager reads the segment's duration +/// and independence from it. +#[derive(Debug)] +pub struct Segment { + /// The output. + pub writer: W, + /// Transport stream packets it took whole. After an error it may also hold part of a packet. + pub packets: u64, + /// Frames written to it. + pub frames: u64, + /// PTS of its first frame. + pub first_pts: Option, + /// Largest PTS of its frames. + pub last_pts: Option, + /// Its first video frame is a keyframe (with no video stream: it holds a frame), so it + /// decodes on its own when it also starts with the tables. + pub starts_with_keyframe: bool, + /// Writing the last packets to it, or flushing it, failed; those packets are lost. + pub error: Option, +} + +struct State { + pid: u16, + codec: Codec, + /// The counter the next packet with a payload carries. + cc: u8, + last_dts: Option, + /// The next packet carries the discontinuity indicator. + disc: bool, + /// Every Opus access unit so far was discarded whole by its start trim. + opus_lead_in: bool, + /// Opus samples discarded by start trims so far. + opus_start_trimmed: u32, +} + +impl State { + /// The counter an adaptation-field-only packet carries: the one before the next payload + /// packet's (§2.4.3.3), so the counter goes up by one at the next payload packet. + fn held_cc(&self) -> u8 { + self.cc.wrapping_sub(1) & 0x0F + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum PcrOn { + Stream(usize), + Own(u16), +} + +/// The output and the batch of packets waiting for it. +struct Sink { + out: W, + batch: Vec, + cap: usize, + /// Whole packets the output has taken. + packets: u64, + /// A mark that moves with every packet built and every batch dropped after an error, so + /// the muxer can tell whether given packets are still the last ones the output gets. + pushed: u64, +} + +impl Sink { + fn push(&mut self, p: &[u8; PACKET_SIZE]) -> io::Result<()> { + self.pushed += 1; + self.batch.extend_from_slice(p); + if self.batch.len() >= self.cap { self.drain() } else { Ok(()) } + } + + /// Writes the batch, counting the whole packets the output takes. On an error the rest of the + /// batch is dropped. + fn drain(&mut self) -> io::Result<()> { + let mut done = 0; + let mut r = Ok(()); + while done < self.batch.len() { + match self.out.write(&self.batch[done..]) { + Ok(0) => { + r = Err(io::Error::from(io::ErrorKind::WriteZero)); + break; + } + Ok(n) => done += n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => { + r = Err(e); + break; + } + } + } + self.packets += (done / PACKET_SIZE) as u64; + if r.is_err() && done < self.batch.len() { + self.pushed += 1; + } + self.batch.clear(); + r + } +} + +/// What the current output has received. +#[derive(Default)] +struct SegState { + start_packets: u64, + frames: u64, + first_pts: Option, + last_pts: Option, + first_video_key: Option, +} + +/// The bytes of a frame after its PES header and prefix. +enum Payload<'a> { + Plain(&'a [u8]), + Av1(av1::Escaper<'a>), +} + +impl Payload<'_> { + /// Fills `out` as far as the payload goes; returns the bytes written. + fn fill(&mut self, out: &mut [u8]) -> usize { + match self { + Payload::Plain(d) => { + let n = d.len().min(out.len()); + out[..n].copy_from_slice(&d[..n]); + *d = &d[n..]; + n + } + Payload::Av1(e) => e.fill(out), + } + } +} + +/// Writes one program as a transport stream. +pub struct Muxer { + sink: Sink, + cfg: Config, + streams: Vec, + has_video: bool, + pat: Vec, + pmt: Vec, + pat_cc: u8, + pmt_cc: u8, + pcr_on: PcrOn, + /// The next PCR on a PID of its own carries the discontinuity indicator. + own_pcr_disc: bool, + /// The 27 MHz clock: the largest DTS so far minus the PCR delay. + clock: Option, + last_pcr: Option, + last_psi: Option, + /// [`Sink::pushed`] right after the last PAT and PMT; `None` once something else may follow + /// them. + psi_end: Option, + psi_forced: bool, + /// The next frame or advance writes a PCR whatever the interval (a new writer). + pcr_forced: bool, + stats: Stats, + seg: SegState, +} + +fn check_pid(pid: u16) -> Result<()> { + if (0x0010..=0x1FFE).contains(&pid) { Ok(()) } else { Err(Error::BadPid(pid)) } +} + +impl Muxer { + /// A muxer for `streams` writing to `out`. Nothing is written until the first frame or + /// [`Muxer::advance`]. + pub fn new(out: W, cfg: Config, streams: &[Stream]) -> Result { + if streams.is_empty() || streams.len() > MAX_STREAMS { + return Err(Error::Config(format!("{} streams; 1 to {MAX_STREAMS} are supported", streams.len()))); + } + if cfg.program_number == 0 { + return Err(Error::Config("program number 0 is reserved for the network PID".into())); + } + check_pid(cfg.pmt_pid)?; + if !(1..=MAX_PCR_INTERVAL).contains(&cfg.pcr_interval) { + return Err(Error::Config(format!("a PCR interval of {} ticks is outside 1 to {MAX_PCR_INTERVAL}", cfg.pcr_interval))); + } + if !(1..=MAX_PCR_DELAY).contains(&cfg.pcr_delay) { + return Err(Error::PcrDelay(cfg.pcr_delay)); + } + if cfg.psi_interval == 0 { + return Err(Error::Config("the PAT and PMT interval must be at least 1 tick".into())); + } + if !(1..=MAX_BATCH_PACKETS).contains(&cfg.batch_packets) { + return Err(Error::Config(format!("a batch of {} packets is outside 1 to {MAX_BATCH_PACKETS}", cfg.batch_packets))); + } + for (i, s) in streams.iter().enumerate() { + check_pid(s.pid)?; + if s.pid == cfg.pmt_pid || streams[..i].iter().any(|t| t.pid == s.pid) { + return Err(Error::DuplicatePid(s.pid)); + } + s.codec.check().map_err(Error::Config)?; + if let Some(l) = s.language + && !l.iter().all(u8::is_ascii_lowercase) + { + return Err(Error::Config("a language code is three lowercase letters".into())); + } + } + let pcr_on = match cfg.pcr_pid { + Some(pid) => { + check_pid(pid)?; + if pid == cfg.pmt_pid { + return Err(Error::DuplicatePid(pid)); + } + streams.iter().position(|s| s.pid == pid).map_or(PcrOn::Own(pid), PcrOn::Stream) + } + None => PcrOn::Stream(streams.iter().position(|s| s.codec.is_video()).unwrap_or(0)), + }; + let pcr_pid = match pcr_on { + PcrOn::Stream(i) => streams.get(i).map_or(0x1FFF, |s| s.pid), + PcrOn::Own(pid) => pid, + }; + let cap = usize::from(cfg.batch_packets) * PACKET_SIZE; + Ok(Self { + sink: Sink { out, batch: Vec::with_capacity(cap), cap, packets: 0, pushed: 0 }, + cfg, + streams: streams + .iter() + .map(|s| State { pid: s.pid, codec: s.codec, cc: 0, last_dts: None, disc: false, opus_lead_in: true, opus_start_trimmed: 0 }) + .collect(), + has_video: streams.iter().any(|s| s.codec.is_video()), + pat: psi::pat(cfg.transport_stream_id, cfg.program_number, cfg.pmt_pid)?, + pmt: psi::pmt(cfg.program_number, pcr_pid, streams)?, + pat_cc: 0, + pmt_cc: 0, + pcr_on, + own_pcr_disc: false, + clock: None, + last_pcr: None, + last_psi: None, + psi_end: None, + psi_forced: false, + pcr_forced: false, + stats: Stats::default(), + seg: SegState::default(), + }) + } + + /// The PID that carries the PCR. + pub fn pcr_pid(&self) -> u16 { + match self.pcr_on { + PcrOn::Stream(i) => self.streams.get(i).map_or(0x1FFF, |s| s.pid), + PcrOn::Own(pid) => pid, + } + } + + /// What has been written so far. + pub fn stats(&self) -> Stats { + Stats { packets: self.sink.packets, ..self.stats } + } + + /// The output. + pub fn get_ref(&self) -> &W { + &self.sink.out + } + + /// The output, for writing between packets. With [`Config::hold_packets`] set, call + /// [`Muxer::flush`] first so no held packet follows what is written here. + pub fn get_mut(&mut self) -> &mut W { + // what the caller writes may separate the last tables from the next keyframe + self.psi_end = None; + &mut self.sink.out + } + + /// Writes the held packets and flushes the output. + pub fn flush(&mut self) -> Result<()> { + self.sink.drain()?; + self.sink.out.flush()?; + Ok(()) + } + + /// Closes the current output for a new segment and sends the following packets to `out`. + /// The held packets go to the old output first, and it is flushed. The new output starts with + /// the PAT and PMT, and the next frame (or [`Muxer::advance`]) writes a PCR; continuity + /// counters and the clock carry on. To start every segment with a keyframe, call this right + /// before writing a video keyframe. + pub fn replace_writer(&mut self, out: W) -> Segment { + self.swap(out, true) + } + + /// Like [`Muxer::replace_writer`], but the packet flow is unchanged: no tables or PCR are + /// added, so the outputs joined end to end hold the same bytes as one output would. For the + /// parts of a low-latency HLS segment. + pub fn replace_writer_continuing(&mut self, out: W) -> Segment { + self.swap(out, false) + } + + fn swap(&mut self, out: W, restart: bool) -> Segment { + let error = self.sink.drain().err().or_else(|| self.sink.out.flush().err()); + if restart { + self.psi_forced = true; + self.pcr_forced = true; + } + let writer = std::mem::replace(&mut self.sink.out, out); + let seg = std::mem::replace(&mut self.seg, SegState { start_packets: self.sink.packets, ..SegState::default() }); + let starts_with_keyframe = if self.has_video { seg.first_video_key.unwrap_or(false) } else { seg.frames > 0 }; + Segment { + writer, + packets: self.sink.packets - seg.start_packets, + frames: seg.frames, + first_pts: seg.first_pts, + last_pts: seg.last_pts, + starts_with_keyframe, + error, + } + } + + /// Writes the PAT and PMT before the next frame. + pub fn repeat_psi(&mut self) { + self.psi_forced = true; + } + + /// Starts a new time base, for an encoder or source that restarts with timestamps that do not + /// follow the old ones. The clock and every stream's previous DTS are forgotten, the next + /// packet of every stream PID and of the PCR PID carries the discontinuity indicator + /// (§2.4.3.5), and the next frame or [`Muxer::advance`] writes the PAT, the PMT and a PCR of + /// the new time base first. Continuity counters carry on. An Opus stream may carry a start + /// trim again, as at its start. + pub fn discontinuity(&mut self) { + self.clock = None; + self.last_pcr = None; + self.last_psi = None; + self.psi_forced = true; + self.pcr_forced = true; + self.own_pcr_disc = matches!(self.pcr_on, PcrOn::Own(_)); + for s in &mut self.streams { + s.last_dts = None; + s.disc = true; + // a restarted Opus encoder starts with its own pre-skip + s.opus_lead_in = true; + s.opus_start_trimmed = 0; + } + } + + /// Writes the held packets, flushes and returns the output. A transport stream has no + /// trailer. + pub fn finish(mut self) -> Result { + self.flush()?; + Ok(self.sink.out) + } + + /// The 27 MHz clock value for a DTS. + fn time(&self, dts: i64) -> Result { + dts.checked_sub(i64::from(self.cfg.pcr_delay)).and_then(|v| v.checked_mul(300)).ok_or(Error::Timestamp("the timestamp is out of range")) + } + + /// Writes the batch unless the configuration holds packets between calls. + fn end_call(&mut self) -> Result<()> { + if !self.cfg.hold_packets { + self.sink.drain()?; + } + Ok(()) + } + + /// Moves the clock without a frame, writing the PCRs and the PAT and PMT that fall due. A + /// live output calls this while no frames arrive, so the PCR stays within its interval. + /// + /// `time` is on the DTS scale (90 kHz): the PCR sent is `time - pcr_delay`, the clock a + /// frame with DTS `time` would set. After `advance(t)`, frames whose DTS is below + /// `t - pcr_delay` are refused. A time behind the clock has no effect. + pub fn advance(&mut self, time: i64) -> Result<()> { + let r = self.advance_inner(time); + let end = self.end_call(); + r.and(end) + } + + fn advance_inner(&mut self, time: i64) -> Result<()> { + let t = self.time(time)?; + let clock = self.clock.map_or(t, |c| c.max(t)); + self.clock = Some(clock); + self.fill_pcr(clock)?; + self.psi_if_due(clock, false)?; + if self.pcr_due(clock) { + self.pcr_packet(clock)?; + } + Ok(()) + } + + /// A PCR packet is due: none yet, a new writer, or the interval has passed. + fn pcr_due(&self, clock: i64) -> bool { + self.pcr_forced || self.last_pcr.is_none_or(|l| clock.saturating_sub(l) >= self.limit()) + } + + /// Writes one frame of stream `index` (an index into the list given to [`Muxer::new`]). + /// The frame is checked before anything is written. + pub fn write_frame(&mut self, index: usize, frame: &Frame<'_>) -> Result<()> { + self.write_frame_with_trim(index, frame, OpusTrim::default()) + } + + /// Writes one Opus frame whose control header carries `trim`. A start trim is allowed only + /// while every earlier access unit of the stream (since the start or the last + /// [`Muxer::discontinuity`]) was discarded whole, and the trims of one + /// access unit cannot exceed its duration. A zero trim writes a plain frame, for any codec. + pub fn write_frame_with_trim(&mut self, index: usize, frame: &Frame<'_>, trim: OpusTrim) -> Result<()> { + let r = self.write_inner(index, frame, trim); + let end = self.end_call(); + r.and(end) + } + + fn write_inner(&mut self, index: usize, frame: &Frame<'_>, trim: OpusTrim) -> Result<()> { + let st = self.streams.get(index).ok_or(Error::NoSuchStream(index))?; + if frame.data.is_empty() { + return Err(Error::EmptyFrame); + } + let codec = st.codec; + let dts = frame.dts.unwrap_or(frame.pts); + if dts > frame.pts { + return Err(Error::Timestamp("the decoding time is after the presentation time")); + } + if let Some(l) = st.last_dts { + if dts < l { + return Err(Error::Timestamp("the decoding time is before the stream's previous one")); + } + if dts == l && codec.is_video() { + return Err(Error::Timestamp("a video frame's decoding time must be after the stream's previous one")); + } + } + let trimmed = trim != OpusTrim::default(); + let mut duration = 0; + if trimmed { + if !codec.is_opus() { + return Err(Error::BadFrame("only Opus frames carry trims")); + } + if trim.start > MAX_OPUS_TRIM || trim.end > MAX_OPUS_TRIM { + return Err(Error::BadFrame("an Opus trim is at most 8191 samples")); + } + if trim.start > 0 && (!st.opus_lead_in || st.opus_start_trimmed + u32::from(trim.start) > 0xFFFF) { + return Err(Error::BadFrame("a start trim is allowed only at the start of an Opus stream, 65 535 samples in all")); + } + duration = pes::opus_samples(frame.data).ok_or(Error::BadFrame("the Opus packet's table of contents is incomplete"))?; + if u32::from(trim.start) + u32::from(trim.end) > duration { + return Err(Error::BadFrame("the trim is longer than the Opus access unit")); + } + } + let with_dts = dts != frame.pts; + let header_len = if with_dts { 19 } else { 14 }; + let trim_bytes = if trim.start > 0 { 2 } else { 0 } + if trim.end > 0 { 2 } else { 0 }; + let limit = pes::data_limit(codec, header_len - 6, trim_bytes); + if frame.data.len() > limit { + return Err(Error::FrameTooLarge { size: frame.data.len(), limit }); + } + let mut prefix = [0u8; pes::PREFIX_MAX]; + let prep = pes::prepare(codec, frame.data, frame.key, trim, &mut prefix)?; + // start codes, escapes and delimiters count toward the reader's limit too + let encoded = prep.prefix_len.saturating_add(prep.body_len); + if codec.is_video() && encoded > MAX_VIDEO_FRAME { + return Err(Error::FrameTooLarge { size: encoded, limit: MAX_VIDEO_FRAME }); + } + // bytes after PES_packet_length + let body = (header_len - 6) + prep.prefix_len + prep.body_len; + let length = match u16::try_from(body) { + Ok(n) => n, + Err(_) if codec.is_video() => 0, + Err(_) => return Err(Error::FrameTooLarge { size: frame.data.len(), limit }), + }; + let t = self.time(dts)?; + // the frame must arrive no later than it decodes: its DTS may not be behind the clock + // that PCRs already sent (the largest DTS so far minus the PCR delay, or an advance) + if dts.checked_mul(300).is_none_or(|d| self.clock.is_some_and(|c| d < c)) { + return Err(Error::Timestamp("the decoding time is behind the transport stream clock")); + } + let mut header = [0u8; pes::HEADER_MAX]; + pes::header(&mut header, codec.stream_id(), length, frame.pts, with_dts.then_some(dts)); + + let clock = self.clock.map_or(t, |c| c.max(t)); + self.clock = Some(clock); + self.fill_pcr(clock)?; + // a keyframe needs the tables right in front of it: not again when they are the last + // packets written, but again when PCRs filling a gap came after them + let tables_last = self.psi_end == Some(self.sink.pushed); + self.psi_if_due(clock, frame.key && codec.is_video() && !tables_last)?; + let mut pcr = None; + if self.pcr_on == PcrOn::Stream(index) { + if self.pcr_forced || self.last_pcr.is_none_or(|l| clock > l) { + pcr = Some(clock); + self.last_pcr = Some(clock); + self.pcr_forced = false; + self.stats.pcrs += 1; + } + } else if self.pcr_due(clock) { + self.pcr_packet(clock)?; + } + let payload = match codec { + Codec::Av1(_) => Payload::Av1(av1::Escaper::new(frame.data)), + _ => Payload::Plain(frame.data), + }; + self.pes_packets(index, &header[..header_len], &prefix[..prep.prefix_len], payload, prep.body_len, pcr, frame.key)?; + if let Some(st) = self.streams.get_mut(index) { + st.last_dts = Some(dts); + if codec.is_opus() { + st.opus_start_trimmed += u32::from(trim.start); + if !trimmed || u32::from(trim.start) < duration { + st.opus_lead_in = false; + } + } + } + self.stats.frames += 1; + let seg = &mut self.seg; + seg.frames += 1; + seg.first_pts.get_or_insert(frame.pts); + seg.last_pts = Some(seg.last_pts.map_or(frame.pts, |p| p.max(frame.pts))); + if codec.is_video() { + seg.first_video_key.get_or_insert(frame.key); + } + Ok(()) + } + + /// The PCR interval at 27 MHz. + fn limit(&self) -> i64 { + i64::from(self.cfg.pcr_interval) * 300 + } + + fn psi_if_due(&mut self, clock: i64, keyframe: bool) -> Result<()> { + let due = self.psi_forced + || self.last_psi.is_none_or(|l| clock.saturating_sub(l) >= i64::from(self.cfg.psi_interval) * 300) + || (keyframe && self.cfg.psi_before_keyframes); + if due { + section_packets(&mut self.sink, 0, &mut self.pat_cc, &self.pat)?; + section_packets(&mut self.sink, self.cfg.pmt_pid, &mut self.pmt_cc, &self.pmt)?; + self.last_psi = Some(clock); + self.psi_end = Some(self.sink.pushed); + self.psi_forced = false; + self.stats.psi += 1; + } + Ok(()) + } + + /// Fills the gap up to `clock`: PCR-only packets until the gap to `clock` is within the PCR + /// interval, and the PAT and PMT wherever they fall due before `clock`, in time order. A new + /// writer gets the PAT and PMT before anything else. + fn fill_pcr(&mut self, clock: i64) -> Result<()> { + let Some(last_pcr) = self.last_pcr else { return Ok(()) }; + if self.psi_forced { + self.psi_if_due(last_pcr, false)?; + } + let limit = self.limit(); + let psi = i64::from(self.cfg.psi_interval) * 300; + // each kind of packet is capped on its own, so a short PAT and PMT interval cannot use + // up the PCRs' share + let (mut pcrs, mut tables) = (0, 0); + loop { + let mut pcr_at = self.last_pcr.map(|l| l.saturating_add(limit)).filter(|&t| t < clock); + if pcrs >= MAX_PCR_FILL && pcr_at.is_some() { + if pcrs == MAX_PCR_FILL { + // counted once: the PCR at `clock` that follows closes the gap + self.stats.pcr_gaps += 1; + pcrs += 1; + } + pcr_at = None; + } + let psi_at = self.last_psi.map(|l| l.saturating_add(psi)).filter(|&t| t < clock && tables < MAX_PCR_FILL); + match (psi_at, pcr_at) { + (Some(s), Some(p)) if s <= p => { + self.psi_if_due(s, false)?; + tables += 1; + } + (Some(s), None) => { + self.psi_if_due(s, false)?; + tables += 1; + } + (_, Some(p)) => { + self.pcr_packet(p)?; + pcrs += 1; + } + (None, None) => return Ok(()), + } + } + } + + /// A packet on the PCR PID with only an adaptation field holding the PCR. + fn pcr_packet(&mut self, pcr: i64) -> Result<()> { + let (pid, cc, disc) = match self.pcr_on { + PcrOn::Stream(i) => match self.streams.get_mut(i) { + Some(s) => (s.pid, s.held_cc(), std::mem::take(&mut s.disc)), + None => (0x1FFF, 0, false), + }, + PcrOn::Own(pid) => (pid, 0, std::mem::take(&mut self.own_pcr_disc)), + }; + let mut b = [0xFF; PACKET_SIZE]; + b[..6].copy_from_slice(&[0x47, (pid >> 8) as u8 & 0x1F, pid as u8, 0x20 | cc, 183, 0x10 | if disc { 0x80 } else { 0 }]); + b[6..12].copy_from_slice(&pes::pcr(pcr)); + self.sink.push(&b)?; + self.stats.pcrs += 1; + self.last_pcr = Some(pcr); + self.pcr_forced = false; + Ok(()) + } + + /// Splits one PES packet (`header`, `prefix`, then `body_len` bytes of `payload`) into + /// transport packets. + #[allow(clippy::too_many_arguments)] + fn pes_packets( + &mut self, + index: usize, + header: &[u8], + prefix: &[u8], + mut payload: Payload<'_>, + body_len: usize, + pcr: Option, + key: bool, + ) -> Result<()> { + let Some(st) = self.streams.get_mut(index) else { return Err(Error::NoSuchStream(index)) }; + let pid = st.pid; + let mut parts = [header, prefix]; + let mut left = header.len() + prefix.len() + body_len; + let mut first = true; + while left > 0 { + let pcr_here = if first { pcr } else { None }; + let rai = first && key; + let disc = first && st.disc; + let fixed = if pcr_here.is_some() || rai || disc { 2 + if pcr_here.is_some() { 6 } else { 0 } } else { 0 }; + let take = left.min(184 - fixed); + // the adaptation field, its length byte included + let af = 184 - take; + let mut b = [0u8; PACKET_SIZE]; + b[0] = 0x47; + b[1] = if first { 0x40 } else { 0 } | (pid >> 8) as u8 & 0x1F; + b[2] = pid as u8; + b[3] = if af > 0 { 0x30 } else { 0x10 } | st.cc; + st.cc = (st.cc + 1) & 0x0F; + if af > 0 { + b[4] = (af - 1) as u8; + if af > 1 { + b[5] = if disc { 0x80 } else { 0 } | if rai { 0x40 } else { 0 } | if pcr_here.is_some() { 0x10 } else { 0 }; + let mut p = 6; + if let Some(v) = pcr_here { + b[6..12].copy_from_slice(&pes::pcr(v)); + p = 12; + } + b[p..4 + af].fill(0xFF); + } + } + if disc { + st.disc = false; + } + let mut at = 4 + af; + for part in &mut parts { + let n = part.len().min(PACKET_SIZE - at); + b[at..at + n].copy_from_slice(&part[..n]); + *part = &part[n..]; + at += n; + } + if at < PACKET_SIZE { + payload.fill(&mut b[at..]); + } + self.sink.push(&b)?; + left -= take; + first = false; + } + Ok(()) + } +} + +/// Writes a PSI section on `pid`: a pointer field of 0, the section, and 0xFF stuffing. +fn section_packets(sink: &mut Sink, pid: u16, cc: &mut u8, section: &[u8]) -> Result<()> { + let mut rest = section; + let mut first = true; + while first || !rest.is_empty() { + let mut b = [0xFF; PACKET_SIZE]; + b[0] = 0x47; + b[1] = if first { 0x40 } else { 0 } | (pid >> 8) as u8 & 0x1F; + b[2] = pid as u8; + b[3] = 0x10 | *cc; + *cc = (*cc + 1) & 0x0F; + let mut at = 4; + if first { + b[4] = 0; + at = 5; + } + let n = rest.len().min(PACKET_SIZE - at); + b[at..at + n].copy_from_slice(&rest[..n]); + rest = &rest[n..]; + sink.push(&b)?; + first = false; + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/media/src/mpegts/mux/pes.rs b/crates/media/src/mpegts/mux/pes.rs new file mode 100644 index 000000000..89127c627 --- /dev/null +++ b/crates/media/src/mpegts/mux/pes.rs @@ -0,0 +1,389 @@ +//! PES packet headers (H.222.0 §2.4.3.6), the adaptation field's PCR (§2.4.3.4), and the bytes +//! written ahead of a frame: access unit delimiters, ADTS headers and Opus control headers. + +use super::{Codec, Error, MAX_VIDEO_FRAME, OpusTrim, av1}; + +/// 2^33: PTS, DTS and the PCR base are 33-bit counters. +pub(crate) const WRAP_90K: i64 = 1 << 33; + +/// Largest PES header this writer produces: 9 bytes, PTS and DTS. +pub(crate) const HEADER_MAX: usize = 19; + +/// Largest prefix: an Opus control header for a 65 535-byte packet (2 bytes, 257 size bytes, a +/// start and an end trim). +pub(crate) const PREFIX_MAX: usize = 2 + 0xFFFF / 255 + 1 + 4; + +/// What [`prepare`] found: the prefix it wrote, and the bytes the frame takes after it. +pub(crate) struct Prepared { + pub(crate) prefix_len: usize, + pub(crate) body_len: usize, +} + +/// Most frame bytes `codec` allows when the PES header has `header` bytes after +/// PES_packet_length and an Opus control header carries `trim` trim bytes. +pub(crate) fn data_limit(codec: Codec, header: usize, trim: usize) -> usize { + let room = 0xFFFF - header; + match codec { + c if c.is_video() => MAX_VIDEO_FRAME, + // ADTS frame_length is 13 bits + Codec::Aac { .. } => (0x1FFF - 7).min(room - 7), + Codec::Opus { .. } | Codec::OpusMapped(_) => { + // the control header takes 3 bytes, a size byte per 255 bytes, and the trims + let budget = room - 3 - trim; + let mut l = budget * 255 / 256; + while l + 1 + (l + 1) / 255 <= budget { + l += 1; + } + while l + l / 255 > budget { + l -= 1; + } + l + } + _ => room, + } +} + +/// Samples per channel at 48 kHz in an Opus packet, from its table of contents (RFC 6716 §3.1). +pub(crate) fn opus_samples(data: &[u8]) -> Option { + let toc = *data.first()?; + let config = usize::from(toc >> 3); + let frame = match config { + 0..=11 => [480, 960, 1920, 2880][config % 4], + 12..=15 => [480, 960][config % 2], + _ => [120, 240, 480, 960][config % 4], + }; + let count = match toc & 3 { + 0 => 1, + 1 | 2 => 2, + _ => u32::from(*data.get(1)? & 0x3F), + }; + Some(frame * count) +} + +/// Checks that an ADTS frame or a run of them fills `data` exactly. +fn check_adts(data: &[u8]) -> Result<(), Error> { + let mut at = 0; + while at < data.len() { + let f = &data[at..]; + let &[0xFF, b1, _, b3, b4, b5, _, ..] = f else { return Err(Error::BadFrame("an AAC frame must start with an ADTS header")) }; + if b1 & 0xF6 != 0xF0 { + return Err(Error::BadFrame("an AAC frame must start with an ADTS header")); + } + let header = if b1 & 1 == 0 { 9 } else { 7 }; + let len = usize::from(b3 & 3) << 11 | usize::from(b4) << 3 | usize::from(b5 >> 5); + if len < header || len > f.len() { + return Err(Error::BadFrame("an ADTS frame_length does not match the frame")); + } + at += len; + } + Ok(()) +} + +/// A 33-bit timestamp with its 4-bit prefix and marker bits (§2.4.3.7). +fn timestamp(prefix: u8, v: i64) -> [u8; 5] { + let v = v.rem_euclid(WRAP_90K); + [prefix << 4 | ((v >> 29) & 0x0E) as u8 | 1, (v >> 22) as u8, ((v >> 14) & 0xFE) as u8 | 1, (v >> 7) as u8, ((v << 1) & 0xFE) as u8 | 1] +} + +/// Writes a PES header into `out` and returns its length. `length` is the PES_packet_length field +/// (0 for an unbounded video packet). +pub(crate) fn header(out: &mut [u8; HEADER_MAX], stream_id: u8, length: u16, pts: i64, dts: Option) -> usize { + let [hi, lo] = length.to_be_bytes(); + // '10', not scrambled, no priority, data_alignment_indicator set, not copyrighted, a copy + out[..7].copy_from_slice(&[0, 0, 1, stream_id, hi, lo, 0x84]); + match dts { + Some(dts) => { + out[7] = 0xC0; + out[8] = 10; + out[9..14].copy_from_slice(×tamp(3, pts)); + out[14..19].copy_from_slice(×tamp(1, dts)); + 19 + } + None => { + out[7] = 0x80; + out[8] = 5; + out[9..14].copy_from_slice(×tamp(2, pts)); + 14 + } + } +} + +/// The six program_clock_reference bytes for a 27 MHz clock value: the 33-bit base (clock / 300), +/// six reserved bits, and the 9-bit extension (clock % 300). +pub(crate) fn pcr(clock: i64) -> [u8; 6] { + let v = clock.rem_euclid(WRAP_90K * 300); + let (base, ext) = (v / 300, v % 300); + [(base >> 25) as u8, (base >> 17) as u8, (base >> 9) as u8, (base >> 1) as u8, ((base & 1) << 7) as u8 | 0x7E | (ext >> 8) as u8, ext as u8] +} + +/// The first NAL unit's first header byte, when `data` starts with an Annex B start code. +fn first_nal(data: &[u8]) -> Option { + let at = if data.starts_with(&[0, 0, 1]) { + 3 + } else if data.starts_with(&[0, 0, 0, 1]) { + 4 + } else { + return None; + }; + data.get(at).copied() +} + +/// Checks that `data` is a frame of `codec`, writes what goes in front of it into `out`, and +/// returns the prefix length and the bytes the frame itself takes. +pub(crate) fn prepare(codec: Codec, data: &[u8], key: bool, trim: OpusTrim, out: &mut [u8; PREFIX_MAX]) -> Result { + if let Codec::Av1(_) = codec { + return Ok(Prepared { prefix_len: 0, body_len: av1::check(data, key)? }); + } + let prefix_len = prefix(codec, data, trim, out)?; + Ok(Prepared { prefix_len, body_len: data.len() }) +} + +/// Checks a frame of a codec carried as it is and writes its prefix. Returns the prefix length. +fn prefix(codec: Codec, data: &[u8], trim: OpusTrim, out: &mut [u8; PREFIX_MAX]) -> Result { + match codec { + Codec::H264 => { + let nal = first_nal(data).ok_or(Error::BadFrame("an H.264 frame must start with an Annex B start code"))?; + if nal & 0x1F == 9 { + return Ok(0); + } + // access unit delimiter, primary_pic_type 7 (any slice type) (H.222.0 §2.14) + out[..6].copy_from_slice(&[0, 0, 0, 1, 0x09, 0xF0]); + Ok(6) + } + Codec::Hevc => { + let nal = first_nal(data).ok_or(Error::BadFrame("an HEVC frame must start with an Annex B start code"))?; + if (nal >> 1) & 0x3F == 35 { + return Ok(0); + } + // access unit delimiter (nal_unit_type 35), pic_type 2 (any slice type) (H.222.0 §2.17) + out[..7].copy_from_slice(&[0, 0, 0, 1, 0x46, 0x01, 0x50]); + Ok(7) + } + Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 => { + first_nal(data).ok_or(Error::BadFrame("an MPEG video frame must start with a start code"))?; + Ok(0) + } + Codec::AacAdts => { + check_adts(data)?; + Ok(0) + } + Codec::Aac { object_type, sample_rate_index, channels } => { + let len = data.len() + 7; + if len > 0x1FFF { + return Err(Error::FrameTooLarge { size: data.len(), limit: 0x1FFF - 7 }); + } + // ADTS fixed and variable header (ISO/IEC 13818-7 §6.2): MPEG-4, no CRC, buffer + // fullness 0x7FF (variable rate), one raw data block + out[..7].copy_from_slice(&[ + 0xFF, + 0xF1, + (object_type - 1) << 6 | sample_rate_index << 2 | channels >> 2, + (channels & 3) << 6 | (len >> 11) as u8, + (len >> 3) as u8, + ((len & 7) as u8) << 5 | 0x1F, + 0xFC, + ]); + Ok(7) + } + Codec::Opus { .. } | Codec::OpusMapped(_) => { + // opus_control_header: the 11-bit prefix 0x3FF, the trim flags, no extension, the + // payload size as 0xFF bytes and a last byte, then the trims (3 reserved bits and + // 13 bits each) + let n = data.len() / 255; + let trims = if trim.start > 0 { 2 } else { 0 } + if trim.end > 0 { 2 } else { 0 }; + if 3 + n + trims > PREFIX_MAX { + return Err(Error::FrameTooLarge { size: data.len(), limit: data_limit(codec, 8, trims) }); + } + out[0] = 0x7F; + out[1] = 0xE0 | if trim.start > 0 { 0x10 } else { 0 } | if trim.end > 0 { 0x08 } else { 0 }; + out[2..2 + n].fill(0xFF); + out[2 + n] = (data.len() % 255) as u8; + let mut at = 3 + n; + for t in [trim.start, trim.end] { + if t > 0 { + out[at..at + 2].copy_from_slice(&(t & 0x1FFF).to_be_bytes()); + at += 2; + } + } + Ok(at) + } + Codec::Ac3 => match data { + [0x0B, 0x77, ..] => Ok(0), + _ => Err(Error::BadFrame("an AC-3 frame must start with its sync word")), + }, + Codec::Eac3 => match data { + // bsid, the top five bits of byte 5, is 11 to 16 for E-AC-3 (ATSC A/52) + [0x0B, 0x77, _, _, _, b5, ..] if (11..=16).contains(&(b5 >> 3)) => Ok(0), + _ => Err(Error::BadFrame("an E-AC-3 frame must start with its sync word and a bsid of 11 to 16")), + }, + Codec::MpegAudio { low_sample_rate } => match data { + [0xFF, b, ..] if b & 0xE0 == 0xE0 => { + // version: 3 MPEG-1, 2 MPEG-2, 0 MPEG 2.5, 1 reserved; layer 0 is reserved + let version = (b >> 3) & 3; + if version == 1 || (b >> 1) & 3 == 0 { + return Err(Error::BadFrame("the MPEG audio frame header has a reserved version or layer")); + } + if (version == 3) == low_sample_rate { + return Err(Error::BadFrame("the MPEG audio frame's version does not match the stream's low_sample_rate")); + } + Ok(0) + } + _ => Err(Error::BadFrame("an MPEG audio frame must start with its sync word")), + }, + Codec::Av1(_) => Err(Error::BadFrame("AV1 frames are not carried with a prefix")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Reads a 33-bit timestamp back from its five bytes. + fn read(b: &[u8]) -> i64 { + (((b[0] >> 1) & 7) as i64) << 30 | (b[1] as i64) << 22 | ((b[2] >> 1) as i64) << 15 | (b[3] as i64) << 7 | (b[4] >> 1) as i64 + } + + #[test] + fn timestamps_carry_their_prefix_and_markers() { + for v in [0, 1, 90_000, (1 << 32) + 12_345, WRAP_90K - 1] { + let b = timestamp(2, v); + assert_eq!(b[0] >> 4, 2); + assert_eq!([b[0] & 1, b[2] & 1, b[4] & 1], [1, 1, 1]); + assert_eq!(read(&b), v); + } + assert_eq!(read(×tamp(2, WRAP_90K + 5)), 5, "wraps at 2^33"); + assert_eq!(read(×tamp(2, -1)), WRAP_90K - 1); + } + + #[test] + fn headers_hold_pts_and_dts() { + let mut h = [0u8; HEADER_MAX]; + assert_eq!(header(&mut h, 0xE0, 0, 3000, Some(0)), 19); + assert_eq!(&h[..9], &[0, 0, 1, 0xE0, 0, 0, 0x84, 0xC0, 10]); + assert_eq!((h[9] >> 4, read(&h[9..14]), h[14] >> 4, read(&h[14..19])), (3, 3000, 1, 0)); + assert_eq!(header(&mut h, 0xC0, 300, 7, None), 14); + assert_eq!(&h[4..9], &[1, 44, 0x84, 0x80, 5]); + } + + #[test] + fn pcr_splits_base_and_extension() { + let clock = 123_456_789i64 * 300 + 299; + let b = pcr(clock); + let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64; + let ext = ((b[4] & 1) as i64) << 8 | b[5] as i64; + assert_eq!((base, ext, b[4] & 0x7E), (123_456_789, 299, 0x7E)); + } + + const NO_TRIM: OpusTrim = OpusTrim { start: 0, end: 0 }; + + #[test] + fn access_unit_delimiters_are_added_once() { + let mut p = [0u8; PREFIX_MAX]; + assert_eq!(prefix(Codec::H264, &[0, 0, 0, 1, 0x65, 0x88], NO_TRIM, &mut p).unwrap(), 6); + assert_eq!(prefix(Codec::H264, &[0, 0, 1, 0x09, 0xF0, 0, 0, 1, 0x65], NO_TRIM, &mut p).unwrap(), 0); + assert_eq!(prefix(Codec::Hevc, &[0, 0, 0, 1, 0x26, 0x01], NO_TRIM, &mut p).unwrap(), 7); + assert_eq!(prefix(Codec::Hevc, &[0, 0, 1, 0x46, 0x01, 0x50], NO_TRIM, &mut p).unwrap(), 0); + assert!(matches!(prefix(Codec::H264, &[0x65, 0x88], NO_TRIM, &mut p), Err(Error::BadFrame(_)))); + assert!(matches!(prefix(Codec::H264, &[0, 0, 1], NO_TRIM, &mut p), Err(Error::BadFrame(_)))); + } + + #[test] + fn opus_control_header_codes_the_size_and_trims() { + let mut p = [0u8; PREFIX_MAX]; + let opus = Codec::Opus { channels: 2 }; + assert_eq!(prefix(opus, &[0xFC; 254], NO_TRIM, &mut p).unwrap(), 3); + assert_eq!(&p[..3], &[0x7F, 0xE0, 254]); + assert_eq!(prefix(opus, &[0xFC; 510], NO_TRIM, &mut p).unwrap(), 5); + assert_eq!(&p[..5], &[0x7F, 0xE0, 0xFF, 0xFF, 0]); + assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 312, end: 0 }, &mut p).unwrap(), 5); + assert_eq!(&p[..5], &[0x7F, 0xF0, 10, 0x01, 0x38]); + assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 1, end: 8191 }, &mut p).unwrap(), 7); + assert_eq!(&p[..7], &[0x7F, 0xF8, 10, 0, 1, 0x1F, 0xFF]); + assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 0, end: 2 }, &mut p).unwrap(), 5); + assert_eq!(&p[..5], &[0x7F, 0xE8, 10, 0, 2]); + } + + #[test] + fn opus_limits_match_the_pes_length() { + for (header, trim) in [(8, 0), (13, 0), (8, 4), (13, 2)] { + let l = data_limit(Codec::Opus { channels: 2 }, header, trim); + let body = |n: usize| header + 3 + n / 255 + trim + n; + assert!(body(l) <= 0xFFFF && body(l + 1) > 0xFFFF, "{header} {trim}: {l}"); + } + assert_eq!(data_limit(Codec::Ac3, 8, 0), 0xFFFF - 8); + assert_eq!(data_limit(Codec::Mpeg4Part2, 13, 0), MAX_VIDEO_FRAME); + } + + #[test] + fn opus_durations_from_the_table_of_contents() { + assert_eq!(opus_samples(&[0xFC]), Some(960), "CELT 20 ms, one frame"); + assert_eq!(opus_samples(&[0x08 | 1]), Some(1920), "SILK 20 ms, two frames"); + assert_eq!(opus_samples(&[0x18 | 3, 3]), Some(3 * 2880), "SILK 60 ms, three frames"); + assert_eq!(opus_samples(&[0x80]), Some(120), "CELT 2.5 ms"); + assert_eq!(opus_samples(&[0x03]), None); + assert_eq!(opus_samples(&[]), None); + } + + #[test] + fn adts_header_for_raw_aac() { + let mut p = [0u8; PREFIX_MAX]; + let codec = Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }; + assert_eq!(prefix(codec, &[0; 100], NO_TRIM, &mut p).unwrap(), 7); + // AAC LC, 48 kHz, 2 channels, 107 bytes + assert_eq!(&p[..7], &[0xFF, 0xF1, 0x4C, 0x80, 0x0D, 0x7F, 0xFC]); + assert!(matches!(prefix(codec, &[0; 8185], NO_TRIM, &mut p), Err(Error::FrameTooLarge { .. }))); + assert_eq!(data_limit(codec, 8, 0), 8184); + } + + fn adts(len: usize) -> Vec { + let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC]; + v.resize(len, 0x11); + v + } + + #[test] + fn adts_frame_lengths_must_tile_the_frame() { + let mut p = [0u8; PREFIX_MAX]; + assert_eq!(prefix(Codec::AacAdts, &adts(100), NO_TRIM, &mut p).unwrap(), 0); + let two = [adts(100), adts(57)].concat(); + assert_eq!(prefix(Codec::AacAdts, &two, NO_TRIM, &mut p).unwrap(), 0); + let mut short = adts(100); + short.pop(); + assert!(matches!(prefix(Codec::AacAdts, &short, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "one byte short"); + let mut long = adts(100); + long.push(0); + assert!(matches!(prefix(Codec::AacAdts, &long, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "a trailing byte"); + let mut zero = adts(100); + zero[3] &= 0xFC; + zero[4] = 0; + zero[5] &= 0x1F; + assert!(matches!(prefix(Codec::AacAdts, &zero, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "frame_length 0"); + // a header with a CRC is 9 bytes, so a frame_length of 8 does not hold it + let mut crc = adts(8); + crc[1] = 0xF0; + assert!(matches!(prefix(Codec::AacAdts, &crc, NO_TRIM, &mut p), Err(Error::BadFrame(_)))); + } + + #[test] + fn mpeg_audio_versions_match_the_stream_type() { + let mut p = [0u8; PREFIX_MAX]; + let (mpeg1, mpeg2, mpeg25, reserved) = ([0xFF, 0xFB, 0x90], [0xFF, 0xF3, 0x90], [0xFF, 0xE3, 0x90], [0xFF, 0xEB, 0x90]); + let high = Codec::MpegAudio { low_sample_rate: false }; + let low = Codec::MpegAudio { low_sample_rate: true }; + assert!(prefix(high, &mpeg1, NO_TRIM, &mut p).is_ok()); + assert!(prefix(low, &mpeg2, NO_TRIM, &mut p).is_ok()); + assert!(prefix(low, &mpeg25, NO_TRIM, &mut p).is_ok()); + assert!(prefix(low, &mpeg1, NO_TRIM, &mut p).is_err()); + assert!(prefix(high, &mpeg2, NO_TRIM, &mut p).is_err()); + assert!(prefix(high, &reserved, NO_TRIM, &mut p).is_err()); + assert!(prefix(high, &[0xFF, 0xF9, 0x90], NO_TRIM, &mut p).is_err(), "layer 0"); + } + + #[test] + fn eac3_needs_its_bsid() { + let mut p = [0u8; PREFIX_MAX]; + assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34, 16 << 3], NO_TRIM, &mut p).is_ok()); + assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34, 8 << 3], NO_TRIM, &mut p).is_err(), "AC-3's bsid"); + assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34], NO_TRIM, &mut p).is_err()); + } +} diff --git a/crates/media/src/mpegts/mux/psi.rs b/crates/media/src/mpegts/mux/psi.rs new file mode 100644 index 000000000..b4c55c3fb --- /dev/null +++ b/crates/media/src/mpegts/mux/psi.rs @@ -0,0 +1,216 @@ +//! Program specific information: the program association section and the program map section +//! (H.222.0 §2.4.4), each ending with the CRC-32 of Annex A that the demuxer checks. + +pub(crate) use super::super::ts::crc32_mpeg as crc32; +use super::{Codec, Error, OpusMapping, Stream}; + +/// Largest `section_length` of a program association or program map section (§2.4.4.3, §2.4.4.8). +pub(crate) const MAX_SECTION_LENGTH: usize = 1021; + +/// Writes `section_length` into bytes 1 and 2 and appends the CRC. `s` holds the section from +/// `table_id` up to the CRC. +fn finish(mut s: Vec) -> Result, Error> { + let length = s.len() + 4 - 3; + if length > MAX_SECTION_LENGTH { + return Err(Error::PsiTooLarge { length }); + } + s[1] = 0xB0 | (length >> 8) as u8; + s[2] = length as u8; + let crc = crc32(&s); + s.extend_from_slice(&crc.to_be_bytes()); + Ok(s) +} + +/// The program association section with one program. +pub(crate) fn pat(transport_stream_id: u16, program_number: u16, pmt_pid: u16) -> Result, Error> { + let mut s = vec![0x00, 0, 0]; + s.extend_from_slice(&transport_stream_id.to_be_bytes()); + // reserved, version_number 0, current_next_indicator 1; section_number 0, last_section_number 0 + s.extend_from_slice(&[0xC1, 0x00, 0x00]); + s.extend_from_slice(&program_number.to_be_bytes()); + s.extend_from_slice(&(0xE000 | pmt_pid).to_be_bytes()); + finish(s) +} + +/// The program map section. +pub(crate) fn pmt(program_number: u16, pcr_pid: u16, streams: &[Stream]) -> Result, Error> { + let mut s = vec![0x02, 0, 0]; + s.extend_from_slice(&program_number.to_be_bytes()); + s.extend_from_slice(&[0xC1, 0x00, 0x00]); + s.extend_from_slice(&(0xE000 | pcr_pid).to_be_bytes()); + // program_info_length 0 + s.extend_from_slice(&[0xF0, 0x00]); + for st in streams { + s.push(st.codec.stream_type()); + s.extend_from_slice(&(0xE000 | st.pid).to_be_bytes()); + let at = s.len(); + s.extend_from_slice(&[0xF0, 0x00]); + descriptors(st, &mut s); + let len = s.len() - at - 2; + s[at] = 0xF0 | (len >> 8) as u8; + s[at + 1] = len as u8; + } + finish(s) +} + +/// The elementary stream descriptors of one stream. +fn descriptors(st: &Stream, s: &mut Vec) { + match st.codec { + // registration_descriptor (§2.6.8) with the format identifier "AC-3" + Codec::Ac3 => s.extend_from_slice(&[0x05, 4, b'A', b'C', b'-', b'3']), + // registration "EAC3" (ATSC A/52) with stream type 0x87 + Codec::Eac3 => s.extend_from_slice(&[0x05, 4, b'E', b'A', b'C', b'3']), + Codec::Opus { channels } => { + // registration_descriptor "Opus", then the Opus audio descriptor as an extension + // descriptor (tag 0x7F) whose channel_config_code is the channel count (1 to 8) + s.extend_from_slice(&[0x05, 4, b'O', b'p', b'u', b's']); + s.extend_from_slice(&[0x7F, 2, OPUS_DESCRIPTOR_EXTENSION, channels]); + } + Codec::OpusMapped(m) => { + s.extend_from_slice(&[0x05, 4, b'O', b'p', b'u', b's']); + let mut body = [0u8; 10]; + let n = opus_explicit(&m, &mut body); + s.extend_from_slice(&[0x7F, 1 + n as u8, OPUS_DESCRIPTOR_EXTENSION]); + s.extend_from_slice(&body[..n]); + } + Codec::Av1(c) => { + // registration_descriptor "AV01" first, then the AV1 video descriptor (tag 0x80) + // (Carriage of AV1 in MPEG-2 TS, §2) + s.extend_from_slice(&[0x05, 4, b'A', b'V', b'0', b'1']); + let b = |v: bool, shift: u8| u8::from(v) << shift; + s.extend_from_slice(&[ + 0x80, + 4, + 0x81, + c.seq_profile << 5 | c.seq_level_idx_0, + b(c.seq_tier_0, 7) + | b(c.high_bitdepth, 6) + | b(c.twelve_bit, 5) + | b(c.monochrome, 4) + | b(c.chroma_subsampling_x, 3) + | b(c.chroma_subsampling_y, 2) + | c.chroma_sample_position, + // hdr_wcg_idc, then reserved zeros and no initial_presentation_delay + c.hdr_wcg_idc << 6, + ]); + } + _ => {} + } + if let Some(lang) = st.language { + // ISO_639_language_descriptor (§2.6.18), audio_type 0 (undefined) + s.extend_from_slice(&[0x0A, 4, lang[0], lang[1], lang[2], 0]); + } +} + +/// `descriptor_tag_extension` of the Opus audio descriptor. The Opus transport draft leaves the +/// value open; 0x80 is the value in use for it. +pub(crate) const OPUS_DESCRIPTOR_EXTENSION: u8 = 0x80; + +/// 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 opus_audio_descriptor body for an explicit channel configuration (channel_config_code +/// 0x81): 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, padded +/// with zero bits to a byte. Returns its length. +fn opus_explicit(m: &OpusMapping, out: &mut [u8; 10]) -> usize { + out[..3].copy_from_slice(&[0x81, m.channels, m.family]); + if m.family == 0 { + return 3; + } + let (ch, streams, coupled) = (u32::from(m.channels), u32::from(m.streams), u32::from(m.coupled)); + let mut acc: u64 = 0; + let mut bits = 0; + let mut put = |v: u32, n: u32| { + acc = acc << n | u64::from(v & ((1 << n) - 1)); + bits += n; + }; + put(streams - 1, bits_for(ch)); + put(coupled, bits_for(streams + 1)); + let width = bits_for(streams + coupled + 1); + for &c in &m.mapping[..usize::from(m.channels)] { + put(if c == 255 { (1 << width) - 1 } else { u32::from(c) }, width); + } + let bytes = bits.div_ceil(8) as usize; + let acc = acc << (bytes as u32 * 8 - bits); + for (i, o) in out[3..3 + bytes].iter_mut().enumerate() { + *o = (acc >> (8 * (bytes - 1 - i))) as u8; + } + 3 + bytes +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc_check_value() { + // the CRC-32/MPEG-2 check value of the ASCII digits 1 to 9 + assert_eq!(crc32(b"123456789"), 0x0376_E6E7); + } + + #[test] + fn sections_end_with_a_crc_over_the_whole_section() { + let pat = pat(7, 1, 0x1000).unwrap(); + assert_eq!(pat.len(), 16); + assert_eq!(crc32(&pat), 0); + assert_eq!(&pat[..3], &[0x00, 0xB0, 13]); + assert_eq!(&pat[8..12], &[0x00, 0x01, 0xF0, 0x00]); + let st = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Opus { channels: 2 }).with_language(*b"eng")]; + let pmt = pmt(1, 0x100, &st).unwrap(); + assert_eq!(crc32(&pmt), 0); + assert_eq!(pmt.len(), 3 + ((pmt[1] as usize & 0x0F) << 8 | pmt[2] as usize)); + assert_eq!(&pmt[8..10], &[0xE1, 0x00], "PCR_PID"); + assert_eq!(&pmt[12..17], &[0x1B, 0xE1, 0x00, 0xF0, 0x00], "H.264 without descriptors"); + assert_eq!(&pmt[17..22], &[0x06, 0xE1, 0x01, 0xF0, 16]); + } + + #[test] + fn a_section_past_the_length_limit_is_refused() { + let st: Vec = (0..200).map(|i| Stream::new(0x100 + i, Codec::Ac3).with_language(*b"eng")).collect(); + assert!(matches!(pmt(1, 0x100, &st), Err(Error::PsiTooLarge { .. }))); + } + + /// The descriptors of one stream's PMT entry. + fn stream_descriptors(codec: Codec) -> Vec { + let pmt = pmt(1, 0x100, &[Stream::new(0x100, codec)]).unwrap(); + let len = ((pmt[15] as usize & 0x0F) << 8) | pmt[16] as usize; + pmt[17..17 + len].to_vec() + } + + #[test] + fn explicit_opus_mappings_pack_their_fields() { + // 6 channels, family 1, 4 streams, 2 coupled: 3 + 3 + 6 * 3 = 24 bits + let m = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }; + let d = stream_descriptors(Codec::OpusMapped(m)); + let want = 0b011 << 21 | 0b010 << 18 | 0b000_100_001_010_011_101; + assert_eq!(&d[6..], &[0x7F, 7, 0x80, 0x81, 6, 1, (want >> 16) as u8, (want >> 8) as u8, want as u8]); + // 3 channels, family 255, 3 streams, none coupled, one silent: 2 + 2 + 3 * 2 = 10 bits + let m = OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [2, 255, 0, 0, 0, 0, 0, 0] }; + let d = stream_descriptors(Codec::OpusMapped(m)); + assert_eq!(&d[6..], &[0x7F, 6, 0x80, 0x81, 3, 255, 0b10_00_10_11, 0b00_000000]); + // family 0 carries no stream fields + let m = OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] }; + assert_eq!(&stream_descriptors(Codec::OpusMapped(m))[6..], &[0x7F, 4, 0x80, 0x81, 2, 0]); + } + + #[test] + fn av1_and_eac3_descriptors() { + let c = crate::mpegts::mux::Av1Config { + seq_profile: 1, + seq_level_idx_0: 8, + seq_tier_0: false, + high_bitdepth: true, + twelve_bit: false, + monochrome: false, + chroma_subsampling_x: false, + chroma_subsampling_y: false, + chroma_sample_position: 0, + hdr_wcg_idc: 3, + }; + assert_eq!(stream_descriptors(Codec::Av1(c)), [0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x28, 0x40, 0xC0]); + assert_eq!(stream_descriptors(Codec::Eac3), [0x05, 4, b'E', b'A', b'C', b'3']); + } +} diff --git a/crates/media/src/mpegts/mux/tests.rs b/crates/media/src/mpegts/mux/tests.rs new file mode 100644 index 000000000..d007ea755 --- /dev/null +++ b/crates/media/src/mpegts/mux/tests.rs @@ -0,0 +1,915 @@ +use super::*; + +use std::cell::RefCell; +use std::rc::Rc; + +const WIDE_OPUS: OpusMapping = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }; + +/// One packet's header fields. +#[derive(Debug, Clone, Copy)] +struct Pk { + pid: u16, + pusi: bool, + cc: u8, + payload: bool, + rai: bool, + disc: bool, + pcr: Option, +} + +fn walk(ts: &[u8]) -> Vec { + assert_eq!(ts.len() % PACKET_SIZE, 0); + ts.chunks(PACKET_SIZE) + .map(|p| { + assert_eq!(p[0], 0x47); + let afc = p[3] >> 4 & 3; + let (mut rai, mut disc, mut pcr) = (false, false, None); + if afc & 2 != 0 { + let len = p[4] as usize; + assert!(len <= 183); + if afc == 2 { + assert_eq!(len, 183); + } + if len > 0 { + rai = p[5] & 0x40 != 0; + disc = p[5] & 0x80 != 0; + if p[5] & 0x10 != 0 { + let b = &p[6..12]; + let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64; + pcr = Some(base * 300 + (((b[4] & 1) as i64) << 8 | b[5] as i64)); + } + } + } + Pk { pid: ((p[1] & 0x1F) as u16) << 8 | p[2] as u16, pusi: p[1] & 0x40 != 0, cc: p[3] & 0x0F, payload: afc & 1 != 0, rai, disc, pcr } + }) + .collect() +} + +fn h264(key: bool) -> Vec { + if key { + vec![0, 0, 0, 1, 0x67, 0x42, 0, 0x1E, 0, 0, 0, 1, 0x68, 0xCE, 0, 0, 1, 0x65, 0x88, 0x84, 0x21] + } else { + vec![0, 0, 0, 1, 0x41, 0x9A, 0x11] + } +} + +fn mux(cfg: Config, streams: &[Stream], f: impl FnOnce(&mut Muxer>)) -> Vec { + let mut m = Muxer::new(Vec::new(), cfg, streams).unwrap(); + f(&mut m); + m.finish().unwrap() +} + +#[test] +fn starts_with_pat_pmt_and_a_pcr_on_the_first_frame() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| { + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + assert_eq!(pk.len(), 3); + assert_eq!((pk[0].pid, pk[0].pusi), (0, true)); + assert_eq!((pk[1].pid, pk[1].pusi), (0x1000, true)); + assert_eq!((pk[2].pid, pk[2].pusi, pk[2].rai), (0x100, true, true)); + assert_eq!(pk[2].pcr, Some((90_000 - 63_000) * 300)); + // the payload ends the packet: the access unit delimiter, then the frame + let frame = h264(true); + let p = &ts[2 * PACKET_SIZE..]; + assert_eq!(&p[PACKET_SIZE - frame.len()..PACKET_SIZE], &frame[..]); + assert_eq!(&p[PACKET_SIZE - frame.len() - 6 - 14..PACKET_SIZE - frame.len() - 6][..4], &[0, 0, 1, 0xE0]); + assert_eq!(&p[PACKET_SIZE - frame.len() - 6..PACKET_SIZE - frame.len()], &[0, 0, 0, 1, 9, 0xF0]); +} + +#[test] +fn every_stuffing_length_fills_the_packet() { + // frames whose PES packet ends at every offset of a packet, with and without a PCR + for n in 1..=400usize { + let ts = mux(Config { pcr_pid: Some(0x200), ..Config::default() }, &[Stream::new(0x100, Codec::MpegAudio { low_sample_rate: false })], |m| { + let mut data = vec![0u8; n]; + data[0] = 0xFF; + if n > 1 { + data[1] = 0xFB; + } + if n == 1 { + assert!(matches!(m.write_frame(0, &Frame { data: &data, pts: 90_000, dts: None, key: true }), Err(Error::BadFrame(_)))); + return; + } + m.write_frame(0, &Frame { data: &data, pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &data, pts: 92_000, dts: None, key: false }).unwrap(); + }); + if n == 1 { + continue; + } + let pk = walk(&ts); + let mut payload = 0; + for (p, raw) in pk.iter().zip(ts.chunks(PACKET_SIZE)) { + if p.pid == 0x100 { + let start = if raw[3] & 0x20 != 0 { 5 + raw[4] as usize } else { 4 }; + payload += PACKET_SIZE - start; + } + } + assert_eq!(payload, 2 * (14 + n), "{n}"); + } +} + +#[test] +fn continuity_counters_count_payload_packets_per_pid() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| { + let big = { + let mut v = h264(true); + v.resize(10_000, 0x55); + v + }; + for k in 0..40i64 { + m.write_frame(0, &Frame { data: &big, pts: 90_000 + k * 3000, dts: None, key: k % 10 == 0 }).unwrap(); + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 1, 2, 3], pts: 90_000 + k * 3000, dts: None, key: true }).unwrap(); + } + }); + let mut last: std::collections::HashMap = Default::default(); + for p in walk(&ts) { + if let Some(&c) = last.get(&p.pid) { + let want = if p.payload { (c + 1) & 0x0F } else { c }; + assert_eq!(p.cc, want, "PID {:#x}", p.pid); + } + last.insert(p.pid, p.cc); + } +} + +#[test] +fn pcr_never_lapses_past_the_interval() { + for interval in [900u32, 3600, MAX_PCR_INTERVAL] { + // video on 0x100 carries the PCR; a 2 s gap in the video is filled from the audio clock + let ts = + mux(Config { pcr_interval: interval, ..Config::default() }, &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| { + let mut t = 90_000i64; + for k in 0..200i64 { + if !(50..110).contains(&k) { + m.write_frame(0, &Frame { data: &h264(k == 0), pts: t, dts: None, key: k == 0 }).unwrap(); + } + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 0], pts: t, dts: None, key: true }).unwrap(); + t += 3000; + } + }); + let pcrs: Vec = walk(&ts).iter().filter(|p| p.pid == 0x100).filter_map(|p| p.pcr).collect(); + assert!(pcrs.len() > 1); + for w in pcrs.windows(2) { + assert!(w[1] > w[0], "PCR goes forward"); + assert!(w[1] - w[0] <= i64::from(interval) * 300, "interval {interval}: {} apart", w[1] - w[0]); + } + } +} + +#[test] +fn pcr_on_a_pid_of_its_own_and_through_advance() { + let mut m = Muxer::new(Vec::new(), Config { pcr_pid: Some(0x1FF), ..Config::default() }, &[Stream::new(0x101, Codec::Ac3)]).unwrap(); + assert_eq!(m.pcr_pid(), 0x1FF); + m.advance(63_000).unwrap(); + m.advance(63_000 + 90_000).unwrap(); + m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000 + 90_000, dts: None, key: true }).unwrap(); + let st = m.stats(); + let ts = m.finish().unwrap(); + let pk = walk(&ts); + let pcrs: Vec = pk.iter().filter(|p| p.pid == 0x1FF).map(|p| p.pcr.unwrap()).collect(); + assert_eq!(pcrs.first(), Some(&0)); + assert_eq!(pcrs.last(), Some(&(90_000 * 300))); + assert!(pcrs.windows(2).all(|w| w[1] - w[0] <= 3600 * 300)); + assert!(pk.iter().filter(|p| p.pid == 0x1FF).all(|p| !p.payload && p.cc == 0)); + assert_eq!(st.pcrs as usize, pcrs.len()); + assert_eq!(pcrs.len(), 26, "one PCR, 24 to fill the second, one at its end"); + // at the start, then every 100 ms of the gap, the last one at its end + assert_eq!(st.psi, 11); + let mut last_psi = None; + let mut pcr = 0; + for p in &pk { + if let Some(v) = p.pcr { + pcr = v; + } + if p.pid == 0 { + if let Some(l) = last_psi { + assert!(pcr - l <= (9000 + 3600) * 300, "PAT {} after the last", pcr - l); + } + last_psi = Some(pcr); + } + } + assert_eq!(st.bytes(), ts.len() as u64); +} + +#[test] +fn a_pcr_packet_before_the_first_payload_keeps_the_counter_continuous() { + // the audio frame comes first, so the video PID carries a PCR-only packet before its first + // payload packet + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| { + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + }); + let video: Vec = walk(&ts).into_iter().filter(|p| p.pid == 0x100).collect(); + assert_eq!(video.len(), 2); + assert!(!video[0].payload && video[0].pcr.is_some()); + assert!(video[1].payload); + assert_eq!(video[1].cc, (video[0].cc + 1) & 0x0F); +} + +#[test] +fn a_long_gap_is_closed_by_one_pcr() { + let mut m = Muxer::new(Vec::new(), Config { pcr_interval: 1, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap(); + m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000 + 90_000, dts: None, key: true }).unwrap(); + assert_eq!(m.stats().pcr_gaps, 1); + let pcrs: Vec = walk(&m.finish().unwrap()).iter().filter_map(|p| p.pcr).collect(); + assert_eq!(pcrs.len() as u32, 2 + MAX_PCR_FILL); + assert_eq!(pcrs.last(), Some(&(90_000 * 300))); +} + +#[test] +fn psi_repeats_on_keyframes_and_new_writers() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(false), pts: 93_000, dts: None, key: false }).unwrap(); + assert_eq!(m.stats().psi, 1); + m.write_frame(0, &Frame { data: &h264(true), pts: 96_000, dts: None, key: true }).unwrap(); + assert_eq!(m.stats().psi, 2); + let first = m.replace_writer(Vec::new()).writer; + m.write_frame(0, &Frame { data: &h264(false), pts: 99_000, dts: None, key: false }).unwrap(); + let second = m.finish().unwrap(); + let pk = walk(&second); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "a new segment starts with the PAT and PMT"); + let pk_first = walk(&first); + let last_video = pk_first.iter().rev().find(|p| p.pid == 0x100).unwrap().cc; + assert_eq!(pk.iter().find(|p| p.pid == 0x100).unwrap().cc, (last_video + 1) & 0x0F, "counters carry on"); +} + +#[test] +fn a_keyframe_after_a_gap_follows_the_tables_directly() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| { + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + // the gap reaches past the table interval and several PCR intervals + m.write_frame(0, &Frame { data: &h264(true), pts: 110_000, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + let keys: Vec = pk.iter().enumerate().filter(|(_, p)| p.pid == 0x100 && p.rai).map(|(i, _)| i).collect(); + assert_eq!(keys.len(), 2); + for k in keys { + assert_eq!((pk[k - 2].pid, pk[k - 1].pid), (0, 0x1000), "the PAT and PMT right before the keyframe at packet {k}"); + } + assert!(pk.iter().any(|p| p.pid == 0x100 && !p.payload), "PCR-only packets fill the gap"); + // a packet the caller writes between the tables and a keyframe brings the tables again + let mut null = [0xFF; PACKET_SIZE]; + null[..4].copy_from_slice(&[0x47, 0x1F, 0xFF, 0x10]); + let cfg = Config { pcr_interval: 9_000, psi_interval: 3_600, ..Config::default() }; + let ts = mux(cfg, &[Stream::new(0x100, Codec::H264)], |m| { + m.advance(90_000).unwrap(); + // the tables fall due here and the PCR does not, so the tables are the last packets + m.advance(93_600).unwrap(); + m.get_mut().extend_from_slice(&null); + m.write_frame(0, &Frame { data: &h264(true), pts: 93_600, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + let k = pk.iter().position(|p| p.pid == 0x100 && p.rai).unwrap(); + assert_eq!((pk[k - 3].pid, pk[k - 2].pid, pk[k - 1].pid), (0x1FFF, 0, 0x1000)); +} + +#[test] +fn tables_lost_with_a_failed_write_come_again_before_a_keyframe() { + let cfg = Config { pcr_interval: 9_000, psi_interval: 3_600, ..Config::default() }; + // the second write fails: the one at the end of the second advance + let mut m = Muxer::new(Flaky { fail_on: Some(2), calls: 0, data: Vec::new() }, cfg, &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.advance(90_000).unwrap(); + // the tables fall due and are dropped with the failed batch + assert!(matches!(m.advance(93_600), Err(Error::Io(_)))); + m.write_frame(0, &Frame { data: &h264(true), pts: 93_600, dts: None, key: true }).unwrap(); + let pk = walk(&m.finish().unwrap().data); + let k = pk.iter().position(|p| p.pid == 0x100 && p.rai).unwrap(); + assert_eq!((pk[k - 2].pid, pk[k - 1].pid), (0, 0x1000)); +} + +#[test] +fn every_new_segment_carries_a_pcr() { + for pcr_pid in [None, Some(0x1F0)] { + let mut m = Muxer::new(Vec::new(), Config { pcr_pid, ..Config::default() }, &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + m.replace_writer(Vec::new()); + // a frame within the PCR interval + m.write_frame(0, &Frame { data: &h264(false), pts: 90_001, dts: None, key: false }).unwrap(); + let segment = m.replace_writer(Vec::new()).writer; + m.advance(91_000).unwrap(); + let third = m.finish().unwrap(); + let want = pcr_pid.unwrap_or(0x100); + for (n, ts) in [segment, third].iter().enumerate() { + let pk = walk(ts); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "{pcr_pid:?} segment {n}"); + assert!(pk.iter().any(|p| p.pid == want && p.pcr.is_some()), "{pcr_pid:?} segment {n} has a PCR"); + } + } +} + +#[test] +fn a_segment_after_an_idle_gap_starts_with_the_tables() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + m.replace_writer(Vec::new()); + m.advance(180_000).unwrap(); + let pk = walk(&m.finish().unwrap()); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000)); + assert!(pk.len() > 10, "the gap is filled with PCRs"); +} + +#[test] +fn short_table_intervals_hold_in_idle_gaps() { + let mut m = Muxer::new(Vec::new(), Config { psi_interval: 900, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap(); + m.advance(63_000).unwrap(); + m.advance(63_000 + 90_000).unwrap(); + // every 900 ticks: at the start, 99 times inside the second, and at its end + assert_eq!(m.stats().psi, 101); + // a table interval of one tick fills at most MAX_PCR_FILL repeats per gap, and the PCRs still + // fill the gap + let mut m = Muxer::new(Vec::new(), Config { psi_interval: 1, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap(); + m.advance(63_000).unwrap(); + m.advance(63_000 + 90_000).unwrap(); + assert_eq!(m.stats().psi, 2 + u64::from(MAX_PCR_FILL)); + assert_eq!((m.stats().pcrs, m.stats().pcr_gaps), (26, 0)); +} + +#[test] +fn frames_behind_the_sent_clock_are_refused() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 900_000, dts: None, key: true }).unwrap(); + // the clock is 900 000 - 63 000: audio up to the PCR delay behind the video is fine + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_000, dts: None, key: true }).unwrap(); + let before = m.get_ref().len(); + assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_001, dts: None, key: true }), Err(Error::Timestamp(_)))); + m.advance(2_000_000).unwrap(); + let after = m.get_ref().len(); + assert!(after > before); + assert!(matches!(m.write_frame(0, &Frame { data: &h264(false), pts: 1_000_000, dts: None, key: false }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), after, "nothing is written for a refused frame"); +} + +#[test] +fn timestamps_and_dts() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| { + m.write_frame(0, &Frame { data: &h264(true), pts: (1 << 33) + 6000, dts: Some((1 << 33) + 3000), key: true }).unwrap(); + }); + let p = &ts[2 * PACKET_SIZE..]; + let start = 5 + p[4] as usize; + let h = &p[start..]; + assert_eq!(&h[..9], &[0, 0, 1, 0xE0, 0, (3 + 10 + 6 + h264(true).len()) as u8, 0x84, 0xC0, 10]); + assert_eq!(h[9] >> 4, 3); + assert_eq!(h[14] >> 4, 1); +} + +#[test] +fn bad_frames_and_timestamps_write_nothing() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]).unwrap(); + fn f(data: &[u8], pts: i64, dts: Option) -> Frame<'_> { + Frame { data, pts, dts, key: true } + } + assert!(matches!(m.write_frame(2, &f(&h264(true), 90_000, None)), Err(Error::NoSuchStream(2)))); + assert!(matches!(m.write_frame(0, &f(&[], 90_000, None)), Err(Error::EmptyFrame))); + assert!(matches!(m.write_frame(0, &f(&h264(true), 90_000, Some(90_001))), Err(Error::Timestamp(_)))); + assert!(matches!(m.write_frame(0, &f(&[0x65, 0x88], 90_000, None)), Err(Error::BadFrame(_)))); + assert!(matches!(m.write_frame(1, &f(&[0xFF, 0xF1, 0, 0, 0, 0], 90_000, None)), Err(Error::BadFrame(_)))); + // ten ADTS frames of 7000 bytes: each is valid, together they pass the PES length + let one = { + let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (7000 >> 11) as u8, (7000 >> 3) as u8, ((7000 & 7) as u8) << 5 | 0x1F, 0xFC]; + v.resize(7000, 0x11); + v + }; + let long_adts = one.repeat(10); + assert!(matches!(m.write_frame(1, &f(&long_adts, 90_000, None)), Err(Error::FrameTooLarge { limit: 65_527, .. }))); + assert!(matches!(m.write_frame(0, &f(&h264(true), i64::MIN, None)), Err(Error::Timestamp(_)))); + assert!(m.get_ref().is_empty()); + m.write_frame(0, &f(&h264(true), 90_000, None)).unwrap(); + assert!(matches!(m.write_frame(0, &f(&h264(true), 80_000, None)), Err(Error::Timestamp(_)))); + // video has no PES length limit + let mut big = h264(true); + big.resize(200_000, 1); + m.write_frame(0, &f(&big, 93_000, None)).unwrap(); +} + +#[test] +fn settings_are_checked() { + let one = [Stream::new(0x100, Codec::H264)]; + let bad = |cfg: Config, streams: &[Stream]| matches!(Muxer::new(Vec::new(), cfg, streams), Err(Error::Config(_))); + let err = |cfg: Config, streams: &[Stream]| Muxer::new(Vec::new(), cfg, streams).err(); + let d = Config::default(); + assert!(bad(d, &[])); + assert!(bad(d, &[Stream::new(0x100, Codec::H264); MAX_STREAMS + 1])); + assert!(bad(Config { program_number: 0, ..d }, &one)); + assert!(matches!(err(Config { pmt_pid: 0x0F, ..d }, &one), Some(Error::BadPid(0x0F)))); + assert!(matches!(err(Config { pmt_pid: 0x1FFF, ..d }, &one), Some(Error::BadPid(0x1FFF)))); + assert!(bad(Config { pcr_interval: 0, ..d }, &one)); + assert!(bad(Config { pcr_interval: MAX_PCR_INTERVAL + 1, ..d }, &one)); + assert!(bad(Config { psi_interval: 0, ..d }, &one)); + assert!(bad(Config { batch_packets: 0, ..d }, &one)); + assert!(bad(Config { batch_packets: MAX_BATCH_PACKETS + 1, ..d }, &one)); + assert!(matches!(err(Config { pcr_delay: 0, ..d }, &one), Some(Error::PcrDelay(0)))); + assert!(matches!(err(Config { pcr_delay: MAX_PCR_DELAY + 1, ..d }, &one), Some(Error::PcrDelay(90_001)))); + assert!(err(Config { pcr_delay: MAX_PCR_DELAY, ..d }, &one).is_none()); + assert!(err(Config { pcr_delay: 1, ..d }, &one).is_none()); + assert!(matches!(err(Config { pcr_pid: Some(0x1000), ..d }, &one), Some(Error::DuplicatePid(0x1000)))); + assert!(matches!(err(Config { pcr_pid: Some(0x2000), ..d }, &one), Some(Error::BadPid(0x2000)))); + assert!(matches!(err(d, &[Stream::new(0x0005, Codec::H264)]), Some(Error::BadPid(5)))); + assert!(matches!(err(d, &[Stream::new(0x1000, Codec::H264)]), Some(Error::DuplicatePid(0x1000)))); + assert!(matches!(err(d, &[Stream::new(0x100, Codec::H264), Stream::new(0x100, Codec::Ac3)]), Some(Error::DuplicatePid(0x100)))); + assert!(!bad(Config { pcr_pid: Some(0x1FFE), ..d }, &one)); +} + +#[test] +fn stream_settings_are_checked() { + let bad = |cfg: Config, streams: &[Stream]| matches!(Muxer::new(Vec::new(), cfg, streams), Err(Error::Config(_))); + let err = |cfg: Config, streams: &[Stream]| Muxer::new(Vec::new(), cfg, streams).err(); + let d = Config::default(); + // the widest program fits: 32 streams of the longest descriptors + let wide: Vec = (0..MAX_STREAMS as u16).map(|i| Stream::new(0x100 + i, Codec::OpusMapped(WIDE_OPUS)).with_language(*b"eng")).collect(); + assert!(err(d, &wide).is_none()); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { streams: 7, ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { coupled: 5, ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [0, 1, 2, 3, 4, 10, 0, 0], ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 0, ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 2, ..WIDE_OPUS }))]), "a reserved family"); + assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 255, ..WIDE_OPUS }))])); + let stereo = OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] }; + assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(stereo))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { coupled: 255, ..stereo }))]), "no overflow"); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [1, 0, 0, 0, 0, 0, 0, 0], ..stereo }))]), "swapped"); + assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [0, 1, 2, 3, 4, 255, 0, 0], ..WIDE_OPUS }))])); + let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + assert!(!bad(d, &[Stream::new(0x100, Codec::Av1(av1))])); + assert!(bad(d, &[Stream::new(0x100, Codec::Av1(Av1Config { seq_profile: 3, ..av1 }))])); + assert!(Av1Config::from_av1c(&[0x01, 0x08, 0x0C, 0x00]).is_err()); + assert!(Av1Config::from_av1c(&[0x81, 0x08, 0x0C]).is_err()); + assert!(bad(d, &[Stream::new(0x100, Codec::Opus { channels: 0 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Opus { channels: 9 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 0, sample_rate_index: 3, channels: 2 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 2, sample_rate_index: 13, channels: 2 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 0 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"e1g")])); + assert!(bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"ENG")])); + assert!(!bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"eng")])); + // the first video stream carries the PCR by default + let m = Muxer::new(Vec::new(), d, &[Stream::new(0x101, Codec::Ac3), Stream::new(0x100, Codec::H264)]).unwrap(); + assert_eq!(m.pcr_pid(), 0x100); +} + +#[test] +fn wide_programs_split_the_pmt_across_packets() { + let streams: Vec = (0..MAX_STREAMS as u16).map(|i| Stream::new(0x100 + i, Codec::Opus { channels: 2 }).with_language(*b"eng")).collect(); + let ts = mux(Config::default(), &streams, |m| { + m.write_frame(0, &Frame { data: &[0xFC, 1], pts: 90_000, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + let pmt: Vec<_> = pk.iter().filter(|p| p.pid == 0x1000).collect(); + assert_eq!(pmt.len(), 4, "32 stream entries of 21 bytes"); + assert!(pmt[0].pusi && pmt[1..].iter().all(|p| !p.pusi)); + assert_eq!(pmt.iter().map(|p| p.cc).collect::>(), [0, 1, 2, 3]); + let mut section: Vec = + ts.chunks(PACKET_SIZE).zip(&pk).filter(|(_, p)| p.pid == 0x1000).flat_map(|(raw, p)| raw[if p.pusi { 5 } else { 4 }..].to_vec()).collect(); + let len = 3 + ((section[1] as usize & 0x0F) << 8 | section[2] as usize); + section.truncate(len); + assert_eq!(psi::crc32(§ion), 0); +} + +/// An output that records the length of every write call. +#[derive(Clone, Default)] +struct Calls(Rc>>); + +impl Write for Calls { + fn write(&mut self, b: &[u8]) -> io::Result { + self.0.borrow_mut().push(b.len()); + Ok(b.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// Video and audio for `seconds`, a 2 s GOP at 30 frames a second, in DTS order: (stream, frame). +fn av_timeline(seconds: i64) -> Vec<(usize, Vec, i64, bool)> { + let mut v = Vec::new(); + for k in 0..seconds * 30 { + let key = k % 60 == 0; + let mut f = h264(key); + f.resize(if key { 3000 } else { 700 }, 0x55); + v.push((0, f, 90_000 + k * 3000, key)); + } + for k in 0..seconds * 1000 / 32 { + v.push((1, vec![0x0B, 0x77, 0, 0, 0x08, 0x40, 0x40, 1, 2, 3], 90_000 + k * 2880, true)); + } + v.sort_by_key(|f| f.2); + v +} + +fn av_streams() -> [Stream; 2] { + [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)] +} + +#[test] +fn packets_go_out_in_batches() { + for hold in [false, true] { + let calls = Calls::default(); + let mut m = Muxer::new(calls.clone(), Config { hold_packets: hold, ..Config::default() }, &av_streams()).unwrap(); + for (s, f, t, key) in av_timeline(2) { + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + let before = m.stats(); + m.flush().unwrap(); + let st = m.stats(); + // held packets are counted once the output takes them + assert_eq!(before.packets == st.packets, !hold); + m.finish().unwrap(); + let lens = calls.0.borrow(); + assert!(lens.iter().all(|&n| n % PACKET_SIZE == 0 && n > 0 && n <= 7 * PACKET_SIZE), "{lens:?}"); + assert_eq!(lens.iter().sum::() as u64, st.bytes()); + if hold { + assert!(lens[..lens.len() - 1].iter().all(|&n| n == 7 * PACKET_SIZE), "held: full batches only"); + } else { + assert!(lens.len() as u64 >= st.frames, "a write at the end of every call"); + } + } +} + +#[test] +fn held_packets_reach_the_old_writer_before_a_swap() { + let cfg = Config { hold_packets: true, batch_packets: 348, ..Config::default() }; + let mut m = Muxer::new(Vec::new(), cfg, &av_streams()).unwrap(); + let mut segments = Vec::new(); + for (s, f, t, key) in av_timeline(10) { + if s == 0 && key && t > 90_000 { + segments.push(m.replace_writer(Vec::new())); + } + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + // held packets count once they reach the output + let held = m.stats(); + let last = m.replace_writer(Vec::new()); + let st = m.stats(); + assert!(held.packets < st.packets); + segments.push(last); + assert_eq!(segments.len(), 5, "a 2 s GOP over 10 s"); + let mut packets = 0; + let mut frames = 0; + for (n, seg) in segments.iter().enumerate() { + assert!(seg.error.is_none()); + assert_eq!(seg.writer.len() as u64, seg.packets * PACKET_SIZE as u64, "segment {n}"); + assert!(seg.starts_with_keyframe, "segment {n}"); + let pk = walk(&seg.writer); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "segment {n}"); + assert!(pk[2].pid == 0x100 && pk[2].pcr.is_some() && pk[2].rai, "segment {n}: the keyframe with a PCR"); + assert_eq!(seg.first_pts, Some(90_000 + n as i64 * 180_000)); + assert!(seg.last_pts.unwrap() < 90_000 + (n as i64 + 1) * 180_000); + packets += seg.packets; + frames += seg.frames; + } + assert_eq!((packets, frames), (st.packets, st.frames)); + // a segment cut before a frame that is not a keyframe says so + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + assert!(m.replace_writer(Vec::new()).starts_with_keyframe); + m.write_frame(0, &Frame { data: &h264(false), pts: 93_000, dts: None, key: false }).unwrap(); + assert!(!m.replace_writer(Vec::new()).starts_with_keyframe); +} + +#[test] +fn a_continuing_swap_leaves_the_packets_unchanged() { + let one = mux(Config::default(), &av_streams(), |m| { + for (s, f, t, key) in av_timeline(3) { + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + }); + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + let mut parts = Vec::new(); + for (n, (s, f, t, key)) in av_timeline(3).into_iter().enumerate() { + if n % 7 == 6 { + parts.push(m.replace_writer_continuing(Vec::new()).writer); + } + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + parts.push(m.finish().unwrap()); + assert!(parts.len() > 10); + assert_eq!(parts.concat(), one); +} + +#[test] +fn a_discontinuity_starts_a_new_time_base() { + for pcr_pid in [None, Some(0x1F0)] { + let mut m = Muxer::new(Vec::new(), Config { pcr_pid, ..Config::default() }, &av_streams()).unwrap(); + for (s, f, t, key) in av_timeline(2) { + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + let before = m.stats().packets as usize; + m.discontinuity(); + // the encoder restarts at a smaller timestamp, the audio first this time + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 9], pts: 100_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 100_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(false), pts: 103_000, dts: None, key: false }).unwrap(); + let ts = m.finish().unwrap(); + let pk = walk(&ts); + assert!(pk[..before].iter().all(|p| !p.disc)); + let after = &pk[before..]; + assert_eq!((after[0].pid, after[1].pid), (0, 0x1000), "{pcr_pid:?}: the tables first"); + let pcr_on = pcr_pid.unwrap_or(0x100); + let first_pcr = after.iter().find(|p| p.pcr.is_some()).unwrap(); + assert_eq!((first_pcr.pid, first_pcr.disc, first_pcr.pcr), (pcr_on, true, Some((100_000 - 63_000) * 300)), "{pcr_pid:?}"); + for pid in [0x100, 0x101] { + let first = after.iter().find(|p| p.pid == pid).unwrap(); + assert!(first.disc, "{pcr_pid:?}: PID {pid:#x}"); + assert_eq!(after.iter().filter(|p| p.pid == pid && p.disc).count(), 1, "{pcr_pid:?}: once on PID {pid:#x}"); + } + } +} + +#[test] +fn the_clock_after_advance_is_on_the_dts_scale() { + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + m.advance(900_000).unwrap(); + let pcrs: Vec = walk(m.get_ref()).iter().filter_map(|p| p.pcr).collect(); + assert_eq!(pcrs, [(900_000 - 63_000) * 300]); + let before = m.get_ref().len(); + assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_001, dts: None, key: true }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), before); + m.write_frame(0, &Frame { data: &h264(true), pts: 900_000 - 63_000, dts: None, key: true }).unwrap(); +} + +#[test] +fn streams_may_skew_by_the_pcr_delay() { + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + // video 500 ms ahead of the audio + for k in 0..30i64 { + m.write_frame(0, &Frame { data: &h264(k == 0), pts: 135_000 + k * 3000, dts: None, key: k == 0 }).unwrap(); + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000 + k * 3000, dts: None, key: true }).unwrap(); + } + // 800 ms behind the video is refused + let before = m.get_ref().len(); + m.write_frame(0, &Frame { data: &h264(false), pts: 900_000, dts: None, key: false }).unwrap(); + let mid = m.get_ref().len(); + assert!(mid > before); + assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 72_000, dts: None, key: true }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), mid); +} + +#[test] +fn video_decoding_times_must_increase() { + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 93_000, dts: Some(90_000), key: true }).unwrap(); + let before = m.get_ref().len(); + assert!(matches!(m.write_frame(0, &Frame { data: &h264(false), pts: 96_000, dts: Some(90_000), key: false }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), before); + // audio frames may share a time + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap(); +} + +#[test] +fn video_frames_past_the_reader_limit_are_refused() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + // zeroed pages are not touched before the size check + let mut big = vec![0u8; MAX_VIDEO_FRAME + 1]; + big[..5].copy_from_slice(&[0, 0, 0, 1, 0x65]); + assert!(matches!( + m.write_frame(0, &Frame { data: &big, pts: 90_000, dts: None, key: true }), + Err(Error::FrameTooLarge { limit: MAX_VIDEO_FRAME, .. }) + )); + assert_eq!(m.stats(), Stats::default()); + assert!(m.get_ref().is_empty()); + // an AV1 frame under the limit whose escapes take it over + let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::Av1(av1))]).unwrap(); + let mut tu = vec![0x0A, 0x05, 0x00, 0x00, 0x00, 0x02, 0x7F, 0x32]; + let payload = MAX_VIDEO_FRAME - 100; + let mut n = payload; + while n >= 0x80 { + tu.push((n & 0x7F) as u8 | 0x80); + n >>= 7; + } + tu.push(n as u8); + tu.resize(tu.len() + payload, 0); + *tu.last_mut().unwrap() = 1; + assert!(tu.len() <= MAX_VIDEO_FRAME); + assert!(matches!( + m.write_frame(0, &Frame { data: &tu, pts: 90_000, dts: None, key: true }), + Err(Error::FrameTooLarge { limit: MAX_VIDEO_FRAME, size }) if size > MAX_VIDEO_FRAME + )); + assert!(m.get_ref().is_empty()); +} + +#[test] +fn audio_specific_configs_become_adts_fields() { + let asc = |b: [u8; 2]| Codec::aac_from_asc(&b); + assert_eq!(asc([0x11, 0x90]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }); + assert_eq!(asc([0x12, 0x08]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 4, channels: 1 }); + assert_eq!(asc([0x11, 0xB0]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 6 }); + assert_eq!(asc([0x11, 0xB8]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 7 }); + assert!(asc([0x17, 0x80]).is_err(), "explicit sampling frequency"); + assert!(asc([0x29, 0x90]).is_err(), "SBR"); + assert!(asc([0x11, 0x80]).is_err(), "channel configuration 0"); + assert!(asc([0x11, 0x94]).is_err(), "frameLengthFlag 1"); + assert!(Codec::aac_from_asc(&[0x11]).is_err()); +} + +#[test] +fn opus_trims_follow_the_draft_rules() { + let opus = [Stream::new(0x100, Codec::Opus { channels: 2 }), Stream::new(0x101, Codec::Ac3)]; + let mut m = Muxer::new(Vec::new(), Config::default(), &opus).unwrap(); + // 8 CELT frames of 20 ms: 7680 samples + let au = [0xFF, 8, 0x11, 0x22]; + let f = |k: i64| Frame { data: &au, pts: 90_000 + k * 14_400, dts: None, key: true }; + assert!(matches!(m.write_frame_with_trim(1, &f(0), OpusTrim { start: 1, end: 0 }), Err(Error::BadFrame(_))), "not Opus"); + assert!(matches!(m.write_frame_with_trim(0, &f(0), OpusTrim { start: 7681, end: 0 }), Err(Error::BadFrame(_))), "longer than the unit"); + assert!(matches!(m.write_frame_with_trim(0, &f(0), OpusTrim { start: 8192, end: 0 }), Err(Error::BadFrame(_))), "13 bits"); + assert!(m.get_ref().is_empty()); + // whole units may be discarded at the start, 65 535 samples in all + for k in 0..8 { + m.write_frame_with_trim(0, &f(k), OpusTrim { start: 7680, end: 0 }).unwrap(); + } + assert!(matches!(m.write_frame_with_trim(0, &f(8), OpusTrim { start: 7680, end: 0 }), Err(Error::BadFrame(_)))); + m.write_frame_with_trim(0, &f(8), OpusTrim { start: 312, end: 0 }).unwrap(); + // the lead-in is over + assert!(matches!(m.write_frame_with_trim(0, &f(9), OpusTrim { start: 1, end: 0 }), Err(Error::BadFrame(_)))); + m.write_frame(0, &f(9)).unwrap(); + m.write_frame_with_trim(0, &f(10), OpusTrim { start: 0, end: 100 }).unwrap(); + // a restarted encoder trims its own start again + m.discontinuity(); + m.write_frame_with_trim(0, &f(0), OpusTrim { start: 312, end: 0 }).unwrap(); + m.write_frame_with_trim(0, &f(1), OpusTrim { start: 0, end: 100 }).unwrap(); + let ts = m.finish().unwrap(); + // the last unit's control header: end trim flag, size 4, end_trim 100 + let last = ts.chunks(PACKET_SIZE).rev().find(|p| p[1] & 0x40 != 0 && (u16::from(p[1] & 0x1F) << 8 | u16::from(p[2])) == 0x100).unwrap(); + let pes = &last[5 + last[4] as usize..]; + assert_eq!(&pes[14..19], &[0x7F, 0xE8, 4, 0, 100]); +} + +/// Each stream PID's PES packets: (random access indicator of the first packet, bytes). +fn pes_of(ts: &[u8], pids: &[u16]) -> std::collections::HashMap)>> { + let mut out: std::collections::HashMap)>> = Default::default(); + for (raw, p) in ts.chunks(PACKET_SIZE).zip(walk(ts)) { + if !pids.contains(&p.pid) || !p.payload { + continue; + } + let start = if raw[3] & 0x20 != 0 { 5 + raw[4] as usize } else { 4 }; + let list = out.entry(p.pid).or_default(); + if p.pusi { + list.push((p.rai, Vec::new())); + } + list.last_mut().unwrap().1.extend_from_slice(&raw[start..]); + } + out +} + +/// Reads a timestamp, checking its prefix and marker bits. +fn read_ts(b: &[u8], prefix: u8) -> i64 { + assert_eq!(b[0] >> 4, prefix); + assert_eq!([b[0] & 1, b[2] & 1, b[4] & 1], [1, 1, 1], "marker bits"); + (((b[0] >> 1) & 7) as i64) << 30 | (b[1] as i64) << 22 | ((b[2] >> 1) as i64) << 15 | (b[3] as i64) << 7 | (b[4] >> 1) as i64 +} + +#[test] +fn pes_headers_hold_their_fixed_bits_lengths_and_keyframes() { + let streams = [ + Stream::new(0x100, Codec::H264), + Stream::new(0x101, Codec::Ac3), + Stream::new(0x102, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }), + ]; + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + let mut frames: [Vec<(bool, i64, i64)>; 3] = Default::default(); + let mut outputs = Vec::new(); + for k in 0..120i64 { + if k % 40 == 0 && k > 0 { + outputs.push(m.replace_writer(Vec::new()).writer); + } + let key = k % 20 == 0; + let mut v = h264(key); + v.resize(if key { 30_000 } else { 70_000 + (k as usize * 997) % 9000 }, 0x55); + let dts = 90_000 + k * 3000; + let pts = dts + if key { 0 } else { 6000 }; + m.write_frame(0, &Frame { data: &v, pts, dts: Some(dts), key }).unwrap(); + frames[0].push((key, pts, dts)); + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 1, 2, 3], pts: dts, dts: None, key: true }).unwrap(); + frames[1].push((true, dts, dts)); + m.write_frame(2, &Frame { data: &vec![7; 1 + (k as usize * 31) % 1500], pts: dts, dts: None, key: true }).unwrap(); + frames[2].push((true, dts, dts)); + } + outputs.push(m.finish().unwrap()); + let mut seen = [0usize; 3]; + for ts in &outputs { + for (pid, list) in pes_of(ts, &[0x100, 0x101, 0x102]) { + let s = usize::from(pid - 0x100); + for (rai, pes) in list { + let (key, pts, dts) = frames[s][seen[s]]; + seen[s] += 1; + assert_eq!(&pes[..3], &[0, 0, 1]); + assert_eq!(pes[3], streams[s].codec.stream_id()); + assert_eq!(pes[6], 0x84, "'10', data_alignment_indicator"); + let length = usize::from(pes[4]) << 8 | usize::from(pes[5]); + if s == 0 && pes.len() - 6 > 0xFFFF { + assert_eq!(length, 0); + } else { + assert_eq!(length, pes.len() - 6, "PID {pid:#x}"); + } + assert_eq!(rai, key, "PID {pid:#x}"); + if pts == dts { + assert_eq!((pes[7], pes[8]), (0x80, 5)); + assert_eq!(read_ts(&pes[9..14], 2), pts); + } else { + assert_eq!((pes[7], pes[8]), (0xC0, 10)); + assert_eq!((read_ts(&pes[9..14], 3), read_ts(&pes[14..19], 1)), (pts, dts)); + } + } + } + } + assert_eq!(seen, [120, 120, 120]); +} + +/// An output that fails on one write call. +struct Flaky { + fail_on: Option, + calls: usize, + data: Vec, +} + +impl Write for Flaky { + fn write(&mut self, b: &[u8]) -> io::Result { + self.calls += 1; + if Some(self.calls) == self.fail_on { + return Err(io::Error::other("upload failed")); + } + self.data.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn a_new_writer_recovers_from_an_io_error() { + let mut m = Muxer::new(Flaky { fail_on: Some(3), calls: 0, data: Vec::new() }, Config::default(), &av_streams()).unwrap(); + let mut failed = false; + let mut recovered = None; + for (s, f, t, key) in av_timeline(2) { + match m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }) { + Ok(()) => {} + Err(Error::Io(_)) if !failed => { + failed = true; + let old = m.replace_writer(Flaky { fail_on: None, calls: 0, data: Vec::new() }); + assert_eq!(old.writer.data.len() % PACKET_SIZE, 0); + recovered = Some(m.stats().packets); + } + Err(e) => panic!("{e}"), + } + } + assert!(failed && recovered.is_some()); + let ts = m.finish().unwrap().data; + let pk = walk(&ts); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000)); + assert!(pk.iter().take(4).any(|p| p.pcr.is_some()), "a PCR right after the tables"); + // counters run on within the new output + let mut last: std::collections::HashMap = Default::default(); + for p in &pk { + if let Some(&c) = last.get(&p.pid) { + assert_eq!(p.cc, if p.payload { (c + 1) & 0x0F } else { c }); + } + last.insert(p.pid, p.cc); + } +} + +/// An output that takes `take` bytes in all and then fails. +struct Short { + take: usize, + data: Vec, +} + +impl Write for Short { + fn write(&mut self, b: &[u8]) -> io::Result { + if self.data.len() >= self.take { + return Err(io::Error::other("disk full")); + } + // at most 100 bytes a call, so a batch goes out in several calls + let n = b.len().min(100).min(self.take - self.data.len()); + self.data.extend_from_slice(&b[..n]); + Ok(n) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn packet_counts_hold_only_what_the_output_took() { + let take = 5 * PACKET_SIZE + 50; + let mut m = Muxer::new(Short { take, data: Vec::new() }, Config::default(), &av_streams()).unwrap(); + let mut failed = false; + for (s, f, t, key) in av_timeline(1) { + if m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).is_err() { + failed = true; + break; + } + } + assert!(failed); + assert_eq!(m.stats().packets, 5); + let seg = m.replace_writer(Short { take: usize::MAX, data: Vec::new() }); + assert_eq!((seg.packets, seg.writer.data.len()), (5, take)); + // the new output takes a partial write in several calls and counts every packet + m.write_frame(0, &Frame { data: &h264(true), pts: 200_000, dts: None, key: true }).unwrap(); + let st = m.stats(); + let seg = m.replace_writer(Short { take: 0, data: Vec::new() }); + assert_eq!(seg.writer.data.len() as u64, seg.packets * PACKET_SIZE as u64); + assert_eq!(st.packets, 5 + seg.packets); +} diff --git a/crates/media/tests/main.rs b/crates/media/tests/main.rs index 61e48eacc..599b71b30 100644 --- a/crates/media/tests/main.rs +++ b/crates/media/tests/main.rs @@ -6,6 +6,12 @@ mod common; mod fuzz; #[cfg(feature = "matroska")] mod fuzz_matroska; +#[cfg(feature = "mpegts")] +mod mpegts_mux; +#[cfg(feature = "mpegts")] +mod mpegts_mux_fuzz; +#[cfg(feature = "mpegts")] +mod mpegts_mux_readback; #[cfg(feature = "avi")] mod oracle_avi; #[cfg(feature = "avi")] diff --git a/crates/media/tests/mpegts_mux/mod.rs b/crates/media/tests/mpegts_mux/mod.rs new file mode 100644 index 000000000..4a3e6f2d1 --- /dev/null +++ b/crates/media/tests/mpegts_mux/mod.rs @@ -0,0 +1,260 @@ +//! Frames for the read-back tests, and a packet-level check of what the muxer wrote. + +#![allow(dead_code)] + +use std::collections::HashMap; + +use craft_media::mpegts::mux::{Codec, Frame, Muxer, PACKET_SIZE}; + +/// A frame queued for the muxer, with the bytes the demuxer should give back for it. +pub struct Item { + pub stream: usize, + pub data: Vec, + pub pts: i64, + pub dts: i64, + pub key: bool, + pub expect: Vec, +} + +/// Writes `items` in DTS order (stable, so equal DTS keep their order). +pub fn write_all(m: &mut Muxer>, items: &mut [Item]) { + items.sort_by_key(|i| i.dts); + for i in items.iter() { + let dts = (i.dts != i.pts).then_some(i.dts); + m.write_frame(i.stream, &Frame { data: &i.data, pts: i.pts, dts, key: i.key }).unwrap(); + } +} + +pub fn h264(key: bool, disposable: bool, size: usize, seed: u8) -> Vec { + let mut v = if key { + vec![0, 0, 0, 1, 0x67, 0x42, 0xC0, 0x1E, 0xDA, 0, 0, 0, 1, 0x68, 0xCE, 0x3C, 0x80, 0, 0, 1, 0x65, 0x88, 0x84] + } else if disposable { + vec![0, 0, 0, 1, 0x01, 0x9E] + } else { + vec![0, 0, 0, 1, 0x41, 0x9A] + }; + fill(&mut v, size, seed); + v +} + +pub fn hevc(key: bool, size: usize, seed: u8) -> Vec { + let mut v = if key { + vec![0, 0, 0, 1, 0x40, 0x01, 0x0C, 0, 0, 0, 1, 0x42, 0x01, 0x01, 0, 0, 0, 1, 0x44, 0x01, 0xC1, 0, 0, 1, 0x26, 0x01, 0xAF] + } else { + vec![0, 0, 0, 1, 0x02, 0x01, 0xD0] + }; + fill(&mut v, size, seed); + v +} + +/// An MPEG-2 picture (I with a sequence and GOP header, or P), `size` bytes. +pub fn mpeg2(key: bool, temporal_reference: u16, size: usize, seed: u8) -> Vec { + let mut v = Vec::new(); + if key { + v.extend_from_slice(&[0, 0, 1, 0xB3, 0x14, 0x00, 0xF0, 0x13, 0xFF, 0xFF, 0xE0, 0x18]); + v.extend_from_slice(&[0, 0, 1, 0xB8, 0x00, 0x08, 0x00, 0x00]); + } + let pct: u8 = if key { 1 } else { 2 }; + let tr = temporal_reference & 0x3FF; + v.extend_from_slice(&[0, 0, 1, 0x00, (tr >> 2) as u8, ((tr & 3) as u8) << 6 | pct << 3 | 0x07, 0xFF, 0xF8]); + v.extend_from_slice(&[0, 0, 1, 0x01, 0x12]); + fill(&mut v, size, seed); + v +} + +/// Pads with bytes that never form a start code. +pub fn fill(v: &mut Vec, size: usize, seed: u8) { + let mut x = seed as u32 | 1; + while v.len() < size { + x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345); + v.push(((x >> 16) as u8).max(1)); + } +} + +/// An ADTS frame: AAC LC, 48 kHz, 2 channels, `payload` bytes after the header. +pub fn adts(payload: usize, seed: u8) -> Vec { + let len = payload + 7; + let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC]; + fill(&mut v, len, seed); + v +} + +/// An AC-3 sync frame: 48 kHz, 64 kbit/s, 256 bytes. +pub fn ac3(seed: u8) -> Vec { + let mut v = vec![0x0B, 0x77, 0, 0, 0x08, 0x40, 0x40]; + fill(&mut v, 256, seed); + v +} + +/// An MPEG-1 Layer III frame (48 kHz, 128 kbit/s, 384 bytes), or with `low` an MPEG-2 one +/// (24 kHz, 64 kbit/s, 192 bytes). +pub fn mp3(low: bool, seed: u8) -> Vec { + let (mut v, size) = if low { (vec![0xFF, 0xF3, 0x84, 0x44], 192) } else { (vec![0xFF, 0xFB, 0x94, 0x44], 384) }; + fill(&mut v, size, seed); + v +} + +/// An E-AC-3 sync frame: independent substream 0, 256 bytes, 48 kHz, six blocks, 2/0, bsid 16. +pub fn eac3(seed: u8) -> Vec { + let mut v = vec![0x0B, 0x77, 0x00, 0x7F, 0x34, 0x80]; + fill(&mut v, 256, seed); + v +} + +/// An MPEG-4 Part 2 frame: a visual object sequence, visual object, video object layer and an +/// I-VOP, or a P-VOP alone. +pub fn mpeg4(key: bool, size: usize, seed: u8) -> Vec { + let mut v = if key { + vec![0, 0, 1, 0xB0, 0x01, 0, 0, 1, 0xB5, 0x09, 0, 0, 1, 0x00, 0, 0, 1, 0x20, 0x00, 0x84, 0x40, 0, 0, 1, 0xB6, 0x10] + } else { + vec![0, 0, 1, 0xB6, 0x50] + }; + fill(&mut v, size, seed); + v +} + +pub fn leb128(mut n: usize, v: &mut Vec) { + loop { + let b = (n & 0x7F) as u8; + n >>= 7; + if n == 0 { + v.push(b); + return; + } + v.push(b | 0x80); + } +} + +/// An AV1 temporal unit in the low overhead format: a temporal delimiter, a sequence header on +/// keyframes, and a frame OBU whose payload holds sequences that need emulation prevention. +pub fn av1(key: bool, size: usize, seed: u8) -> Vec { + let mut v = vec![0x12, 0x00]; + if key { + v.extend_from_slice(&[0x0A, 0x05, 0x00, 0x00, 0x00, 0x02, 0x7F]); + } + let mut payload = vec![0, 0, 1, 0, 0, 3, 0, 0, 0]; + fill(&mut payload, size, seed); + v.push(0x32); + leb128(payload.len(), &mut v); + v.extend_from_slice(&payload); + v +} + +/// The OBUs of a temporal unit without its temporal delimiters. +pub fn av1_without_delimiters(tu: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut at = 0; + while at < tu.len() { + let h = tu[at]; + let mut i = at + 1 + usize::from(h & 4 != 0); + let (mut size, mut shift) = (0usize, 0); + loop { + let b = tu[i]; + i += 1; + size |= usize::from(b & 0x7F) << shift; + shift += 7; + if b & 0x80 == 0 { + break; + } + } + if (h >> 3) & 0x0F != 2 { + out.extend_from_slice(&tu[at..i + size]); + } + at = i + size; + } + out +} + +/// Takes the start codes and emulation prevention bytes out of an AV1 PES payload, checking +/// that no 0x000000, 0x000001 or 0x000002 appears inside an OBU and that every 0x000003 is +/// followed by 0x00 to 0x03. +pub fn av1_unescape(es: &[u8]) -> Vec { + assert!(es.starts_with(&[0, 0, 1])); + let mut out = Vec::new(); + let (mut zeros, mut i) = (0, 0); + while i < es.len() { + if zeros == 0 && es[i..].starts_with(&[0, 0, 1]) { + i += 3; + continue; + } + let b = es[i]; + i += 1; + if zeros >= 2 { + assert!(b >= 3, "0x0000{b:02X} inside an OBU"); + zeros = 0; + if b == 3 { + assert!(es.get(i).is_some_and(|&n| n <= 3), "0x000003 followed by a byte that needs no escape"); + continue; + } + out.push(b); + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + out.push(b); + } + 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 +} + +/// What the demuxer gives back for a video frame: an access unit delimiter first. +pub fn with_aud(codec: Codec, data: &[u8]) -> Vec { + let mut v = match codec { + Codec::H264 => vec![0, 0, 0, 1, 0x09, 0xF0], + Codec::Hevc => vec![0, 0, 0, 1, 0x46, 0x01, 0x50], + _ => Vec::new(), + }; + v.extend_from_slice(data); + v +} + +/// Checks the packet layer: sync bytes, continuity counters, adaptation fields, and the PCR on +/// `pcr_pid` never more than `limit` (27 MHz) apart. Returns the PCRs. +pub fn check_packets(ts: &[u8], pcr_pid: u16, limit: i64) -> Vec { + assert_eq!(ts.len() % PACKET_SIZE, 0); + let mut cc: HashMap = HashMap::new(); + let mut pcrs = Vec::new(); + for p in ts.chunks(PACKET_SIZE) { + assert_eq!(p[0], 0x47); + assert_eq!(p[1] & 0x80, 0, "transport error indicator"); + assert_eq!(p[3] & 0xC0, 0, "scrambling"); + let pid = ((p[1] & 0x1F) as u16) << 8 | p[2] as u16; + let afc = p[3] >> 4 & 3; + assert_ne!(afc, 0); + let payload = afc & 1 != 0; + if let Some(&c) = cc.get(&pid) { + assert_eq!(p[3] & 0x0F, if payload { (c + 1) & 0x0F } else { c }, "continuity on PID {pid:#x}"); + } + cc.insert(pid, p[3] & 0x0F); + if afc & 2 != 0 { + let len = p[4] as usize; + assert!(if payload { len <= 182 } else { len == 183 }); + if len > 0 && p[5] & 0x10 != 0 { + assert!(len >= 7, "PCR flag in an adaptation field of {len} byte{}", if len == 1 { "" } else { "s" }); + assert_eq!(pid, pcr_pid, "a PCR off the PCR PID"); + let b = &p[6..12]; + assert_eq!(b[4] & 0x7E, 0x7E, "reserved bits"); + let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64; + let ext = ((b[4] & 1) as i64) << 8 | b[5] as i64; + assert!(ext < 300); + pcrs.push(base * 300 + ext); + } + if len > 1 { + assert!(p[6 + if p[5] & 0x10 != 0 { 6 } else { 0 }..5 + len].iter().all(|&b| b == 0xFF), "stuffing bytes"); + } + } + } + let wrap = (1i64 << 33) * 300; + for w in pcrs.windows(2) { + let d = (w[1] - w[0]).rem_euclid(wrap); + assert!(d > 0 && d <= limit, "PCRs {} apart (limit {limit})", d); + } + pcrs +} diff --git a/crates/media/tests/mpegts_mux_fuzz.rs b/crates/media/tests/mpegts_mux_fuzz.rs new file mode 100644 index 000000000..0067e5a17 --- /dev/null +++ b/crates/media/tests/mpegts_mux_fuzz.rs @@ -0,0 +1,229 @@ +//! Random programs, frames and timelines: the packet layer stays valid, and every frame reads back +//! with the demuxer, across random idle gaps and output swaps. Random bytes for every codec never +//! panic. +// Test code: a failed unwrap is a failed test. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::mpegts_mux; + +use craft_media::mpegts; +use craft_media::mpegts::mux::{Av1Config, Codec, Config, Error, Frame, MAX_PCR_DELAY, MAX_PCR_INTERVAL, Muxer, OpusMapping, OpusTrim, Stream}; +use mpegts_mux::*; +use proptest::prelude::*; + +/// One step of a plan: (stream, size, DTS step, PTS offset, key, idle time before it, cut before +/// it: 0 none, 1 a new segment, 2 a continuing swap). +type Step = (usize, usize, i64, i64, bool, Option, u8); + +#[derive(Debug, Clone)] +struct Plan { + pcr_interval: u32, + pcr_own: bool, + pcr_delay: u32, + psi_interval: u32, + psi_before_keyframes: bool, + batch_packets: u16, + hold_packets: bool, + frames: Vec, +} + +/// The streams of the read-back property, in the order of `Step`'s stream index. +const STREAMS: usize = 8; + +fn plan() -> impl Strategy { + let step = (0usize..STREAMS, 1usize..4000, 1i64..12_000, 0i64..9000, any::(), prop::option::weighted(0.2, 0i64..40_000), 0u8..3); + ( + 1u32..=MAX_PCR_INTERVAL, + any::(), + 1u32..=MAX_PCR_DELAY, + 1u32..200_000, + any::(), + 1u16..400, + any::(), + prop::collection::vec(step, 5..60), + ) + .prop_map(|(pcr_interval, pcr_own, pcr_delay, psi_interval, psi_before_keyframes, batch_packets, hold_packets, frames)| Plan { + pcr_interval, + pcr_own, + pcr_delay, + psi_interval, + psi_before_keyframes, + batch_packets, + hold_packets, + frames, + }) +} + +/// A frame of stream `s` and the bytes the demuxer gives back for it. +fn frame(s: usize, size: usize, key: bool, n: usize) -> (Vec, Vec) { + let seed = n as u8; + match s { + 0 => { + let d = h264(key, false, size.max(30), seed); + let e = with_aud(Codec::H264, &d); + (d, e) + } + 1 => { + let mut d = vec![0xFC]; + fill(&mut d, size.min(1500), seed); + let e = opus_unit(&d); + (d, e) + } + 2 => { + let mut d = Vec::new(); + fill(&mut d, size.min(2000), seed); + let len = d.len() + 7; + let mut e = vec![0xFF, 0xF1, 0x50, 0x40 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC]; + e.extend_from_slice(&d); + (d, e) + } + 3 => { + let d = hevc(key, size.max(40), seed); + let e = with_aud(Codec::Hevc, &d); + (d, e) + } + 4 => (ac3(seed), ac3(seed)), + 5 => (eac3(seed), eac3(seed)), + 6 => (mp3(false, seed), mp3(false, seed)), + _ => { + let d = mpeg2(key, (n % 1024) as u16, size.max(40), seed); + (d.clone(), d) + } + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn random_programs_read_back(p in plan()) { + let streams = [ + Stream::new(0x100, Codec::H264), + Stream::new(0x101, Codec::Opus { channels: 2 }), + Stream::new(0x102, Codec::Aac { object_type: 2, sample_rate_index: 4, channels: 1 }), + Stream::new(0x103, Codec::Hevc), + Stream::new(0x104, Codec::Ac3), + Stream::new(0x105, Codec::Eac3), + Stream::new(0x106, Codec::MpegAudio { low_sample_rate: false }), + Stream::new(0x107, Codec::Mpeg2Video), + ]; + let cfg = Config { + pcr_interval: p.pcr_interval, + pcr_pid: p.pcr_own.then_some(0x1F0), + pcr_delay: p.pcr_delay, + psi_interval: p.psi_interval, + psi_before_keyframes: p.psi_before_keyframes, + batch_packets: p.batch_packets, + hold_packets: p.hold_packets, + ..Config::default() + }; + let mut m = Muxer::new(Vec::new(), cfg, &streams).unwrap(); + let mut t = 100_000i64; + let mut want: [Vec<(Vec, i64, i64)>; STREAMS] = Default::default(); + let mut segments = Vec::new(); + let mut restarted = false; + for (n, &(s, size, step, offset, key, idle, cut)) in p.frames.iter().enumerate() { + if let Some(idle) = idle { + // an idle gap that ends no later than the next frame's DTS + m.advance(t + idle.min(step)).unwrap(); + } + t += step; + match cut { + 1 => { + segments.push((true, m.replace_writer(Vec::new()))); + restarted = true; + } + 2 => segments.push((false, m.replace_writer_continuing(Vec::new()))), + _ => {} + } + let (data, expect) = frame(s, size, key, n); + let pts = if matches!(s, 0 | 3 | 7) { t + offset } else { t }; + m.write_frame(s, &Frame { data: &data, pts, dts: Some(t), key }).unwrap(); + want[s].push((expect, pts, t)); + } + let pcr_pid = m.pcr_pid(); + m.flush().unwrap(); + let stats = m.stats(); + let last = m.finish().unwrap(); + // an output that follows `replace_writer` starts with the PAT + let mut parts: Vec> = Vec::new(); + let mut fresh = false; + for (restart, seg) in segments { + prop_assert!(seg.error.is_none()); + prop_assert_eq!(seg.writer.len() as u64, seg.packets * 188); + if fresh && !seg.writer.is_empty() { + prop_assert_eq!((seg.writer[1] & 0x1F, seg.writer[2]), (0, 0)); + } + fresh = restart; + parts.push(seg.writer); + } + if fresh && !last.is_empty() { + prop_assert_eq!((last[1] & 0x1F, last[2]), (0, 0)); + } + parts.push(last); + let ts = parts.concat(); + prop_assert_eq!(ts.len() as u64, stats.bytes()); + if stats.pcr_gaps == 0 && !restarted { + check_packets(&ts, pcr_pid, i64::from(p.pcr_interval) * 300); + } + let file = mpegts::open(&ts).unwrap(); + prop_assert!(file.warnings.is_empty(), "{:?}", file.warnings); + for (k, w) in want.iter().enumerate() { + let units = &file.streams[k].units; + prop_assert_eq!(units.len(), w.len(), "stream {}", k); + for (n, (u, (bytes, pts, dts))) in units.iter().zip(w).enumerate() { + prop_assert_eq!(u.pts, Some(*pts)); + prop_assert_eq!(u.dts.or(u.pts), Some(*dts)); + prop_assert_eq!(&file.read_unit(&ts, k, n).unwrap(), bytes); + } + } + } + + #[test] + fn random_bytes_never_panic( + codec in 0usize..14, + frames in prop::collection::vec((prop::collection::vec(any::(), 0..3000), any::(), prop::option::of(any::()), any::(), any::(), any::()), 1..30), + interval in 0u32..20_000, + ) { + let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + let mapped = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }; + let codec = [ + Codec::H264, + Codec::Hevc, + Codec::Mpeg2Video, + Codec::AacAdts, + Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }, + Codec::Opus { channels: 2 }, + Codec::Ac3, + Codec::MpegAudio { low_sample_rate: false }, + Codec::MpegAudio { low_sample_rate: true }, + Codec::Mpeg1Video, + Codec::Mpeg4Part2, + Codec::Av1(av1), + Codec::Eac3, + Codec::OpusMapped(mapped), + ][codec]; + let cfg = Config { pcr_interval: interval, ..Config::default() }; + let Ok(mut m) = Muxer::new(Vec::new(), cfg, &[Stream::new(0x100, codec)]) else { + prop_assert!(interval == 0 || interval > MAX_PCR_INTERVAL); + return Ok(()); + }; + for (n, (data, pts, dts, key, start, end)) in frames.iter().enumerate() { + let trim = if n % 3 == 0 { OpusTrim { start: *start, end: *end } } else { OpusTrim::default() }; + match m.write_frame_with_trim(0, &Frame { data, pts: *pts, dts: *dts, key: *key }, trim) { + Ok(()) | Err(Error::BadFrame(_) | Error::EmptyFrame | Error::Timestamp(_) | Error::FrameTooLarge { .. }) => {} + Err(e) => prop_assert!(false, "{e}"), + } + let _ = m.advance(*pts); + if n % 7 == 6 { + m.discontinuity(); + } + } + let ts = m.finish().unwrap(); + prop_assert_eq!(ts.len() % 188, 0); + // the demuxer recognizes a transport stream by five sync bytes in a row + if ts.len() >= 5 * 188 { + prop_assert!(mpegts::open(&ts).is_ok()); + } + } +} diff --git a/crates/media/tests/mpegts_mux_readback.rs b/crates/media/tests/mpegts_mux_readback.rs new file mode 100644 index 000000000..7d8471525 --- /dev/null +++ b/crates/media/tests/mpegts_mux_readback.rs @@ -0,0 +1,356 @@ +//! The transport stream writer's output read back with the demuxer: streams, codecs, every +//! frame's bytes and timestamps, keyframes, the PCR, and no continuity or CRC warnings. +// Test code: a failed unwrap is a failed test. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::mpegts_mux; + +use craft_media::mpegts::mux::{Av1Config, Codec, Config, Error, Frame, MAX_PCR_INTERVAL, Muxer, OpusMapping, Stream}; +use craft_media::mpegts::{self, Codec as Demuxed, StreamId}; +use mpegts_mux::*; + +const DELAY: i64 = 63_000; + +/// Muxes `items`, reads the file back and compares every unit. Returns the file and the PCRs. +fn round_trip(cfg: Config, streams: &[Stream], items: &mut [Item], want: &[Demuxed]) -> (Vec, Vec) { + let mut m = Muxer::new(Vec::new(), cfg, streams).unwrap(); + write_all(&mut m, items); + let pcr_pid = m.pcr_pid(); + let stats = m.stats(); + let ts = m.finish().unwrap(); + assert_eq!(stats.bytes(), ts.len() as u64); + assert_eq!(stats.frames, items.len() as u64); + let pcrs = check_packets(&ts, pcr_pid, i64::from(cfg.pcr_interval) * 300); + + let file = mpegts::open(&ts).unwrap(); + assert_eq!(file.format, mpegts::Format::Ts { packet_size: 188, sync_offset: 0 }); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + assert_eq!(file.program, Some(cfg.program_number)); + assert_eq!(file.streams.len(), streams.len()); + assert!(file.pcr_range.is_some()); + for (s, (st, codec)) in file.streams.iter().zip(streams.iter().zip(want)) { + assert_eq!(s.id, StreamId::Pid(st.pid)); + assert_eq!(&s.codec, codec, "PID {:#x}", st.pid); + assert_eq!(s.stream_type, st.codec.stream_type()); + assert_eq!(s.language, st.language.map(|l| String::from_utf8(l.to_vec()).unwrap())); + } + for (k, _) in streams.iter().enumerate() { + let mine: Vec<&Item> = items.iter().filter(|i| i.stream == k).collect(); + let units = &file.streams[k].units; + assert_eq!(units.len(), mine.len(), "stream {k}"); + for (n, (u, i)) in units.iter().zip(&mine).enumerate() { + assert_eq!(u.pts, Some(i.pts), "stream {k} unit {n}"); + assert_eq!(u.dts.or(u.pts), Some(i.dts), "stream {k} unit {n}"); + if streams[k].codec.is_video() && !matches!(want[k], Demuxed::Unknown(_)) { + assert_eq!(u.key, i.key, "stream {k} unit {n}"); + } + assert_eq!(file.read_unit(&ts, k, n).unwrap(), i.expect, "stream {k} unit {n}"); + } + } + (ts, pcrs) +} + +#[test] +fn every_codec_in_one_program() { + let streams = [ + Stream::new(0x100, Codec::H264), + Stream::new(0x101, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }).with_language(*b"eng"), + Stream::new(0x102, Codec::Opus { channels: 2 }).with_language(*b"deu"), + Stream::new(0x103, Codec::Ac3), + Stream::new(0x104, Codec::MpegAudio { low_sample_rate: false }), + ]; + let mut items = Vec::new(); + let t0 = 90_000; + for k in 0..90i64 { + // decode order I P B B P B B ...: P pictures shown 3 frames later, B pictures 1 later + let key = k % 30 == 0; + let (disposable, show) = match k % 3 { + 0 => (false, 3), + _ => (true, 1), + }; + let size = if key { 9000 } else { 300 + (k as usize * 37) % 2000 }; + let data = h264(key, disposable && !key, size, k as u8); + let dts = t0 + k * 3000; + items.push(Item { stream: 0, expect: with_aud(Codec::H264, &data), data, pts: dts + show * 3000, dts, key }); + } + for k in 0..140i64 { + let raw = { + let mut v = Vec::new(); + fill(&mut v, 200 + (k as usize * 13) % 600, k as u8); + v + }; + let mut expect = adts(0, 0)[..7].to_vec(); + let len = raw.len() + 7; + expect[3] = 0x80 | (len >> 11) as u8; + expect[4] = (len >> 3) as u8; + expect[5] = ((len & 7) as u8) << 5 | 0x1F; + expect.extend_from_slice(&raw); + items.push(Item { stream: 1, data: raw, pts: t0 + k * 1920, dts: t0 + k * 1920, key: true, expect }); + } + 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 }); + } + for k in 0..90i64 { + let f = ac3(k as u8); + items.push(Item { stream: 3, expect: f.clone(), data: f, pts: t0 + k * 2880, dts: t0 + k * 2880, key: true }); + } + for k in 0..120i64 { + 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 (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()))); + assert_eq!(pcrs[0], (t0 - DELAY) * 300); + // 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))); +} + +#[test] +fn hevc_with_adts_and_a_pcr_pid_of_its_own() { + let streams = [Stream::new(0x1FFE, Codec::Hevc), Stream::new(0x0010, Codec::AacAdts)]; + let cfg = Config { pcr_pid: Some(0x0011), pcr_interval: MAX_PCR_INTERVAL, psi_interval: 45_000, ..Config::default() }; + let mut items = Vec::new(); + for k in 0..60i64 { + let key = k % 20 == 0; + let data = hevc(key, if key { 20_000 } else { 700 }, k as u8); + let t = 70_000 + k * 3003; + items.push(Item { stream: 0, expect: with_aud(Codec::Hevc, &data), data, pts: t, dts: t, key }); + } + for k in 0..95i64 { + let f = adts(150 + k as usize, k as u8); + let t = 70_000 + k * 1920; + items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); + } + let (ts, _) = round_trip(cfg, &streams, &mut items, &[Demuxed::Hevc, Demuxed::AacAdts]); + let file = mpegts::open(&ts).unwrap(); + assert!(file.pcr_range.is_some(), "the demuxer reads the PCR from the PMT's PCR_PID"); +} + +#[test] +fn mpeg2_video_and_low_rate_mpeg_audio() { + let streams = [Stream::new(0x200, Codec::Mpeg2Video), Stream::new(0x201, Codec::MpegAudio { low_sample_rate: true })]; + let mut items = Vec::new(); + for k in 0..50i64 { + let key = k % 12 == 0; + let data = mpeg2(key, (k % 12) as u16, if key { 4000 } else { 900 }, k as u8); + let t = 100_000 + k * 3600; + items.push(Item { stream: 0, expect: data.clone(), data, pts: t, dts: t, key }); + } + for k in 0..70i64 { + let f = mp3(true, k as u8); + let t = 100_000 + k * 2160; + items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); + } + round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg2Video, Demuxed::MpegAudio]); +} + +#[test] +fn timestamps_run_past_the_33_bit_wrap() { + let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Opus { channels: 1 })]; + let start = (1i64 << 33) - 90_000; + let mut items = Vec::new(); + for k in 0..90i64 { + let data = h264(k == 0, false, 500, k as u8); + let t = start + k * 3000; + items.push(Item { stream: 0, expect: with_aud(Codec::H264, &data), data, pts: t, dts: t, key: k == 0 }); + } + 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 }); + } + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Unknown(6)]); +} + +#[test] +fn eac3_mpeg1_video_and_mpeg4_part2() { + let streams = + [Stream::new(0x100, Codec::Mpeg1Video), Stream::new(0x101, Codec::Eac3).with_language(*b"spa"), Stream::new(0x102, Codec::Mpeg4Part2)]; + let mut items = Vec::new(); + for k in 0..50i64 { + let key = k % 12 == 0; + let data = mpeg2(key, (k % 12) as u16, if key { 4000 } else { 900 }, k as u8); + let t = 100_000 + k * 3600; + items.push(Item { stream: 0, expect: data.clone(), data, pts: t, dts: t, key }); + let data = mpeg4(key, if key { 3000 } else { 600 }, k as u8); + items.push(Item { stream: 2, expect: data.clone(), data, pts: t, dts: t, key }); + } + for k in 0..60i64 { + let f = eac3(k as u8); + 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)]); +} + +#[test] +fn av1_reads_back_as_its_obus() { + let config = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + let streams = [Stream::new(0x100, Codec::Av1(config)), Stream::new(0x101, Codec::Opus { channels: 2 })]; + let mut tus = Vec::new(); + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + for k in 0..60i64 { + let key = k % 30 == 0; + let tu = av1(key, if key { 20_000 } else { 300 + (k as usize * 113) % 3000 }, k as u8); + 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)); + } + 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].stream_type, 0x06); + let units = &file.streams[0].units; + assert_eq!(units.len(), tus.len()); + for (n, (u, (tu, t))) 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}"); + } +} + +#[test] +fn opus_with_an_explicit_mapping_and_trims() { + let mapping = OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [0, 1, 2, 0, 0, 0, 0, 0] }; + let streams = [Stream::new(0x100, Codec::OpusMapped(mapping))]; + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + let mut want = Vec::new(); + 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 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); + } + 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()); + for (n, w) in want.iter().enumerate() { + assert_eq!(&file.read_unit(&ts, 0, n).unwrap(), w); + } +} + +#[test] +fn a_discontinuity_reads_back_in_both_time_bases() { + let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]; + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + let mut want: [Vec<(Vec, i64)>; 2] = Default::default(); + for (part, start) in [(0, 900_000i64), (1, 200_000)] { + if part == 1 { + m.discontinuity(); + } + for k in 0..30i64 { + let data = h264(k == 0, false, 400, k as u8); + let t = start + k * 3000; + m.write_frame(0, &Frame { data: &data, pts: t, dts: None, key: k == 0 }).unwrap(); + want[0].push((with_aud(Codec::H264, &data), t)); + let f = adts(100, k as u8); + m.write_frame(1, &Frame { data: &f, pts: t, dts: None, key: true }).unwrap(); + want[1].push((f, t)); + } + } + let ts = m.finish().unwrap(); + let file = mpegts::open(&ts).unwrap(); + for (k, w) in want.iter().enumerate() { + let units = &file.streams[k].units; + assert_eq!(units.len(), w.len(), "stream {k}"); + for (n, (u, (bytes, t))) in units.iter().zip(w).enumerate() { + assert_eq!(u.pts.map(|p| p.rem_euclid(1 << 33)), Some(*t), "stream {k} unit {n}"); + assert_eq!(&file.read_unit(&ts, k, n).unwrap(), bytes, "stream {k} unit {n}"); + } + } +} + +/// An output that fails on its third write call. +struct Flaky { + fail_on: Option, + calls: usize, + data: Vec, +} + +impl std::io::Write for Flaky { + fn write(&mut self, b: &[u8]) -> std::io::Result { + self.calls += 1; + if Some(self.calls) == self.fail_on { + return Err(std::io::Error::other("upload failed")); + } + self.data.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[test] +fn the_output_after_an_io_error_reads_on_its_own() { + let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)]; + let mut m = Muxer::new(Flaky { fail_on: Some(3), calls: 0, data: Vec::new() }, Config::default(), &streams).unwrap(); + let mut after = [0usize; 2]; + let mut failed = false; + for k in 0..60i64 { + let t = 90_000 + k * 3000; + let data = h264(k % 30 == 0, false, 2000, k as u8); + for (s, frame) in + [(0, Frame { data: &data, pts: t, dts: None, key: k % 30 == 0 }), (1, Frame { data: &ac3(k as u8), pts: t, dts: None, key: true })] + { + match m.write_frame(s, &frame) { + Ok(()) if failed => after[s] += 1, + Ok(()) => {} + Err(Error::Io(_)) if !failed => { + failed = true; + m.replace_writer(Flaky { fail_on: None, calls: 0, data: Vec::new() }); + } + Err(e) => panic!("{e}"), + } + } + } + assert!(failed); + let ts = m.finish().unwrap().data; + let file = mpegts::open(&ts).unwrap(); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + // every frame written after the error reads back + assert_eq!(file.streams[1].units.len(), after[1]); + assert_eq!(file.streams[0].units.len(), after[0]); +} + +#[test] +fn a_single_frame_and_a_huge_one() { + let streams = [Stream::new(0x100, Codec::H264)]; + // 1000 bytes: the demuxer needs five packets in a row to recognize the file + let one = h264(true, false, 1000, 1); + let mut items = vec![Item { stream: 0, expect: with_aud(Codec::H264, &one), data: one, pts: 90_000, dts: 90_000, key: true }]; + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264]); + // past PES_packet_length's 65 535 bytes: an unbounded video PES packet + let big = h264(true, false, 3_000_000, 2); + let small = h264(false, false, 100, 3); + let mut items = vec![ + Item { stream: 0, expect: with_aud(Codec::H264, &big), data: big, pts: 90_000, dts: 90_000, key: true }, + Item { stream: 0, expect: with_aud(Codec::H264, &small), data: small, pts: 93_000, dts: 93_000, key: false }, + ]; + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264]); +} + +#[test] +#[should_panic(expected = "PCR flag in an adaptation field of 1 byte")] +fn the_packet_checker_refuses_a_pcr_flag_in_a_short_adaptation_field() { + // adaptation_field_length 1 holds only the flags byte, so the six bytes after it are payload + let mut p = vec![0x7E; 188]; + p[..6].copy_from_slice(&[0x47, 0x01, 0x00, 0x30, 0x01, 0x10]); + check_packets(&p, 0x100, 3600 * 300); +} diff --git a/crates/midi/src/lib.rs b/crates/midi/src/lib.rs index 9d1fa3914..a47561566 100644 --- a/crates/midi/src/lib.rs +++ b/crates/midi/src/lib.rs @@ -10,6 +10,8 @@ //! Written from the public Standard MIDI Files 1.0 specification. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +/// Live MIDI 1.0 channel-voice message decoding. +pub mod live; mod sequence; mod smf; pub mod source_timed; diff --git a/crates/midi/src/live.rs b/crates/midi/src/live.rs new file mode 100644 index 000000000..f4ac1fae7 --- /dev/null +++ b/crates/midi/src/live.rs @@ -0,0 +1,85 @@ +//! Live MIDI 1.0 channel-voice message decoding. + +/// Decoded MIDI 1.0 channel-voice message. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChannelMessage { + /// Note Off (`0x8n`, key, release velocity). + NoteOff { channel: u8, key: u8, velocity: u8 }, + /// Note On (`0x9n`, key, velocity). + NoteOn { channel: u8, key: u8, velocity: u8 }, + /// Polyphonic key pressure / aftertouch (`0xAn`, key, pressure). + PolyPressure { channel: u8, key: u8, pressure: u8 }, + /// Control Change (`0xBn`, controller `0..=127`, value `0..=127`). + ControlChange { channel: u8, controller: u8, value: u8 }, + /// Channel pressure / aftertouch (`0xDn`, pressure `0..=127`). + ChannelPressure { channel: u8, pressure: u8 }, + /// 14-bit Pitch Bend (`0xEn`, value `0..=16383`). + PitchBend { channel: u8, value: u16 }, +} + +impl ChannelMessage { + /// Parses one MIDI 1.0 channel-voice message from raw wire bytes. + /// + /// Returns `None` for truncated messages, out-of-range data bytes (`> 127`), + /// system messages (`0xF0..=0xFF`), or Program Change (`0xCn`). + #[must_use] + pub fn parse(message: &[u8]) -> Option { + let &status = message.first()?; + let channel = status & 0x0F; + let &a = message.get(1)?; + if a > 127 { + return None; + } + match status & 0xF0 { + 0x80 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::NoteOff { channel, key: a, velocity: b }) + } + 0x90 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::NoteOn { channel, key: a, velocity: b }) + } + 0xA0 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::PolyPressure { channel, key: a, pressure: b }) + } + 0xB0 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::ControlChange { channel, controller: a, value: b }) + } + 0xD0 => Some(Self::ChannelPressure { channel, pressure: a }), + 0xE0 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::PitchBend { channel, value: (u16::from(b) << 7) | u16::from(a) }) + } + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::ChannelMessage; + + #[test] + fn parses_channel_voice_messages() { + assert_eq!(ChannelMessage::parse(&[0x92, 60, 100]), Some(ChannelMessage::NoteOn { channel: 2, key: 60, velocity: 100 })); + assert_eq!(ChannelMessage::parse(&[0x82, 60, 64]), Some(ChannelMessage::NoteOff { channel: 2, key: 60, velocity: 64 })); + assert_eq!(ChannelMessage::parse(&[0xA5, 64, 90]), Some(ChannelMessage::PolyPressure { channel: 5, key: 64, pressure: 90 })); + assert_eq!(ChannelMessage::parse(&[0xB1, 74, 127]), Some(ChannelMessage::ControlChange { channel: 1, controller: 74, value: 127 })); + assert_eq!(ChannelMessage::parse(&[0xD3, 55]), Some(ChannelMessage::ChannelPressure { channel: 3, pressure: 55 })); + assert_eq!(ChannelMessage::parse(&[0xE0, 0x00, 0x40]), Some(ChannelMessage::PitchBend { channel: 0, value: 8192 })); + assert_eq!(ChannelMessage::parse(&[0xEF, 0x7F, 0x7F]), Some(ChannelMessage::PitchBend { channel: 15, value: 16383 })); + } + + #[test] + fn rejects_invalid_and_truncated_messages() { + assert_eq!(ChannelMessage::parse(&[]), None); + assert_eq!(ChannelMessage::parse(&[0x90, 60]), None); + assert_eq!(ChannelMessage::parse(&[0x90, 128, 64]), None); + assert_eq!(ChannelMessage::parse(&[0x90, 60, 128]), None); + assert_eq!(ChannelMessage::parse(&[0xD0, 128]), None); + assert_eq!(ChannelMessage::parse(&[0xC0, 10]), None); + assert_eq!(ChannelMessage::parse(&[0xF8]), None); + } +} diff --git a/crates/pkcs7/README.md b/crates/pkcs7/README.md index fc715c3b9..b0339a848 100644 --- a/crates/pkcs7/README.md +++ b/crates/pkcs7/README.md @@ -7,6 +7,11 @@ message or a digital ID file is made of. keeps its exact encoding, so a signed structure is verified over the bytes that were signed. Reading is strict DER; `parse_ber` also takes indefinite lengths and segmented strings, which PKCS #12 files from Windows use. Nesting is bounded. +- **`inspection`**: borrowed definite-length cursors without child-list allocations and borrowed X.509 wire fields. + Each sibling list is bounded to 4,096 elements and child cursors to depth 32; callers must + separately bound whole-document traversal. Redundant lengths are flagged. Optional and + trailing fields remain explicitly uninspected until their cursors are consumed. This is + evidence extraction, not a complete certificate validator or a signature/trust verdict. - **`x509`**: certificates (RFC 5280): names, validity, key, the extensions that matter for signing (basic constraints, key usage, extended key usage, key identifiers, OCSP and CRL locations), `build_chain` / `build_chain_noted` (issuers that may issue, path length, validity, @@ -42,3 +47,7 @@ Weak algorithms are read, not refused, because old signed documents use them: `DigestAlg::weakness` and `PublicKey::weakness` say when one is weak, and the caller decides. Moved from PdfCraft's `pdfcraft-sign`. + +The inspection profile follows Craft Anything’s bounded reader and Afloat’s raw-certificate +and non-minimal-length contributions (craft-anything #1131, #1514, #1646). Existing verification +and trust APIs are unchanged; high-level CMS/metadata adapters remain separate work. diff --git a/crates/pkcs7/src/inspection.rs b/crates/pkcs7/src/inspection.rs new file mode 100644 index 000000000..aacc6aa94 --- /dev/null +++ b/crates/pkcs7/src/inspection.rs @@ -0,0 +1,186 @@ +//! Bounded, borrowed inspection of definite-length ASN.1 and X.509 wire fields. +//! +//! These views are evidence, not validated certificates or signature/trust verdicts. They do +//! not replace [`crate::x509::Certificate`]. Unknown algorithms and original encodings are kept. +//! The profile follows Craft Anything's inspection reader (including Afloat's raw-field and +//! non-minimal-length work); callers retain their existing semantic and verification checks. + +use crate::der::{Tlv, tag}; + +pub mod cms; + +/// Maximum siblings read by one cursor, matching the inspection consumer's bound. +pub const MAX_CHILDREN: usize = 4096; +/// Maximum nesting accepted when obtaining child cursors. Root elements have depth zero. +pub const MAX_DEPTH: usize = 32; + +/// An inspection stopped without establishing that the remaining bytes are complete. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum InspectionError { + #[error("malformed or unsupported definite-length element")] + Malformed, + #[error("inspection child limit reached")] + ChildLimit, + #[error("inspection depth limit reached")] + DepthLimit, + #[error("missing or unexpected certificate field")] + Field, +} + +/// One borrowed wire element. Redundant definite lengths are readable but explicitly noted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Element<'a> { + tlv: Tlv<'a>, + depth: usize, + non_minimal_length: bool, +} + +impl<'a> Element<'a> { + pub fn tag(&self) -> u8 { + self.tlv.tag + } + pub fn raw(&self) -> &'a [u8] { + self.tlv.raw + } + pub fn value(&self) -> &'a [u8] { + self.tlv.value + } + pub fn non_minimal_length(&self) -> bool { + self.non_minimal_length + } + + /// Inspect children without allocating a child list. Primitive values are not interpreted as children. + pub fn children(&self) -> Result, InspectionError> { + if self.tlv.tag & 0x20 == 0 { + return Err(InspectionError::Field); + } + // Prevent callers following nested wire fields from silently exceeding the profile. + if self.depth >= MAX_DEPTH { + return Err(InspectionError::DepthLimit); + } + Ok(Cursor::at_depth(self.tlv.value, self.depth + 1)) + } +} + +/// A non-recursive sibling cursor with a hard per-list work bound and no child-list allocation. +/// +/// Successful reads allocate no memory; the underlying parser may allocate an error message. +/// `Ok(None)` means complete input, never a malformed/limited prefix. Errors are sticky and +/// leave the offending remainder available. Separate cursors have separate sibling budgets; +/// this does not impose a global budget on an application's traversal of many lists. +#[derive(Clone, Debug)] +pub struct Cursor<'a> { + remaining: &'a [u8], + count: usize, + depth: usize, + stopped: Option, +} + +impl<'a> Cursor<'a> { + pub fn new(input: &'a [u8]) -> Self { + Self::at_depth(input, 0) + } + fn at_depth(input: &'a [u8], depth: usize) -> Self { + Self { remaining: input, count: 0, depth, stopped: None } + } + /// Bytes not yet inspected. An empty remainder alone is not a recursive DER validation. + pub fn remaining(&self) -> &'a [u8] { + self.remaining + } + pub fn next_element(&mut self) -> Result>, InspectionError> { + if let Some(error) = self.stopped { + return Err(error); + } + if self.remaining.is_empty() { + return Ok(None); + } + if self.count == MAX_CHILDREN { + self.stopped = Some(InspectionError::ChildLimit); + return Err(InspectionError::ChildLimit); + } + let input = self.remaining; + let (tlv, rest) = match Tlv::parse(input) { + Ok(value) => value, + Err(_) => { + self.stopped = Some(InspectionError::Malformed); + return Err(InspectionError::Malformed); + } + }; + let non_minimal_length = input.get(1).is_some_and(|b| b & 0x80 != 0) && (input.get(2) == Some(&0) || tlv.value.len() < 128); + self.remaining = rest; + self.count += 1; + Ok(Some(Element { tlv, depth: self.depth, non_minimal_length })) + } + fn required(&mut self, expected: u8) -> Result, InspectionError> { + self.next_element()?.filter(|e| e.tag() == expected).ok_or(InspectionError::Field) + } +} + +/// Borrowed required X.509 wire fields, without algorithm, signature, key or trust validation. +/// +/// The BIT STRING is retained whole, including its unused-bit count. Both AlgorithmIdentifier +/// encodings are retained independently: their equality and parameter policy are the verifier's +/// responsibility. Optional/trailing fields remain in bounded cursors rather than being silently +/// reported as complete. Parsing this view does not walk nested names, keys or extensions. +#[derive(Clone, Debug)] +pub struct CertificateView<'a> { + pub certificate: Element<'a>, + pub tbs: Element<'a>, + pub version: Option>, + pub serial: Element<'a>, + pub signed_algorithm: Element<'a>, + pub issuer: Element<'a>, + pub validity: Element<'a>, + pub subject: Element<'a>, + pub spki: Element<'a>, + pub signature_algorithm: Element<'a>, + pub signature_bits: Element<'a>, + pub remaining_certificate_fields: Cursor<'a>, + pub remaining_tbs_fields: Cursor<'a>, +} + +impl<'a> CertificateView<'a> { + /// Inspect required fields of the first certificate; return bytes following its outer TLV. + /// Readable prefixes do not imply complete optional fields. Inspect the returned cursors to + /// distinguish complete, malformed, and limited tails. Existing strict verification stays separate. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let certificate = roots.required(tag::SEQUENCE)?; + let mut outer = certificate.children()?; + let tbs = outer.required(tag::SEQUENCE)?; + let signature_algorithm = outer.required(tag::SEQUENCE)?; + let signature_bits = outer.required(tag::BIT_STRING)?; + let mut fields = tbs.children()?; + let first = fields.next_element()?.ok_or(InspectionError::Field)?; + let (version, serial) = if first.tag() == tag::ctx(0) { + (Some(first), fields.required(tag::INTEGER)?) + } else if first.tag() == tag::INTEGER { + (None, first) + } else { + return Err(InspectionError::Field); + }; + let signed_algorithm = fields.required(tag::SEQUENCE)?; + let issuer = fields.required(tag::SEQUENCE)?; + let validity = fields.required(tag::SEQUENCE)?; + let subject = fields.required(tag::SEQUENCE)?; + let spki = fields.required(tag::SEQUENCE)?; + Ok(( + Self { + certificate, + tbs, + version, + serial, + signed_algorithm, + issuer, + validity, + subject, + spki, + signature_algorithm, + signature_bits, + remaining_certificate_fields: outer, + remaining_tbs_fields: fields, + }, + roots.remaining(), + )) + } +} diff --git a/crates/pkcs7/src/inspection/cms.rs b/crates/pkcs7/src/inspection/cms.rs new file mode 100644 index 000000000..e59d84a8c --- /dev/null +++ b/crates/pkcs7/src/inspection/cms.rs @@ -0,0 +1,103 @@ +//! Borrowed CMS wire prefixes. These do not validate signed attributes or authenticate signers. +//! Optional/remaining fields are explicit cursors, governed by the parent inspection bounds. +//! +//! Each `parse` starts a new depth root. Callers traversing nested structures must retain their +//! whole-document work/depth policy; reparsing a slice does not carry a previous cursor's budget. +//! The required wire tags and exact SignedData OID are this view's structural profile, not a +//! replacement for a consumer's acceptance or diagnostic policy. Existing parsers remain unchanged. + +use super::{Cursor, Element, InspectionError}; +use crate::der::tag; + +/// Required SignedData fields inside ContentInfo, without copying certificates or content. +/// All optional certificate/CRL/signer sets remain in `remaining_fields` for bounded inspection. +#[derive(Clone, Debug)] +pub struct SignedDataView<'a> { + pub content_info: Element<'a>, + pub signed_data: Element<'a>, + pub version: Element<'a>, + pub digest_algorithms: Element<'a>, + pub encapsulated_content: Element<'a>, + pub remaining_fields: Cursor<'a>, + pub remaining_explicit_fields: Cursor<'a>, + pub remaining_content_info_fields: Cursor<'a>, +} + +impl<'a> SignedDataView<'a> { + /// Read the required prefix and retain every tail. Matching the ContentInfo OID is not a + /// signature check. Encapsulated content, certificates, attributes and identities are unvalidated. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let content_info = roots.required(tag::SEQUENCE)?; + let mut fields = content_info.children()?; + let kind = fields.required(tag::OID)?; + if kind.value() != [0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 1, 7, 2] { + return Err(InspectionError::Field); + } + let explicit = fields.required(tag::ctx(0))?; + let mut wrapped = explicit.children()?; + let signed_data = wrapped.required(tag::SEQUENCE)?; + let mut inner = signed_data.children()?; + let version = inner.required(tag::INTEGER)?; + let digest_algorithms = inner.required(tag::SET)?; + let encapsulated_content = inner.required(tag::SEQUENCE)?; + Ok(( + Self { + content_info, + signed_data, + version, + digest_algorithms, + encapsulated_content, + remaining_fields: inner, + remaining_explicit_fields: wrapped, + remaining_content_info_fields: fields, + }, + roots.remaining(), + )) + } +} + +/// One SignerInfo's raw required fields, not an authentication or identity-match result. +/// The identity remains its original issuer/serial SEQUENCE or context-specific key identifier. +/// Version consistency, algorithm policy, signed-attribute validation and re-encoding remain the +/// caller's responsibility; this view never substitutes an encapsulated content type or digest. +#[derive(Clone, Debug)] +pub struct SignerInfoView<'a> { + pub signer_info: Element<'a>, + pub version: Element<'a>, + pub identifier: Element<'a>, + pub digest_algorithm: Element<'a>, + pub signed_attributes: Option>, + pub signature_algorithm: Element<'a>, + pub signature: Element<'a>, + pub remaining_fields: Cursor<'a>, +} + +impl<'a> SignerInfoView<'a> { + /// Read one signer's required wire fields, retaining any optional tail and subsequent signers. + /// An absent signature field is an error, not an implicitly empty authenticated signature. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let signer_info = roots.required(tag::SEQUENCE)?; + let mut fields = signer_info.children()?; + let version = fields.required(tag::INTEGER)?; + let identifier = fields.next_element()?.ok_or(InspectionError::Field)?; + if identifier.tag() != tag::SEQUENCE && identifier.tag() != tag::ctx_prim(0) { + return Err(InspectionError::Field); + } + let digest_algorithm = fields.required(tag::SEQUENCE)?; + let next = fields.next_element()?.ok_or(InspectionError::Field)?; + let (signed_attributes, signature_algorithm) = if next.tag() == tag::ctx(0) { + (Some(next), fields.required(tag::SEQUENCE)?) + } else if next.tag() == tag::SEQUENCE { + (None, next) + } else { + return Err(InspectionError::Field); + }; + let signature = fields.required(tag::OCTET_STRING)?; + Ok(( + Self { signer_info, version, identifier, digest_algorithm, signed_attributes, signature_algorithm, signature, remaining_fields: fields }, + roots.remaining(), + )) + } +} diff --git a/crates/pkcs7/src/lib.rs b/crates/pkcs7/src/lib.rs index 776be2749..0b501515d 100644 --- a/crates/pkcs7/src/lib.rs +++ b/crates/pkcs7/src/lib.rs @@ -29,6 +29,7 @@ pub mod cms; pub mod der; mod ec512; +pub mod inspection; pub mod keys; pub mod pkcs12; pub mod revocation; diff --git a/crates/pkcs7/tests/it/inspection.rs b/crates/pkcs7/tests/it/inspection.rs new file mode 100644 index 000000000..e079a19f5 --- /dev/null +++ b/crates/pkcs7/tests/it/inspection.rs @@ -0,0 +1,119 @@ +//! Benign wire parity and boundary tests; no signature/trust decisions are made by these views. +use craft_pkcs7::der::{self, tag}; +use craft_pkcs7::inspection::{CertificateView, Cursor, InspectionError, MAX_CHILDREN, MAX_DEPTH}; + +#[test] +fn cursor_keeps_exact_bytes_and_length_notes() { + for (encoded, note) in [(vec![4, 3, 1, 2, 3], false), (vec![4, 0x81, 3, 1, 2, 3], true), (vec![4, 0x82, 0, 3, 1, 2, 3], true)] { + let mut cursor = Cursor::new(&encoded); + let element = cursor.next_element().unwrap().unwrap(); + assert_eq!(element.raw(), encoded); + assert_eq!(element.raw().as_ptr(), encoded.as_ptr()); + assert_eq!(element.value(), &[1, 2, 3]); + assert_eq!(element.non_minimal_length(), note); + assert_eq!(cursor.next_element(), Ok(None)); + } + let canonical = der::octets(&[7; 128]); + assert!(!Cursor::new(&canonical).next_element().unwrap().unwrap().non_minimal_length()); +} + +#[test] +fn cursor_distinguishes_completion_and_sticky_partial_results() { + let bytes = [5, 0, 4]; // One complete NULL followed by an incomplete header. + let mut cursor = Cursor::new(&bytes); + assert_eq!(cursor.next_element().unwrap().unwrap().tag(), tag::NULL); + assert_eq!(cursor.next_element(), Err(InspectionError::Malformed)); + assert_eq!(cursor.next_element(), Err(InspectionError::Malformed)); + assert_eq!(cursor.remaining(), &[4]); + assert_eq!(Cursor::new(&[0x30, 0x80, 0, 0]).next_element(), Err(InspectionError::Malformed)); + assert_eq!(Cursor::new(&[0x30, 0]).next_element().unwrap().unwrap().raw(), &[0x30, 0]); +} + +#[test] +fn sibling_limit_allows_exact_completion_without_allocating_a_child_list() { + let mut bytes = [5, 0].repeat(MAX_CHILDREN); + let mut cursor = Cursor::new(&bytes); + for _ in 0..MAX_CHILDREN { + assert!(cursor.next_element().unwrap().is_some()); + } + assert_eq!(cursor.next_element(), Ok(None)); + bytes.extend_from_slice(&[5, 0]); + let mut cursor = Cursor::new(&bytes); + for _ in 0..MAX_CHILDREN { + cursor.next_element().unwrap(); + } + assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit)); + assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit)); + assert_eq!(cursor.remaining(), &[5, 0]); +} + +#[test] +fn nested_cursor_depth_is_explicitly_bounded() { + let mut bytes = der::seq(&[]); + for _ in 0..MAX_DEPTH { + bytes = der::seq(&[&bytes]); + } + let mut element = Cursor::new(&bytes).next_element().unwrap().unwrap(); + for _ in 0..MAX_DEPTH { + element = element.children().unwrap().next_element().unwrap().unwrap(); + } + assert!(matches!(element.children(), Err(InspectionError::DepthLimit))); +} + +fn certificate(version: bool, tail: &[u8]) -> (Vec, Vec, Vec, Vec) { + // Unknown algorithms are still inspectable. These are wire fixtures, not signed certificates. + let algorithm = der::seq(&[&der::oid("1.2.3.4"), &der::tlv(tag::NULL, &[])]); + let name = der::seq(&[]); + let spki = der::seq(&[&algorithm, &der::bit_string(&[1, 2, 3])]); + let version_field = if version { der::explicit(0, &der::int(2)) } else { vec![] }; + let tbs = der::seq(&[&version_field, &der::int(7), &algorithm, &name, &der::seq(&[]), &name, &spki, tail]); + let cert = der::seq(&[&tbs, &algorithm, &der::bit_string(&[9, 8, 7])]); + (cert, tbs, algorithm, spki) +} + +#[test] +fn certificate_fields_are_borrowed_exact_and_do_not_consume_trailing_input() { + for version in [false, true] { + let (mut bytes, tbs, algorithm, spki) = certificate(version, &[]); + let len = bytes.len(); + bytes.extend_from_slice(&[5, 0]); + let (mut view, rest) = CertificateView::parse(&bytes).unwrap(); + assert_eq!(view.certificate.raw(), &bytes[..len]); + assert_eq!(view.certificate.raw().as_ptr(), bytes.as_ptr()); + assert_eq!(view.tbs.raw(), tbs); + assert_eq!(view.signed_algorithm.raw(), algorithm); + assert_eq!(view.signature_algorithm.raw(), algorithm); + assert_eq!(view.spki.raw(), spki); + assert_eq!(view.serial.value(), &[7]); + assert_eq!(view.signature_bits.value(), &[0, 9, 8, 7]); + assert_eq!(view.version.is_some(), version); + assert_eq!(rest, &[5, 0]); + assert_eq!(view.remaining_tbs_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_certificate_fields.next_element(), Ok(None)); + } +} + +#[test] +fn required_fields_do_not_hide_optional_tail_diagnostics() { + let (bytes, _, _, _) = certificate(false, &[0xa3]); + let (mut view, _) = CertificateView::parse(&bytes).unwrap(); + assert_eq!(view.remaining_tbs_fields.remaining(), &[0xa3]); + assert_eq!(view.remaining_tbs_fields.next_element(), Err(InspectionError::Malformed)); + // This partial wire view is deliberately not accepted as a validated certificate. + assert!(craft_pkcs7::Certificate::parse(&bytes).is_err()); +} + +#[test] +fn existing_certificate_fixture_retains_signed_components() { + let cert = craft_pkcs7::x509::load_certificates(include_bytes!("../data/ca.crt.pem")).unwrap().remove(0); + let (view, rest) = CertificateView::parse(&cert.raw).unwrap(); + assert!(rest.is_empty()); + let parts = cert.clone().into_parts(); + assert_eq!(view.tbs.raw(), parts.tbs); + assert_eq!(view.signature_algorithm.raw(), parts.sig_alg); + assert_eq!(view.signature_bits.value().first(), Some(&0)); + assert_eq!(&view.signature_bits.value()[1..], parts.signature); + assert_eq!(view.issuer.raw(), parts.issuer.raw); + assert_eq!(view.subject.raw(), parts.subject.raw); + assert_eq!(view.spki.raw(), parts.public_key.spki()); +} diff --git a/crates/pkcs7/tests/it/inspection_cms.rs b/crates/pkcs7/tests/it/inspection_cms.rs new file mode 100644 index 000000000..ffdc75a42 --- /dev/null +++ b/crates/pkcs7/tests/it/inspection_cms.rs @@ -0,0 +1,111 @@ +use craft_pkcs7::der::{self, tag}; +use craft_pkcs7::inspection::InspectionError; +use craft_pkcs7::inspection::cms::{SignedDataView, SignerInfoView}; + +fn fixture(key_id: bool, attrs: bool) -> (Vec, Vec) { + let digest = der::seq(&[&der::oid("2.16.840.1.101.3.4.2.1")]); + let sig_alg = der::seq(&[&der::oid("1.2.840.113549.1.1.1"), &der::tlv(tag::NULL, &[])]); + let identifier = if key_id { der::tlv(tag::ctx_prim(0), &[7, 8]) } else { der::seq(&[&der::seq(&[]), &der::int(7)]) }; + let attributes = if attrs { + let content = der::seq(&[&der::oid("1.2.840.113549.1.9.3"), &der::set_of(&[&der::oid("1.2.840.113549.1.7.1")])]); + let digest_attr = der::seq(&[&der::oid("1.2.840.113549.1.9.4"), &der::set_of(&[&der::octets(&[6; 32])])]); + der::tlv(tag::ctx(0), &[content, digest_attr].concat()) + } else { + vec![] + }; + let signer = der::seq(&[&der::int(if key_id { 3 } else { 1 }), &identifier, &digest, &attributes, &sig_alg, &der::octets(&[1, 2, 3])]); + let content = der::seq(&[&der::oid("1.2.840.113549.1.7.1"), &der::explicit(0, &der::octets(b"hello"))]); + let signed_data = der::seq(&[&der::int(1), &der::set_of(&[&digest]), &content, &der::set_of(&[&signer])]); + (der::seq(&[&der::oid("1.2.840.113549.1.7.2"), &der::explicit(0, &signed_data)]), signer) +} + +#[test] +fn cms_fields_retain_encodings_and_both_identifier_forms() { + for key_id in [false, true] { + for attrs in [false, true] { + let (cms, signer) = fixture(key_id, attrs); + let (mut view, rest) = SignedDataView::parse(&cms).unwrap(); + assert!(rest.is_empty()); + assert_eq!(view.content_info.raw().as_ptr(), cms.as_ptr()); + assert_eq!(view.version.value(), &[1]); + let signer_set = view.remaining_fields.next_element().unwrap().unwrap(); + let (mut si, rest) = SignerInfoView::parse(signer_set.value()).unwrap(); + assert_eq!(si.signer_info.raw(), signer); + assert!(rest.is_empty()); + assert_eq!(si.identifier.tag(), if key_id { 0x80 } else { 0x30 }); + assert_eq!(si.signed_attributes.is_some(), attrs); + assert_eq!(si.signature.value(), &[1, 2, 3]); + assert_eq!(si.remaining_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_explicit_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_content_info_fields.next_element(), Ok(None)); + } + } +} + +#[test] +fn signer_prefix_does_not_hide_optional_tail_or_consume_next_signer() { + let (_, signer) = fixture(false, true); + let parsed = der::Tlv::parse_all(&signer).unwrap(); + let with_tail = der::seq(&[parsed.value, &[0xa1]]); + let joined = [with_tail, signer.clone()].concat(); + let (mut view, rest) = SignerInfoView::parse(&joined).unwrap(); + assert_eq!(rest, signer); + assert_eq!(view.remaining_fields.next_element(), Err(InspectionError::Malformed)); + assert_eq!(view.remaining_fields.remaining(), &[0xa1]); +} + +// Ordinary optional sets and complete trailing TLVs, never interpreted as trust evidence here. +fn optional_fixture(certificate_count: usize, with_crl: bool, tails: bool) -> (Vec, Vec, Vec) { + let certificate = craft_pkcs7::x509::load_certificates(include_bytes!("../data/ca.crt.pem")).unwrap().remove(0).raw; + let (base, signer) = fixture(false, true); + let (view, _) = SignedDataView::parse(&base).unwrap(); + let certificates = der::tlv(tag::ctx(0), &certificate.repeat(certificate_count)); + let crl = if with_crl { der::tlv(tag::ctx(1), &der::seq(&[])) } else { vec![] }; + let tail = if tails { der::tlv(tag::NULL, &[]) } else { vec![] }; + let signed_data = der::seq(&[ + view.version.raw(), + view.digest_algorithms.raw(), + view.encapsulated_content.raw(), + &certificates, + &crl, + &der::set_of(&[&signer]), + &tail, + ]); + let wrapped = der::tlv(tag::ctx(0), &[signed_data, tail.clone()].concat()); + let content = der::seq(&[&der::oid("1.2.840.113549.1.7.2"), &wrapped, &tail]); + ([content, tail].concat(), certificate, crl) +} + +#[test] +fn optional_certificate_crl_sets_and_all_tails_remain_visible() { + for with_crl in [false, true] { + let (bytes, cert, crl) = optional_fixture(2, with_crl, true); + let (mut view, rest) = SignedDataView::parse(&bytes).unwrap(); + assert_eq!(rest, &[5, 0]); + let certs = view.remaining_fields.next_element().unwrap().unwrap(); + assert_eq!(certs.tag(), tag::ctx(0)); + assert_eq!(certs.value(), cert.repeat(2)); + if with_crl { + assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().raw(), crl); + } + assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().tag(), tag::SET); + for cursor in [&mut view.remaining_fields, &mut view.remaining_explicit_fields, &mut view.remaining_content_info_fields] { + assert_eq!(cursor.next_element().unwrap().unwrap().raw(), &[5, 0]); + assert_eq!(cursor.next_element(), Ok(None)); + } + } +} + +#[test] +fn signer_unsigned_attributes_remain_raw_and_separate_from_signed_attributes() { + let (_, signer) = fixture(true, true); + let fields = der::Tlv::parse_all(&signer).unwrap(); + let unsigned = der::tlv(tag::ctx(1), &der::seq(&[])); + let bytes = der::seq(&[fields.value, &unsigned]); + let (mut view, rest) = SignerInfoView::parse(&bytes).unwrap(); + assert!(rest.is_empty()); + assert_eq!(view.signed_attributes.unwrap().tag(), tag::ctx(0)); + assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().raw(), unsigned); + assert_eq!(view.remaining_fields.next_element(), Ok(None)); +} diff --git a/crates/pkcs7/tests/it/main.rs b/crates/pkcs7/tests/it/main.rs index 4a10ec793..1c6616b39 100644 --- a/crates/pkcs7/tests/it/main.rs +++ b/crates/pkcs7/tests/it/main.rs @@ -5,4 +5,7 @@ mod ber; mod chain; mod cms; mod crypto; +mod inspection; mod store_keys; + +mod inspection_cms; diff --git a/crates/plotter/Cargo.toml b/crates/plotter/Cargo.toml index 1c8649c28..6f8b7e91a 100644 --- a/crates/plotter/Cargo.toml +++ b/crates/plotter/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true workspace = true [dependencies] +kurbo = { workspace = true } thiserror = { workspace = true } serde = { workspace = true, optional = true } diff --git a/crates/plotter/src/hpgl.rs b/crates/plotter/src/hpgl.rs index 5f6759241..f7edbe337 100644 --- a/crates/plotter/src/hpgl.rs +++ b/crates/plotter/src/hpgl.rs @@ -12,6 +12,9 @@ pub mod lex; use crate::{Command, Error, Framing, Job, Program, y_up}; +pub mod plot; +pub mod write; + /// Plotter units per mm (1 plu = 0.025 mm). pub const UNITS_PER_MM: f64 = 40.0; diff --git a/crates/plotter/src/hpgl/plot.rs b/crates/plotter/src/hpgl/plot.rs new file mode 100644 index 000000000..ae7da6441 --- /dev/null +++ b/crates/plotter/src/hpgl/plot.rs @@ -0,0 +1,62 @@ +//! HP-GL/2 plotter state types: stroke attributes, line patterns, and fill/cap/join rules. + +use kurbo::Point; + +/// Plotter units per millimeter (0.025 mm each). +pub const PLU_PER_MM: f64 = 40.0; + +/// The hard-clip limits taken for P1 and P2 when the file sets none (plotter units): 11 × 8.5 in. +pub const HARD_CLIP: Point = Point::new(11176.0, 8636.0); + +/// How far from the origin art may lie (plotter units, twice the range the format defines). +pub const LIMIT: f64 = 16_777_216.0; + +/// Fill rule for polygon mode. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum FillRule { + #[default] + EvenOdd, + NonZero, +} + +/// Line cap style (`LA` kind 1). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum LineCap { + #[default] + Butt, + Square, + Triangular, + Round, +} + +/// Line join style (`LA` kind 2). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum LineJoin { + #[default] + Miter, + MiterBevel, + Triangular, + Round, + Bevel, + None, +} + +/// A stroke as the pen draws it (lengths in plotter units). +#[derive(Clone, Debug, PartialEq)] +pub struct Stroke { + pub color: [u8; 3], + pub width: f64, + pub cap: LineCap, + pub join: LineJoin, + pub miter: f64, + pub dash: Option, +} + +/// A line type as dashes (lengths in plotter units). +#[derive(Clone, Debug, PartialEq)] +pub struct LinePattern { + /// Dash, gap, dash, gap…: an even number of lengths. + pub pattern: Vec, + /// How far into the pattern each line starts. + pub offset: f64, +} diff --git a/crates/plotter/src/hpgl/write.rs b/crates/plotter/src/hpgl/write.rs new file mode 100644 index 000000000..1d1cac34e --- /dev/null +++ b/crates/plotter/src/hpgl/write.rs @@ -0,0 +1,157 @@ +//! HP-GL/2 export helpers: region clipping ([`clip`]), inside-first nesting ([`nest`]), and +//! base-64 `PE` polyline encoding. + +pub mod clip; +pub mod nest; + +use std::io::Write as _; + +/// The largest coordinate written, plotter units (2²³ − 1). +pub const MAX_COORD: i64 = (1 << 23) - 1; + +/// The most pens a palette holds. +pub const MAX_PENS: usize = 255; + +/// A pen in an HP-GL/2 palette. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Pen { + pub number: usize, + pub rgb: [u8; 3], +} + +/// Encodes a standalone HP-GL/2 `PE` command as bytes, not UTF-8 text. +/// The first point is absolute; each path starts with a pen-up move. +pub fn encode_pe(paths: &[&[(i64, i64)]]) -> Vec { + let mut out = b"PE".to_vec(); + append_paths(&mut out, paths.iter().copied(), &mut None); + out.push(b';'); + out +} + +fn append_paths<'a>(out: &mut Vec, paths: impl Iterator, at: &mut Option<(i64, i64)>) { + for path in paths { + for (index, &(x, y)) in path.iter().enumerate() { + if index == 0 { + // '<' lifts the pen for this move; '=' alone only selects absolute coordinates. + out.push(b'<'); + } + let relative = at.and_then(|(px, py)| { + let dx = x.checked_sub(px)?; + let dy = y.checked_sub(py)?; + (dx.unsigned_abs() <= MAX_COORD as u64 && dy.unsigned_abs() <= MAX_COORD as u64).then_some((dx, dy)) + }); + let (dx, dy) = match relative { + Some(delta) => delta, + None => { + out.push(b'='); + (x, y) + } + }; + push_pe_num(out, dx); + push_pe_num(out, dy); + *at = Some((x, y)); + } + } +} + +fn push_pe_num(out: &mut Vec, value: i64) { + // Widen before shifting so even i64::MIN is encoded without overflow. + let mut number = (u128::from(value.unsigned_abs()) << 1) | u128::from(value < 0); + while number >= 64 { + out.push(63 + (number & 63) as u8); + number >>= 6; + } + out.push(191 + number as u8); +} + +/// Writes an HP-GL/2 byte stream for up to 255 pens and corresponding paths. +/// Pen numbers outside 1..=255 are ignored. Extra palettes/paths are ignored together. +/// The caller owns coordinate admission and output-size budgets. +pub fn write_hpgl2(pens: &[Pen], paths_per_pen: &[Vec>]) -> Vec { + let pens: Vec<_> = pens.iter().take(MAX_PENS).enumerate().filter(|(_, pen)| (1..=MAX_PENS).contains(&pen.number)).collect(); + let mut out = b"IN;".to_vec(); + if let Some(maximum) = pens.iter().map(|(_, pen)| pen.number).max() { + // Raster devices number pens from zero, so reserve the selected pen's slot too. + let count = (maximum + 1).next_power_of_two().max(2); + let _ = write!(out, "NP{count};"); + for (_, pen) in &pens { + let [r, g, b] = pen.rgb; + let _ = write!(out, "PC{},{r},{g},{b};", pen.number); + } + } + let mut at = None; + for (index, pen) in pens { + let Some(paths) = paths_per_pen.get(index) else { continue }; + if paths.is_empty() { + continue; + } + let _ = write!(out, "PU;SP{};PE", pen.number); + // Position is shared across pen changes, not reset to the origin for each PE command. + append_paths(&mut out, paths.iter().map(Vec::as_slice), &mut at); + out.push(b';'); + } + out.extend_from_slice(b"PU;SP0;"); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pe_numbers_are_raw_bytes_and_paths_lift_the_pen() { + let first: &[(i64, i64)] = &[(0, 0), (10, -10)]; + let second: &[(i64, i64)] = &[(20, 0), (20, 10)]; + assert_eq!(encode_pe(&[first, second]), b"PE<=\xbf\xbf\xd3\xd4<\xd3\xd3\xbf\xd3;"); + } + + #[test] + fn stream_preserves_position_across_pen_changes() { + let pens = [Pen { number: 1, rgb: [1, 2, 3] }, Pen { number: 2, rgb: [4, 5, 6] }]; + let paths = vec![vec![vec![(0, 0), (10, 0)]], vec![vec![(20, 0), (20, 10)]]]; + assert_eq!(write_hpgl2(&pens, &paths), b"IN;NP4;PC1,1,2,3;PC2,4,5,6;PU;SP1;PE<=\xbf\xbf\xd3\xbf;PU;SP2;PE<\xd3\xbf\xbf\xd3;PU;SP0;"); + } + + #[test] + fn large_relative_move_uses_absolute_coordinates() { + let path = [(-MAX_COORD, 0), (MAX_COORD, 0)]; + let result = encode_pe(&[&path]); + assert_eq!(result.iter().filter(|&&b| b == b'=').count(), 2); + } + + #[test] + fn empty_plot_and_sparse_pen_number_are_preserved() { + assert_eq!(write_hpgl2(&[], &[]), b"IN;PU;SP0;"); + assert_eq!(write_hpgl2(&[Pen { number: 255, rgb: [0, 0, 0] }], &[]), b"IN;NP256;PC255,0,0,0;PU;SP0;"); + } + + #[test] + fn multibyte_pe_numbers_are_not_utf8() { + assert_eq!(encode_pe(&[&[(32, -32)]]), b"PE<=?\xc0@\xc0;"); + } + + #[test] + fn invalid_pens_keep_the_original_path_indices() { + let pens = [Pen { number: 0, rgb: [1, 2, 3] }, Pen { number: 2, rgb: [4, 5, 6] }]; + let paths = vec![vec![vec![(100, 100)]], vec![vec![(0, 0), (10, 0)]]]; + assert_eq!(write_hpgl2(&pens, &paths), b"IN;NP4;PC2,4,5,6;PU;SP2;PE<=\xbf\xbf\xd3\xbf;PU;SP0;"); + assert_eq!(write_hpgl2(&[Pen { number: 256, rgb: [0, 0, 0] }], &paths), b"IN;PU;SP0;"); + } + + #[test] + fn palette_cap_also_caps_drawn_paths() { + let mut pens = vec![Pen { number: 0, rgb: [0, 0, 0] }; MAX_PENS + 1]; + pens[MAX_PENS - 1] = Pen { number: 255, rgb: [1, 2, 3] }; + pens[MAX_PENS] = Pen { number: 1, rgb: [4, 5, 6] }; + let paths = vec![vec![vec![(0, 0), (10, 0)]]; MAX_PENS + 1]; + assert_eq!(write_hpgl2(&pens, &paths), b"IN;NP256;PC255,1,2,3;PU;SP255;PE<=\xbf\xbf\xd3\xbf;PU;SP0;"); + } + + #[test] + fn extreme_coordinates_do_not_overflow() { + let path = [(i64::MIN, i64::MAX), (i64::MAX, i64::MIN)]; + let output = encode_pe(&[&path]); + assert!(output.starts_with(b"PE<=")); + assert!(output.ends_with(b";")); + } +} diff --git a/crates/plotter/src/hpgl/write/clip.rs b/crates/plotter/src/hpgl/write/clip.rs new file mode 100644 index 000000000..2d0595178 --- /dev/null +++ b/crates/plotter/src/hpgl/write/clip.rs @@ -0,0 +1,267 @@ +//! Polylines cut by a region: each segment is split where it crosses the region's edges, and the +//! pieces whose middle lies inside are kept, joined where they meet. + +use kurbo::{Point, Rect}; + +use crate::hpgl::plot::FillRule; + +/// A clipping region: closed rings (each closes implicitly) and the rule that decides inside. +pub struct Region { + rings: Vec>, + rule: FillRule, + bounds: Rect, +} + +impl Region { + /// The region of `rings` under `rule`; `None` when it has no ring of three points or more. + pub fn new(rings: Vec>, rule: FillRule) -> Option { + let rings: Vec> = rings.into_iter().filter(|r| r.len() >= 3).collect(); + let bounds = rings.iter().flatten().fold(None, |b: Option, p| Some(b.map_or(Rect::from_points(*p, *p), |b| b.union_pt(*p))))?; + Some(Self { rings, rule, bounds }) + } + + /// The edges this region has, which [`Region::cut`] tests each segment against. + fn edges(&self) -> u64 { + self.rings.iter().map(|r| r.len() as u64).sum() + } + + /// Does `p` lie on one of the region's edges (within a millionth of a point)? + fn on_edge(&self, p: Point) -> bool { + self.rings.iter().any(|ring| { + ring.iter().enumerate().any(|(i, &a)| { + let b = ring[(i + 1) % ring.len()]; + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + (a + ab * t).distance(p) <= 1e-6 + }) + }) + } + + /// Is `p` inside (non-zero winding or an odd number of crossings), or on an edge? + fn contains(&self, p: Point) -> bool { + if self.on_edge(p) { + return true; + } + let mut winding = 0i64; + for ring in &self.rings { + for (i, &a) in ring.iter().enumerate() { + let b = ring[(i + 1) % ring.len()]; + if a.y <= p.y { + if b.y > p.y && cross(a, b, p) > 0.0 { + winding += 1; + } + } else if b.y <= p.y && cross(a, b, p) < 0.0 { + winding -= 1; + } + } + } + match self.rule { + FillRule::NonZero => winding != 0, + FillRule::EvenOdd => winding % 2 != 0, + } + } + + /// Where segment `a`–`b` crosses this region's edges, as fractions of its length strictly + /// between 0 and 1, sorted. + fn crossings(&self, a: Point, b: Point) -> Vec { + let mut ts = vec![]; + for ring in &self.rings { + for (i, &c) in ring.iter().enumerate() { + let d = ring[(i + 1) % ring.len()]; + if let Some(t) = intersect(a, b, c, d) + && t > 1e-12 + && t < 1.0 - 1e-12 + { + ts.push(t); + } + } + } + ts.sort_by(f64::total_cmp); + ts.dedup_by(|x, y| (*x - *y).abs() <= 1e-12); + ts + } + + /// The parts of polyline `line` inside the region, each a polyline of two points or more. + /// Every test of a point or a segment against an edge takes one from `budget`; `None` when + /// the budget runs out first. + pub fn cut(&self, line: &[Point], budget: &mut u64) -> Option>> { + let edges = self.edges(); + let mut out: Vec> = vec![]; + let mut cur: Vec = vec![]; + for w in line.windows(2) { + let (a, b) = (w[0], w[1]); + // A segment wholly off the region's box lies outside it. + let near = overlaps(Rect::from_points(a, b), self.bounds); + let ts = if near { + spend(budget, edges)?; + self.crossings(a, b) + } else { + vec![] + }; + let mut from = 0.0; + for to in ts.into_iter().chain([1.0]) { + let (p, q) = (a.lerp(b, from), a.lerp(b, to)); + // Each piece between crossings is tested on its own: its edge and winding tests. + let inside = if near { + spend(budget, edges.saturating_mul(2))?; + self.contains(p.midpoint(q)) + } else { + false + }; + if inside { + if cur.last().is_none_or(|l| l.distance(p) > 1e-9) { + flush(&mut out, &mut cur); + cur.push(p); + } + cur.push(q); + } else { + flush(&mut out, &mut cur); + } + from = to; + } + } + flush(&mut out, &mut cur); + // A closed line that leaves the region and comes back: its last piece ends where its + // first starts, at the line's start, and the two are one piece. + if line.len() > 2 + && line.first() == line.last() + && out.len() >= 2 + && let (Some(end), Some(start)) = (out.last().and_then(|l| l.last()), out.first().and_then(|l| l.first())) + && end.distance(*start) <= 1e-9 + { + let first = out.remove(0); + if let Some(last) = out.last_mut() { + last.extend(first.into_iter().skip(1)); + } + } + Some(out) + } +} + +/// Take `n` from `budget`; `None` when it holds less. +fn spend(budget: &mut u64, n: u64) -> Option<()> { + *budget = budget.checked_sub(n)?; + Some(()) +} + +fn flush(out: &mut Vec>, cur: &mut Vec) { + let line = std::mem::take(cur); + if line.len() >= 2 { + out.push(line); + } +} + +fn overlaps(a: Rect, b: Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Which side of line `a`–`b` point `p` lies on (positive: left). +fn cross(a: Point, b: Point, p: Point) -> f64 { + (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y) +} + +/// Where segment `a`–`b` crosses segment `c`–`d`, as a fraction of `a`–`b`; `None` when they +/// are parallel or don't meet. +fn intersect(a: Point, b: Point, c: Point, d: Point) -> Option { + let (r, s) = (b - a, d - c); + let den = r.x * s.y - r.y * s.x; + if den.abs() <= f64::EPSILON * (r.hypot() * s.hypot()).max(f64::MIN_POSITIVE) { + return None; + } + let ac = c - a; + let t = (ac.x * s.y - ac.y * s.x) / den; + let u = (ac.x * r.y - ac.y * r.x) / den; + ((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u)).then_some(t) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec { + vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)] + } + + /// `line` cut by `r` with no limit on the work. + fn cut(r: &Region, line: &[Point]) -> Vec> { + let mut unlimited = u64::MAX; + r.cut(line, &mut unlimited).unwrap() + } + + #[test] + fn a_line_across_a_square_keeps_its_middle() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + let pieces = cut(&r, &[Point::new(-5.0, 5.0), Point::new(15.0, 5.0)]); + assert_eq!(pieces, vec![vec![Point::new(0.0, 5.0), Point::new(10.0, 5.0)]]); + // Wholly outside, nothing; wholly inside, the line as it is. + assert!(cut(&r, &[Point::new(20.0, 0.0), Point::new(30.0, 0.0)]).is_empty()); + let inside = vec![Point::new(1.0, 1.0), Point::new(9.0, 1.0), Point::new(9.0, 9.0)]; + assert_eq!(cut(&r, &inside), vec![inside]); + } + + /// Each piece between crossings costs a pass over the edges: a line through the teeth of a + /// comb spends far more than its two points times the edges. + #[test] + fn every_piece_between_crossings_is_paid_for() { + let mut ring = vec![]; + for i in 0..100 { + let x = f64::from(i) * 4.0; + ring.extend([Point::new(x, 0.0), Point::new(x + 2.0, 0.0), Point::new(x + 2.0, 10.0), Point::new(x + 4.0, 10.0)]); + } + ring.extend([Point::new(400.0, 20.0), Point::new(0.0, 20.0)]); + let r = Region::new(vec![ring], FillRule::NonZero).unwrap(); + let line = [Point::new(-1.0, 5.0), Point::new(401.0, 5.0)]; + // 402 edges, 200 crossings, 201 pieces: 402 + 201 × 2 × 402 tests. + let need = 402 + 201 * 2 * 402; + let mut budget = need; + assert_eq!(r.cut(&line, &mut budget).map(|p| p.len()), Some(100)); + assert_eq!(budget, 0); + let mut short = need - 1; + assert!(r.cut(&line, &mut short).is_none()); + // A segment off the region's box costs nothing. + assert_eq!(r.cut(&[Point::new(0.0, 30.0), Point::new(9.0, 30.0)], &mut 0), Some(vec![])); + } + + /// A line along any of the region's edges is inside it. + #[test] + fn a_line_on_an_edge_is_kept() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + for line in [ + [Point::new(0.0, 0.0), Point::new(10.0, 0.0)], + [Point::new(10.0, 0.0), Point::new(10.0, 10.0)], + [Point::new(10.0, 10.0), Point::new(0.0, 10.0)], + [Point::new(0.0, 10.0), Point::new(0.0, 0.0)], + ] { + assert_eq!(cut(&r, &line), vec![line.to_vec()], "{line:?}"); + } + } + + #[test] + fn a_line_leaving_and_coming_back_is_two_pieces() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0)]; + assert_eq!(cut(&r, &line), vec![vec![Point::new(5.0, 5.0), Point::new(10.0, 5.0)], vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0)]]); + } + + /// A closed line that starts inside, leaves and comes back is one piece: the part after it + /// comes back runs on into the part before it left. + #[test] + fn a_closed_line_cut_once_stays_one_piece() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0)]; + assert_eq!(cut(&r, &line), vec![vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0), Point::new(10.0, 5.0)]]); + } + + #[test] + fn the_fill_rule_decides_a_hole() { + let rings = vec![square(0.0, 0.0, 10.0, 10.0), square(3.0, 3.0, 7.0, 7.0)]; + let line = [Point::new(-1.0, 5.0), Point::new(11.0, 5.0)]; + // Both rings wind the same way: even-odd cuts a hole, non-zero doesn't. + let even_odd = cut(&Region::new(rings.clone(), FillRule::EvenOdd).unwrap(), &line); + assert_eq!(even_odd, vec![vec![Point::new(0.0, 5.0), Point::new(3.0, 5.0)], vec![Point::new(7.0, 5.0), Point::new(10.0, 5.0)]]); + let non_zero = cut(&Region::new(rings, FillRule::NonZero).unwrap(), &line); + assert_eq!(non_zero.len(), 1); + assert!(Region::new(vec![vec![Point::ZERO, Point::new(1.0, 1.0)]], FillRule::NonZero).is_none()); + } +} diff --git a/crates/plotter/src/hpgl/write/nest.rs b/crates/plotter/src/hpgl/write/nest.rs new file mode 100644 index 000000000..e64c7942f --- /dev/null +++ b/crates/plotter/src/hpgl/write/nest.rs @@ -0,0 +1,357 @@ +//! Which of a pen's paths lie inside which of its closed paths, in plotter units, for drawing the +//! inner paths first. + +/// The box of `p`: `[x0, y0, x1, y1]`. +pub fn bounds(p: &[(i64, i64)]) -> [i64; 4] { + p.iter().fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |b, q| [b[0].min(q.0), b[1].min(q.1), b[2].max(q.0), b[3].max(q.1)]) +} + +/// For each of `paths` (`boxes` are their [`bounds`]), the closed paths it lies inside: none of +/// its segments crosses the closed path's line, each part of it between the points where it meets +/// that line lies inside the closed path (by the even-odd rule) or on the line, and at least one +/// part lies inside. A path touching the line of the one around it is inside it, a path crossing +/// it is not, and copies of one outline are not inside each other. A path is tested only against +/// closed paths larger than it (by the area of their box, then the area they enclose, then paint +/// order), so no two paths are each inside the other, and only against the closed paths in the +/// grid cell of its box's first corner. `None` once `work` is spent: a grid cell filled and a +/// box compared cost one each, and each segment tested costs the closed path's points for its +/// crossings and again for each part of it. +pub fn outer(paths: &[Vec<(i64, i64)>], boxes: &[[i64; 4]], work: &mut u64) -> Option>> { + let size: Vec<(i128, i128)> = paths + .iter() + .zip(boxes) + .map(|(p, b)| { + let box_area = (i128::from(b[2]) - i128::from(b[0])) * (i128::from(b[3]) - i128::from(b[1])); + (box_area, if closed(p) { twice_area(p) } else { 0 }) + }) + .collect(); + let rings: Vec = (0..paths.len()).filter(|&i| paths.get(i).is_some_and(|p| closed(p))).collect(); + let mut out = vec![vec![]; paths.len()]; + if rings.is_empty() { + return Some(out); + } + let grid = Grid::new(&rings, boxes, work)?; + for (a, (p, ab)) in paths.iter().zip(boxes).enumerate() { + for &r in grid.at(ab[0], ab[1]) { + spend(work, 1)?; + let (Some(rb), Some(ring)) = (boxes.get(r), paths.get(r)) else { continue }; + let smaller = (size.get(a), a) < (size.get(r), r); + if !smaller || rb[0] > ab[0] || rb[1] > ab[1] || rb[2] < ab[2] || rb[3] < ab[3] { + continue; + } + if inside(p, ring, work)? + && let Some(o) = out.get_mut(a) + { + o.push(r); + } + } + } + Some(out) +} + +/// The most cells along each side of a [`Grid`]. +const MAX_GRID_SIDE: usize = 512; +/// The most cells of a [`Grid`] a closed path is listed in; one whose box covers more is listed +/// once, among the wide ones. A closed path has 4 points or more, so the grid lists no more +/// entries than the pen has points. +const MAX_CELLS_PER_PATH: usize = 4; + +/// A grid over the boxes of a pen's closed paths, about one cell for each, up to +/// [`MAX_GRID_SIDE`] a side: each cell lists, in paint order, the closed paths whose box covers +/// it, and the closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells are listed +/// apart. A closed path whose box holds a point is among the wide ones or in that point's cell. +struct Grid { + /// The first corner of the closed paths' boxes together. + x0: i128, + y0: i128, + /// Their width and height, plus one. + w: i128, + h: i128, + /// Cells along each side. + side: usize, + /// The cells row by row. + cells: Vec>, + /// The closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells. + wide: Vec, +} + +impl Grid { + /// The grid of the closed paths `rings` (indices into `boxes`). `None` once `work` is spent. + fn new(rings: &[usize], boxes: &[[i64; 4]], work: &mut u64) -> Option { + let all = rings + .iter() + .filter_map(|&r| boxes.get(r)) + .fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |e, b| [e[0].min(b[0]), e[1].min(b[1]), e[2].max(b[2]), e[3].max(b[3])]); + let side = ((rings.len() as f64).sqrt().ceil() as usize).clamp(1, MAX_GRID_SIDE); + let (x0, y0) = (i128::from(all[0]), i128::from(all[1])); + let mut grid = Self { + x0, + y0, + w: (i128::from(all[2]) - x0 + 1).max(1), + h: (i128::from(all[3]) - y0 + 1).max(1), + side, + cells: vec![vec![]; side * side], + wide: vec![], + }; + for &r in rings { + let Some(b) = boxes.get(r) else { continue }; + let (Some((cx0, cy0)), Some((cx1, cy1))) = (grid.cell(b[0], b[1]), grid.cell(b[2], b[3])) else { continue }; + let covered = (cx1 - cx0 + 1) * (cy1 - cy0 + 1); + if covered > MAX_CELLS_PER_PATH { + spend(work, 1)?; + grid.wide.push(r); + continue; + } + spend(work, covered as u64)?; + for cy in cy0..=cy1 { + for cell in grid.cells.get_mut(cy * side + cx0..=cy * side + cx1).into_iter().flatten() { + cell.push(r); + } + } + } + Some(grid) + } + + /// The column and row of the cell holding `(x, y)`, `None` outside the grid. + fn cell(&self, x: i64, y: i64) -> Option<(usize, usize)> { + let (dx, dy) = (i128::from(x) - self.x0, i128::from(y) - self.y0); + if dx < 0 || dy < 0 || dx >= self.w || dy >= self.h { + return None; + } + let side = self.side as i128; + Some(((dx * side / self.w) as usize, (dy * side / self.h) as usize)) + } + + /// The wide closed paths, then those listed in the cell holding `(x, y)`. + fn at(&self, x: i64, y: i64) -> impl Iterator { + let cell = self.cell(x, y).and_then(|(cx, cy)| self.cells.get(cy * self.side + cx)).map_or(&[][..], Vec::as_slice); + self.wide.iter().chain(cell) + } +} + +/// Takes `n` from `work`; `None`, with `work` at 0, when it has less. +fn spend(work: &mut u64, n: u64) -> Option<()> { + let left = work.checked_sub(n); + *work = left.unwrap_or(0); + left.map(|_| ()) +} + +/// Does `p` start and end at one point, with three other points or more? +fn closed(p: &[(i64, i64)]) -> bool { + p.len() > 3 && p.first() == p.last() +} + +/// Twice the area the closed path `p` encloses. +fn twice_area(p: &[(i64, i64)]) -> i128 { + let sum: i128 = p + .windows(2) + .map(|w| match w { + [a, b] => i128::from(a.0) * i128::from(b.1) - i128::from(b.0) * i128::from(a.1), + _ => 0, + }) + .sum(); + sum.abs() +} + +/// Does `p` lie inside the closed path `ring`, as [`outer`] decides? `None` once `work` is spent. +fn inside(p: &[(i64, i64)], ring: &[(i64, i64)], work: &mut u64) -> Option { + let mut any = false; + for w in p.windows(2) { + let [s, e] = w else { continue }; + spend(work, ring.len() as u64)?; + // Where the segment meets the line without crossing it: its ends and the ring's points on + // it. Between two of these the segment is all inside or all outside. + let mut stops = vec![*s, *e]; + for edge in ring.windows(2) { + let [a, b] = edge else { continue }; + if crosses((*s, *e), (*a, *b)) { + return Some(false); + } + if a != s && a != e && on((*s, *e), *a) { + stops.push(*a); + } + } + let along = |q: &(i64, i64)| { + (i128::from(q.0) - i128::from(s.0)) * (i128::from(e.0) - i128::from(s.0)) + + (i128::from(q.1) - i128::from(s.1)) * (i128::from(e.1) - i128::from(s.1)) + }; + stops.sort_by_key(along); + stops.dedup(); + for part in stops.windows(2) { + let [m, n] = part else { continue }; + spend(work, ring.len() as u64)?; + // The part's middle, doubled so it is whole. + match locate((i128::from(m.0) + i128::from(n.0), i128::from(m.1) + i128::from(n.1)), ring) { + Some(false) => return Some(false), + Some(true) => any = true, + None => {} + } + } + } + Some(any) +} + +/// Which side of the line through `a` and `b` `c` is on: 1 left, -1 right, 0 on it. +fn side(a: (i64, i64), b: (i64, i64), c: (i64, i64)) -> i128 { + let d = (i128::from(b.0) - i128::from(a.0)) * (i128::from(c.1) - i128::from(a.1)) + - (i128::from(b.1) - i128::from(a.1)) * (i128::from(c.0) - i128::from(a.0)); + d.signum() +} + +/// Do segments `u` and `v` cross at a point inside both, each passing from one side of the other +/// to the other side? +fn crosses(u: ((i64, i64), (i64, i64)), v: ((i64, i64), (i64, i64))) -> bool { + side(u.0, u.1, v.0) * side(u.0, u.1, v.1) < 0 && side(v.0, v.1, u.0) * side(v.0, v.1, u.1) < 0 +} + +/// Does `q` lie on segment `u`? +fn on(u: ((i64, i64), (i64, i64)), q: (i64, i64)) -> bool { + let ((x0, y0), (x1, y1)) = u; + side(u.0, u.1, q) == 0 && q.0 >= x0.min(x1) && q.0 <= x0.max(x1) && q.1 >= y0.min(y1) && q.1 <= y0.max(y1) +} + +/// Where the doubled point `q` lies against the closed path `ring`: `Some(true)` inside by the +/// even-odd rule, `Some(false)` outside, `None` on its line. +fn locate(q: (i128, i128), ring: &[(i64, i64)]) -> Option { + let mut inside = false; + for w in ring.windows(2) { + let [a, b] = w else { continue }; + let (a, b) = ((2 * i128::from(a.0), 2 * i128::from(a.1)), (2 * i128::from(b.0), 2 * i128::from(b.1))); + // Which side of the segment's line `q` is on, 0 on it. + let side = (b.0 - a.0) * (q.1 - a.1) - (b.1 - a.1) * (q.0 - a.0); + if side == 0 && q.0 >= a.0.min(b.0) && q.0 <= a.0.max(b.0) && q.1 >= a.1.min(b.1) && q.1 <= a.1.max(b.1) { + return None; + } + // A segment crossing the level of `q` to its right. + if (a.1 > q.1) != (b.1 > q.1) && (side > 0) == (b.1 > a.1) { + inside = !inside; + } + } + Some(inside) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x0: i64, y0: i64, x1: i64, y1: i64) -> Vec<(i64, i64)> { + vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] + } + + fn nest(paths: &[Vec<(i64, i64)>]) -> Option>> { + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let mut work = u64::MAX; + outer(paths, &boxes, &mut work) + } + + #[test] + fn points_inside_outside_and_on_the_line() { + let ring = square(0, 0, 10, 10); + assert_eq!(locate((10, 10), &ring), Some(true)); + assert_eq!(locate((30, 10), &ring), Some(false)); + assert_eq!(locate((10, -2), &ring), Some(false)); + assert_eq!(locate((20, 10), &ring), None); + assert_eq!(locate((0, 0), &ring), None); + } + + #[test] + fn a_path_inside_another_lies_inside_it_and_not_the_other_way() { + let paths = [square(0, 0, 100, 100), square(10, 10, 20, 20), vec![(30, 30), (40, 40)]]; + assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0]])); + } + + #[test] + fn touching_counts_as_inside_and_crossing_does_not() { + // A square with a corner on the outline's left edge, a triangle whose corners lie on the + // outline's edges, and a square that crosses the outline. + let paths = [square(0, 0, 100, 100), square(0, 40, 20, 60), vec![(0, 50), (50, 0), (100, 50), (0, 50)], square(90, 90, 120, 95)]; + assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0], vec![]])); + } + + /// Every point of a copy lies on the other's line, and none inside it. + #[test] + fn copies_of_one_outline_do_not_lie_inside_each_other() { + let paths = [square(0, 0, 10, 10), square(0, 0, 10, 10), vec![(10, 10), (10, 0), (0, 0), (0, 10), (10, 10)]]; + assert_eq!(nest(&paths), Some(vec![vec![], vec![], vec![]])); + } + + /// A line whose ends and middle lie inside an outline but which crosses a slot cut into it. + #[test] + fn a_line_across_a_slot_is_not_inside() { + let slotted = vec![(0, 0), (100, 0), (100, 100), (14, 100), (14, 40), (12, 40), (12, 100), (0, 100), (0, 0)]; + assert_eq!(nest(&[slotted, vec![(10, 50), (40, 50)]]), Some(vec![vec![], vec![]])); + } + + /// A line that leaves an outline and comes back through two of its corners, crossing none of + /// its sides, and one that runs along the bottom of a slot. + #[test] + fn a_line_through_corners_is_inside_only_where_it_stays_inside() { + let v_slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (15, 40), (10, 50), (10, 100), (0, 100), (0, 0)]; + assert_eq!(nest(&[v_slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![]])); + let slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (10, 50), (10, 100), (0, 100), (0, 0)]; + assert_eq!(nest(&[slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![0]])); + } + + /// An outline that crosses itself encloses no area by its signed sum, yet a line in one of its + /// lobes lies inside it. + #[test] + fn a_line_inside_a_lobe_of_a_crossed_outline_lies_inside_it() { + let bow = vec![(0, 0), (100, 100), (0, 100), (100, 0), (0, 0)]; + assert_eq!(twice_area(&bow), 0); + assert_eq!(nest(&[bow, vec![(40, 80), (60, 80)]]), Some(vec![vec![], vec![0]])); + } + + #[test] + fn a_ring_inside_a_ring_inside_a_ring_lies_inside_both() { + let paths = [square(20, 20, 80, 80), square(0, 0, 100, 100), square(40, 40, 60, 60)]; + assert_eq!(nest(&paths), Some(vec![vec![1], vec![], vec![0, 1]])); + } + + /// 10,000 parts in rows, each with a hole: each hole is tested against the few closed paths + /// near it, not against every part. + #[test] + fn parts_in_rows_are_tested_only_against_the_closed_paths_near_them() { + let mut paths = vec![]; + for row in 0..100 { + for col in 0..100 { + let (x, y) = (col * 30, row * 30); + paths.push(square(x, y, x + 20, y + 20)); + paths.push(square(x + 5, y + 5, x + 15, y + 15)); + } + } + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let mut work = 5_000_000; + let found = outer(&paths, &boxes, &mut work); + let want: Vec> = (0..paths.len()).map(|i| if i % 2 == 1 { vec![i - 1] } else { vec![] }).collect(); + assert_eq!(found, Some(want)); + } + + /// 400 closed paths that each cover most of the grid are listed once each, not in every cell + /// they cover. + #[test] + fn closed_paths_covering_many_cells_are_listed_once() { + let mut paths: Vec> = (0..400).map(|i| square(i, i, 1000 + i, 1000 + i)).collect(); + paths.extend((0..400).map(|i| { + let (x, y) = ((i % 20) * 50, (i / 20) * 50); + square(x, y, x + 10, y + 10) + })); + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let rings: Vec = (0..paths.len()).collect(); + let mut work = u64::MAX; + let Some(grid) = Grid::new(&rings, &boxes, &mut work) else { panic!("the budget ran out") }; + assert_eq!(grid.wide, (0..400).collect::>()); + assert!(grid.cells.iter().map(Vec::len).sum::() <= 400 * MAX_CELLS_PER_PATH); + } + + #[test] + fn finding_what_lies_inside_stops_at_its_budget() { + let paths: Vec> = (0..50).map(|i| square(-i, -i, 100 + i, 100 + i)).collect(); + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let mut work = 1_000; + assert_eq!(outer(&paths, &boxes, &mut work), None); + assert_eq!(work, 0); + let mut work = u64::MAX; + let found = outer(&paths, &boxes, &mut work); + assert_eq!(found.map(|o| o.iter().map(Vec::len).sum::()), Some(50 * 49 / 2)); + } +} diff --git a/crates/ppt-binary/Cargo.toml b/crates/ppt-binary/Cargo.toml new file mode 100644 index 000000000..897aad8a4 --- /dev/null +++ b/crates/ppt-binary/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "craft-ppt-binary" +description = "Reader for the PowerPoint 97-2003 binary file format (.ppt, .pot, .pps; [MS-PPT], [MS-ODRAW]) into the craft-pptx presentation model, on craft-cfb." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-cfb = { workspace = true } +craft-drawingml = { workspace = true } +craft-pptx = { workspace = true } +log = { workspace = true } +miniz_oxide = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +# Pictures in the tests: a PNG to embed, and the BMP a DIB blip becomes. +image = { version = "0.25", default-features = false, features = ["png", "bmp"] } diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md new file mode 100644 index 000000000..d1bbdd24e --- /dev/null +++ b/crates/ppt-binary/README.md @@ -0,0 +1,40 @@ +# craft-ppt-binary + +Reader for the PowerPoint 97-2003 binary file format (`.ppt`, `.pot` and `.pps`) into the +`craft-pptx` presentation model. It is DeckCraft's reader, on `craft-cfb` for the compound file. +Import only: there is no `.ppt` writer. + +| Document | Used for | +|---|---| +| [MS-PPT] PowerPoint (.ppt) Binary File Format (Microsoft Open Specifications) | the Current User stream, the edit chain and persist directories, documents, masters, slides, notes, text and its styles, headers and footers | +| [MS-ODRAW] Office Drawing Binary File Formats | shapes, their property tables and geometry, the BLIP store and its pictures | +| [MS-CFB] Compound File Binary File Format | through `craft-cfb` | + +```rust +// Not a compound file: an error, never a panic. +assert!(!craft_ppt_binary::sniff(b"not a .ppt")); +assert!(craft_ppt_binary::import(b"not a .ppt", &craft_pptx::Plain).is_err()); +``` + +- `sniff(bytes)`, `import(bytes, &defaults)` and `import_checked(bytes, &defaults)`, which also + names the slides the file lists but whose objects are gone. +- Main masters become masters, with their colour scheme, fonts, text styles, background and + decorative shapes. Title masters become layouts of their main master. +- Slides keep their shapes (preset and freeform geometry, groups, rotation and flips), fills, + lines, shadows, pictures (PNG, JPEG, DIB, TIFF, EMF and WMF), tables (as groups of shapes, the + way the file stores them), and text with the master's styles resolved into it, along with + fields, numbering, headers and footers, notes, and hidden slides. +- Damaged files read as far as they can: a broken edit chain falls back to a scan of the edits, + and unknown or damaged records are skipped. Sizes, counts, nesting and picture decoding are + bounded. +- Password-protected files are refused (`PptError::Encrypted`), as are PowerPoint 95 and earlier + files (`PptError::TooOld`). + +The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from: +its layouts and placeholders. The file's masters then place and style the placeholders that +master has. With `craft_pptx::Plain` (one blank layout, no placeholders), the slides still read +with their own boxes. + +The reader was written for DeckCraft (storytold/deckcraft#1137); the history of +`crates/ppt-binary` names its authors. Its tests build `.ppt` files from records; no file made +by PowerPoint is used. diff --git a/crates/ppt-binary/src/blip.rs b/crates/ppt-binary/src/blip.rs new file mode 100644 index 000000000..56b6abaec --- /dev/null +++ b/crates/ppt-binary/src/blip.rs @@ -0,0 +1,404 @@ +//! Pictures ([MS-ODRAW] §2.2.32–2.2.45): the drawing group's blip store lists every picture +//! (`FBSE`), either holding its blip or pointing into the `Pictures` stream. Shapes name a picture +//! by its 1-based index in the store. + +use crate::doc::rt; +use crate::record::Rec; + +/// Largest picture inflated from a compressed metafile. +const MAX_INFLATED: usize = 64 << 20; +/// Most bytes all of a file's pictures may decode to together: 2 GiB, the total a `.pptx` package +/// may inflate to (`craft_pptx::MAX_TOTAL`). Pictures are the only part of a `.ppt` +/// that inflates, so a small hostile file can't make the import hold more than a `.pptx` could. +/// It also fits a 32-bit `usize` (wasm32), where a 4 GiB constant wraps to 0. +const MAX_TOTAL: usize = 2 << 30; +// A zero or tiny budget would drop every picture without a word, and the shift above can wrap on +// a 32-bit target (wasm32) without any error, so the build checks it on every target. +const _: () = assert!(MAX_TOTAL >= MAX_INFLATED); + +/// A decoded picture: file extension, content type and bytes as a file of that type. +#[derive(Clone, Debug, PartialEq)] +pub struct Picture { + pub ext: &'static str, + pub content_type: &'static str, + pub data: Vec, +} + +/// The blip store: each entry's blip record, decoded only when a shape first asks for it, every +/// entry at most once, and all of them together within [`MAX_TOTAL`] bytes. +pub struct Store<'a> { + entries: Vec>>, + budget: usize, +} + +impl<'a> Store<'a> { + pub fn new(dgg: Option>, pictures_stream: &'a [u8]) -> Self { + let entries = match dgg.and_then(|d| d.child(rt::BSTORE)) { + Some(bstore) => bstore.children().map(|r| if r.kind == rt::FBSE { fbse(&r, pictures_stream) } else { None }).collect(), + None => vec![], + }; + Store { entries, budget: MAX_TOTAL } + } + + /// The picture at `index` (0-based; shapes use 1-based ids), taken out of the store. `None` + /// for an entry that is empty, can't be read, was taken already, or would pass the budget. + pub fn take(&mut self, index: usize) -> Option { + let blip = self.entries.get_mut(index)?.take()?; + self.decode_charged(&blip) + } + + /// A blip held in a shape's own property ([MS-ODRAW] §2.2.37: a complex `fillBlip` or `pib` + /// whose extra bytes are the blip record itself), decoded within the same budget. + pub fn decode_inline(&mut self, bytes: &[u8]) -> Option { + let blip = Rec::at(bytes, 0).filter(|r| (0xF018..=0xF117).contains(&r.kind))?; + self.decode_charged(&blip) + } + + /// Decode `blip` and take its size from the budget. A compressed metafile is also charged + /// its compressed bytes, which inflating reads whatever it produces, and one that fails to + /// inflate is charged what the inflate may have produced before failing: many entries pointing + /// at one damaged stream (or one that inflates to nothing) would otherwise each inflate it again + /// for free. + fn decode_charged(&mut self, blip: &Rec) -> Option { + let bounds = inflate_bounds(blip, self.budget); + let pic = decode(blip, self.budget); + let cost = match (&pic, bounds) { + (Some(p), Some((input, _))) => input.saturating_add(p.data.len()), + (Some(p), None) => p.data.len(), + (None, Some((input, output))) => input.saturating_add(output), + (None, None) => 0, + }; + self.budget = self.budget.saturating_sub(cost); + pic + } +} + +/// For a compressed metafile (EMF or WMF, with one UID or, for instances 0x3D5 and 0x217, two): +/// the compressed bytes inflating it reads, and the most bytes it may produce so that both +/// together stay within `limit`. `None` for any other blip, or when the compressed bytes alone +/// pass `limit`. +fn inflate_bounds(b: &Rec, limit: usize) -> Option<(usize, usize)> { + if !matches!(b.kind, 0xF01A | 0xF01B) { + return None; + } + let uids = if matches!(b.instance, 0x3D5 | 0x217) { 32 } else { 16 }; + let h = b.data.get(uids..uids + 34)?; + let size = crate::record::u32_at(h, 0)? as usize; + if *h.get(32)? != 0 { + return None; + } + let input = b.data.get(uids + 34..)?.len(); + let output = limit.checked_sub(input)?; + Some((input, size.min(MAX_INFLATED).min(output))) +} + +fn fbse<'a>(r: &Rec<'a>, pictures: &'a [u8]) -> Option> { + // btWin32, btMacOS, rgbUid[16], tag, size, cRef, foDelay, unused, cbName, unused, unused. + let size = r.u32(20)? as usize; + let offset = r.u32(28)? as usize; + let name_len = usize::from(r.u8(33)?); + if size == 0 { + return None; + } + let embedded_at = 36usize.checked_add(name_len)?; + if r.data.len() > embedded_at { Rec::at(r.data, embedded_at) } else { Rec::at(pictures, offset) } +} + +/// Decode one blip record into at most `limit` bytes. +pub fn decode(b: &Rec, limit: usize) -> Option { + // The instance says whether a second UID follows the first. + let (kind, two_uids): (u16, bool) = match b.instance { + 0x3D4 | 0x216 | 0x542 | 0x46A | 0x6E2 | 0x6E0 | 0x7A8 | 0x6E4 => (b.kind, false), + 0x3D5 | 0x217 | 0x543 | 0x46B | 0x6E3 | 0x6E1 | 0x7A9 | 0x6E5 => (b.kind, true), + _ => (b.kind, false), + }; + let uids = if two_uids { 32 } else { 16 }; + // The bytes a picture is copied from, refused before copying when they (plus `extra` bytes of + // header to add) would pass the budget. + let within = |bytes: &'_ [u8], extra: usize| bytes.len().checked_add(extra).is_some_and(|n| n <= limit); + let bitmap = || b.data.get(uids + 1..).filter(|d| within(d, 0)).map(<[u8]>::to_vec); + match kind { + // EMF, WMF: a metafile header then (usually deflated) data. + 0xF01A | 0xF01B => { + let h = b.data.get(uids..uids + 34)?; + let size = crate::record::u32_at(h, 0)? as usize; + let compressed = *h.get(32)? == 0; + let body = b.data.get(uids + 34..)?; + let data = if compressed { + miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(body, inflate_bounds(b, limit)?.1).ok()? + } else { + body.get(..size.min(body.len())).filter(|d| within(d, 0))?.to_vec() + }; + let (ext, content_type) = if kind == 0xF01A { ("emf", "image/x-emf") } else { ("wmf", "image/x-wmf") }; + Some(Picture { ext, content_type, data }) + } + // Bitmaps: a one-byte tag then the file. + 0xF01D | 0xF02A => Some(Picture { ext: "jpg", content_type: "image/jpeg", data: bitmap()? }), + 0xF01E => Some(Picture { ext: "png", content_type: "image/png", data: bitmap()? }), + 0xF029 => Some(Picture { ext: "tif", content_type: "image/tiff", data: bitmap()? }), + 0xF01F => Some(Picture { ext: "bmp", content_type: "image/bmp", data: dib_to_bmp(b.data.get(uids + 1..).filter(|d| within(d, 14))?)? }), + // PICT (Macintosh) has no decoder here. + _ => None, + } + .filter(|p| p.data.len() <= limit) +} + +/// A device-independent bitmap with the 14-byte file header a `.bmp` needs in front. +fn dib_to_bmp(dib: &[u8]) -> Option> { + let header = crate::record::u32_at(dib, 0)? as usize; + let (bits, compression, used) = if header == 12 { + (usize::from(crate::record::u16_at(dib, 10)?), 0, 0) + } else { + (usize::from(crate::record::u16_at(dib, 14)?), crate::record::u32_at(dib, 16)?, crate::record::u32_at(dib, 32)? as usize) + }; + let entry = if header == 12 { 3 } else { 4 }; + // The colour table: up to 2^bits entries (all of them when biClrUsed is 0) for 8 bits or + // fewer; biClrUsed entries, an optional table, for more. + let colors = match bits { + 0..=8 if used > 0 => used.min(1 << bits), + 0..=8 => 1 << bits, + _ => used, + }; + // BI_BITFIELDS with the 40-byte header: three masks follow it. + let masks = if compression == 3 && header == 40 { 12 } else { 0 }; + let offset = 14usize.checked_add(header)?.checked_add(colors.checked_mul(entry)?)?.checked_add(masks)?; + let file_len = 14usize.checked_add(dib.len())?; + // Pixels starting past the end are no bitmap. + if offset > file_len { + return None; + } + let total = u32::try_from(file_len).ok()?; + let mut out = Vec::with_capacity(dib.len() + 14); + out.extend_from_slice(b"BM"); + out.extend_from_slice(&total.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&u32::try_from(offset).ok()?.to_le_bytes()); + out.extend_from_slice(dib); + Some(out) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::build::*; + + fn decode_all(b: &Rec) -> Option { + decode(b, usize::MAX) + } + + /// Many entries pointing at one deflated metafile decode within the shared budget, each + /// at most once. + #[test] + fn the_store_decodes_lazily_within_a_budget() { + let wmf = vec![7u8; 1000]; + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + let pictures = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat()); + let mut fbse = vec![0u8; 36]; + fbse[20..24].copy_from_slice(&(pictures.len() as u32).to_le_bytes()); + let entries: Vec> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect(); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]); + let mut store = Store::new(Rec::at(&dgg, 0), &pictures); + store.budget = 2500; + assert_eq!(store.take(0).map(|p| p.data.len()), Some(1000)); + assert!(store.take(0).is_none(), "taken already"); + assert!(store.take(1).is_some()); + assert!(store.take(2).is_none(), "past the budget"); + assert!(store.take(99).is_none()); + } + + /// A compressed metafile that fails to inflate still costs the budget what it may have + /// inflated, so entries pointing at one damaged stream can't each inflate it again for free. + #[test] + fn a_failed_inflate_is_charged_to_the_budget() { + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&1000u32.to_le_bytes()); + let damaged = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &[0x78, 0x9C, 0xFF, 0xFF]].concat()); + let mut fbse = vec![0u8; 36]; + fbse[20..24].copy_from_slice(&(damaged.len() as u32).to_le_bytes()); + let entries: Vec> = (0..3).map(|_| atom(rt::FBSE, 3, &fbse)).collect(); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 3, &entries)]); + let mut store = Store::new(Rec::at(&dgg, 0), &damaged); + store.budget = 2500; + assert!(store.take(0).is_none()); + assert_eq!(store.budget, 1496, "1000 bytes it may have inflated and the 4 it read"); + assert!(store.take(1).is_none()); + assert!(store.take(2).is_none()); + assert_eq!(store.budget, 0, "the last attempt is charged what was left"); + // A picture that isn't a compressed metafile costs nothing when it can't be read. + let mut store = Store::new(None, &[]); + store.budget = 10; + assert!(store.decode_inline(&atom(0xF01E, 0x6E0, &[0; 4])).is_none()); + assert_eq!(store.budget, 10); + } + + /// A compressed metafile that inflates to nothing (a declared size of 0 and a run of empty + /// stored blocks, here with a bad checksum) still costs the bytes it makes the inflate read, so + /// many entries pointing at it run out of budget instead of each reading it again for free. + #[test] + fn inflating_is_charged_the_compressed_bytes() { + let mut z = vec![0x78, 0x01]; + for _ in 0..200 { + z.extend_from_slice(&[0x00, 0x00, 0x00, 0xFF, 0xFF]); + } + z.extend_from_slice(&[0x01, 0x00, 0x00, 0xFF, 0xFF, 1, 2, 3, 4]); + let empty = atom(0xF01B, 0x216, &[&[0u8; 16][..], &[0u8; 34], &z].concat()); + let mut fbse = vec![0u8; 36]; + fbse[20..24].copy_from_slice(&(empty.len() as u32).to_le_bytes()); + let entries: Vec> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect(); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]); + let mut store = Store::new(Rec::at(&dgg, 0), &empty); + store.budget = 2 * z.len() + 10; + assert!(store.take(0).is_none()); + assert_eq!(store.budget, z.len() + 10); + assert!(store.take(1).is_none()); + assert_eq!(store.budget, 10); + // Too little left for its compressed bytes: not inflated, and nothing charged. + assert!(store.take(2).is_none()); + assert_eq!(store.budget, 10); + // One that inflates is charged its compressed bytes as well as what they inflate to. + let wmf = vec![7u8; 100]; + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + let blip = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat()); + let mut store = Store::new(None, &[]); + store.budget = 1000; + assert_eq!(store.decode_inline(&blip).map(|p| p.data.len()), Some(100)); + assert_eq!(store.budget, 1000 - 100 - z.len()); + } + + #[test] + fn decodes_png_and_deflated_metafiles() { + let png = [&[0u8; 17][..], b"\x89PNG..."].concat(); + let p = decode_all(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap()).unwrap(); + assert_eq!((p.ext, &p.data[..4]), ("png", &b"\x89PNG"[..])); + // Over the remaining budget: refused before it is copied. + assert!(decode(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap(), 6).is_none()); + + let wmf = b"\x01\x00\x09\x00\x00\x03 a tiny metafile".to_vec(); + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + header[28..32].copy_from_slice(&(z.len() as u32).to_le_bytes()); + let body = [&[0u8; 16][..], &header, &z].concat(); + let p = decode_all(&Rec::at(&atom(0xF01B, 0x216, &body), 0).unwrap()).unwrap(); + assert_eq!((p.ext, p.data), ("wmf", wmf)); + // Damaged deflate data is no picture rather than a panic. + let bad = [&[0u8; 16][..], &header, &[1, 2, 3]].concat(); + assert!(decode_all(&Rec::at(&atom(0xF01A, 0x3D4, &bad), 0).unwrap()).is_none()); + } + + #[test] + fn a_dib_becomes_a_bmp_the_image_crate_reads() { + // 1×1, 24-bit. + let mut dib = vec![0u8; 40]; + dib[0] = 40; + dib[4] = 1; + dib[8] = 1; + dib[12] = 1; + dib[14] = 24; + dib.extend_from_slice(&[0, 0, 255, 0]); + let body = [&[0u8; 17][..], &dib].concat(); + let p = decode_all(&Rec::at(&atom(0xF01F, 0x7A8, &body), 0).unwrap()).unwrap(); + assert_eq!(&p.data[..2], b"BM"); + assert_eq!(u32::from_le_bytes(p.data[10..14].try_into().unwrap()), 54); + let img = image::load_from_memory_with_format(&p.data, image::ImageFormat::Bmp).unwrap().to_rgba8(); + assert_eq!(img.dimensions(), (1, 1)); + assert_eq!(img.get_pixel(0, 0).0, [255, 0, 0, 255]); + } + + /// The pixels start after the colour table: biClrUsed entries for more than 8 bits (none when + /// it is 0), at most 2^bits for fewer, and a table running past the DIB is no picture. + #[test] + fn a_dib_colour_table_is_sized_by_its_bit_depth() { + let dib = |bits: u16, used: u32, extra: usize| { + let mut d = vec![0u8; 40]; + d[0] = 40; + d[14..16].copy_from_slice(&bits.to_le_bytes()); + d[32..36].copy_from_slice(&used.to_le_bytes()); + d.resize(40 + extra, 0); + d + }; + let offset = |b: &[u8]| dib_to_bmp(b).map(|bmp| u32::from_le_bytes(bmp[10..14].try_into().unwrap())); + assert_eq!(offset(&dib(24, 0, 4)), Some(54)); + assert_eq!(offset(&dib(24, 300, 1204)), Some(54 + 1200), "more than 256 entries for 24 bits"); + assert_eq!(offset(&dib(8, 300, 1028)), Some(54 + 1024), "8 bits: at most 256"); + assert_eq!(offset(&dib(4, 0, 68)), Some(54 + 64)); + assert_eq!(offset(&dib(24, 300, 100)), None, "the table runs past the DIB"); + assert_eq!(offset(&dib(32, u32::MAX, 0)), None); + } + + /// JPEG (RGB and CMYK), TIFF and a PNG with a second UID: the instance says how many UIDs come + /// before the tag byte, and the bytes after it are the file. + #[test] + fn decodes_each_bitmap_kind() { + let file = b"the picture file"; + for (kind, instance, uids, ext) in [ + (0xF01D, 0x46A, 16, "jpg"), + (0xF01D, 0x46B, 32, "jpg"), + (0xF02A, 0x6E2, 16, "jpg"), + (0xF029, 0x6E4, 16, "tif"), + (0xF029, 0x6E5, 32, "tif"), + (0xF01E, 0x6E1, 32, "png"), + ] { + let body = [&vec![0xAAu8; uids][..], &[0xFF], file].concat(); + let p = decode_all(&Rec::at(&atom(kind, instance, &body), 0).unwrap()).unwrap(); + assert_eq!((p.ext, p.data.as_slice()), (ext, &file[..]), "{kind:#x}/{instance:#x}"); + } + } + + /// A metafile stored without compression (compression byte 0xFE) is copied as it is, up to its + /// stated size; with two UIDs the header starts 32 bytes in. + #[test] + fn decodes_an_uncompressed_metafile() { + let emf = b"\x01\x00\x00\x00 an enhanced metafile".to_vec(); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(emf.len() as u32).to_le_bytes()); + header[28..32].copy_from_slice(&(emf.len() as u32).to_le_bytes()); + header[32] = 0xFE; + for (instance, uids) in [(0x3D4, 16), (0x3D5, 32)] { + let body = [&vec![0u8; uids][..], &header, &emf, b"trailing"].concat(); + let p = decode_all(&Rec::at(&atom(0xF01A, instance, &body), 0).unwrap()).unwrap(); + assert_eq!((p.ext, &p.data), ("emf", &emf)); + } + } + + /// A metafile whose inflated size (with its compressed bytes) would pass the remaining budget is refused, compressed or not. + #[test] + fn a_metafile_over_the_budget_is_refused() { + let wmf = vec![9u8; 4000]; + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + let deflated = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat()); + // The budget covers the compressed bytes read as well as the bytes they inflate to. + assert!(decode(&Rec::at(&deflated, 0).unwrap(), 3999 + z.len()).is_none()); + assert_eq!(decode(&Rec::at(&deflated, 0).unwrap(), 4000 + z.len()).map(|p| p.data.len()), Some(4000)); + header[32] = 0xFE; + let raw = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &wmf].concat()); + assert!(decode(&Rec::at(&raw, 0).unwrap(), 3999).is_none()); + assert!(decode(&Rec::at(&raw, 0).unwrap(), 4000).is_some()); + } + + /// An FBSE may hold its blip itself, after its name, instead of pointing into the Pictures + /// stream. + #[test] + fn a_blip_inside_its_fbse_is_read() { + let png = [&[0u8; 17][..], b"\x89PNG inside"].concat(); + let blip = atom(0xF01E, 0x6E0, &png); + let name = "p".encode_utf16().flat_map(u16::to_le_bytes).collect::>(); + let mut fbse = [0u8; 36]; + fbse[20..24].copy_from_slice(&(blip.len() as u32).to_le_bytes()); + fbse[33] = name.len() as u8; + let entry = atom(rt::FBSE, 6, &[&fbse[..], &name, &blip].concat()); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 1, &[entry])]); + // The Pictures stream is empty: the blip can only come from the FBSE. + let mut store = Store::new(Rec::at(&dgg, 0), &[]); + let p = store.take(0).unwrap(); + assert_eq!((p.ext, &p.data[..]), ("png", &b"\x89PNG inside"[..])); + } +} diff --git a/crates/ppt-binary/src/convert.rs b/crates/ppt-binary/src/convert.rs new file mode 100644 index 000000000..f7897cdbb --- /dev/null +++ b/crates/ppt-binary/src/convert.rs @@ -0,0 +1,1181 @@ +//! Building a `craft_pptx` presentation from the parsed `.ppt` structure. +//! +//! Each main master becomes a master: the caller's default master (its layouts and placeholders), +//! with the file's colours, fonts, text styles, background and decorative shapes, and the file's +//! placeholder boxes on the placeholders the default master has. A title master becomes a layout +//! of its main master. Slide shapes keep their own boxes, and their text carries its formatting +//! resolved against the master's text styles, so it draws the same whatever the layouts hold. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use craft_pptx::style::{Dash, LineCap, LineEnd, LineJoin, PictureFill, PictureMode, Shadow}; +use craft_pptx::text::{Align, Anchor as TextAnchor, AutoFit, BodyProps, Bullet, LevelStyle, ListStyle, ParaProps, RunKind, Spacing, TabStop}; +use craft_pptx::{ + Background, ColorRef, Defaults, Effects, Fill, Layout, LayoutId, LayoutType, Line, Master, MediaId, Paragraph, PhType, Placeholder, Presentation, + Run, RunProps, Shape, ShapeId, ShapeKind, Size, Slide, SlideId, TextBody, Theme, Xfrm, +}; +use craft_pptx::{ColorTransform, Rgba, SchemeSlot}; + +use crate::doc::{self, Doc, Listed, rt}; +use crate::draw::{self, Props, RawShape, prop}; +use crate::geom; +use crate::record::{MAX_DEPTH, Rec}; +use crate::text::{self, Cf, FieldKind, Pf, StyleSheet, TextBlock, TextColor, ty}; + +/// Master units (576 per inch) per point. +const MU: f64 = 8.0; +/// EMUs per point. +const EMU: f64 = 12700.0; + +/// The eight colours of a `.ppt` colour scheme: background, text, shadow, title text, fill, +/// accent, accent and hyperlink, accent and followed hyperlink. +type Scheme = [Rgba; 8]; + +const DEFAULT_SCHEME: Scheme = [ + Rgba::rgb(0xFF, 0xFF, 0xFF), + Rgba::rgb(0, 0, 0), + Rgba::rgb(0x80, 0x80, 0x80), + Rgba::rgb(0, 0, 0), + Rgba::rgb(0xBB, 0xE0, 0xE3), + Rgba::rgb(0x33, 0x33, 0x99), + Rgba::rgb(0, 0x99, 0x99), + Rgba::rgb(0x99, 0xCC, 0x00), +]; + +fn scheme_of(container: &Rec) -> Option { + let r = container.children_of(rt::COLOR_SCHEME).find(|r| r.instance == 1)?; + let mut s = DEFAULT_SCHEME; + for (i, c) in s.iter_mut().enumerate() { + *c = Rgba::rgb(r.u8(i * 4)?, r.u8(i * 4 + 1)?, r.u8(i * 4 + 2)?); + } + Some(s) +} + +/// What converting one drawing needs besides the shapes. +struct Scope<'s, 'a> { + scheme: Scheme, + styles: &'s StyleSheet, + /// The slide list's outline text, for placeholders that point at it. + outline: &'s [crate::record::Records<'a>], + /// Each outline block's numbering (`StyleTextProp9Atom` entries), by outline index. + numbering: &'s [Option>], + /// The outline blocks a shape has taken already. Each block is one shape's text: a second + /// shape pointing at it keeps its own, so a big block can't be copied into every shape. + used_outline: RefCell>, + master: bool, + /// Where `hspMaster` shape ids are looked up: the slide's master, then a title master's main + /// master. + masters: Chain, +} + +/// Master slide ids, nearest first. +type Chain = [Option; 2]; + +struct Ctx<'a> { + p: Presentation, + fonts: Vec, + blips: crate::blip::Store<'a>, + media: HashMap>, + /// Pictures held in a shape's own property, by where their bytes start, so a master shape's + /// picture inherited by many slides is added once. + inline_media: HashMap>, + /// The slides' outline numbering, by slide id and text type ([`doc::outline_numbering`]). + numbering: HashMap<(u32, u32), Vec>>, + defaults: Props<'a>, + /// Master shapes by master slide id and shape id, for slide shapes that inherit from one + /// (`hspMaster`). Keyed by master too, so a shape id repeated in another master can't replace + /// this master's shape. + master_props: HashMap<(u32, u32), Props<'a>>, + /// The caller's defaults: the master each of the file's masters starts from. + app: &'a dyn Defaults, + /// Notes pages converted already. Distinct slides can share a slide id, and so a notes page: + /// it goes to the first of them only, so its text isn't copied into every one. + used_notes: HashSet, +} + +pub fn convert<'a>(d: &Doc<'a>, pictures: &'a [u8], app: &'a dyn Defaults) -> Presentation { + let atom = d.document_atom(); + let side = + |v: Option, fallback: f64| v.map(|v| f64::from(v) / MU).filter(|v| v.is_finite() && *v >= 1.0 && *v <= 56.0 * 72.0).unwrap_or(fallback); + let size = Size::new(side(atom.as_ref().map(|a| a.slide_w), 720.0), side(atom.as_ref().map(|a| a.slide_h), 540.0)); + // Ids above 256, as a new presentation's are. + let mut p = Presentation { slide_size: size, default_text_style: app.default_text_style(), next_id: 256, ..Default::default() }; + p.notes_size = Size::new(side(atom.as_ref().map(|a| a.notes_w), 540.0), side(atom.as_ref().map(|a| a.notes_h), 720.0)); + p.first_slide_number = atom.as_ref().map_or(1, |a| u32::from(a.first_slide_number)); + let dgg = d.document.child(rt::DRAWING_GROUP).and_then(|g| g.child(rt::DGG_CONTAINER)); + let mut cx = Ctx { + p, + fonts: doc::fonts(d), + blips: crate::blip::Store::new(dgg, pictures), + media: HashMap::new(), + inline_media: HashMap::new(), + numbering: doc::outline_numbering(&d.document), + defaults: draw::default_props(dgg), + master_props: HashMap::new(), + app, + used_notes: HashSet::new(), + }; + let environment = d.document.child(rt::ENVIRONMENT); + if let Some(hf) = doc::headers_footers(&d.document, 3) { + cx.p.header_footer = craft_pptx::HeaderFooter { + date: hf.date, + slide_number: hf.slide_number, + footer: hf.footer, + footer_text: hf.footer_text, + date_text: if hf.user_date { hf.date_text } else { String::new() }, + date_format: format!("datetime{}", hf.format.min(12) + 1), + ..Default::default() + }; + } + + // Main masters first, then title masters as layouts of theirs. + let mut masters: HashMap = HashMap::new(); + for m in d.masters.iter().filter(|m| m.rec.kind == rt::MAIN_MASTER) { + if let Some(info) = cx.main_master(m, environment, size) { + masters.insert(m.slide_id, info); + } + } + if cx.p.masters.is_empty() { + let m = cx.default_master(size, None); + cx.p.masters.push(Arc::new(m)); + } + for m in d.masters.iter().filter(|m| m.rec.kind == rt::SLIDE) { + cx.title_master(m, &mut masters); + } + + // Each slide's notes page, by the slide id its NotesAtom names (the first one wins), built once: + // a scan per slide would be slides × notes pages. + let mut notes_of: HashMap = HashMap::new(); + for (i, n) in d.notes.iter().enumerate() { + if n.rec.kind == rt::NOTES + && let Some(id) = n.rec.child(rt::NOTES_ATOM).and_then(|a| a.u32(0)) + { + notes_of.entry(id).or_insert(i); + } + } + // An unknown master falls back to the first main master. Title masters share their main + // master's index, so including them would tie, and HashMap order would pick the winner. Found + // once, as is each master's layout for each layout type: a search per slide would be slides × + // masters (or layouts). A title master's layout is only for the slides that name it. + let first_main = masters.values().filter(|m| m.layout.is_none()).min_by_key(|m| m.index).cloned(); + let title_layouts: HashSet = masters.values().filter_map(|m| m.layout).collect(); + let layouts: Vec = cx.p.masters.iter().map(|m| layout_table(m, &title_layouts)).collect(); + let find = Find { masters: &masters, first_main: first_main.as_ref(), layouts: &layouts, notes_of: ¬es_of }; + for s in &d.slides { + if s.rec.kind != rt::SLIDE { + continue; + } + if let Some(slide) = cx.slide(d, s, &find) { + cx.p.slides.push(Arc::new(slide)); + } + } + cx.p +} + +/// A master's first layout of each layout type, and its first layout. +type LayoutTable = (Vec<(LayoutType, LayoutId)>, Option); + +fn layout_table(m: &Master, skip: &HashSet) -> LayoutTable { + let mut kinds: Vec<(LayoutType, LayoutId)> = vec![]; + let layouts = m.layouts.iter().filter(|l| !skip.contains(&l.id)); + let first = layouts.clone().next().map(|l| l.id); + for l in layouts { + // Layout types are few, so the list stays short. + if !kinds.iter().any(|(k, _)| *k == l.kind) { + kinds.push((l.kind, l.id)); + } + } + (kinds, first) +} + +/// What a slide's master, layout and notes page are looked up in. +struct Find<'f> { + masters: &'f HashMap, + first_main: Option<&'f MasterInfo>, + layouts: &'f [LayoutTable], + notes_of: &'f HashMap, +} + +/// A converted master: where it went and what its slides inherit. +#[derive(Clone)] +struct MasterInfo { + index: usize, + scheme: Scheme, + styles: Arc, + /// A layout made for a title master; slides of that title master use it. + layout: Option, + /// This master's slide id, then its main master's for a title master. + ids: Chain, + /// The placeholders of the defaults' title layout, taken before any title master adds layouts + /// of its own: what each title master's layout starts from. Empty when there is none. + title_base: Arc>, +} + +impl<'a> Ctx<'a> { + fn alloc(&mut self) -> Option { + self.p.alloc_id() + } + + /// The caller's default master for slides of `size`, with ids above every id handed out so + /// far. With `theme`, the master wears it and is named after it. + fn default_master(&mut self, size: Size, theme: Option) -> Master { + let (mut master, last) = self.app.master(size, self.p.next_id); + self.p.next_id = self.p.next_id.max(last); + if let Some(theme) = theme { + master.name = theme.name.clone(); + master.theme = theme; + } + master + } + + fn main_master(&mut self, m: &Listed<'a>, environment: Option>, size: Size) -> Option { + let scheme = scheme_of(&m.rec).unwrap_or(DEFAULT_SCHEME); + let styles = Arc::new(StyleSheet::new(environment, Some(&m.rec))); + let theme = self.theme(&scheme, &styles); + let mut master = self.default_master(size, Some(theme)); + let drawing = draw::drawing(&m.rec); + self.remember_master_props(m.slide_id, &drawing.shapes, 0); + let ids = [Some(m.slide_id), None]; + let scope = + Scope { scheme, styles: &styles, outline: &m.outline, numbering: &[], used_outline: Default::default(), master: true, masters: ids }; + master.background = drawing.background.as_ref().and_then(|b| self.background(b, &scope)); + for raw in &drawing.shapes { + if let Some(ph) = raw.placeholder.filter(|p| p.kind != 0) { + // The master's placeholders set where new slides' placeholders go. + if let (Some(kind), Some(x)) = (ph_type(ph.kind), raw.anchor.map(|a| xfrm(&a, TOP, 0.0, false, false))) + && let Some(s) = master.shapes.iter_mut().find(|s| s.ph_type().is_some_and(|t| same_family(t, kind))) + { + s.xfrm = Some(x); + // The footer row sits in the same place on every layout, with the master's look: + // its first paragraph's alignment and its first run's size and colour. + if matches!(kind, PhType::Date | PhType::Footer | PhType::SlideNum) { + let look = self.shape(raw, &scope, 0, TOP).and_then(|c| c.text).and_then(|t| t.paragraphs.into_iter().next()); + let style = |t: &mut TextBody| { + if let Some(p) = &look { + let mut level = t.list_style.level(0).cloned().unwrap_or_default(); + level.para.align = p.props.align.or(level.para.align); + if let Some(run) = p.runs.first() { + level.run.size = run.props.size.or(level.run.size); + level.run.fill = run.props.fill.clone().or(level.run.fill.take()); + } + t.list_style.set(0, level); + } + }; + if let Some(t) = s.text.as_mut() { + style(t); + } + for l in &mut master.layouts { + for ls in l.shapes.iter_mut().filter(|ls| ls.ph_type() == Some(kind)) { + ls.xfrm = Some(x); + if let Some(t) = ls.text.as_mut() { + style(t); + } + } + } + } + } + continue; + } + if let Some(s) = self.shape(raw, &scope, 0, TOP) { + master.shapes.push(s); + } + } + master.title_style = self.list_style(&styles, ty::TITLE, &scheme); + master.body_style = self.list_style(&styles, ty::BODY, &scheme); + master.other_style = self.list_style(&styles, ty::OTHER, &scheme); + let title_base = master + .layouts + .iter() + .find(|l| l.kind == LayoutType::Title) + .map(|l| l.shapes.iter().filter(|s| s.ph.is_some()).cloned().collect()) + .unwrap_or_default(); + let index = self.p.masters.len(); + self.p.masters.push(Arc::new(master)); + Some(MasterInfo { index, scheme, styles, layout: None, ids, title_base: Arc::new(title_base) }) + } + + /// A title master: a layout of its main master holding its background and shapes. + fn title_master(&mut self, m: &Listed<'a>, masters: &mut HashMap) { + let atom = doc::slide_atom(&m.rec); + let Some(parent) = masters.get(&atom.master_id).cloned() else { return }; + let scheme = if atom.follow_master_scheme { parent.scheme } else { scheme_of(&m.rec).unwrap_or(parent.scheme) }; + let Some(id) = self.alloc() else { return }; + let drawing = draw::drawing(&m.rec); + self.remember_master_props(m.slide_id, &drawing.shapes, 0); + let ids = [Some(m.slide_id), parent.ids[0]]; + let scope = Scope { + scheme, + styles: &parent.styles, + outline: &m.outline, + numbering: &[], + used_outline: Default::default(), + master: true, + masters: ids, + }; + let background = if atom.follow_master_background { None } else { drawing.background.as_ref().and_then(|b| self.background(b, &scope)) }; + let shapes: Vec = + drawing.shapes.iter().filter(|r| r.placeholder.is_none_or(|p| p.kind == 0)).filter_map(|r| self.shape(r, &scope, 0, TOP)).collect(); + // Its placeholders follow the main master's own title layout (from the defaults, taken once + // when the main master was made), with ids of their own. A layout made for an earlier title + // master holds that one's shapes and placeholder boxes, so it is never the base. + let mut placeholders = Vec::with_capacity(parent.title_base.len()); + for mut s in parent.title_base.iter().cloned() { + let Some(id) = self.alloc() else { break }; + s.id = ShapeId(id); + placeholders.push(s); + } + // The title master's own placeholders say where its slides' placeholders go, as a main + // master's do; one the title layout lacks is added. + for raw in &drawing.shapes { + let Some(ph) = raw.placeholder.filter(|p| p.kind != 0) else { continue }; + let (Some(kind), Some(x)) = (ph_type(ph.kind), raw.anchor.map(|a| xfrm(&a, TOP, 0.0, false, false))) else { continue }; + if let Some(s) = placeholders.iter_mut().find(|s| s.ph_type().is_some_and(|t| same_family(t, kind))) { + s.xfrm = Some(x); + continue; + } + let Some(id) = self.alloc() else { break }; + placeholders.push(Shape { + id: ShapeId(id), + name: raw.props.string(prop::NAME).unwrap_or_else(|| default_name(raw)), + xfrm: Some(x), + ph: Some(Placeholder { kind, idx: ph.position, ..Default::default() }), + text: Some(TextBody::default()), + ..Default::default() + }); + } + let Some(master) = self.p.masters.get_mut(parent.index) else { return }; + Arc::make_mut(master).layouts.push(Layout { + id: LayoutId(id), + name: "Title Master".into(), + kind: LayoutType::Title, + shapes: shapes.into_iter().chain(placeholders).collect(), + background, + show_master_shapes: atom.follow_master_objects, + ..Default::default() + }); + masters.insert(m.slide_id, MasterInfo { layout: Some(LayoutId(id)), scheme, ids, ..parent }); + } + + fn remember_master_props(&mut self, master: u32, shapes: &[RawShape<'a>], depth: usize) { + if depth > MAX_DEPTH { + return; + } + for s in shapes { + self.master_props.insert((master, s.spid), s.props.clone()); + self.remember_master_props(master, &s.children, depth + 1); + } + } + + /// A theme carrying the master's colours and fonts, so shapes added later match the deck. + fn theme(&self, scheme: &Scheme, styles: &StyleSheet) -> Theme { + let mut t = Theme { name: "Imported".into(), ..Default::default() }; + for (slot, i) in [ + (SchemeSlot::Lt1, 0), + (SchemeSlot::Dk1, 1), + (SchemeSlot::Lt2, 2), + (SchemeSlot::Dk2, 3), + (SchemeSlot::Accent1, 4), + (SchemeSlot::Accent2, 5), + (SchemeSlot::Hlink, 6), + (SchemeSlot::FolHlink, 7), + ] { + if let Some(c) = scheme.get(i) { + t.colors.set(slot, *c); + } + } + if let Some(f) = styles.resolve(ty::TITLE, 0).1.font.and_then(|i| self.fonts.get(usize::from(i))) { + t.fonts.major.latin = f.clone(); + } + if let Some(f) = styles.resolve(ty::BODY, 0).1.font.and_then(|i| self.fonts.get(usize::from(i))) { + t.fonts.minor.latin = f.clone(); + } + t + } + + fn list_style(&self, styles: &StyleSheet, text_type: u32, scheme: &Scheme) -> ListStyle { + let mut ls = ListStyle::default(); + for level in 0..5u8 { + let (pf, cf) = styles.resolve(text_type, level); + let run = self.run_props(&cf, scheme); + let para = self.para_props(&pf, scheme, run.size.unwrap_or(18.0)); + ls.set(level, LevelStyle { para, run }); + } + ls + } + + fn slide(&mut self, d: &Doc<'a>, s: &Listed<'a>, find: &Find) -> Option { + let atom = doc::slide_atom(&s.rec); + let info = find.masters.get(&atom.master_id).or(find.first_main).cloned(); + let (index, master_scheme, styles, title_layout, ids) = match &info { + Some(m) => (m.index, m.scheme, m.styles.clone(), m.layout, m.ids), + None => (0, DEFAULT_SCHEME, Arc::new(StyleSheet::new(d.document.child(rt::ENVIRONMENT), None)), None, [None; 2]), + }; + let scheme = if atom.follow_master_scheme { master_scheme } else { scheme_of(&s.rec).unwrap_or(master_scheme) }; + let layout = title_layout.or_else(|| { + let kind = layout_kind(atom.geom); + let (kinds, first) = find.layouts.get(index)?; + kinds.iter().find(|(k, _)| *k == kind).map(|(_, id)| *id).or(*first) + })?; + let id = SlideId(self.alloc()?); + let drawing = draw::drawing(&s.rec); + // The n-th outline block of a text type takes the n-th numbering entry for that type. + let mut seen: HashMap = HashMap::new(); + let numbering: Vec>> = s + .outline + .iter() + .map(|block| { + let tt = block.clone().next().filter(|h| h.kind == rt::TEXT_HEADER).and_then(|h| h.u32(0))?; + let k = seen.entry(tt).or_insert(0); + let n = *k; + *k += 1; + self.numbering.get(&(s.slide_id, tt)).and_then(|v| v.get(n)).cloned() + }) + .collect(); + let scope = Scope { + scheme, + styles: &styles, + outline: &s.outline, + numbering: &numbering, + used_outline: Default::default(), + master: false, + masters: ids, + }; + let background = if atom.follow_master_background { None } else { drawing.background.as_ref().and_then(|b| self.background(b, &scope)) }; + let mut shapes: Vec = drawing.shapes.iter().filter_map(|r| self.shape(r, &scope, 0, TOP)).collect(); + // The slide's own headers and footers, else the document's for every slide. + if let Some(hf) = doc::headers_footers(&s.rec, 0).or_else(|| doc::headers_footers(&d.document, 3)) { + self.footers(&mut shapes, &hf); + } + let hidden = s.rec.child(rt::SLIDE_SHOW_SLIDE_INFO).and_then(|i| i.u16(10)).is_some_and(|f| f & 0x4 != 0); + let notes = find + .notes_of + .get(&s.slide_id) + .filter(|&&i| self.used_notes.insert(i)) + .and_then(|&i| d.notes.get(i)) + .map(|n| self.notes(n, &styles, scheme)) + .unwrap_or_default(); + Some(Slide { id, layout, shapes, background, hidden, show_master_shapes: atom.follow_master_objects, notes, ..Default::default() }) + } + + /// The date, footer and slide number placeholders `hf` turns on, for those the slide doesn't + /// hold itself. They take their place and look from the layout and master. + fn footers(&mut self, shapes: &mut Vec, hf: &doc::HeadersFooters) { + let field = |text: &str, field: String| TextBody { + paragraphs: vec![Paragraph { + runs: vec![Run { text: text.into(), props: Default::default(), kind: RunKind::Field { field } }], + ..Default::default() + }], + ..Default::default() + }; + let wanted = [ + (PhType::Date, hf.date, "Date Placeholder"), + (PhType::Footer, hf.footer && !hf.footer_text.is_empty(), "Footer Placeholder"), + (PhType::SlideNum, hf.slide_number, "Slide Number Placeholder"), + ]; + for (kind, on, name) in wanted { + if !on || shapes.iter().any(|s| s.ph_type() == Some(kind)) { + continue; + } + let text = match kind { + PhType::SlideNum => field("‹#›", "slidenum".into()), + PhType::Date if hf.user_date => TextBody::from_text(&hf.date_text), + // formatId 0–12 are the thirteen date formats, in DrawingML's order. + PhType::Date => field("", format!("datetime{}", hf.format.min(12) + 1)), + _ => TextBody::from_text(&hf.footer_text), + }; + let Some(id) = self.alloc() else { return }; + shapes.push(Shape { + id: ShapeId(id), + name: name.into(), + ph: Some(Placeholder { kind, ..Default::default() }), + text: Some(text), + ..Default::default() + }); + } + } + + /// The text of a notes page's notes placeholder. + fn notes(&mut self, n: &Listed<'a>, styles: &StyleSheet, scheme: Scheme) -> TextBody { + let drawing = draw::drawing(&n.rec); + // Notes masters aren't imported, so there are no master shapes to inherit from. + let scope = + Scope { scheme, styles, outline: &n.outline, numbering: &[], used_outline: Default::default(), master: false, masters: [None; 2] }; + for raw in &drawing.shapes { + let Some(block) = self.text_block(raw, &scope) else { continue }; + // The notes body placeholder; a slide number or header placeholder on the page isn't notes. + let is_notes = match raw.placeholder.filter(|p| p.kind != 0) { + Some(p) => matches!(p.kind, 0x06 | 0x0C), + None => block.text_type == ty::NOTES, + }; + if is_notes { + let mut body = self.text_body(&block, &scope, &raw.props); + body.body = BodyProps::default(); + return body; + } + } + TextBody::default() + } + + fn background(&mut self, raw: &RawShape<'a>, scope: &Scope) -> Option { + let props = self.props_of(raw, scope, false); + let fill = self.fill(&props, scope, true)?; + Some(Background::Fill { fill }) + } + + /// The shape's properties with what it inherits: its master shape's, then (for placeholders, + /// text boxes and picture frames) no fill and no line, then the drawing defaults. + fn props_of(&self, raw: &RawShape<'a>, scope: &Scope, unfilled: bool) -> Props<'a> { + let mut props = raw.props.clone(); + let inherited = + props.get(prop::HSP_MASTER).and_then(|spid| scope.masters.iter().flatten().find_map(|&master| self.master_props.get(&(master, spid)))); + if let Some(m) = inherited { + props.inherit(m); + } + if unfilled { + props.inherit(&no_fill_no_line()); + } + props.inherit(&self.defaults); + props + } + + fn shape(&mut self, raw: &RawShape<'a>, scope: &Scope, depth: usize, map: Map) -> Option { + if raw.deleted || depth > MAX_DEPTH { + return None; + } + let ph = raw.placeholder.filter(|p| p.kind != 0); + let text_box = raw.shape_type == 202; + // A picture frame (also an OLE object's frame) shows its picture with no fill or line of + // its own unless it says so; the drawing defaults' fill would cover a transparent picture. + let picture_frame = raw.shape_type == PICTURE_FRAME; + let props = self.props_of(raw, scope, ph.is_some() || text_box || picture_frame); + let rot = props.fixed(prop::ROTATION).unwrap_or(0.0); + let anchor = raw.anchor?; + let mut s = Shape { + id: ShapeId(self.alloc()?), + name: props.string(prop::NAME).unwrap_or_else(|| default_name(raw)), + xfrm: Some(xfrm(&anchor, map, rot, raw.flip_h, raw.flip_v)), + descr: props.string(prop::DESCRIPTION).unwrap_or_default(), + hidden: props.flag(prop::GROUP_BOOLS, 1).unwrap_or(false), + ..Default::default() + }; + if raw.is_group { + // Children are placed in slide points; the group's child space is its own box. + let at = s.xfrm.unwrap_or_default(); + let inner = Map::into_group(&at, &raw.group_rect.unwrap_or(anchor)); + let children = raw.children.iter().filter_map(|c| self.shape(c, scope, depth + 1, inner)).collect(); + let child = Xfrm::new(at.x, at.y, at.w, at.h); + s.kind = ShapeKind::Group { children, child }; + return Some(s); + } + if !scope.master + && let Some(ph) = ph + && let Some(kind) = ph_type(ph.kind) + { + s.ph = Some(Placeholder { kind, idx: ph.position, ..Default::default() }); + } + s.geom = geom::geometry(raw.shape_type, &props); + if geom::is_connector(raw.shape_type) { + s.kind = ShapeKind::Connector { start: None, end: None }; + } + // A picture: a picture frame, or any shape showing a picture (an OLE object's preview). + if let Some(media) = self.picture(&props, prop::PIB) { + let crop = |id| props.fixed(id).unwrap_or(0.0).clamp(-1.0, 1.0); + s.kind = ShapeKind::Picture { + fill: PictureFill { + media, + crop: [crop(prop::CROP_LEFT), crop(prop::CROP_TOP), crop(prop::CROP_RIGHT), crop(prop::CROP_BOTTOM)], + ..Default::default() + }, + }; + } + s.fill = Some(self.fill(&props, scope, false).unwrap_or(Fill::None)); + s.line = Some(self.line(&props, scope)); + if let Some(shadow) = self.shadow(&props, scope) { + s.effects = Some(Effects { outer_shadow: Some(shadow), ..Default::default() }); + } + if let Some(block) = self.text_block(raw, scope) { + s.text = Some(self.text_body(&block, scope, &props)); + } else if ph.is_some() { + // An empty placeholder draws nothing (its prompt shows only while editing). + s.text = Some(TextBody::default()); + } + Some(s) + } + + /// The picture a `pib` or `fillBlip` property names: a blip store entry (1-based), or a blip + /// held in the property's own complex bytes. + fn picture(&mut self, props: &Props<'a>, id: u16) -> Option { + let Some(bytes) = props.complex(id) else { + return props.get(id).filter(|&i| i > 0).and_then(|i| self.media(i as usize)); + }; + let key = bytes.as_ptr() as usize; + if let Some(m) = self.inline_media.get(&key) { + return *m; + } + let n = self.inline_media.len() + 1; + let id = self.blips.decode_inline(bytes).and_then(|pic| self.p.add_media(&format!("inline{n}.{}", pic.ext), pic.content_type, pic.data)); + self.inline_media.insert(key, id); + id + } + + fn media(&mut self, pib: usize) -> Option { + if let Some(m) = self.media.get(&pib) { + return *m; + } + let id = + self.blips.take(pib.wrapping_sub(1)).and_then(|pic| self.p.add_media(&format!("image{pib}.{}", pic.ext), pic.content_type, pic.data)); + self.media.insert(pib, id); + id + } + + fn color(&self, v: u32, props: &Props, scope: &Scope, depth: u8) -> Rgba { + let [r, g, b, flags] = v.to_le_bytes(); + if flags & 0x08 != 0 { + return scope.scheme.get(usize::from(r)).copied().unwrap_or(Rgba::BLACK); + } + if flags & 0x10 != 0 { + // A system colour index; the high ones stand for the shape's own fill and line colours. + let other = match r { + 0xF0 => Some(prop::FILL_COLOR), + 0xF1 => Some(prop::LINE_COLOR), + 0xF3 => Some(prop::FILL_BACK_COLOR), + _ => None, + }; + return match other.and_then(|id| props.get(id)) { + Some(o) if depth < 2 => self.color(o, props, scope, depth + 1), + _ => Rgba::BLACK, + }; + } + if flags & 0x01 != 0 { + return Rgba::BLACK; + } + Rgba::rgb(r, g, b) + } + + fn color_ref(&self, id: u16, fallback: u32, opacity: Option, props: &Props, scope: &Scope) -> ColorRef { + let c = ColorRef::rgb(self.color(props.get(id).unwrap_or(fallback), props, scope, 0)); + match opacity.and_then(|o| props.fixed(o)).filter(|a| *a < 1.0) { + Some(a) => c.with(ColorTransform::Alpha((a.clamp(0.0, 1.0) * 100_000.0) as i32)), + None => c, + } + } + + fn fill(&mut self, props: &Props<'a>, scope: &Scope, background: bool) -> Option { + if !background && !props.flag(prop::FILL_BOOLS, 4).unwrap_or(true) { + return None; + } + let fg = self.color_ref(prop::FILL_COLOR, 0x00FF_FFFF, Some(prop::FILL_OPACITY), props, scope); + let bg = self.color_ref(prop::FILL_BACK_COLOR, 0x00FF_FFFF, Some(prop::FILL_BACK_OPACITY), props, scope); + Some(match props.get(prop::FILL_TYPE).unwrap_or(0) { + // Texture (tiled) and picture (stretched). + t @ (2 | 3) => match self.picture(props, prop::FILL_BLIP) { + Some(media) => { + let mode = if t == 2 { + PictureMode::Tile { tx: 0.0, ty: 0.0, sx: 1.0, sy: 1.0, flip: String::new(), align: "tl".into() } + } else { + PictureMode::default() + }; + Fill::Picture(PictureFill { media, mode, ..Default::default() }) + } + None => Fill::solid(fg), + }, + // Gradients. + t @ 4..=8 => { + use craft_pptx::style::{Gradient, GradientShape}; + let focus = props.get(prop::FILL_FOCUS).map_or(0, |v| v as i32).clamp(-100, 100); + let stops = gradient_stops(focus, &fg, &bg); + let shape = if matches!(t, 5 | 6) { + // Position 0 is the centre (the focus rectangle), 1 the shape's edge. + GradientShape::Path { path: if t == 5 { "rect".into() } else { "shape".into() }, focus: [0.5, 0.5, 0.5, 0.5] } + } else { + GradientShape::Linear { angle: linear_angle(props.fixed(prop::FILL_ANGLE).unwrap_or(0.0)), scaled: false } + }; + Fill::Gradient(Gradient { stops, shape: Some(shape), flip: None, rotate_with_shape: Some(true), tile: [0.0; 4] }) + } + 9 => Fill::Background, + _ => Fill::solid(fg), + }) + } + + fn line(&self, props: &Props, scope: &Scope) -> Line { + if !props.flag(prop::LINE_BOOLS, 3).unwrap_or(true) { + return Line::none(); + } + let width = props.get(prop::LINE_WIDTH).map_or(9525.0, f64::from) / EMU; + let mut l = Line::solid(self.color_ref(prop::LINE_COLOR, 0, Some(prop::LINE_OPACITY), props, scope), width); + l.dash = Some(Dash::Preset { + name: match props.get(prop::LINE_DASHING).unwrap_or(0) { + 1 => "sysDash", + 2 => "sysDot", + 3 => "sysDashDot", + 4 => "sysDashDotDot", + 5 => "dot", + 6 => "dash", + 7 => "lgDash", + 8 => "dashDot", + 9 => "lgDashDot", + 10 => "lgDashDotDot", + _ => "solid", + } + .into(), + }); + l.compound = props.get(prop::LINE_STYLE).map(|v| match v { + 1 => craft_pptx::style::Compound::Double, + 2 => craft_pptx::style::Compound::ThickThin, + 3 => craft_pptx::style::Compound::ThinThick, + 4 => craft_pptx::style::Compound::Triple, + _ => craft_pptx::style::Compound::Single, + }); + l.join = props.get(prop::LINE_JOIN).map(|v| match v { + 0 => LineJoin::Bevel, + 1 => LineJoin::Miter, + _ => LineJoin::Round, + }); + l.cap = props.get(prop::LINE_CAP).map(|v| match v { + 0 => LineCap::Round, + 1 => LineCap::Square, + _ => LineCap::Flat, + }); + let end = |kind: u16, w: u16, len: u16| { + let k = match props.get(kind).unwrap_or(0) { + 1 => "triangle", + 2 => "stealth", + 3 => "diamond", + 4 => "oval", + 5 => "arrow", + _ => return None, + }; + let size = |v: Option| match v { + Some(0) => "sm", + Some(2) => "lg", + _ => "med", + }; + Some(LineEnd { kind: k.into(), w: size(props.get(w)).into(), len: size(props.get(len)).into() }) + }; + l.head = end(prop::LINE_START_ARROW, prop::LINE_START_ARROW_WIDTH, prop::LINE_START_ARROW_LENGTH); + l.tail = end(prop::LINE_END_ARROW, prop::LINE_END_ARROW_WIDTH, prop::LINE_END_ARROW_LENGTH); + l + } + + fn shadow(&self, props: &Props, scope: &Scope) -> Option { + if !props.flag(prop::SHADOW_BOOLS, 1).unwrap_or(false) { + return None; + } + let dx = props.get(prop::SHADOW_OFFSET_X).map_or(25400.0, |v| f64::from(v as i32)) / EMU; + let dy = props.get(prop::SHADOW_OFFSET_Y).map_or(25400.0, |v| f64::from(v as i32)) / EMU; + Some(Shadow { + color: self.color_ref(prop::SHADOW_COLOR, 0x0080_8080, Some(prop::SHADOW_OPACITY), props, scope), + blur: 0.0, + dist: dx.hypot(dy), + dir: dy.atan2(dx).to_degrees().rem_euclid(360.0), + inner: false, + sx: 1.0, + sy: 1.0, + kx: 0.0, + ky: 0.0, + align: String::new(), + rotate_with_shape: false, + }) + } + + /// The text block of a shape: its own, or the slide list's outline block it points at. A text + /// box holding the reference may also hold its own ruler ([MS-PPT] OfficeArtClientTextbox: + /// `OutlineTextRefAtom` then an optional `TextRulerAtom`); the margins and indents it sets + /// win over the block's. + fn text_block(&self, raw: &RawShape<'a>, scope: &Scope) -> Option { + let tb = raw.text?; + let own = text::read_block(tb.children())?; + let own_ruler = own.ruler; + match own.outline_ref { + Some(i) if own.chars.is_empty() && scope.used_outline.borrow_mut().insert(i as usize) => scope + .outline + .get(i as usize) + .and_then(|r| text::read_block(r.clone())) + .map(|mut b| { + b.outline_index = Some(i as usize); + for ((lm, ind), (own_lm, own_ind)) in b.ruler.iter_mut().zip(own_ruler) { + *lm = own_lm.or(*lm); + *ind = own_ind.or(*ind); + } + b + }) + .or(Some(own)), + _ => Some(own), + } + } + + fn text_body(&self, block: &TextBlock, scope: &Scope, props: &Props) -> TextBody { + let inset = |id, d: f64| props.get(id).map_or(d, |v| f64::from(v as i32) / EMU).max(0.0); + let body = BodyProps { + inset_l: Some(inset(prop::TEXT_LEFT, 7.2)), + inset_t: Some(inset(prop::TEXT_TOP, 3.6)), + inset_r: Some(inset(prop::TEXT_RIGHT, 7.2)), + inset_b: Some(inset(prop::TEXT_BOTTOM, 3.6)), + anchor: Some(match props.get(prop::ANCHOR_TEXT).unwrap_or(0) { + // middle, middle centred + 1 | 4 => TextAnchor::Middle, + // bottom, bottom centred, and their baseline forms + 2 | 5 | 7 | 9 => TextAnchor::Bottom, + _ => TextAnchor::Top, + }), + anchor_ctr: Some(matches!(props.get(prop::ANCHOR_TEXT), Some(3 | 4 | 5 | 8 | 9))), + wrap: Some(props.get(prop::WRAP_TEXT) != Some(2)), + autofit: Some(AutoFit::None), + ..Default::default() + }; + TextBody { body, paragraphs: self.paragraphs(block, scope), ..Default::default() } + } + + fn paragraphs(&self, block: &TextBlock, scope: &Scope) -> Vec { + let chars = &block.chars; + let total = chars.len(); + let fields: HashMap = block.fields.iter().map(|(p, k)| (*p as usize, *k)).collect(); + // Where each formatting run starts. + let starts = |counts: &mut dyn Iterator| -> Vec { + let mut at = 0usize; + counts + .map(|n| { + let s = at; + at = at.saturating_add(n as usize); + s + }) + .collect() + }; + let para_starts = starts(&mut block.para_runs.iter().map(|r| r.0)); + let char_starts = starts(&mut block.char_runs.iter().map(|r| r.0)); + // The starts never decrease (a running sum), so both lookups are binary searches. A scan per + // run, break and field made text with many runs quadratic: 1M one-character runs, about 10 MB + // of file, took minutes. + let run_at = |starts: &[usize], i: usize| starts.partition_point(|&s| s <= i).checked_sub(1); + let mut out = vec![]; + let mut start = 0usize; + loop { + let end = chars.get(start..).and_then(|rest| rest.iter().position(|&c| c == 0x0D)).map_or(total, |e| start + e); + let (level, pf_exc) = run_at(¶_starts, start).and_then(|i| block.para_runs.get(i)).map_or((0, None), |r| (r.1, Some(&r.2))); + let (mut pf, base_cf) = scope.styles.resolve(block.text_type, level); + if let Some((lm, ind)) = block.ruler.get(usize::from(level)) { + if lm.is_some() { + pf.left_margin = *lm; + } + if ind.is_some() { + pf.indent = *ind; + } + } + if let Some(e) = pf_exc { + pf.apply(e); + } + let cf_at = |i: usize| -> Cf { + let mut cf = base_cf.clone(); + if let Some(e) = run_at(&char_starts, i).and_then(|k| block.char_runs.get(k)) { + cf.apply(&e.1); + } + cf + }; + let first_cf = cf_at(start); + let first = self.run_props(&first_cf, &scope.scheme); + let mut para = Paragraph { level, props: self.para_props(&pf, &scope.scheme, first.size.unwrap_or(18.0)), ..Default::default() }; + // A bulleted paragraph whose PowerPoint 2000 formatting numbers it. + if matches!(para.props.bullet, Some(Bullet::Char { .. })) + && let Some((scheme, start_at)) = block + .outline_index + .and_then(|i| scope.numbering.get(i)) + .and_then(Option::as_ref) + .zip(first_cf.pp9rt) + .and_then(|(entries, i)| entries.get(usize::from(i))) + .and_then(|e| e.auto_number) + { + para.props.bullet = + Some(Bullet::AutoNum { scheme: text::auto_number_scheme(scheme).into(), start_at: u32::try_from(start_at).unwrap_or(1).max(1) }); + } + let mut i = start; + while i < end { + let props = self.run_props(&cf_at(i), &scope.scheme); + let c = chars.get(i).copied().unwrap_or(0); + if let Some(k) = fields.get(&i) { + let field = match k { + FieldKind::SlideNumber => "slidenum", + FieldKind::DateTime => "datetime1", + }; + para.runs.push(Run { + text: if *k == FieldKind::SlideNumber { "‹#›".into() } else { String::new() }, + props, + kind: RunKind::Field { field: field.into() }, + }); + i += 1; + continue; + } + if c == 0x0B { + para.runs.push(Run { text: String::new(), props, kind: RunKind::Break }); + i += 1; + continue; + } + // A text run: up to the next format change, field, break or the paragraph's end. + let next_change = char_starts.get(char_starts.partition_point(|&s| s <= i)).copied().unwrap_or(end).min(end); + let mut j = i; + while j < next_change && !fields.contains_key(&j) && chars.get(j) != Some(&0x0B) { + j += 1; + } + let j = j.max(i + 1); + let units: Vec = chars.get(i..j).unwrap_or(&[]).iter().copied().filter(|&u| u >= 0x20 || u == 0x09).collect(); + para.runs.push(Run::with(String::from_utf16_lossy(&units), props)); + i = j; + } + para.end_props = first; + para.normalize(); + out.push(para); + if end >= total { + break; + } + start = end + 1; + } + out + } + + fn run_props(&self, cf: &Cf, scheme: &Scheme) -> RunProps { + let font = |i: Option| i.and_then(|i| self.fonts.get(usize::from(i))).filter(|f| !f.is_empty()).cloned(); + RunProps { + font: font(cf.font).or_else(|| self.fonts.first().cloned()), + font_ea: font(cf.ea_font), + font_sym: font(cf.symbol_font), + size: cf.size.map(f64::from).filter(|s| (1.0..=4000.0).contains(s)), + bold: Some(cf.bold.unwrap_or(false)), + italic: Some(cf.italic.unwrap_or(false)), + underline: Some(if cf.underline.unwrap_or(false) { "sng" } else { "none" }.into()), + baseline: cf.position.filter(|p| *p != 0).map(|p| f64::from(p) / 100.0), + fill: cf.color.map(|c| Fill::solid(ColorRef::rgb(text_color(c, scheme)))), + shadow: cf.shadow.filter(|&on| on).map(|_| text_shadow(scheme)), + ..Default::default() + } + } + + fn para_props(&self, pf: &Pf, scheme: &Scheme, text_size: f64) -> ParaProps { + let spacing = |v: i16| if v >= 0 { Spacing::Pct(f64::from(v) / 100.0) } else { Spacing::Pts(-f64::from(v) / MU) }; + let margin = f64::from(pf.left_margin.unwrap_or(0)) / MU; + let indent = f64::from(pf.indent.unwrap_or(0)) / MU; + let bullet = if pf.has_bullet == Some(true) { + let c = pf.bullet_char.filter(|&c| c >= 0x20).unwrap_or(0x2022); + Bullet::Char { char: char::from_u32(u32::from(c)).unwrap_or('•').to_string() } + } else { + Bullet::None + }; + let has_bullet = matches!(bullet, Bullet::Char { .. }); + ParaProps { + align: Some(match pf.align.unwrap_or(0) { + 1 => Align::Center, + 2 => Align::Right, + 3 | 5 => Align::Justify, + 4 => Align::Distributed, + 6 => Align::JustLow, + _ => Align::Left, + }), + margin_left: Some(margin), + indent: Some(indent - margin), + line_spacing: Some(spacing(pf.line_spacing.unwrap_or(100))), + space_before: Some(spacing(pf.space_before.unwrap_or(0))), + space_after: Some(spacing(pf.space_after.unwrap_or(0))), + bullet: Some(bullet), + bullet_font: if has_bullet && pf.bullet_has_font == Some(true) { + pf.bullet_font.and_then(|i| self.fonts.get(usize::from(i))).cloned() + } else { + None + }, + bullet_color: if has_bullet && pf.bullet_has_color == Some(true) { + pf.bullet_color.map(|c| ColorRef::rgb(text_color(c, scheme))) + } else { + None + }, + bullet_size: if has_bullet && pf.bullet_has_size == Some(true) { + pf.bullet_size.map(|v| if v > 0 { f64::from(v) / 100.0 } else { -f64::from(v) / text_size.max(1.0) }).map(|v| v.clamp(0.25, 4.0)) + } else { + None + }, + default_tab: pf.default_tab.map(|t| f64::from(t) / MU), + tabs: pf.tabs.as_ref().map(|t| { + t.iter() + .map(|(pos, kind)| TabStop { + pos: f64::from(*pos) / MU, + align: match kind { + 1 => "ctr", + 2 => "r", + 3 => "dec", + _ => "l", + } + .into(), + }) + .collect() + }), + ..Default::default() + } + } +} + +fn text_color(c: TextColor, scheme: &Scheme) -> Rgba { + match c { + TextColor::Rgb(r, g, b) => Rgba::rgb(r, g, b), + TextColor::Scheme(i) => scheme.get(usize::from(i)).copied().unwrap_or(Rgba::BLACK), + } +} + +/// A text shadow in the colour scheme's shadow colour. The record holds only the on/off bit, so +/// the distance and direction are the app's own Text Shadow command's (`format.textShadow`); with +/// no blur in the record, none is added. +fn text_shadow(scheme: &Scheme) -> Shadow { + Shadow { + color: ColorRef::rgb(scheme.get(2).copied().unwrap_or(Rgba::rgb(0x80, 0x80, 0x80))), + blur: 0.0, + dist: 2.0, + dir: 45.0, + inner: false, + sx: 1.0, + sy: 1.0, + kx: 0.0, + ky: 0.0, + align: String::new(), + rotate_with_shape: false, + } +} + +/// A shaded fill's stops ([MS-ODRAW] `fillFocus`: the position of the last colour, the back +/// colour). Focus 0 starts at the back colour and ends at the fill colour, ±100 the other way; in +/// between, the back colour sits at that point with the fill colour at both ends. +fn gradient_stops(focus: i32, fg: &ColorRef, bg: &ColorRef) -> Vec { + use craft_pptx::style::GradientStop; + let stop = |pos: f64, c: &ColorRef| GradientStop { pos, color: c.clone() }; + match focus { + 0 => vec![stop(0.0, bg), stop(1.0, fg)], + 100 | -100 => vec![stop(0.0, fg), stop(1.0, bg)], + f => vec![stop(0.0, fg), stop(f64::from(f.abs()) / 100.0, bg), stop(1.0, fg)], + } +} + +/// The DrawingML angle (0° runs left to right, turning clockwise) of a linear fill's `fillAngle`, +/// for stops from [`gradient_stops`]: the gradient starts on the left at -90°, the top at -180°, +/// the right at -270°, turning clockwise as the angle falls. 0° starts at the top too: that is how +/// LibreOffice reads it, and how it writes a top-to-bottom gradient. +fn linear_angle(a: f64) -> f64 { + if a == 0.0 { 90.0 } else { (270.0 - a).rem_euclid(360.0) } +} + +/// `msosptPictureFrame`. +const PICTURE_FRAME: u16 = 75; + +fn no_fill_no_line<'a>() -> Props<'a> { + let mut p = Props::default(); + p.set(prop::FILL_BOOLS, 0x0010_0000); // fFilled set to false + p.set(prop::LINE_BOOLS, 0x0008_0000); // fLine set to false + p +} + +/// Maps anchor coordinates to slide points: master units at the top level, a group's child units +/// inside it (`x * sx + ox`). +#[derive(Clone, Copy, Debug)] +struct Map { + sx: f64, + sy: f64, + ox: f64, + oy: f64, +} + +const TOP: Map = Map { sx: 1.0 / MU, sy: 1.0 / MU, ox: 0.0, oy: 0.0 }; + +impl Map { + /// The map for the children of a group placed at `at` (points) whose child space is `rect`. + fn into_group(at: &Xfrm, rect: &draw::Anchor) -> Map { + let (w, h) = (rect.right - rect.left, rect.bottom - rect.top); + let sx = if w.abs() > f64::EPSILON { at.w / w } else { 0.0 }; + let sy = if h.abs() > f64::EPSILON { at.h / h } else { 0.0 }; + Map { sx, sy, ox: at.x - rect.left * sx, oy: at.y - rect.top * sy } + } +} + +/// A box in points from an anchor. A shape turned by 45–135° or 225–315° stores the box of its +/// turned outline: swap it back. +fn xfrm(a: &draw::Anchor, m: Map, rot: f64, flip_h: bool, flip_v: bool) -> Xfrm { + let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; + let (l, t, r, b) = (finite(a.left * m.sx + m.ox), finite(a.top * m.sy + m.oy), finite(a.right * m.sx + m.ox), finite(a.bottom * m.sy + m.oy)); + let (mut x, mut y, mut w, mut h) = (l.min(r), t.min(b), (r - l).abs(), (b - t).abs()); + let rot = if rot.is_finite() { rot.rem_euclid(360.0) } else { 0.0 }; + if (45.0..135.0).contains(&rot) || (225.0..315.0).contains(&rot) { + let (cx, cy) = (x + w / 2.0, y + h / 2.0); + std::mem::swap(&mut w, &mut h); + x = cx - w / 2.0; + y = cy - h / 2.0; + } + Xfrm { x, y, w, h, rot, flip_h, flip_v } +} + +fn default_name(raw: &RawShape) -> String { + match raw.shape_type { + 75 => "Picture".into(), + 202 => "Text Box".into(), + 20 => "Line".into(), + _ if raw.is_group => "Group".into(), + _ => format!("Shape {}", raw.spid & 0x3FF), + } +} + +/// `PlaceholderEnum` as a placeholder type. +fn ph_type(kind: u8) -> Option { + Some(match kind { + 0x01 | 0x0D | 0x11 => PhType::Title, + 0x03 | 0x0F => PhType::CtrTitle, + 0x04 | 0x10 => PhType::SubTitle, + 0x02 | 0x06 | 0x0C | 0x0E | 0x12 => PhType::Body, + 0x07 => PhType::Date, + 0x08 => PhType::SlideNum, + 0x09 => PhType::Footer, + 0x0A => PhType::Header, + 0x05 | 0x0B => PhType::SlideImage, + 0x13 | 0x19 => PhType::Obj, + 0x14 => PhType::Chart, + 0x15 => PhType::Table, + 0x16 => PhType::ClipArt, + 0x17 => PhType::Diagram, + 0x18 => PhType::Media, + 0x1A => PhType::Picture, + _ => return None, + }) +} + +fn same_family(a: PhType, b: PhType) -> bool { + let title = |t| matches!(t, PhType::Title | PhType::CtrTitle); + a == b || (title(a) && title(b)) +} + +/// `SlideLayoutType` as a layout type. +fn layout_kind(geom: u32) -> LayoutType { + match geom { + 0 => LayoutType::Title, + 7 => LayoutType::TitleOnly, + 8 | 9 | 10 | 11 | 13 | 14 => LayoutType::TwoContent, + 16 => LayoutType::Blank, + 17 => LayoutType::VerticalTitleAndText, + 18 => LayoutType::TitleAndVerticalText, + _ => LayoutType::TitleAndContent, + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + + /// [MS-ODRAW] `fillFocus` is where the back colour sits; LibreOffice draws 0° from the top + /// (storytold/deckcraft#1137 review: the linear gradient's colours were reversed, the radial one inside out). + #[test] + fn shaded_fills_put_the_back_colour_at_the_focus() { + let (fg, bg) = (ColorRef::rgb(Rgba::rgb(255, 0, 0)), ColorRef::rgb(Rgba::rgb(0, 0, 255))); + let at = |stops: &[craft_pptx::style::GradientStop]| stops.iter().map(|s| (s.pos, s.color == fg)).collect::>(); + assert_eq!(at(&gradient_stops(0, &fg, &bg)), [(0.0, false), (1.0, true)]); + assert_eq!(at(&gradient_stops(100, &fg, &bg)), [(0.0, true), (1.0, false)]); + assert_eq!(at(&gradient_stops(-50, &fg, &bg)), [(0.0, true), (0.5, false), (1.0, true)]); + // 0° and -180° start at the top, -90° on the left, -270° on the right, -315° at the + // bottom right (DrawingML: 90° runs top to bottom, 0° left to right). + for (a, dm) in [(0.0, 90.0), (-90.0, 0.0), (-180.0, 90.0), (-270.0, 180.0), (-315.0, 225.0), (-45.0, 315.0)] { + assert_eq!(linear_angle(a), dm, "{a}"); + } + } +} diff --git a/crates/ppt-binary/src/doc.rs b/crates/ppt-binary/src/doc.rs new file mode 100644 index 000000000..d0aa46f0e --- /dev/null +++ b/crates/ppt-binary/src/doc.rs @@ -0,0 +1,390 @@ +//! The document structure of the `PowerPoint Document` stream ([MS-PPT] §2.1–2.4): the current +//! user's pointer to the last edit, the chain of edits with their persist directories (which map +//! object ids to stream offsets, newer edits winning), the document container and the lists of +//! masters, slides and notes. + +use std::collections::{HashMap, HashSet, VecDeque}; + +use crate::PptError; +use crate::record::{Rec, Records}; + +pub mod rt { + //! Record types used here ([MS-PPT] §2.13.24, [MS-ODRAW] §2.1.4). + pub const DOCUMENT: u16 = 0x03E8; + pub const DOCUMENT_ATOM: u16 = 0x03E9; + pub const SLIDE: u16 = 0x03EE; + pub const SLIDE_ATOM: u16 = 0x03EF; + pub const NOTES: u16 = 0x03F0; + pub const NOTES_ATOM: u16 = 0x03F1; + pub const ENVIRONMENT: u16 = 0x03F2; + pub const SLIDE_PERSIST_ATOM: u16 = 0x03F3; + pub const MAIN_MASTER: u16 = 0x03F8; + pub const SLIDE_SHOW_SLIDE_INFO: u16 = 0x03F9; + pub const DRAWING_GROUP: u16 = 0x040B; + pub const DRAWING: u16 = 0x040C; + pub const COLOR_SCHEME: u16 = 0x07F0; + pub const LIST: u16 = 0x07D0; + pub const PROG_TAGS: u16 = 0x1388; + pub const PROG_BINARY_TAG: u16 = 0x138A; + pub const BINARY_TAG_DATA: u16 = 0x138B; + pub const STYLE_TEXT_PROP9: u16 = 0x0FAC; + pub const OUTLINE_TEXT_PROPS9: u16 = 0x0FAE; + pub const OUTLINE_TEXT_PROPS_HEADER: u16 = 0x0FAF; + pub const FONT_COLLECTION: u16 = 0x07D5; + pub const OUTLINE_TEXT_REF: u16 = 0x0F9E; + pub const TEXT_HEADER: u16 = 0x0F9F; + pub const TEXT_CHARS: u16 = 0x0FA0; + pub const STYLE_TEXT_PROP: u16 = 0x0FA1; + pub const TEXT_MASTER_STYLE: u16 = 0x0FA3; + pub const TEXT_CF_EXCEPTION: u16 = 0x0FA4; + pub const TEXT_PF_EXCEPTION: u16 = 0x0FA5; + pub const TEXT_RULER: u16 = 0x0FA6; + pub const TEXT_BYTES: u16 = 0x0FA8; + pub const FONT_ENTITY: u16 = 0x0FB7; + pub const CSTRING: u16 = 0x0FBA; + pub const SLIDE_NUMBER_MC: u16 = 0x0FD8; + pub const HEADERS_FOOTERS: u16 = 0x0FD9; + pub const HEADERS_FOOTERS_ATOM: u16 = 0x0FDA; + pub const SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0; + pub const USER_EDIT: u16 = 0x0FF5; + pub const CURRENT_USER: u16 = 0x0FF6; + pub const DATETIME_MC: u16 = 0x0FF7; + pub const GENERIC_DATE_MC: u16 = 0x0FF8; + pub const PLACEHOLDER_ATOM: u16 = 0x0BC3; + pub const PERSIST_DIRECTORY: u16 = 0x1772; + pub const CRYPT_SESSION: u16 = 0x2F14; + + pub const DGG_CONTAINER: u16 = 0xF000; + pub const BSTORE: u16 = 0xF001; + pub const DG_CONTAINER: u16 = 0xF002; + pub const SPGR_CONTAINER: u16 = 0xF003; + pub const SP_CONTAINER: u16 = 0xF004; + pub const FBSE: u16 = 0xF007; + pub const FSPGR: u16 = 0xF009; + pub const FSP: u16 = 0xF00A; + pub const FOPT: u16 = 0xF00B; + pub const CLIENT_TEXTBOX: u16 = 0xF00D; + pub const CHILD_ANCHOR: u16 = 0xF00F; + pub const CLIENT_ANCHOR: u16 = 0xF010; + pub const CLIENT_DATA: u16 = 0xF011; + pub const SECONDARY_FOPT: u16 = 0xF121; + pub const TERTIARY_FOPT: u16 = 0xF122; +} + +/// `headerToken` of a `CurrentUserAtom` for an encrypted document. +const ENCRYPTED_TOKEN: u32 = 0xF3D1_C4DF; +/// `headerToken` of an unencrypted PowerPoint 97+ document. +const PLAIN_TOKEN: u32 = 0xE391_C05F; +/// Edits followed at most along the `offsetLastEdit` chain. +const MAX_EDITS: usize = 4096; + +/// A master, slide or notes page as listed in a `SlideListWithTextContainer`. +#[derive(Clone, Debug)] +pub struct Listed<'a> { + /// The container (`SlideContainer`, `MainMasterContainer`, `NotesContainer`). + pub rec: Rec<'a>, + /// The id other records use for it (`SlideAtom.masterIdRef`, `NotesAtom.slideIdRef`). + pub slide_id: u32, + /// The outline text stored in the list after its `SlidePersistAtom` (placeholders point at it + /// with an `OutlineTextRefAtom`). + pub outline: Vec>, +} + +/// The parsed structure of a `.ppt`. +pub struct Doc<'a> { + pub document: Rec<'a>, + pub masters: Vec>, + pub slides: Vec>, + pub notes: Vec>, + /// Slides the slide list names but whose objects couldn't be found: what a damaged file lost. + pub lost: Vec, +} + +/// Read the structure from the `Current User` and `PowerPoint Document` streams. +pub fn read<'a>(current_user: &[u8], stream: &'a [u8]) -> Result, PptError> { + let damaged = |s: &str| PptError::Damaged(s.to_string()); + // The current user names the newest edit; without it (some writers omit the stream), scan + // for the last UserEditAtom in the stream. + let mut edit_at = None; + // [MS-PPT] allows only the two tokens. Any other value (or none, in a truncated record) is a + // damaged PowerPoint 97 file or an older format; only the scan below can tell which. + let mut unknown_token = false; + if let Some(cu) = Rec::at(current_user, 0).filter(|r| r.kind == rt::CURRENT_USER) { + match cu.u32(4) { + Some(ENCRYPTED_TOKEN) => return Err(PptError::Encrypted), + Some(PLAIN_TOKEN) => edit_at = cu.u32(8).map(|v| v as usize), + _ => unknown_token = true, + } + } + let edit_at = match edit_at.filter(|&at| Rec::at(stream, at).is_some_and(|r| r.kind == rt::USER_EDIT)) { + Some(at) => at, + None => match Records::new(stream).filter(|r| r.kind == rt::USER_EDIT).last() { + Some(r) => r.offset, + None if unknown_token => return Err(PptError::TooOld), + None => return Err(damaged("no edit record")), + }, + }; + // Walk the edits newest first; the first entry seen for a persist id wins. + let mut persist: HashMap = HashMap::new(); + let mut doc_ref = None; + let mut seen = HashSet::new(); + // Many edits may name one persist directory; it is read once (its first reading wins anyway). + let mut dirs_seen = HashSet::new(); + // All directories together are read within one stream's worth of words. Real directories + // don't overlap, so they fit. Hostile ones nested inside each other would otherwise each be + // read to the end of the stream, once per edit (MAX_EDITS × the stream). + let mut words = stream.len() / 4; + let mut at = edit_at; + // The chain ends at an edit whose previous offset is 0. Ending anywhere else (a loop, an + // offset that isn't an edit, too many edits) means older edits were cut off. + let mut broken = true; + for _ in 0..MAX_EDITS { + if !seen.insert(at) { + break; + } + let Some(edit) = Rec::at(stream, at).filter(|r| r.kind == rt::USER_EDIT) else { break }; + if doc_ref.is_none() { + doc_ref = edit.u32(16); + // An encryptSessionPersistIdRef follows only in encrypted documents. + if edit.data.len() >= 32 { + return Err(PptError::Encrypted); + } + } + if let Some(dir) = + edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY) + { + read_persist_directory(dir.data, &mut persist, &mut words); + } + match edit.u32(8) { + Some(0) => { + broken = false; + break; + } + None => break, + Some(prev) => at = prev as usize, + } + } + if broken { + // Recover what the cut-off edits held: every edit in the stream, newest (last written) + // first, fills only the persist ids the chain left unset. Past MAX_EDITS, the newest are + // kept: they are the ones that win. + log::warn!("ppt: the edit history is broken; reading every edit in the stream"); + let mut edits: VecDeque = VecDeque::with_capacity(MAX_EDITS.min(64)); + for edit in Records::new(stream).filter(|r| r.kind == rt::USER_EDIT) { + if edits.len() == MAX_EDITS { + edits.pop_front(); + } + edits.push_back(edit); + } + for edit in edits.into_iter().rev() { + if let Some(dir) = + edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY) + { + read_persist_directory(dir.data, &mut persist, &mut words); + } + } + } + let lookup = |id: u32| persist.get(&id).and_then(|&o| Rec::at(stream, o)); + let document = doc_ref.and_then(lookup).filter(|r| r.kind == rt::DOCUMENT).ok_or_else(|| damaged("no document container"))?; + if lookup_kind(&persist, stream, rt::CRYPT_SESSION) { + return Err(PptError::Encrypted); + } + let mut doc = Doc { document, masters: vec![], slides: vec![], notes: vec![], lost: vec![] }; + // Each object is listed once. PowerPoint never lists one twice, and a hostile file that lists a + // big drawing many times would otherwise have it converted again for every listing (shapes × + // listings, from linear input). + let mut listed = HashSet::new(); + for list in document.children_of(rt::SLIDE_LIST_WITH_TEXT) { + let out = match list.instance { + 0 => &mut doc.slides, + 1 => &mut doc.masters, + 2 => &mut doc.notes, + _ => continue, + }; + let mut current: Option = None; + for r in list.children() { + if r.kind == rt::SLIDE_PERSIST_ATOM { + if let Some(l) = current.take() { + out.push(l); + } + let (Some(pid), Some(slide_id)) = (r.u32(0), r.u32(12)) else { continue }; + match lookup(pid) { + // The slide list names slides; anything else there is a slide the file lost. + Some(rec) if list.instance == 0 && rec.kind != rt::SLIDE => { + log::warn!("ppt: slide persist id {pid} is not a slide"); + doc.lost.push(format!("slide {slide_id}")); + } + Some(rec) if !listed.insert(rec.offset) => log::warn!("ppt: persist id {pid} is listed again; skipped"), + Some(rec) => current = Some(Listed { rec, slide_id, outline: vec![] }), + None => { + log::warn!("ppt: slide persist id {pid} has no object"); + if list.instance == 0 { + doc.lost.push(format!("slide {slide_id}")); + } + } + } + } else if r.kind == rt::TEXT_HEADER + && let Some(l) = current.as_mut() + { + // An outline text block starts at its header and runs to the next header or persist atom. + let rest = list.data.get(r.offset..).unwrap_or(&[]); + l.outline.push(Records::new(rest)); + } + } + if let Some(l) = current.take() { + out.push(l); + } + } + Ok(doc) +} + +/// Read one persist directory into `persist`, taking each word read from `words`. +fn read_persist_directory(b: &[u8], persist: &mut HashMap, words: &mut usize) { + let mut c = crate::record::Cursor::new(b); + let mut next = |c: &mut crate::record::Cursor| { + *words = words.checked_sub(1)?; + c.u32() + }; + while let Some(head) = next(&mut c) { + let first = head & 0x000F_FFFF; + let count = head >> 20; + for k in 0..count { + let Some(off) = next(&mut c) else { return }; + persist.entry(first.saturating_add(k)).or_insert(off as usize); + } + } +} + +fn lookup_kind(persist: &HashMap, stream: &[u8], kind: u16) -> bool { + persist.values().any(|&o| Rec::at(stream, o).is_some_and(|r| r.kind == kind)) +} + +/// The `DocumentAtom`: slide and notes sizes in master units (576 per inch), first slide number. +pub struct DocumentAtom { + pub slide_w: i32, + pub slide_h: i32, + pub notes_w: i32, + pub notes_h: i32, + pub first_slide_number: u16, +} + +impl Doc<'_> { + pub fn document_atom(&self) -> Option { + let a = self.document.child(rt::DOCUMENT_ATOM)?; + Some(DocumentAtom { + slide_w: a.i32(0)?, + slide_h: a.i32(4)?, + notes_w: a.i32(8)?, + notes_h: a.i32(12)?, + first_slide_number: a.u16(32).unwrap_or(1), + }) + } +} + +/// The `SlideAtom` of a slide or master. +#[derive(Clone, Copy, Debug, Default)] +pub struct SlideAtom { + /// `SlideLayoutType`. + pub geom: u32, + pub master_id: u32, + pub follow_master_objects: bool, + pub follow_master_scheme: bool, + pub follow_master_background: bool, +} + +pub fn slide_atom(container: &Rec) -> SlideAtom { + let Some(a) = container.child(rt::SLIDE_ATOM) else { + return SlideAtom { follow_master_objects: true, follow_master_scheme: true, follow_master_background: true, ..Default::default() }; + }; + let flags = a.u16(20).unwrap_or(0x7); + SlideAtom { + geom: a.u32(0).unwrap_or(0), + master_id: a.u32(12).unwrap_or(0), + follow_master_objects: flags & 0x1 != 0, + follow_master_scheme: flags & 0x2 != 0, + follow_master_background: flags & 0x4 != 0, + } +} + +/// Font names by index (`FontCollectionContainer` in the environment). +pub fn fonts(doc: &Doc) -> Vec { + let Some(coll) = doc.document.child(rt::ENVIRONMENT).and_then(|e| e.child(rt::FONT_COLLECTION)) else { return vec![] }; + coll.children_of(rt::FONT_ENTITY) + .map(|f| { + let units: Vec = (0..32).filter_map(|i| f.u16(i * 2)).take_while(|&u| u != 0).collect(); + String::from_utf16_lossy(&units) + }) + .collect() +} + +/// What a `HeadersFootersContainer` ([MS-PPT] §2.4.15.1 and §2.5.16) says the footer row +/// shows: the date (today's in a format, or fixed text), the slide number and the footer text. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct HeadersFooters { + /// `formatId`: 0–12, the date format. + pub format: u16, + pub date: bool, + /// The date is fixed text (`fHasUserDate`) rather than today's. + pub user_date: bool, + pub slide_number: bool, + pub footer: bool, + pub date_text: String, + pub footer_text: String, +} + +/// The UTF-16 units of a `CString` body, up to its first NUL: the record has no terminator, but a +/// writer that adds one would otherwise put a NUL into the text, or make a tag name fail to match. +fn cstring_units(b: &[u8]) -> impl Iterator + '_ { + b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|&u| u != 0) +} + +/// The slides' headers and footers in `container`, from its `HeadersFootersContainer` of +/// `instance`: 3 in the document (`SlideHeadersFootersContainer`, for every slide), 0 in a slide or +/// main master (`PerSlideHeadersFootersContainer`, its own). +pub fn headers_footers(container: &Rec, instance: u16) -> Option { + let hf = container.children().find(|r| r.kind == rt::HEADERS_FOOTERS && r.instance == instance)?; + let atom = hf.child(rt::HEADERS_FOOTERS_ATOM)?; + let flags = atom.u16(2)?; + let text = |instance: u16| { + hf.children() + .find(|r| r.kind == rt::CSTRING && r.instance == instance) + .map(|r| String::from_utf16_lossy(&cstring_units(r.data).collect::>())) + .unwrap_or_default() + }; + Some(HeadersFooters { + format: atom.u16(0).unwrap_or(0), + date: flags & 0x01 != 0, + user_date: flags & 0x04 != 0, + slide_number: flags & 0x08 != 0, + footer: flags & 0x20 != 0, + date_text: text(0), + footer_text: text(2), + }) +} + +/// The PowerPoint 2000 paragraph formatting of the slides' outline text ([MS-PPT] §2.4.22.10, +/// the document's `___PPT9` tag): by slide id and text type, one `StyleTextProp9Atom` for each of +/// the slide's outline blocks of that type, in order. +pub fn outline_numbering(document: &Rec) -> HashMap<(u32, u32), Vec>> { + let mut out: HashMap<(u32, u32), Vec>> = HashMap::new(); + let tags = document.child(rt::LIST).and_then(|l| l.child(rt::PROG_TAGS)); + let Some(tags) = tags else { return out }; + let ppt9 = tags + .children_of(rt::PROG_BINARY_TAG) + .find(|tag| tag.child(rt::CSTRING).is_some_and(|name| cstring_units(name.data).eq("___PPT9".encode_utf16()))); + let Some(data) = ppt9.and_then(|t| t.child(rt::BINARY_TAG_DATA)) else { return out }; + // The tag's data is an atom whose body holds records. + for props in Records::new(data.data).filter(|r| r.kind == rt::OUTLINE_TEXT_PROPS9) { + let mut header = None; + for r in props.children() { + if r.kind == rt::OUTLINE_TEXT_PROPS_HEADER { + header = r.u32(0).zip(r.u32(4)); + } else if r.kind == rt::STYLE_TEXT_PROP9 + && let Some(key) = header.take() + { + out.entry(key).or_default().push(crate::text::read_style9(r.data)); + } + } + } + out +} diff --git a/crates/ppt-binary/src/draw.rs b/crates/ppt-binary/src/draw.rs new file mode 100644 index 000000000..2b1e8ec79 --- /dev/null +++ b/crates/ppt-binary/src/draw.rs @@ -0,0 +1,522 @@ +//! OfficeArt drawings ([MS-ODRAW]) as `.ppt` stores them: a tree of shape group containers and +//! shape containers, each shape with its `FSP` (type, id, flags), property tables (`FOPT`), +//! anchor and client records (placeholder, text). + +use std::collections::HashMap; + +use crate::doc::rt; +use crate::record::{MAX_DEPTH, Rec}; + +/// Property ids ([MS-ODRAW] §2.3). +pub mod prop { + pub const ROTATION: u16 = 0x0004; + pub const TEXT_LEFT: u16 = 0x0081; + pub const TEXT_TOP: u16 = 0x0082; + pub const TEXT_RIGHT: u16 = 0x0083; + pub const TEXT_BOTTOM: u16 = 0x0084; + pub const WRAP_TEXT: u16 = 0x0085; + pub const ANCHOR_TEXT: u16 = 0x0087; + pub const CROP_TOP: u16 = 0x0100; + pub const CROP_BOTTOM: u16 = 0x0101; + pub const CROP_LEFT: u16 = 0x0102; + pub const CROP_RIGHT: u16 = 0x0103; + pub const PIB: u16 = 0x0104; + pub const GEO_LEFT: u16 = 0x0140; + pub const GEO_TOP: u16 = 0x0141; + pub const GEO_RIGHT: u16 = 0x0142; + pub const GEO_BOTTOM: u16 = 0x0143; + pub const SHAPE_PATH: u16 = 0x0144; + pub const VERTICES: u16 = 0x0145; + pub const SEGMENT_INFO: u16 = 0x0146; + pub const ADJUST_VALUE: u16 = 0x0147; + pub const FILL_TYPE: u16 = 0x0180; + pub const FILL_COLOR: u16 = 0x0181; + pub const FILL_OPACITY: u16 = 0x0182; + pub const FILL_BACK_COLOR: u16 = 0x0183; + pub const FILL_BACK_OPACITY: u16 = 0x0184; + pub const FILL_BLIP: u16 = 0x0186; + pub const FILL_ANGLE: u16 = 0x018B; + pub const FILL_FOCUS: u16 = 0x018C; + pub const FILL_BOOLS: u16 = 0x01BF; + pub const LINE_COLOR: u16 = 0x01C0; + pub const LINE_OPACITY: u16 = 0x01C1; + pub const LINE_WIDTH: u16 = 0x01CB; + pub const LINE_STYLE: u16 = 0x01CD; + pub const LINE_DASHING: u16 = 0x01CE; + pub const LINE_START_ARROW: u16 = 0x01D0; + pub const LINE_END_ARROW: u16 = 0x01D1; + pub const LINE_START_ARROW_WIDTH: u16 = 0x01D2; + pub const LINE_START_ARROW_LENGTH: u16 = 0x01D3; + pub const LINE_END_ARROW_WIDTH: u16 = 0x01D4; + pub const LINE_END_ARROW_LENGTH: u16 = 0x01D5; + pub const LINE_JOIN: u16 = 0x01D6; + pub const LINE_CAP: u16 = 0x01D7; + pub const LINE_BOOLS: u16 = 0x01FF; + pub const SHADOW_COLOR: u16 = 0x0201; + pub const SHADOW_OPACITY: u16 = 0x0204; + pub const SHADOW_OFFSET_X: u16 = 0x0205; + pub const SHADOW_OFFSET_Y: u16 = 0x0206; + pub const SHADOW_BOOLS: u16 = 0x023F; + pub const HSP_MASTER: u16 = 0x0301; + pub const NAME: u16 = 0x0380; + pub const DESCRIPTION: u16 = 0x0381; + pub const GROUP_BOOLS: u16 = 0x03BF; +} + +/// UTF-16 units kept of a string property. +pub const MAX_STRING: usize = 4096; + +/// Distinct properties one set keeps. Ids are 14 bits, so a file's tables could name about 16K of +/// them, and every shape copies the drawing defaults' and its master shape's sets into its own: +/// unbounded, that is shapes × 16K. [MS-ODRAW] defines a few hundred properties and a real shape +/// or the drawing defaults set tens of them. Entries past the limit are still read (their complex +/// data keeps its place) but not kept. +pub const MAX_PROPS: usize = 1024; + +/// One property value: the 32-bit operand and, for complex properties, the extra bytes. +#[derive(Clone, Copy, Debug)] +pub struct PropVal<'a> { + pub op: u32, + pub complex: Option<&'a [u8]>, +} + +/// A shape's merged property tables (primary first; secondary and tertiary fill gaps). +#[derive(Clone, Debug, Default)] +pub struct Props<'a> { + map: HashMap>, +} + +impl<'a> Props<'a> { + /// Read one `FOPT` body: `count` 6-byte entries then the complex data in entry order. Entries + /// already present are kept (the caller adds the most specific table first). + pub fn add_table(&mut self, r: &Rec<'a>) { + let count = usize::from(r.instance); + let mut complex_at = count.saturating_mul(6); + for i in 0..count { + let (Some(id), Some(op)) = (r.u16(i * 6), r.u32(i * 6 + 2)) else { break }; + let is_complex = id & 0x8000 != 0; + let pid = id & 0x3FFF; + let complex = if is_complex { + let len = op as usize; + let data = r.data.get(complex_at..complex_at.saturating_add(len).min(r.data.len())); + complex_at = complex_at.saturating_add(len); + data + } else { + None + }; + self.fill_gap(pid, PropVal { op, complex }); + } + } + + /// Fill gaps from another set (a master shape's or the drawing defaults). + pub fn inherit(&mut self, other: &Props<'a>) { + for (k, v) in &other.map { + self.fill_gap(*k, *v); + } + } + + /// Add `v` for `id` where this set doesn't say it already. A boolean property word ([MS-ODRAW]: + /// the last id of each 64-id group) holds sixteen flags, each with its own `fUse` bit 16 + /// places up, so it is merged flag by flag: a shape that sets only `fNoFillHitTest` still + /// inherits `fFilled` from its master or the defaults. + fn fill_gap(&mut self, id: u16, v: PropVal<'a>) { + let full = self.map.len() >= MAX_PROPS; + match self.map.get_mut(&id) { + None if full => {} + None => { + self.map.insert(id, v); + } + Some(have) if id & 0x3F == 0x3F => { + let unset = !(have.op >> 16) & 0xFFFF; + let take = (v.op >> 16) & unset; + have.op |= take << 16; + have.op = (have.op & !take) | (v.op & take); + } + Some(_) => {} + } + } + + /// Set a simple (non-complex) property. + pub fn set(&mut self, id: u16, op: u32) { + self.map.insert(id, PropVal { op, complex: None }); + } + + pub fn get(&self, id: u16) -> Option { + self.map.get(&id).map(|v| v.op) + } + + pub fn complex(&self, id: u16) -> Option<&'a [u8]> { + self.map.get(&id).and_then(|v| v.complex) + } + + /// A 16.16 fixed-point value. + pub fn fixed(&self, id: u16) -> Option { + self.get(id).map(|v| f64::from(v as i32) / 65536.0) + } + + /// A boolean from a bool-property word: bit `bit` holds the value, bit `bit + 16` says it is set. + pub fn flag(&self, id: u16, bit: u32) -> Option { + let v = self.get(id)?; + (v & (1 << (bit + 16)) != 0).then_some(v & (1 << bit) != 0) + } + + /// A UTF-16 string property (names, alt text), at most [`MAX_STRING`] units: a master shape's + /// name is copied into every shape that inherits it. + pub fn string(&self, id: u16) -> Option { + let b = self.complex(id)?; + let units: Vec = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take(MAX_STRING).take_while(|&u| u != 0).collect(); + Some(String::from_utf16_lossy(&units)).filter(|s| !s.is_empty()) + } + + /// An `IMsoArray` property: element size and the elements' bytes. + pub fn array(&self, id: u16) -> Option<(usize, &'a [u8])> { + let b = self.complex(id)?; + let n = usize::from(crate::record::u16_at(b, 0)?); + let size = crate::record::u16_at(b, 4)?; + // 0xFFF0 marks 4-byte elements stored as two 2-byte halves. + let size = if size == 0xFFF0 { 4 } else { usize::from(size) }; + if size == 0 { + return None; + } + let body = b.get(6..)?; + let len = n.saturating_mul(size).min(body.len() / size * size); + Some((size, body.get(..len)?)) + } +} + +/// An anchor rectangle in its own coordinate units: master units for a client anchor, the parent +/// group's units for a child anchor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Anchor { + pub left: f64, + pub top: f64, + pub right: f64, + pub bottom: f64, +} + +/// The placeholder a shape stands for (`OEPlaceholderAtom`). +#[derive(Clone, Copy, Debug)] +pub struct Placeholder { + pub position: u32, + /// `PlaceholderEnum`. + pub kind: u8, +} + +/// One shape of a drawing, before conversion. +#[derive(Clone, Debug)] +pub struct RawShape<'a> { + /// `MSOSPT` shape type. + pub shape_type: u16, + pub spid: u32, + pub flip_h: bool, + pub flip_v: bool, + pub patriarch: bool, + pub deleted: bool, + pub props: Props<'a>, + pub anchor: Option, + /// For a group: the child coordinate rectangle (`FSPGR`). + pub group_rect: Option, + pub children: Vec>, + pub is_group: bool, + pub placeholder: Option, + /// The records of the shape's text box (`OfficeArtClientTextbox`). + pub text: Option>, +} + +/// The top-level shapes and the background shape of a `DrawingContainer`. +pub struct Drawing<'a> { + pub shapes: Vec>, + pub background: Option>, +} + +/// Read the drawing of a slide, master or notes container. +pub fn drawing<'a>(container: &Rec<'a>) -> Drawing<'a> { + let mut out = Drawing { shapes: vec![], background: None }; + let Some(dg) = container.child(rt::DRAWING).and_then(|d| d.child(rt::DG_CONTAINER)) else { return out }; + // The background is the container's own shape (`OfficeArtDgContainer.shape`, [MS-ODRAW] + // 2.2.13), not one found by its fBackground flag. + if let Some(bg) = dg.child(rt::SP_CONTAINER) { + out.background = Some(shape(&bg)); + } + if let Some(top) = dg.child(rt::SPGR_CONTAINER) { + // The first shape of the top group is the patriarch, standing for the drawing itself. + out.shapes = group_children(&top, 0).into_iter().filter(|s| !s.patriarch).collect(); + } + out +} + +fn group_children<'a>(gr: &Rec<'a>, depth: usize) -> Vec> { + if depth > MAX_DEPTH { + return vec![]; + } + let mut out = vec![]; + for r in gr.children() { + match r.kind { + rt::SP_CONTAINER => out.push(shape(&r)), + rt::SPGR_CONTAINER => { + let mut kids = r.children(); + // A group container's first shape describes the group itself. + let Some(head) = kids.next().filter(|h| h.kind == rt::SP_CONTAINER) else { continue }; + let mut g = shape(&head); + g.is_group = true; + g.children = group_children(&r, depth + 1).into_iter().skip(1).collect(); + out.push(g); + } + _ => {} + } + } + out +} + +fn rect_i32(r: &Rec) -> Option { + Some(Anchor { left: f64::from(r.i32(0)?), top: f64::from(r.i32(4)?), right: f64::from(r.i32(8)?), bottom: f64::from(r.i32(12)?) }) +} + +fn shape<'a>(sp: &Rec<'a>) -> RawShape<'a> { + let mut s = RawShape { + shape_type: 0, + spid: 0, + flip_h: false, + flip_v: false, + patriarch: false, + deleted: false, + props: Props::default(), + anchor: None, + group_rect: None, + children: vec![], + is_group: false, + placeholder: None, + text: None, + }; + // Tables in specificity order: primary (the last one first), then secondary and tertiary. + let mut primary: Vec = vec![]; + let mut tables: Vec = vec![]; + for r in sp.children() { + match r.kind { + rt::FSP => { + s.shape_type = r.instance; + s.spid = r.u32(0).unwrap_or(0); + let f = r.u32(4).unwrap_or(0); + s.patriarch = f & 0x4 != 0; + s.deleted = f & 0x8 != 0; + s.flip_h = f & 0x40 != 0; + s.flip_v = f & 0x80 != 0; + } + rt::FOPT => primary.push(r), + rt::SECONDARY_FOPT | rt::TERTIARY_FOPT => tables.push(r), + rt::FSPGR => s.group_rect = rect_i32(&r), + rt::CHILD_ANCHOR => s.anchor = rect_i32(&r), + rt::CLIENT_ANCHOR => { + s.anchor = if r.data.len() >= 16 { + // RectStruct: top, left, right, bottom. + (|| { + Some(Anchor { + top: f64::from(r.i32(0)?), + left: f64::from(r.i32(4)?), + right: f64::from(r.i32(8)?), + bottom: f64::from(r.i32(12)?), + }) + })() + } else { + // SmallRectStruct: top, left, right, bottom. + (|| { + Some(Anchor { + top: f64::from(r.i16(0)?), + left: f64::from(r.i16(2)?), + right: f64::from(r.i16(4)?), + bottom: f64::from(r.i16(6)?), + }) + })() + }; + } + rt::CLIENT_DATA => { + if let Some(p) = r.child(rt::PLACEHOLDER_ATOM) { + s.placeholder = Some(Placeholder { position: p.u32(0).unwrap_or(0), kind: p.u8(4).unwrap_or(0) }); + } + } + rt::CLIENT_TEXTBOX => s.text = Some(r), + _ => {} + } + } + for t in primary.iter().rev().chain(&tables) { + s.props.add_table(t); + } + s +} + +/// The drawing-wide default properties (`OfficeArtDggContainer`'s `FOPT`). +pub fn default_props<'a>(dgg: Option>) -> Props<'a> { + let mut p = Props::default(); + if let Some(dgg) = dgg { + for t in dgg.children().filter(|r| matches!(r.kind, rt::FOPT | rt::SECONDARY_FOPT | rt::TERTIARY_FOPT)) { + p.add_table(&t); + } + } + p +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::build::*; + + pub fn fopt(entries: &[(u16, u32)], complex: &[u8]) -> Vec { + let mut b = vec![]; + for (id, op) in entries { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + b.extend_from_slice(complex); + atom(rt::FOPT, entries.len() as u16, &b) + } + + #[test] + fn reads_properties_and_complex_strings() { + let name: Vec = "Logo\0".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let t = fopt(&[(prop::FILL_COLOR, 0x0011_2233), (0x8000 | prop::NAME, name.len() as u32), (prop::FILL_BOOLS, 0x0010_0000)], &name); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(p.get(prop::FILL_COLOR), Some(0x0011_2233)); + assert_eq!(p.string(prop::NAME).as_deref(), Some("Logo")); + assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false)); + assert_eq!(p.flag(prop::LINE_BOOLS, 3), None); + } + + /// A boolean word inherits the flags it doesn't set (storytold/deckcraft#1137 review): a text box that sets only + /// `fNoFillHitTest` (bit 4 is `fFilled`, bit 0 `fNoFillHitTest`) still gets "not filled" + /// from below, and its own flags win over the inherited ones. + #[test] + fn boolean_properties_merge_flag_by_flag() { + let mut p = Props::default(); + p.set(prop::FILL_BOOLS, 0x0001_0001); // fNoFillHitTest = true; fFilled not said + p.set(prop::LINE_BOOLS, 0x0008_0008); // fLine = true + let mut below = Props::default(); + below.set(prop::FILL_BOOLS, 0x0011_0000); // fFilled = false, fNoFillHitTest = false + below.set(prop::LINE_BOOLS, 0x0008_0000); // fLine = false + p.inherit(&below); + assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false)); + assert_eq!(p.flag(prop::FILL_BOOLS, 0), Some(true)); + assert_eq!(p.flag(prop::LINE_BOOLS, 3), Some(true)); + // The same merge applies between a shape's own tables. + let t = fopt(&[(prop::FILL_BOOLS, 0x0001_0001)], &[]); + let t2 = fopt(&[(prop::FILL_BOOLS, 0x0010_0010)], &[]); + let mut q = Props::default(); + q.add_table(&Rec::at(&t, 0).unwrap()); + q.add_table(&Rec::at(&t2, 0).unwrap()); + assert_eq!(q.flag(prop::FILL_BOOLS, 4), Some(true)); + assert_eq!(q.flag(prop::FILL_BOOLS, 0), Some(true)); + // Non-boolean properties still keep the first value. + let mut r = Props::default(); + r.set(prop::FILL_COLOR, 1); + let mut s = Props::default(); + s.set(prop::FILL_COLOR, 2); + r.inherit(&s); + assert_eq!(r.get(prop::FILL_COLOR), Some(1)); + } + + /// A string property longer than [`MAX_STRING`] units is cut there. + #[test] + fn a_long_string_property_is_capped() { + let name: Vec = "x".repeat(10_000).encode_utf16().flat_map(u16::to_le_bytes).collect(); + let t = fopt(&[(0x8000 | prop::NAME, name.len() as u32)], &name); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(p.string(prop::NAME).map(|s| s.len()), Some(MAX_STRING)); + } + + /// A table naming more than [`MAX_PROPS`] properties keeps that many, and still reads the + /// complex data after them and the records after it. + #[test] + fn a_property_set_keeps_at_most_max_props() { + let mut entries: Vec<(u16, u32)> = (0..MAX_PROPS as u16 + 100).map(|i| (0x1000 + i, u32::from(i))).collect(); + let name: Vec = "Kept\0".encode_utf16().flat_map(u16::to_le_bytes).collect(); + entries.insert(0, (0x8000 | prop::NAME, name.len() as u32)); + let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat()); + let anchor = atom(rt::CHILD_ANCHOR, 0, &[1i32, 2, 3, 4].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let sp = container(rt::SP_CONTAINER, 0, &[fsp, fopt(&entries, &name), anchor]); + let s = shape(&Rec::at(&sp, 0).unwrap()); + assert_eq!(s.props.map.len(), MAX_PROPS); + assert_eq!(s.props.string(prop::NAME).as_deref(), Some("Kept")); + assert_eq!(s.props.get(0x1000), Some(0)); + assert_eq!(s.props.get(0x1000 + MAX_PROPS as u16), None, "past the limit"); + assert_eq!(s.anchor, Some(Anchor { left: 1.0, top: 2.0, right: 3.0, bottom: 4.0 })); + // Inheriting can't pass the limit either. + let mut p = Props::default(); + p.set(prop::FILL_COLOR, 1); + p.inherit(&s.props); + assert_eq!(p.map.len(), MAX_PROPS); + } + + /// A shape's later primary property table wins over its earlier one, and both over its + /// secondary table. + #[test] + fn the_last_primary_table_wins() { + let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat()); + let secondary = { + let mut b = vec![]; + for (id, op) in [(prop::FILL_COLOR, 3u32), (prop::LINE_COLOR, 3)] { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + atom(rt::SECONDARY_FOPT, 2, &b) + }; + let sp = container( + rt::SP_CONTAINER, + 0, + &[fsp, secondary, fopt(&[(prop::FILL_COLOR, 1), (prop::LINE_WIDTH, 1)], &[]), fopt(&[(prop::FILL_COLOR, 2)], &[])], + ); + let s = shape(&Rec::at(&sp, 0).unwrap()); + assert_eq!((s.props.get(prop::FILL_COLOR), s.props.get(prop::LINE_WIDTH), s.props.get(prop::LINE_COLOR)), (Some(2), Some(1), Some(3))); + } + + #[test] + fn a_complex_length_past_the_record_is_clipped() { + let t = fopt(&[(0x8000 | prop::NAME, 0xFFFF_FFFF), (0x8000 | prop::DESCRIPTION, 10)], b"A\0"); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(p.string(prop::NAME).as_deref(), Some("A")); + assert_eq!(p.complex(prop::DESCRIPTION), None); + } + + #[test] + fn reads_groups_anchors_and_placeholders() { + let fsp = |t: u16, id: u32, flags: u32| atom(rt::FSP, t, &[id.to_le_bytes(), flags.to_le_bytes()].concat()); + let small = + |t: i16, l: i16, r: i16, b: i16| atom(rt::CLIENT_ANCHOR, 0, &[t, l, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let child = + |l: i32, t: i32, r: i32, b: i32| atom(rt::CHILD_ANCHOR, 0, &[l, t, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let ph = container(rt::CLIENT_DATA, 0, &[atom(rt::PLACEHOLDER_ATOM, 0, &[0, 0, 0, 0, 0x0D, 0, 0, 0])]); + let patriarch = container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &[0; 16]), fsp(0, 1024, 0x5)]); + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 1025, 0xA00), small(10, 20, 300, 80), ph]); + let group = container( + rt::SPGR_CONTAINER, + 0, + &[ + container( + rt::SP_CONTAINER, + 0, + &[ + atom(rt::FSPGR, 1, &[0i32, 0, 100, 100].iter().flat_map(|v| v.to_le_bytes()).collect::>()), + fsp(0, 1026, 0x201), + small(100, 100, 200, 200), + ], + ), + container(rt::SP_CONTAINER, 0, &[fsp(3, 1027, 0x40), child(0, 0, 50, 50)]), + ], + ); + let drawing = container(rt::DRAWING, 0, &[container(rt::DG_CONTAINER, 0, &[container(rt::SPGR_CONTAINER, 0, &[patriarch, title, group])])]); + let slide = container(rt::SLIDE, 0, &[drawing]); + let d = super::drawing(&Rec::at(&slide, 0).unwrap()); + assert_eq!(d.shapes.len(), 2); + let t = &d.shapes[0]; + assert_eq!(t.placeholder.unwrap().kind, 0x0D); + assert_eq!(t.anchor, Some(Anchor { left: 20.0, top: 10.0, right: 300.0, bottom: 80.0 })); + let g = &d.shapes[1]; + assert!(g.is_group); + assert_eq!(g.children.len(), 1); + assert!(g.children[0].flip_h); + assert_eq!(g.group_rect.unwrap().right, 100.0); + } +} diff --git a/crates/ppt-binary/src/geom.rs b/crates/ppt-binary/src/geom.rs new file mode 100644 index 000000000..52206018a --- /dev/null +++ b/crates/ppt-binary/src/geom.rs @@ -0,0 +1,454 @@ +//! Shape geometry: OfficeArt shape types (`MSOSPT`, [MS-ODRAW] §2.4.24) as DrawingML preset +//! names, and freeform paths from the vertices and segment properties (§2.3.6). + +use craft_pptx::{CustomPath, Geom}; + +use crate::draw::{Props, prop}; + +/// The preset for a shape type, `None` for a freeform (`msosptNotPrimitive`) or a type with no +/// preset counterpart. +pub fn preset_name(shape_type: u16) -> Option<&'static str> { + Some(match shape_type { + 1 | 75 | 202 | 201 => "rect", + 2 => "roundRect", + 3 => "ellipse", + 4 => "diamond", + 5 => "triangle", + 6 => "rtTriangle", + 7 => "parallelogram", + 8 => "trapezoid", + 9 => "hexagon", + 10 => "octagon", + 11 => "plus", + 12 => "star5", + 13 | 14 => "rightArrow", + 15 => "homePlate", + 16 => "cube", + 17 => "wedgeRoundRectCallout", + 18 => "star16", + 19 => "arc", + 20 => "line", + 21 => "plaque", + 22 => "can", + 23 => "donut", + 32 => "straightConnector1", + 33 => "bentConnector2", + 34 => "bentConnector3", + 35 => "bentConnector4", + 36 => "bentConnector5", + 37 => "curvedConnector2", + 38 => "curvedConnector3", + 39 => "curvedConnector4", + 40 => "curvedConnector5", + 41 | 178 => "callout1", + 42 => "callout2", + 43 => "callout3", + 44 | 179 => "accentCallout1", + 45 => "accentCallout2", + 46 => "accentCallout3", + 47 | 180 => "borderCallout1", + 48 => "borderCallout2", + 49 => "borderCallout3", + 50 | 181 => "accentBorderCallout1", + 51 => "accentBorderCallout2", + 52 => "accentBorderCallout3", + 53 => "ribbon", + 54 => "ribbon2", + 55 => "chevron", + 56 => "pentagon", + 57 => "noSmoking", + 58 => "star8", + 59 => "star16", + 60 => "star32", + 61 => "wedgeRectCallout", + 62 => "wedgeRoundRectCallout", + 63 => "wedgeEllipseCallout", + 64 => "wave", + 65 => "foldedCorner", + 66 => "leftArrow", + 67 => "downArrow", + 68 => "upArrow", + 69 => "leftRightArrow", + 70 => "upDownArrow", + 71 => "irregularSeal1", + 72 => "irregularSeal2", + 73 => "lightningBolt", + 74 => "heart", + 76 => "quadArrow", + 77 => "leftArrowCallout", + 78 => "rightArrowCallout", + 79 => "upArrowCallout", + 80 => "downArrowCallout", + 81 => "leftRightArrowCallout", + 82 => "upDownArrowCallout", + 83 => "quadArrowCallout", + 84 => "bevel", + 85 => "leftBracket", + 86 => "rightBracket", + 87 => "leftBrace", + 88 => "rightBrace", + 89 => "leftUpArrow", + 90 => "bentUpArrow", + 91 => "bentArrow", + 92 => "star24", + 93 => "stripedRightArrow", + 94 => "notchedRightArrow", + 95 => "blockArc", + 96 => "smileyFace", + 97 => "verticalScroll", + 98 => "horizontalScroll", + 99 | 100 => "circularArrow", + 101 => "uturnArrow", + 102 => "curvedRightArrow", + 103 => "curvedLeftArrow", + 104 => "curvedUpArrow", + 105 => "curvedDownArrow", + 106 => "cloudCallout", + 107 => "ellipseRibbon", + 108 => "ellipseRibbon2", + 109 => "flowChartProcess", + 110 => "flowChartDecision", + 111 => "flowChartInputOutput", + 112 => "flowChartPredefinedProcess", + 113 => "flowChartInternalStorage", + 114 => "flowChartDocument", + 115 => "flowChartMultidocument", + 116 => "flowChartTerminator", + 117 => "flowChartPreparation", + 118 => "flowChartManualInput", + 119 => "flowChartManualOperation", + 120 => "flowChartConnector", + 121 => "flowChartPunchedCard", + 122 => "flowChartPunchedTape", + 123 => "flowChartSummingJunction", + 124 => "flowChartOr", + 125 => "flowChartCollate", + 126 => "flowChartSort", + 127 => "flowChartExtract", + 128 => "flowChartMerge", + 129 => "flowChartOfflineStorage", + 130 => "flowChartOnlineStorage", + 131 => "flowChartMagneticTape", + 132 => "flowChartMagneticDisk", + 133 => "flowChartMagneticDrum", + 134 => "flowChartDisplay", + 135 => "flowChartDelay", + 176 => "flowChartAlternateProcess", + 177 => "flowChartOffpageConnector", + 182 => "leftRightUpArrow", + 183 => "sun", + 184 => "moon", + 185 => "bracketPair", + 186 => "bracePair", + 187 => "star4", + 188 => "doubleWave", + 189 => "actionButtonBlank", + 190 => "actionButtonHome", + 191 => "actionButtonHelp", + 192 => "actionButtonInformation", + 193 => "actionButtonForwardNext", + 194 => "actionButtonBackPrevious", + 195 => "actionButtonEnd", + 196 => "actionButtonBeginning", + 197 => "actionButtonReturn", + 198 => "actionButtonDocument", + 199 => "actionButtonSound", + 200 => "actionButtonMovie", + // WordArt text shapes (24–31, 136–175) draw their text as plain text in a rectangle. + 24..=31 | 136..=175 => "rect", + _ => return None, + }) +} + +/// Whether a shape type is a connector. +pub fn is_connector(shape_type: u16) -> bool { + (32..=40).contains(&shape_type) +} + +/// The geometry of a shape: its preset (checked against the presets `craft_drawingml` draws, with a +/// rounded rectangle's corner carried over), else its freeform path, else a rectangle. +pub fn geometry(shape_type: u16, props: &Props) -> Geom { + if let Some(name) = preset_name(shape_type).filter(|n| craft_drawingml::preset::build(n, 100.0, 100.0, &[]).is_some()) { + let mut adj = vec![]; + // A rounded rectangle's corner: a 21600 coordinate in OfficeArt, a 100000 fraction of the + // shorter side in DrawingML. + if shape_type == 2 + && let Some(v) = props.get(prop::ADJUST_VALUE) + { + adj.push(f64::from(v as i32).clamp(0.0, 10800.0) / 21600.0 * 100_000.0); + } + return Geom::Preset { name: name.into(), adj }; + } + custom_path(props).map(|paths| Geom::Custom { paths }).unwrap_or_default() +} + +/// Segments followed at most in one path. +const MAX_SEGMENTS: usize = 1 << 16; +/// Vertices used at most in one path. The path text is copied into every shape that inherits the +/// vertices from a master shape, so it stays a bounded size. +const MAX_POINTS: usize = 8192; + +/// A freeform's path in its geometry box. +fn custom_path(props: &Props) -> Option> { + let (size, verts) = props.array(prop::VERTICES)?; + let points: Vec<(f64, f64)> = match size { + 8 => verts + .as_chunks::<8>() + .0 + .iter() + .take(MAX_POINTS) + .map(|c| (f64::from(i32::from_le_bytes([c[0], c[1], c[2], c[3]])), f64::from(i32::from_le_bytes([c[4], c[5], c[6], c[7]])))) + .collect(), + 4 => verts + .as_chunks::<4>() + .0 + .iter() + .take(MAX_POINTS) + .map(|c| (f64::from(i16::from_le_bytes([c[0], c[1]])), f64::from(i16::from_le_bytes([c[2], c[3]])))) + .collect(), + _ => return None, + }; + if points.is_empty() { + return None; + } + let left = f64::from(props.get(prop::GEO_LEFT).unwrap_or(0) as i32); + let top = f64::from(props.get(prop::GEO_TOP).unwrap_or(0) as i32); + let right = f64::from(props.get(prop::GEO_RIGHT).unwrap_or(21600) as i32); + let bottom = f64::from(props.get(prop::GEO_BOTTOM).unwrap_or(21600) as i32); + let (w, h) = ((right - left).abs().max(1.0), (bottom - top).abs().max(1.0)); + let mut pts = points.iter().map(|(x, y)| (x - left, y - top)); + let mut d = String::new(); + let mut push = |cmd: &str, ps: &[(f64, f64)]| { + d.push_str(cmd); + for (x, y) in ps { + d.push_str(&format!(" {x} {y}")); + } + d.push(' '); + }; + match props.array(prop::SEGMENT_INFO) { + // An empty segment list is no segments ([MS-ODRAW] shapePath: it applies unless the list + // is "neither NULL nor empty"). + Some((2, segs)) if !segs.is_empty() => { + for c in segs.as_chunks::<2>().0.iter().take(MAX_SEGMENTS) { + let v = u16::from_le_bytes(*c); + let count = usize::from(v & 0x1FFF); + match v >> 13 { + // lineTo + 0 => { + for _ in 0..count.max(1) { + let Some(p) = pts.next() else { break }; + push("L", &[p]); + } + } + // curveTo: three points per segment + 1 => { + for _ in 0..count.max(1) { + let ps: Vec<_> = pts.by_ref().take(3).collect(); + if ps.len() < 3 { + break; + } + push("C", &ps); + } + } + 2 => { + let Some(p) = pts.next() else { break }; + push("M", &[p]); + } + 3 => push("Z", &[]), + 4 => break, + // Escapes (MSOPATHESCAPEINFO: escape code in bits 8–12, point count in bits + // 0–7). They aren't drawn as curves, but they use up their points, and the + // segments after them start where they end. + 5 => { + let n = usize::from(v & 0xFF); + let code = (v >> 8) & 0x1F; + let mut last = None; + for _ in 0..n { + last = pts.next().or(last); + } + match code { + // Extension: more points for the escape that follows. Fill and line + // colours: a colour pair, not a place. NoFill, NoLine and the Bézier + // editing hints: no points. + 0x00 | 0x0A..=0x16 => {} + // Elliptical quadrants run from point to point and a quadratic Bézier + // ends on its last point: a line there keeps the path's place. + 0x07..=0x09 => { + if let Some(p) = last { + push("L", &[p]); + } + } + // Angle ellipses and arcs end at a point computed from their angles or + // radial vectors, not at one of their vertices: the path stops rather + // than go on from the wrong place. So does any other escape. + _ => break, + } + } + // Client escapes mean what the writing application says: the path stops + // unless one has no points. + 6 if v & 0xFF != 0 => break, + _ => {} + } + } + } + // No segments: shapePath says how the vertices join (MSOSHAPEPATH), by default + // msoshapeLinesClosed. + _ => { + let shape_path = props.get(prop::SHAPE_PATH).unwrap_or(1); + if let Some(p) = pts.next() { + push("M", &[p]); + } + if matches!(shape_path, 2 | 3) { + loop { + let ps: Vec<_> = pts.by_ref().take(3).collect(); + if ps.len() < 3 { + break; + } + push("C", &ps); + } + } else { + for p in pts { + push("L", &[p]); + } + } + if matches!(shape_path, 1 | 3) { + push("Z", &[]); + } + } + } + let d = d.trim_end().to_string(); + if !d.starts_with('M') { + return None; + } + Some(vec![CustomPath { w, h, d, ..Default::default() }]) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::Rec; + use crate::record::build::atom; + + fn props(entries: &[(u16, u32)], complex: &[u8]) -> Vec { + let mut b = vec![]; + for (id, op) in entries { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + b.extend_from_slice(complex); + atom(crate::doc::rt::FOPT, entries.len() as u16, &b) + } + + fn array(size: u16, elems: &[u8]) -> Vec { + let n = (elems.len() / usize::from(size)) as u16; + [&n.to_le_bytes()[..], &n.to_le_bytes(), &size.to_le_bytes(), elems].concat() + } + + #[test] + fn every_mapped_preset_is_one_craft_drawingml_draws() { + for t in 0..=255u16 { + if let Some(name) = preset_name(t) { + assert!(craft_drawingml::preset::build(name, 100.0, 100.0, &[]).is_some(), "type {t}: {name}"); + } + } + } + + #[test] + fn reads_a_freeform_triangle() { + let verts: Vec = [(0i16, 100i16), (50, 0), (100, 100)].iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect(); + // moveTo, lineTo ×2, close, end + let segs: Vec = [0x4000u16, 0x0002, 0x6001, 0x8000].iter().flat_map(|v| v.to_le_bytes()).collect(); + let v = array(4, &verts); + let s = array(2, &segs); + let t = props( + &[ + (prop::GEO_RIGHT, 100), + (prop::GEO_BOTTOM, 100), + (0x8000 | prop::VERTICES, v.len() as u32), + (0x8000 | prop::SEGMENT_INFO, s.len() as u32), + ], + &[v, s].concat(), + ); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") }; + assert_eq!(paths[0].d, "M 0 100 L 50 0 L 100 100 Z"); + assert_eq!((paths[0].w, paths[0].h), (100.0, 100.0)); + } + + /// A freeform with more vertices than [`MAX_POINTS`] draws through the first of them only. + #[test] + fn a_path_uses_at_most_max_points() { + let verts: Vec = (0..20_000u32).flat_map(|i| [(i as i16 % 100).to_le_bytes(), 0i16.to_le_bytes()].concat()).collect(); + let v = array(4, &verts); + let t = props(&[(0x8000 | prop::VERTICES, v.len() as u32)], &v); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") }; + let d = &paths[0].d; + assert_eq!(d.matches('M').count() + d.matches('L').count(), MAX_POINTS); + } + + fn freeform(verts: &[(i16, i16)], segs: Option<&[u16]>, extra: &[(u16, u32)]) -> Geom { + let verts: Vec = verts.iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect(); + let v = array(4, &verts); + let mut entries = vec![(prop::GEO_RIGHT, 100), (prop::GEO_BOTTOM, 100), (0x8000 | prop::VERTICES, v.len() as u32)]; + entries.extend_from_slice(extra); + let mut complex = v; + if let Some(segs) = segs { + let s = array(2, &segs.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + entries.push((0x8000 | prop::SEGMENT_INFO, s.len() as u32)); + complex.extend_from_slice(&s); + } + let t = props(&entries, &complex); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + geometry(0, &p) + } + + fn path_of(g: Geom) -> String { + let Geom::Custom { paths } = g else { panic!("not custom: {g:?}") }; + paths[0].d.clone() + } + + /// An escape segment uses up its points and the path goes on from where it ends: after + /// elliptical quadrants or a quadratic Bézier, from their last point; an arc ends at a point + /// worked out from its radial vectors, so the path stops there rather than draw the next line + /// from the point before the arc. + #[test] + fn path_escapes_end_where_they_end() { + let verts = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (50, 60)]; + let escape = |code: u16, n: u16| (5u16 << 13) | (code << 8) | n; + // moveTo, escape ArcTo (3) over 4 points, lineTo, end. + assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(3, 4), 0x0001, 0x8000]), &[])), "M 0 0"); + // moveTo, two elliptical quadrants (7), lineTo, end. + let verts = [(0, 0), (10, 10), (20, 0), (50, 60)]; + assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(7, 2), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0 L 50 60"); + // A colour escape uses its point but doesn't move the path. + assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(0x15, 1), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0"); + } + + /// Without segments, shapePath says how the vertices join: closed lines by default, open + /// lines, or Bézier curves three points at a time. An empty segment list is no segments. + #[test] + fn shape_path_joins_vertices_without_segments() { + let tri = [(0, 100), (50, 0), (100, 100)]; + assert_eq!(path_of(freeform(&tri, None, &[])), "M 0 100 L 50 0 L 100 100 Z"); + assert_eq!(path_of(freeform(&tri, Some(&[]), &[])), "M 0 100 L 50 0 L 100 100 Z"); + assert_eq!(path_of(freeform(&tri, None, &[(prop::SHAPE_PATH, 0)])), "M 0 100 L 50 0 L 100 100"); + let curve = [(0, 0), (10, 0), (20, 10), (20, 20)]; + assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 2)])), "M 0 0 C 10 0 20 10 20 20"); + assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 3)])), "M 0 0 C 10 0 20 10 20 20 Z"); + } + + #[test] + fn a_rounded_rectangle_keeps_its_corner() { + let t = props(&[(prop::ADJUST_VALUE, 5400)], &[]); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(geometry(2, &p), Geom::Preset { name: "roundRect".into(), adj: vec![25000.0] }); + assert_eq!(geometry(9999, &Props::default()), Geom::default()); + } +} diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs new file mode 100644 index 000000000..b9b2fa315 --- /dev/null +++ b/crates/ppt-binary/src/lib.rs @@ -0,0 +1,76 @@ +//! Legacy PowerPoint 97–2003 import (`.ppt`, `.pot`, `.pps`), written from Microsoft's public +//! Open Specifications: [MS-PPT] (the presentation records) and [MS-ODRAW] (the shapes and +//! pictures), on `craft-cfb` for the compound file ([MS-CFB]). +//! +//! [`import`] reads a presentation leniently into a [`craft_pptx::Presentation`]: unknown records +//! are skipped, damaged ones are left out, and every size, count and depth is bounded. The caller's +//! [`Defaults`] supply each master's layouts and placeholders, which the file's masters then +//! place and style. There is no `.ppt` writer. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +#[cfg(doctest)] +#[doc = include_str!("../README.md")] +struct ReadmeExamples; + +mod blip; +mod convert; +mod doc; +mod draw; +mod geom; +mod record; +mod text; + +use craft_cfb::{CompoundFile, Error as CfbError}; +use craft_pptx::{Defaults, Presentation}; + +/// Name of the stream holding the presentation. +const DOCUMENT_STREAM: &str = "PowerPoint Document"; + +#[derive(Debug, thiserror::Error)] +pub enum PptError { + #[error("not a PowerPoint 97-2003 presentation")] + NotPpt, + #[error("the presentation is password-protected")] + Encrypted, + #[error("the presentation was made by PowerPoint 95 or earlier")] + TooOld, + #[error("the presentation is damaged: {0}")] + Damaged(String), +} + +/// Does this look like a PowerPoint 97–2003 file (a compound file with a `PowerPoint Document` +/// stream)? +pub fn sniff(bytes: &[u8]) -> bool { + craft_cfb::sniff(bytes) && CompoundFile::open(bytes).is_ok_and(|f| f.has_stream(DOCUMENT_STREAM)) +} + +/// Read a `.ppt` / `.pot` / `.pps` file. `defaults` gives the master each of the file's masters +/// starts from, and the one used when the file has none it can read. +pub fn import(bytes: &[u8], defaults: &dyn Defaults) -> Result { + import_checked(bytes, defaults).map(|(p, _)| p) +} + +/// [`import`], plus the slides the file lists but whose objects couldn't be found, so they are not +/// in the presentation. +pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec), PptError> { + let file = CompoundFile::open(bytes).map_err(|e| match e { + CfbError::NotCfb => PptError::NotPpt, + other => PptError::Damaged(other.to_string()), + })?; + // No stream is longer than the file holding it: a larger stated size is damage, refused + // before anything is allocated for it. + let cap = bytes.len() as u64; + let stream = file.read_path_capped(DOCUMENT_STREAM, cap).map_err(|e| match e { + CfbError::NotFound(_) => PptError::NotPpt, + other => PptError::Damaged(other.to_string()), + })?; + let current_user = file.read_path_capped("Current User", cap).unwrap_or_default(); + // A damaged or missing picture stream costs the pictures, not the presentation. + let pictures = file.read_path_capped("Pictures", cap).unwrap_or_default(); + let d = doc::read(¤t_user, &stream)?; + Ok((convert::convert(&d, &pictures, defaults), d.lost.clone())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ppt-binary/src/record.rs b/crates/ppt-binary/src/record.rs new file mode 100644 index 000000000..62655e2be --- /dev/null +++ b/crates/ppt-binary/src/record.rs @@ -0,0 +1,186 @@ +//! The record framing shared by [MS-PPT] and [MS-ODRAW]: an 8-byte header (version, instance, +//! type, length) followed by `len` bytes, which for a container (version `0xF`) are more records. + +/// The little-endian `u16` at `at`, if `b` holds it. +pub(crate) fn u16_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(2)?)?; + Some(u16::from_le_bytes([*s.first()?, *s.get(1)?])) +} + +/// The little-endian `u32` at `at`, if `b` holds it. +pub(crate) fn u32_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_le_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?])) +} + +/// Containers nest at most this deep; deeper input is treated as damaged and skipped. +pub const MAX_DEPTH: usize = 32; + +/// One record over borrowed bytes. +#[derive(Clone, Copy, Debug)] +pub struct Rec<'a> { + pub ver: u8, + pub instance: u16, + pub kind: u16, + /// The record's body (after the header), clipped to the input. + pub data: &'a [u8], + /// Offset of the header in the slice it was read from. + pub offset: usize, +} + +impl<'a> Rec<'a> { + /// The record whose header starts at `at`, its body clipped to `bytes` (a truncated last record + /// keeps what is there). + pub fn at(bytes: &'a [u8], at: usize) -> Option> { + let vi = u16_at(bytes, at)?; + let kind = u16_at(bytes, at.checked_add(2)?)?; + let len = u32_at(bytes, at.checked_add(4)?)? as usize; + let start = at.checked_add(8)?; + let end = start.saturating_add(len).min(bytes.len()); + Some(Rec { ver: (vi & 0xF) as u8, instance: vi >> 4, kind, data: bytes.get(start..end)?, offset: at }) + } + + pub fn is_container(&self) -> bool { + self.ver == 0xF + } + + /// The records inside this one; none for an atom. + pub fn children(&self) -> Records<'a> { + Records::new(if self.is_container() { self.data } else { &[] }) + } + + /// The first child of type `kind`. + pub fn child(&self, kind: u16) -> Option> { + self.children().find(|r| r.kind == kind) + } + + /// Every child of type `kind`. + pub fn children_of(&self, kind: u16) -> impl Iterator> { + self.children().filter(move |r| r.kind == kind) + } + + pub fn u8(&self, at: usize) -> Option { + self.data.get(at).copied() + } + pub fn u16(&self, at: usize) -> Option { + u16_at(self.data, at) + } + pub fn i16(&self, at: usize) -> Option { + self.u16(at).map(|v| v as i16) + } + pub fn u32(&self, at: usize) -> Option { + u32_at(self.data, at) + } + pub fn i32(&self, at: usize) -> Option { + self.u32(at).map(|v| v as i32) + } +} + +/// Iterates the records laid end to end in a byte slice. +#[derive(Clone, Debug)] +pub struct Records<'a> { + bytes: &'a [u8], + at: usize, +} + +impl<'a> Records<'a> { + pub fn new(bytes: &'a [u8]) -> Self { + Records { bytes, at: 0 } + } +} + +impl<'a> Iterator for Records<'a> { + type Item = Rec<'a>; + fn next(&mut self) -> Option> { + let r = Rec::at(self.bytes, self.at)?; + // Always advance by at least the header, so a zero-length record can't stall the walk. + self.at = self.at.checked_add(8)?.checked_add(r.data.len())?; + Some(r) + } +} + +/// A little-endian reader over a record body for the variable-length structures (text +/// exceptions, style runs): every read is checked and a short body ends the walk. +pub struct Cursor<'a> { + pub b: &'a [u8], + pub at: usize, +} + +impl<'a> Cursor<'a> { + pub fn new(b: &'a [u8]) -> Self { + Cursor { b, at: 0 } + } + /// Bytes left to read. + pub fn remaining(&self) -> usize { + self.b.len().saturating_sub(self.at) + } + pub fn u8(&mut self) -> Option { + let v = *self.b.get(self.at)?; + self.at += 1; + Some(v) + } + pub fn u16(&mut self) -> Option { + let v = u16_at(self.b, self.at)?; + self.at += 2; + Some(v) + } + pub fn i16(&mut self) -> Option { + self.u16().map(|v| v as i16) + } + pub fn u32(&mut self) -> Option { + let v = u32_at(self.b, self.at)?; + self.at += 4; + Some(v) + } +} + +#[cfg(test)] +pub(crate) mod build { + //! Writing records, for tests that build `.ppt` files. + + pub fn atom(kind: u16, instance: u16, body: &[u8]) -> Vec { + head(0, kind, instance, body) + } + + pub fn container(kind: u16, instance: u16, children: &[Vec]) -> Vec { + head(0xF, kind, instance, &children.concat()) + } + + fn head(ver: u16, kind: u16, instance: u16, body: &[u8]) -> Vec { + let mut v = Vec::with_capacity(body.len() + 8); + v.extend_from_slice(&(ver | (instance << 4)).to_le_bytes()); + v.extend_from_slice(&kind.to_le_bytes()); + v.extend_from_slice(&(body.len() as u32).to_le_bytes()); + v.extend_from_slice(body); + v + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::build::*; + use super::*; + + #[test] + fn walks_nested_records() { + let c = container(0x03E8, 0, &[atom(0x03E9, 0, &[1, 2, 3, 4]), atom(0x0FA0, 2, &[9; 6])]); + let r = Rec::at(&c, 0).unwrap(); + assert!(r.is_container()); + let kids: Vec<_> = r.children().collect(); + assert_eq!(kids.len(), 2); + assert_eq!(kids[1].instance, 2); + assert_eq!(r.child(0x03E9).unwrap().u32(0), Some(0x0403_0201)); + } + + #[test] + fn truncated_and_zero_length_records_end_the_walk() { + let mut c = atom(0x1, 0, &[]).repeat(3); + c.extend_from_slice(&[0xF, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0x7F, 1, 2]); + let all: Vec<_> = Records::new(&c).collect(); + assert_eq!(all.len(), 4); + assert_eq!(all[3].data, &[1, 2]); + assert!(Records::new(&[1, 2, 3]).next().is_none()); + } +} diff --git a/crates/ppt-binary/src/tests.rs b/crates/ppt-binary/src/tests.rs new file mode 100644 index 000000000..55ed55396 --- /dev/null +++ b/crates/ppt-binary/src/tests.rs @@ -0,0 +1,1245 @@ +//! End-to-end tests over `.ppt` files built here from records (never files made by PowerPoint). +#![allow(clippy::unwrap_used)] + +use craft_pptx::text::{Align, Bullet, RunKind}; +use craft_pptx::{ + Background, Defaults, Fill, Layout, LayoutId, LayoutType, Master, MasterId, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, ShapeKind, + Size, Slide, TextBody, Xfrm, +}; + +use crate::doc::rt; +use crate::draw::prop; +use crate::record::build::{atom, container}; +use crate::text::tests::{cf_bytes, pf_bytes}; + +/// A default master as an application gives one: title, body and footer placeholders on the +/// master, and the layouts `.ppt` layout types map to, each with its placeholders. The `.ppt` +/// masters place and style these. +struct AppDefaults; + +impl Defaults for AppDefaults { + fn master(&self, size: Size, after: u32) -> (Master, u32) { + let next = std::cell::Cell::new(after); + let id = || { + next.set(next.get() + 1); + next.get() + }; + let (w, h) = (size.width, size.height); + let ph = |kind: PhType, name: &str, x: [f64; 4]| Shape { + id: ShapeId(id()), + name: name.into(), + xfrm: Some(Xfrm::new(x[0] * w, x[1] * h, x[2] * w, x[3] * h)), + ph: Some(Placeholder { kind, ..Default::default() }), + text: Some(TextBody::default()), + ..Default::default() + }; + let title = || ph(PhType::Title, "Title", [0.06, 0.05, 0.88, 0.17]); + let footers = || { + vec![ + ph(PhType::Date, "Date", [0.06, 0.92, 0.22, 0.05]), + ph(PhType::Footer, "Footer", [0.33, 0.92, 0.34, 0.05]), + ph(PhType::SlideNum, "Slide Number", [0.72, 0.92, 0.22, 0.05]), + ] + }; + let mut shapes = vec![title(), ph(PhType::Body, "Text", [0.06, 0.25, 0.88, 0.62])]; + shapes.extend(footers()); + let kinds = [ + (LayoutType::Title, "Title Slide"), + (LayoutType::TitleAndContent, "Title and Content"), + (LayoutType::TitleOnly, "Title Only"), + (LayoutType::TwoContent, "Two Content"), + (LayoutType::VerticalTitleAndText, "Vertical Title and Text"), + (LayoutType::TitleAndVerticalText, "Title and Vertical Text"), + (LayoutType::Blank, "Blank"), + ]; + let layouts = kinds + .into_iter() + .map(|(kind, name)| { + let mut l: Vec = if kind == LayoutType::Blank { vec![] } else { vec![title()] }; + l.extend(footers()); + Layout { id: LayoutId(id()), name: name.into(), kind, shapes: l, show_master_shapes: true, ..Default::default() } + }) + .collect(); + let master = Master { id: MasterId(id()), name: "Default".into(), shapes, layouts, ..Default::default() }; + (master, next.get()) + } +} + +fn import(bytes: &[u8]) -> Result { + crate::import(bytes, &AppDefaults) +} + +fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), crate::PptError> { + crate::import_checked(bytes, &AppDefaults) +} + +/// A version 3 compound file holding `streams` at its root. +fn build(streams: &[(&str, &[u8])]) -> Vec { + craft_cfb::write_streams(craft_cfb::Version::V3, streams).unwrap() +} + +/// With no default master of the caller's, a file's masters still read: the plain master has no +/// placeholders for the file's to place, and the slides keep their own. +#[test] +fn plain_defaults_still_read_the_file() { + let p = crate::import(&file(), &craft_pptx::Plain).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().text(), "Hello\nWorld"); + assert!(p.layout(p.slides[0].layout).is_some()); +} + +fn le32(v: &[u32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +fn utf16(s: &str) -> Vec { + s.encode_utf16().flat_map(u16::to_le_bytes).collect() +} + +fn fopt(entries: &[(u16, u32)]) -> Vec { + let mut b = vec![]; + for (id, op) in entries { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + atom(rt::FOPT, entries.len() as u16, &b) +} + +fn fsp(shape_type: u16, spid: u32, flags: u32) -> Vec { + atom(rt::FSP, shape_type, &le32(&[spid, flags])) +} + +/// A client anchor in master units: top, left, right, bottom. +fn anchor(t: i16, l: i16, r: i16, b: i16) -> Vec { + atom(rt::CLIENT_ANCHOR, 0, &[t, l, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::>()) +} + +fn text_box(text_type: u32, text: &str, extra: &[Vec]) -> Vec { + let mut kids = vec![atom(rt::TEXT_HEADER, 0, &text_type.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16(text))]; + kids.extend_from_slice(extra); + container(rt::CLIENT_TEXTBOX, 0, &kids) +} + +fn placeholder(kind: u8) -> Vec { + container(rt::CLIENT_DATA, 0, &[atom(rt::PLACEHOLDER_ATOM, 0, &[0, 0, 0, 0, kind, 0, 0, 0])]) +} + +fn drawing(background: Option>, shapes: &[Vec]) -> Vec { + let patriarch = container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &[0; 16]), fsp(0, 1024, 0x5)]); + let mut tree = vec![patriarch]; + tree.extend_from_slice(shapes); + let mut dg = vec![container(rt::SPGR_CONTAINER, 0, &tree)]; + dg.extend(background); + container(rt::DRAWING, 0, &[container(rt::DG_CONTAINER, 0, &dg)]) +} + +fn solid_background(rgb: u32) -> Vec { + container(rt::SP_CONTAINER, 0, &[fsp(1, 1025, 0x400 | 0x800), fopt(&[(prop::FILL_COLOR, rgb), (prop::FILL_BOOLS, 0x0010_0010)])]) +} + +fn slide_atom(geom: u32, master_id: u32, flags: u16) -> Vec { + let mut b = geom.to_le_bytes().to_vec(); + b.extend_from_slice(&[0; 8]); + b.extend_from_slice(&le32(&[master_id, 0])); + b.extend_from_slice(&flags.to_le_bytes()); + b.extend_from_slice(&[0; 2]); + atom(rt::SLIDE_ATOM, 0, &b) +} + +/// A master text style with one level: a paragraph and a character exception. +fn master_style(instance: u16, pf: &[u8], cf: &[u8]) -> Vec { + atom(rt::TEXT_MASTER_STYLE, instance, &[&1u16.to_le_bytes()[..], pf, cf].concat()) +} + +const MASTER_ID: u32 = 0x8000_0001; +const SLIDE_ID: u32 = 256; +const TITLE_MASTER_ID: u32 = 0x8000_0002; + +fn master() -> Vec { + master_with(&[]) +} + +/// The test master with `shapes` after its decoration. +fn master_with(shapes: &[Vec]) -> Vec { + // Background, text, shadow, title, fill, accent, hyperlink, followed hyperlink. + let scheme: Vec = [0xFFFFFFu32, 0x000000, 0x808080, 0x000099, 0x00CC00, 0x0000FF, 0x00FF00, 0xFF0000] + .iter() + .flat_map(|c| [(c >> 16) as u8, (c >> 8) as u8, *c as u8, 0]) + .collect(); + let decoration = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 1026, 0xA00), + fopt(&[(prop::FILL_COLOR, 0x0800_0004), (prop::FILL_BOOLS, 0x0010_0010), (prop::LINE_BOOLS, 0x0008_0000)]), + anchor(0, 0, 5760, 400), + ], + ); + container( + rt::MAIN_MASTER, + 0, + &[ + slide_atom(1, 0, 0), + atom(rt::COLOR_SCHEME, 1, &scheme), + master_style(0, &pf_bytes(1, false), &cf_bytes(true, 0, 44, [0x11, 0x22, 0x33])), + master_style(1, &pf_bytes(0, true), &cf_bytes(false, 0, 28, [0, 0, 0])), + drawing(Some(solid_background(0x0000_00FF)), &[&[decoration][..], shapes].concat()), + ], + ) +} + +fn slide() -> Vec { + let title = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 2049, 0xA00), fopt(&[(prop::ANCHOR_TEXT, 1)]), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Hello\rWorld", &[])], + ); + let picture = container(rt::SP_CONTAINER, 0, &[fsp(75, 2050, 0xA00), fopt(&[(prop::PIB, 1)]), anchor(1600, 800, 2400, 2400)]); + let group = container( + rt::SPGR_CONTAINER, + 0, + &[ + container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &le32(&[0, 0, 1000, 1000])), fsp(0, 2051, 0x201), anchor(1600, 3000, 4000, 3200)]), + container( + rt::SP_CONTAINER, + 0, + &[ + fsp(3, 2052, 0x2), + fopt(&[(prop::FILL_COLOR, 0x0000_FF00), (prop::LINE_WIDTH, 25400)]), + atom(rt::CHILD_ANCHOR, 0, &le32(&[500, 0, 1000, 500])), + ], + ), + ], + ); + // "Page *": the star is a slide number field. The first four characters are bold. + let mut style = vec![]; + style.extend_from_slice(&7u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(2, false)); + for (n, bold) in [(4u32, true), (3, false)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&cf_bytes(bold, 1, 12, [0xAB, 0xCD, 0xEF])); + } + let footer = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(202, 2053, 0xA00), + anchor(4000, 500, 2000, 4200), + text_box(4, "Page *", &[atom(rt::STYLE_TEXT_PROP, 0, &style), atom(rt::SLIDE_NUMBER_MC, 0, &5u32.to_le_bytes())]), + ], + ); + // A hidden slide (SlideShowSlideInfoAtom fHidden). + let mut info = vec![0u8; 16]; + info[10] = 0x4; + container( + rt::SLIDE, + 0, + &[slide_atom(1, MASTER_ID, 0x7), atom(rt::SLIDE_SHOW_SLIDE_INFO, 0, &info), drawing(None, &[title, picture, group, footer])], + ) +} + +fn notes() -> Vec { + let number = container(rt::SP_CONTAINER, 0, &[fsp(1, 3073, 0xA00), anchor(0, 0, 100, 100), placeholder(0x08), text_box(2, "*", &[])]); + let body = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 3074, 0xA00), anchor(100, 0, 4000, 4000), placeholder(0x0C), text_box(2, "Say hello\rThen wave", &[])], + ); + container(rt::NOTES, 0, &[atom(rt::NOTES_ATOM, 0, &le32(&[SLIDE_ID, 0])), drawing(None, &[number, body])]) +} + +fn png() -> Vec { + let mut buf = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut buf, image::ImageFormat::Png).unwrap(); + buf.into_inner() +} + +/// The streams of a one-slide presentation, with `edit` choosing the current user's header token. +fn streams(token: u32) -> (Vec, Vec, Vec) { + streams_listing(token, 1) +} + +/// The test document with its slide listed `times` times in the slide list. +fn streams_listing(token: u32, times: usize) -> (Vec, Vec, Vec) { + streams_of(token, times, slide(), None) +} + +/// The test document with `slide` as its slide and, when given, a title master (persist id 5, +/// slide id `TITLE_MASTER_ID`) listed after the main master. +fn streams_of(token: u32, times: usize, slide: Vec, title_master: Option>) -> (Vec, Vec, Vec) { + streams_with_outline(token, times, slide, title_master, &[]) +} + +/// As [`streams_of`], with `outline` (text blocks: header, characters, styles) following the +/// slide's persist atom in the slide list. +fn streams_with_outline(token: u32, times: usize, slide: Vec, title_master: Option>, outline: &[Vec]) -> (Vec, Vec, Vec) { + streams_with_document(token, times, master(), slide, title_master, outline, &[]) +} + +/// As [`streams_with_outline`], with `master` as the main master and `extra` records at the end of +/// the document container. +fn streams_with_document( + token: u32, + times: usize, + master: Vec, + slide: Vec, + title_master: Option>, + outline: &[Vec], + extra: &[Vec], +) -> (Vec, Vec, Vec) { + streams_with_title_masters(token, times, master, slide, title_master.into_iter().collect(), outline, extra) +} + +/// As [`streams_with_document`], with any number of title masters: persist ids 5 on, slide ids +/// `TITLE_MASTER_ID` on. +fn streams_with_title_masters( + token: u32, + times: usize, + master: Vec, + slide: Vec, + title_masters: Vec>, + outline: &[Vec], + extra: &[Vec], +) -> (Vec, Vec, Vec) { + streams_with_notes(token, times, master, slide, title_masters, outline, extra, notes(), &[]) +} + +/// As [`streams_with_title_masters`], with `notes` as the notes page (persist id 4) and +/// `notes_outline` following its persist atom in the notes list. +#[allow(clippy::too_many_arguments)] +fn streams_with_notes( + token: u32, + times: usize, + master: Vec, + slide: Vec, + title_masters: Vec>, + outline: &[Vec], + extra: &[Vec], + notes: Vec, + notes_outline: &[Vec], +) -> (Vec, Vec, Vec) { + let pictures = atom(0xF01E, 0x6E0, &[&[0u8; 17][..], &png()].concat()); + let mut fbse = vec![0u8; 36]; + fbse[0] = 6; + fbse[1] = 6; + fbse[20..24].copy_from_slice(&(pictures.len() as u32).to_le_bytes()); + let bstore = container(rt::BSTORE, 1, &[atom(rt::FBSE, 6, &fbse)]); + let mut font = utf16("Arial"); + font.resize(68, 0); + let mut wing = utf16("Wingdings"); + wing.resize(68, 0); + let mut doc_atom = le32(&[5760, 4320, 4320, 5760, 1, 2, 0, 0]); + doc_atom.extend_from_slice(&1u16.to_le_bytes()); + doc_atom.resize(40, 0); + let persist = |id: u32| { + atom( + rt::SLIDE_PERSIST_ATOM, + 0, + &le32(&[ + id, + 0, + 0, + if id == 2 { + MASTER_ID + } else if id >= 5 { + TITLE_MASTER_ID + (id - 5) + } else if id == 3 { + SLIDE_ID + } else { + SLIDE_ID + 1 + }, + 0, + ]), + ) + }; + let parts = [ + atom(rt::DOCUMENT_ATOM, 0, &doc_atom), + container(rt::ENVIRONMENT, 0, &[container(rt::FONT_COLLECTION, 0, &[atom(rt::FONT_ENTITY, 0, &font), atom(rt::FONT_ENTITY, 1, &wing)])]), + container(rt::DRAWING_GROUP, 0, &[container(rt::DGG_CONTAINER, 0, &[bstore])]), + container( + rt::SLIDE_LIST_WITH_TEXT, + 1, + &(0..=title_masters.len() as u32).map(|k| persist(if k == 0 { 2 } else { 4 + k })).collect::>(), + ), + container(rt::SLIDE_LIST_WITH_TEXT, 0, &[vec![persist(3); times], outline.to_vec()].concat()), + container(rt::SLIDE_LIST_WITH_TEXT, 2, &[vec![persist(4)], notes_outline.to_vec()].concat()), + ]; + let document = container(rt::DOCUMENT, 0, &[&parts[..], extra].concat()); + let mut stream = vec![]; + let mut offsets = vec![]; + let parts: Vec> = [document, master, slide, notes].into_iter().chain(title_masters).collect(); + for part in &parts { + offsets.push(stream.len() as u32); + stream.extend_from_slice(part); + } + let dir_at = stream.len() as u32; + let mut dir = vec![1u32 | ((parts.len() as u32) << 20)]; + dir.extend_from_slice(&offsets); + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&dir))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, 0, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let current_user = atom(rt::CURRENT_USER, 0, &le32(&[0x14, token, edit_at, 0, 0])); + (current_user, stream, pictures) +} + +fn file_with(token: u32) -> Vec { + let (cu, doc, pics) = streams(token); + build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]) +} + +fn file() -> Vec { + file_with(0xE391_C05F) +} + +#[test] +fn imports_a_presentation() { + let bytes = file(); + assert!(crate::sniff(&bytes)); + let p = import(&bytes).unwrap(); + assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0)); + assert_eq!(p.slides.len(), 1); + let s = &p.slides[0]; + assert!(s.hidden); + assert_eq!(s.notes.text(), "Say hello\nThen wave"); + check_title_placeholder(s); + check_picture(&p, s); + check_group(s); + check_text_box(s); + check_master(&p, s); +} + +fn check_title_placeholder(s: &Slide) { + // The title placeholder: its box, its text and the master's title style. + let title = &s.shapes[0]; + assert_eq!(title.ph_type(), Some(PhType::Title)); + let x = title.xfrm.unwrap(); + assert_eq!((x.x, x.y, x.w, x.h), (62.5, 50.0, 595.0, 100.0)); + assert_eq!(title.fill, Some(Fill::None)); + let t = title.text.as_ref().unwrap(); + assert_eq!(t.text(), "Hello\nWorld"); + assert_eq!(t.body.anchor, Some(craft_pptx::text::Anchor::Middle)); + let p0 = &t.paragraphs[0]; + assert_eq!(p0.props.align, Some(Align::Center)); + assert_eq!(p0.props.bullet, Some(Bullet::None)); + let r = &p0.runs[0].props; + assert_eq!((r.size, r.bold, r.font.as_deref()), (Some(44.0), Some(true), Some("Arial"))); + assert_eq!(r.fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0x11, 0x22, 0x33))))); + assert_eq!(s.title(), "Hello\nWorld"); +} + +fn check_picture(p: &Presentation, s: &Slide) { + // The picture. + let ShapeKind::Picture { fill } = &s.shapes[1].kind else { panic!("not a picture: {:?}", s.shapes[1].kind) }; + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert_eq!(media.content_type, "image/png"); + assert!(media.data.starts_with(b"\x89PNG")); +} + +fn check_group(s: &Slide) { + // The group: children in slide points, the child space the group's own box. + let g = &s.shapes[2]; + let ShapeKind::Group { children, child } = &g.kind else { panic!("not a group") }; + let gx = g.xfrm.unwrap(); + assert_eq!((gx.x, gx.y, gx.w, gx.h), (375.0, 200.0, 125.0, 200.0)); + assert_eq!((child.x, child.y, child.w, child.h), (gx.x, gx.y, gx.w, gx.h)); + let e = children[0].xfrm.unwrap(); + assert_eq!((e.x, e.y, e.w, e.h, e.flip_h), (437.5, 200.0, 62.5, 100.0, false)); + assert_eq!(children[0].geom.preset_name(), Some("ellipse")); + assert_eq!(children[0].fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xFF, 0))))); + assert_eq!(children[0].line.as_ref().and_then(|l| l.width), Some(2.0)); +} + +fn check_text_box(s: &Slide) { + // The text box: runs split at the format change, the star a slide number field. + let tb = s.shapes[3].text.as_ref().unwrap(); + let runs = &tb.paragraphs[0].runs; + assert_eq!(tb.paragraphs[0].props.align, Some(Align::Right)); + assert_eq!(runs.len(), 3, "{runs:?}"); + assert_eq!((runs[0].text.as_str(), runs[0].props.bold), ("Page", Some(true))); + assert_eq!((runs[1].text.as_str(), runs[1].props.bold), (" ", Some(false))); + assert_eq!(runs[2].kind, RunKind::Field { field: "slidenum".into() }); + assert_eq!(runs[0].props.font.as_deref(), Some("Wingdings")); + assert_eq!(s.shapes[3].fill, Some(Fill::None)); +} + +fn check_master(p: &Presentation, s: &Slide) { + // The master: its background, colours and decoration. + let m = &p.masters[0]; + assert_eq!(m.background, Some(Background::Fill { fill: Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0xFF, 0, 0))) })); + assert_eq!(m.theme.colors.get(craft_pptx::SchemeSlot::Accent1), Rgba::rgb(0, 0xCC, 0)); + assert!(m.shapes.iter().any(|sh| sh.ph.is_none() && sh.fill == Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xCC, 0)))))); + assert_eq!(m.title_style.level(0).and_then(|l| l.run.size), Some(44.0)); + assert!(p.layout(s.layout).is_some()); +} + +/// A slide listed many times is one slide: a hostile file can't make the importer convert one +/// big drawing again for every listing (180k listings of a 100k-shape slide fit in ~10 MB). +#[test] +fn a_slide_listed_again_is_imported_once() { + let (cu, doc, pics) = streams_listing(0xE391_C05F, 3); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]); + let p = import(&bytes).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!( + p.slides[0].notes.text(), + "Say hello +Then wave" + ); +} + +/// Two slide records with the same slide id share its notes page, which goes to the first only: +/// converting it again for each would copy its text into every one. +#[test] +fn a_notes_page_goes_to_one_slide() { + let again = container(rt::SLIDE_LIST_WITH_TEXT, 0, &[atom(rt::SLIDE_PERSIST_ATOM, 0, &le32(&[6, 0, 0, SLIDE_ID, 0]))]); + let (_, mut stream, pics) = streams_with_document(0xE391_C05F, 1, master(), slide(), None, &[], &[again]); + let first_edit = stream.len() as u32 - 36; + // Persist id 6: a second copy of the slide. + let copy_at = stream.len() as u32; + stream.extend_from_slice(&slide()); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[6 | (1 << 20), copy_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 7]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 2); + assert_eq!(p.slides[0].notes.text(), "Say hello\nThen wave"); + assert_eq!(p.slides[1].notes.text(), ""); +} + +/// As [`a_notes_page_goes_to_one_slide`], with the notes body's text in the notes list's outline +/// block: that block, too, is copied into the first slide's notes only. +#[test] +fn a_notes_pages_outline_text_goes_to_one_slide() { + let body = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 3074, 0xA00), + anchor(100, 0, 4000, 4000), + placeholder(0x0C), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes())]), + ], + ); + let notes = container(rt::NOTES, 0, &[atom(rt::NOTES_ATOM, 0, &le32(&[SLIDE_ID, 0])), drawing(None, &[body])]); + let outline = [atom(rt::TEXT_HEADER, 0, &2u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("From the outline"))]; + let again = container(rt::SLIDE_LIST_WITH_TEXT, 0, &[atom(rt::SLIDE_PERSIST_ATOM, 0, &le32(&[6, 0, 0, SLIDE_ID, 0]))]); + let (_, mut stream, pics) = streams_with_notes(0xE391_C05F, 1, master(), slide(), vec![], &[], &[again], notes, &outline); + let first_edit = stream.len() as u32 - 36; + let copy_at = stream.len() as u32; + stream.extend_from_slice(&slide()); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[6 | (1 << 20), copy_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 7]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 2); + assert_eq!(p.slides[0].notes.text(), "From the outline"); + assert_eq!(p.slides[1].notes.text(), ""); +} + +/// Text with very many formatting runs is laid into runs in about linear time. Each lookup used to +/// scan the run starts from the beginning, so the cost grew with runs²: in a debug build these 640k +/// one-character runs (about 6 MB of file) took 75 s that way, and take about 2 s with binary search. +#[test] +fn many_character_runs_are_not_quadratic() { + const N: usize = 640_000; + let text: String = (0..N).map(|i| if i % 2 == 0 { 'a' } else { '\u{0B}' }).collect(); + let mut style = vec![]; + style.extend_from_slice(&(N as u32 + 1).to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&0u32.to_le_bytes()); // a paragraph exception with no fields + for _ in 0..=N { + style.extend_from_slice(&1u32.to_le_bytes()); + style.extend_from_slice(&0u32.to_le_bytes()); // a character exception with no fields + } + let shape = container( + rt::SP_CONTAINER, + 0, + &[fsp(202, 2060, 0xA00), anchor(0, 0, 1000, 1000), text_box(1, &text, &[atom(rt::STYLE_TEXT_PROP, 0, &style)])], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[shape])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]); + let t = std::time::Instant::now(); + let p = import(&bytes).unwrap(); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); + let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs; + assert_eq!(runs.iter().filter(|r| r.kind == RunKind::Break).count(), N / 2); +} + +/// A slide naming a master that doesn't exist falls back to the first main master, every time. The +/// fallback used to be the lowest index in a HashMap where a title master ties with its main +/// master, so the slide took the "Title Master" layout on some opens and not on others. +#[test] +fn a_slide_with_an_unknown_master_falls_back_the_same_way_every_time() { + let title_master = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[])]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, 0x8000_0099, 0x7), drawing(None, &[])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, Some(title_master)); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]); + for _ in 0..30 { + let p = import(&bytes).unwrap(); + assert_eq!(p.masters[0].layouts.iter().filter(|l| l.name == "Title Master").count(), 1, "the title master became a layout"); + let (_, layout) = p.layout(p.slides[0].layout).unwrap(); + assert_ne!(layout.name, "Title Master"); + } +} + +/// A damaged Current User record doesn't make a PowerPoint 97 file "too old": the newest edit is +/// found by scanning the document stream instead. A file with no edit record at all, behind a +/// token that isn't PowerPoint 97's, is still reported as too old. +#[test] +fn a_damaged_current_user_falls_back_to_the_scan() { + let (cu, doc, pics) = streams(0xE391_C05F); + let open = |cu: &[u8], doc: &[u8]| import(&build(&[("Current User", cu), ("PowerPoint Document", doc), ("Pictures", &pics)])); + // Truncated after the header and two bytes, so the token can't be read. + let truncated = atom(rt::CURRENT_USER, 0, &[0x14, 0]); + assert_eq!(open(&truncated, &doc).unwrap().slides.len(), 1); + // A corrupted token. + let corrupted = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xDEAD_BEEF, 0, 0, 0])); + assert_eq!(open(&corrupted, &doc).unwrap().slides.len(), 1); + assert!(matches!(open(&corrupted, &atom(rt::DOCUMENT_ATOM, 0, &[0; 40])), Err(crate::PptError::TooOld))); + // An intact token that points at no edit still gets the scan, and a stream without one is damaged. + assert!(matches!(open(&cu, &atom(rt::DOCUMENT_ATOM, 0, &[0; 40])), Err(crate::PptError::Damaged(_)))); +} + +/// Persist directories nested inside one another are not each read to the end of the stream. A chain +/// of edits, each naming a directory header 8 bytes after the last one, made every edit reparse the +/// rest of the stream (4095 edits × the filler): about 48 s for this 64 MiB stream in a debug build. +/// Within the shared budget it takes milliseconds, and the file is reported as damaged. +#[test] +fn nested_persist_directories_are_read_within_the_stream() { + const FILLER: usize = 1 << 26; + const EDITS: u32 = 4095; + let (_, mut stream, _) = streams(0xE391_C05F); + let mut prev = stream.len() as u32 - 36; // the test document's own UserEditAtom (8 + 28 bytes) + let base = stream.len() as u32; + for _ in 0..EDITS { + // A PersistDirectoryAtom header whose length runs past the end (clipped to the stream). + stream.extend_from_slice(&0u16.to_le_bytes()); + stream.extend_from_slice(&rt::PERSIST_DIRECTORY.to_le_bytes()); + stream.extend_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); + } + stream.resize(stream.len() + FILLER, 0); + for k in 0..EDITS { + let at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, prev, base + 8 * k, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + prev = at; + } + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, prev, 0, 0])); + // The streams are read directly: the test file builder can't hold a stream this size. + let t = std::time::Instant::now(); + let r = crate::doc::read(&cu, &stream); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); + assert!(matches!(r, Err(crate::PptError::Damaged(_)))); +} + +#[test] +fn an_encrypted_presentation_says_so() { + assert!(matches!(import(&file_with(0xF3D1_C4DF)), Err(crate::PptError::Encrypted))); +} + +#[test] +fn other_files_are_not_ppt() { + assert!(!crate::sniff(b"PK\x03\x04")); + assert!(!crate::sniff(&build(&[("WordDocument", b"x")]))); + assert!(matches!(import(b"not a presentation"), Err(crate::PptError::NotPpt))); + assert!(matches!(import(&build(&[("Workbook", b"x")])), Err(crate::PptError::NotPpt))); +} + +/// Damaged input never panics, loops or allocates without bound: every 4-byte word of the +/// document stream set to hostile values, and truncations of it. +#[test] +fn hostile_documents_never_panic() { + let (cu, doc, pics) = streams(0xE391_C05F); + for at in (0..doc.len().saturating_sub(4)).step_by(3) { + for v in [0u32, 1, 0x7FFF_FFFF, 0xFFFF_FFFF, 0x0000_FFFF, 0xF00F_000F] { + let mut d = doc.clone(); + d[at..at + 4].copy_from_slice(&v.to_le_bytes()); + let f = build(&[("Current User", &cu), ("PowerPoint Document", &d), ("Pictures", &pics)]); + let _ = import(&f); + } + } + for cut in (0..doc.len()).step_by(7) { + let f = build(&[("Current User", &cu), ("PowerPoint Document", &doc[..cut]), ("Pictures", &pics[..cut.min(pics.len())])]); + let _ = import(&f); + } +} + +/// A slide shape that inherits from a master shape (`hspMaster`) takes it from its own master. +/// Master shapes used to be remembered by shape id alone, so a title master reusing the main +/// master's shape id (here 1026, red instead of the scheme's green) replaced it for every slide. +#[test] +fn a_master_shape_id_is_looked_up_in_the_slides_own_master() { + let red = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 1026, 0xA00), fopt(&[(prop::FILL_COLOR, 0x0000_00FF), (prop::FILL_BOOLS, 0x0010_0010)]), anchor(0, 0, 100, 100)], + ); + let title_master = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[red])]); + let inheriting = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), fopt(&[(prop::HSP_MASTER, 1026)]), anchor(0, 0, 100, 100)]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[inheriting])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, Some(title_master)); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides[0].shapes[0].fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xCC, 0))))); +} + +/// A run's shadow bit (TextCFException fontStyle bit 4) gives the run a shadow in the colour +/// scheme's shadow colour (grey in the test scheme). It used to be read and then dropped. +#[test] +fn a_shadowed_run_keeps_its_shadow() { + let mut style = vec![]; + style.extend_from_slice(&7u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, false)); + for (n, shadow) in [(3u32, true), (4, false)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&0x10u32.to_le_bytes()); // mask: shadow + style.extend_from_slice(&(if shadow { 0x10u16 } else { 0 }).to_le_bytes()); + } + let tb = container( + rt::SP_CONTAINER, + 0, + &[fsp(202, 2049, 0xA00), anchor(0, 0, 1000, 1000), text_box(4, "Hi you", &[atom(rt::STYLE_TEXT_PROP, 0, &style)])], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[tb])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs; + assert_eq!(runs[0].text, "Hi "); + let shadow = runs[0].props.shadow.as_ref().expect("the first run is shadowed"); + assert_eq!(shadow.color, craft_pptx::ColorRef::rgb(Rgba::rgb(0x80, 0x80, 0x80))); + assert!(runs[1].props.shadow.is_none()); +} + +/// `tests/fixtures/old-talk.pps`: a one-slide `.pps` built here from records, for applications' +/// tests that need real 97–2003 bytes (DeckCraft's show-on-open test). Run this test with +/// `CRAFT_WRITE_PPT_FIXTURE=1` to rebuild the file after changing the builders. +#[test] +fn the_pps_fixture_is_a_built_presentation() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/old-talk.pps"); + if std::env::var_os("CRAFT_WRITE_PPT_FIXTURE").is_some() { + let title = + container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Old talk", &[])]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None); + std::fs::write(path, build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + } + let p = import(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!(p.slides.len(), 1); + assert!(!p.slides[0].hidden); + let title = p.slides[0].shapes[0].text.as_ref().unwrap(); + assert_eq!(title.paragraphs[0].runs[0].text, "Old talk"); +} + +/// A placeholder whose client text box holds only an `OutlineTextRefAtom` takes its text and +/// formatting from that block of the slide list ([MS-PPT] OfficeArtClientTextbox allows the +/// reference alone). A text box that also has a header but no characters falls back the same way. +#[test] +fn placeholder_text_can_come_from_the_slide_list() { + let mut style = vec![]; + style.extend_from_slice(&7u32.to_le_bytes()); // the text and its closing paragraph mark + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(1, false)); + for (n, bold) in [(2u32, true), (5, false)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&cf_bytes(bold, 0, 40, [0x12, 0x34, 0x56])); + } + let outline = [ + atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()), + atom(rt::TEXT_CHARS, 0, &utf16("Hi all")), + atom(rt::STYLE_TEXT_PROP, 0, &style), + atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), + atom(rt::TEXT_CHARS, 0, &utf16("Second block")), + ]; + let reference = |n: u32| atom(rt::OUTLINE_TEXT_REF, 0, &n.to_le_bytes()); + let only_ref = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), container(rt::CLIENT_TEXTBOX, 0, &[reference(0)])], + ); + let header_and_ref = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 2050, 0xA00), + anchor(1300, 500, 5260, 3000), + placeholder(0x0E), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), reference(1)]), + ], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[only_ref, header_and_ref])]); + let (cu, doc, pics) = streams_with_outline(0xE391_C05F, 1, slide, None, &outline); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let shapes = &p.slides[0].shapes; + let title = shapes[0].text.as_ref().expect("the title has the outline text"); + let runs = &title.paragraphs[0].runs; + assert_eq!((runs[0].text.as_str(), runs[0].props.bold), ("Hi", Some(true))); + assert_eq!((runs[1].text.as_str(), runs[1].props.bold), (" all", Some(false))); + assert_eq!(runs[0].props.size, Some(40.0)); + assert_eq!(title.paragraphs[0].props.align, Some(Align::Center)); + let body = shapes[1].text.as_ref().expect("the body has the second block"); + assert_eq!(body.paragraphs[0].runs[0].text, "Second block"); +} + +/// The newest edit wins: a later edit's persist directory that gives the slide's persist id a new +/// slide replaces the old one. +#[test] +fn a_later_edit_replaces_a_slide() { + let (_, mut stream, pics) = streams(0xE391_C05F); + let first_edit = stream.len() as u32 - 36; // the test document's UserEditAtom (8 + 28 bytes) + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Edited", &[])]); + let slide_at = stream.len() as u32; + stream.extend_from_slice(&container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])])); + // Persist id 3 (the slide) only. + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[3 | (1 << 20), slide_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs[0].text, "Edited"); + // The master, from the first edit's directory, is still there. + assert_eq!(p.masters.len(), 1); +} + +/// An edit whose "previous edit" points back at itself cuts the older edits off the chain, and +/// with them the document, master and notes (storytold/deckcraft#1137 review: such a file opened as an empty deck). +/// Every edit in the stream is read instead, the newest still winning. +#[test] +fn a_broken_edit_chain_is_recovered_from_every_edit() { + let (_, mut stream, pics) = streams(0xE391_C05F); + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Edited", &[])]); + let slide_at = stream.len() as u32; + stream.extend_from_slice(&container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])])); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[3 | (1 << 20), slide_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, edit_at, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let (p, lost) = import_checked(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs[0].text, "Edited"); + assert_eq!(p.masters.len(), 1); + assert!(lost.is_empty(), "{lost:?}"); +} + +/// A slide the list names but whose object is gone is reported as lost, so an application can +/// say so instead of opening a deck that silently misses it. +#[test] +fn a_slide_without_its_object_is_reported_lost() { + let (cu, mut stream, pics) = streams(0xE391_C05F); + // The persist directory (ids 1–4: document, master, slide, notes) ends just before the + // 36-byte edit; point the slide's entry past the end of the stream. + let slide_entry = stream.len() - 36 - 8; + stream[slide_entry..slide_entry + 4].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)]); + let (p, lost) = import_checked(&bytes).unwrap(); + assert!(p.slides.is_empty()); + assert_eq!(lost, vec![format!("slide {SLIDE_ID}")]); +} + +/// Two more signs of an encrypted file besides the Current User token: an edit record long enough +/// to hold `encryptSessionPersistIdRef`, and a `CryptSession` object in the persist directory. +#[test] +fn encryption_is_found_in_the_edit_and_the_persist_directory() { + let open = |doc: &[u8], pics: &[u8]| { + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, doc.len() as u32 - 36, 0, 0])); + import(&build(&[("Current User", &cu), ("PowerPoint Document", doc), ("Pictures", pics)])) + }; + let (_, stream, pics) = streams(0xE391_C05F); + assert!(open(&stream, &pics).is_ok()); + // The edit record with a fifth reference: 28 bytes become 32. The Current User points at the + // new last record, 40 bytes from the end. + let mut long_edit = stream.clone(); + let edit_at = long_edit.len() - 36; + long_edit.truncate(edit_at); + let mut edit = le32(&[0, 0x0300_03F4, 0, 0, 1, 5]); + edit[12..16].copy_from_slice(&stream[edit_at + 8 + 12..edit_at + 8 + 16]); // offsetPersistDirectory + edit.extend_from_slice(&[0; 4]); + edit.extend_from_slice(&6u32.to_le_bytes()); // encryptSessionPersistIdRef + long_edit.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at as u32, 0, 0])); + let r = import(&build(&[("Current User", &cu), ("PowerPoint Document", &long_edit), ("Pictures", &pics)])); + assert!(matches!(r, Err(crate::PptError::Encrypted)), "{:?}", r.err()); + // A CryptSession container given a persist id by a later edit. + let mut crypt = stream.clone(); + let first_edit = crypt.len() as u32 - 36; + let session_at = crypt.len() as u32; + crypt.extend_from_slice(&container(rt::CRYPT_SESSION, 0, &[atom(0x0FFF, 0, &[0; 8])])); + let dir_at = crypt.len() as u32; + crypt.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[9 | (1 << 20), session_at]))); + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 9]); + edit.extend_from_slice(&[0; 4]); + crypt.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + assert!(matches!(open(&crypt, &pics), Err(crate::PptError::Encrypted))); +} + +/// A colour scheme record whose fill colour (index 4) is `fill`, the rest as the test master's. +fn scheme_with_fill(fill: [u8; 3]) -> Vec { + let mut colors: Vec = [0xFFFFFFu32, 0x000000, 0x808080, 0x000099, 0, 0x0000FF, 0x00FF00, 0xFF0000] + .iter() + .flat_map(|c| [(c >> 16) as u8, (c >> 8) as u8, *c as u8, 0]) + .collect(); + colors[16..19].copy_from_slice(&fill); + atom(rt::COLOR_SCHEME, 1, &colors) +} + +/// A shape filled with the scheme's fill colour. +fn scheme_filled(spid: u32) -> Vec { + container( + rt::SP_CONTAINER, + 0, + &[fsp(1, spid, 0xA00), fopt(&[(prop::FILL_COLOR, 0x0800_0004), (prop::FILL_BOOLS, 0x0010_0010)]), anchor(0, 0, 100, 100)], + ) +} + +/// A title master becomes a layout of its main master, with its own background and shapes, and +/// without the master's shapes when it doesn't follow them. A slide of the title master uses that +/// layout. A slide that follows nothing keeps its own background and scheme and hides the +/// master's shapes. +#[test] +fn title_masters_and_slides_that_dont_follow_the_master() { + let title_master = + container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x0), drawing(Some(solid_background(0x0000_FF00)), &[scheme_filled(3000)])]); + let on_title = container(rt::SLIDE, 0, &[slide_atom(0, TITLE_MASTER_ID, 0x7), drawing(None, &[])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, on_title, Some(title_master)); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let (_, layout) = p.layout(p.slides[0].layout).unwrap(); + assert_eq!(layout.name, "Title Master"); + assert_eq!(layout.background, Some(Background::Fill { fill: Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xFF, 0))) })); + assert!(!layout.show_master_shapes); + assert!(layout.shapes.iter().any(|sh| sh.ph.is_none()), "the title master's own shape"); + assert_eq!(p.slides[0].background, None, "the slide follows its master's background"); + + let alone = container( + rt::SLIDE, + 0, + &[slide_atom(1, MASTER_ID, 0x0), scheme_with_fill([0x11, 0x22, 0xCC]), drawing(Some(solid_background(0x0000_00FF)), &[scheme_filled(2049)])], + ); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, alone, None); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let s = &p.slides[0]; + assert_eq!(s.background, Some(Background::Fill { fill: Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0xFF, 0, 0))) })); + assert!(!s.show_master_shapes); + assert_eq!(s.shapes[0].fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0x11, 0x22, 0xCC)))), "the slide's own scheme"); +} + +fn open_streams((cu, doc, pics): (Vec, Vec, Vec)) -> Presentation { + import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap() +} + +/// A picture frame that says nothing about its fill or line draws neither (storytold/deckcraft#1137 review): the +/// drawing defaults' fill would cover a picture's transparent parts, or an OLE chart's preview. +#[test] +fn a_picture_frame_has_no_fill_or_line_of_its_own() { + let p = import(&file()).unwrap(); + let picture = &p.slides[0].shapes[1]; + assert!(matches!(picture.kind, ShapeKind::Picture { .. })); + assert_eq!(picture.fill, Some(Fill::None)); + assert_eq!(picture.line.as_ref().map(|l| l.fill.clone()), Some(Some(Fill::None))); +} + +/// A picture fill whose blip is held in the shape's own `fillBlip` property (complex, with fBid), +/// as table cells with a picture have it (storytold/deckcraft#1137 review), shows that picture. +#[test] +fn a_picture_held_in_the_fill_property_is_read() { + let blip = atom(0xF01E, 0x6E0, &[&[0u8; 17][..], &png()].concat()); + let mut entries = vec![]; + for (id, op) in [(prop::FILL_TYPE, 3u32), (0xC000 | prop::FILL_BLIP, blip.len() as u32), (prop::FILL_BOOLS, 0x0010_0010)] { + entries.extend_from_slice(&id.to_le_bytes()); + entries.extend_from_slice(&op.to_le_bytes()); + } + entries.extend_from_slice(&blip); + let cell = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), atom(rt::FOPT, 3, &entries), anchor(400, 500, 2000, 1200)]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[cell])]); + let p = open_streams(streams_of(0xE391_C05F, 1, slide, None)); + let Some(Fill::Picture(fill)) = &p.slides[0].shapes[0].fill else { panic!("{:?}", p.slides[0].shapes[0].fill) }; + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert!(media.data.starts_with(b"\x89PNG")); +} + +/// The headers and footers the document sets for its slides (storytold/deckcraft#1137 review: the date, footer and +/// slide number were missing) become the slide's footer placeholders, placed and styled as the +/// master's are on every layout. +#[test] +fn headers_and_footers_become_footer_placeholders() { + let cstring = |instance: u16, s: &str| atom(rt::CSTRING, instance, &utf16(s)); + // fHasDate | fHasUserDate | fHasSlideNumber | fHasFooter. The footer string ends in a NUL, as + // some writers add one: the text stops there. + let flags: u16 = 0x01 | 0x04 | 0x08 | 0x20; + let hf = container( + rt::HEADERS_FOOTERS, + 3, + &[ + atom(rt::HEADERS_FOOTERS_ATOM, 0, &[&0u16.to_le_bytes()[..], &flags.to_le_bytes()].concat()), + cstring(0, "26 May 2004"), + cstring(2, "Workshop\0"), + ], + ); + // The master's slide number placeholder: bottom right, right-aligned 10 pt text. + let mut style = vec![]; + style.extend_from_slice(&2u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(2, false)); + style.extend_from_slice(&2u32.to_le_bytes()); + style.extend_from_slice(&cf_bytes(false, 0, 10, [1, 2, 3])); + let number = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 1030, 0xA00), anchor(4000, 5000, 5700, 4300), placeholder(0x08), text_box(4, "*", &[atom(rt::STYLE_TEXT_PROP, 0, &style)])], + ); + let p = open_streams(streams_with_document(0xE391_C05F, 1, master_with(&[number]), slide(), None, &[], &[hf])); + let shapes = &p.slides[0].shapes; + let of = |k: PhType| shapes.iter().find(|s| s.ph_type() == Some(k)).unwrap_or_else(|| panic!("no {k:?}")); + assert_eq!(of(PhType::Date).text.as_ref().unwrap().text(), "26 May 2004"); + assert_eq!(of(PhType::Footer).text.as_ref().unwrap().text(), "Workshop"); + let runs = &of(PhType::SlideNum).text.as_ref().unwrap().paragraphs[0].runs; + assert!(matches!(&runs[0].kind, RunKind::Field { field } if field == "slidenum")); + assert!(p.header_footer.slide_number && p.header_footer.footer && p.header_footer.date); + // Every layout's slide number sits where the master's does, with its look. + let master = &p.masters[0]; + for l in &master.layouts { + let n = l.shapes.iter().find(|s| s.ph_type() == Some(PhType::SlideNum)).unwrap_or_else(|| panic!("no slide number on {}", l.name)); + let x = n.xfrm.unwrap(); + assert_eq!((x.x, x.y), (5000.0 / 8.0, 4000.0 / 8.0), "{}", l.name); + let level = n.text.as_ref().unwrap().list_style.level(0).unwrap(); + assert_eq!((level.para.align, level.run.size), (Some(Align::Right), Some(10.0))); + } +} + +/// Numbered paragraphs (storytold/deckcraft#1137 review: drawn with the bullet character) take their numbering from +/// the document's `___PPT9` tag: the slide's outline block of that text type, and the entry the +/// run's `pp9rt` names. The tag's name ends in a NUL here, as some writers add one. +#[test] +fn outline_numbering_from_the_ppt9_tag() { + // Entry 0: nothing. Entry 1: numbered, "1." (scheme 3), from 4. + let mut prop9 = vec![0u8; 12]; + prop9.extend_from_slice(&0x0300_0000u32.to_le_bytes()); + prop9.extend_from_slice(&1u16.to_le_bytes()); + prop9.extend_from_slice(&3u16.to_le_bytes()); + prop9.extend_from_slice(&4i16.to_le_bytes()); + prop9.extend_from_slice(&[0; 8]); + let tag_data = [atom(rt::OUTLINE_TEXT_PROPS_HEADER, 1, &le32(&[SLIDE_ID, 1])), atom(rt::STYLE_TEXT_PROP9, 0, &prop9)]; + let tag = container( + rt::PROG_BINARY_TAG, + 0, + &[atom(rt::CSTRING, 0, &utf16("___PPT9\0")), atom(rt::BINARY_TAG_DATA, 0, &container(rt::OUTLINE_TEXT_PROPS9, 0, &tag_data))], + ); + let list = container(rt::LIST, 0, &[container(rt::PROG_TAGS, 0, &[tag])]); + // Two bulleted paragraphs: the second's run names entry 1 (pp9rt in fontStyle bits 10–13). + let pp9rt = |i: u16| [&0x0000_0400u32.to_le_bytes()[..], &(i << 10).to_le_bytes()].concat(); + let mut style = vec![]; + style.extend_from_slice(&8u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, true)); + for (n, i) in [(4u32, 0u16), (4, 1)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&pp9rt(i)); + } + let outline = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("One\rTwo")), atom(rt::STYLE_TEXT_PROP, 0, &style)]; + let body = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 2049, 0xA00), + anchor(1300, 500, 5260, 3000), + placeholder(0x0E), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes())]), + ], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[body])]); + let p = open_streams(streams_with_document(0xE391_C05F, 1, master(), slide, None, &outline, &[list])); + let paras = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs; + assert!(matches!(paras[0].props.bullet, Some(Bullet::Char { .. })), "{:?}", paras[0].props.bullet); + assert_eq!(paras[1].props.bullet, Some(Bullet::AutoNum { scheme: "arabicPeriod".into(), start_at: 4 })); +} + +/// An outline block is one shape's text. A second shape pointing at the same block keeps its own +/// (here none), so a hostile file can't copy one big block into every shape of the slide. +#[test] +fn an_outline_block_is_used_by_one_shape() { + let outline = [atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("Shared"))]; + let referring = |spid: u32| { + container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, spid, 0xA00), + anchor(400, 500, 5260, 1200), + placeholder(0x0D), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes())]), + ], + ) + }; + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[referring(2049), referring(2050)])]); + let p = open_streams(streams_with_outline(0xE391_C05F, 1, slide, None, &outline)); + let texts: Vec = p.slides[0].shapes.iter().map(|s| s.text.as_ref().unwrap().text()).collect(); + assert_eq!(texts, ["Shared", ""]); +} + +fn open_plain((cu, doc, pics): (Vec, Vec, Vec)) -> Presentation { + crate::import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]), &craft_pptx::Plain).unwrap() +} + +/// A footer-only `HeadersFootersContainer` of `instance` with `footer` as its text. +fn footer_record(instance: u16, footer: &str) -> Vec { + container( + rt::HEADERS_FOOTERS, + instance, + &[atom(rt::HEADERS_FOOTERS_ATOM, 0, &[&0u16.to_le_bytes()[..], &0x20u16.to_le_bytes()].concat()), atom(rt::CSTRING, 2, &utf16(footer))], + ) +} + +/// A slide's own headers and footers (`PerSlideHeadersFootersContainer`, instance 0) win over the +/// document's for every slide (instance 3). Only the document's used to be looked for. +#[test] +fn a_slides_own_footer_wins_over_the_documents() { + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[]), footer_record(0, "This slide")]); + let p = open_streams(streams_with_document(0xE391_C05F, 1, master(), slide, None, &[], &[footer_record(3, "Every slide")])); + let footer = p.slides[0].shapes.iter().find(|s| s.ph_type() == Some(PhType::Footer)).expect("a footer"); + assert_eq!(footer.text.as_ref().unwrap().text(), "This slide"); + assert_eq!(p.header_footer.footer_text, "Every slide"); +} + +/// A text box that points at an outline block keeps its own `TextRulerAtom`: the margin it sets +/// (one inch at level 1) wins over the block's. It used to be dropped with the reference. +#[test] +fn a_text_boxs_own_ruler_applies_to_its_outline_text() { + let outline = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("Indented"))]; + let ruler = atom(rt::TEXT_RULER, 0, &[&(1u32 << 3).to_le_bytes()[..], &576u16.to_le_bytes()].concat()); + let body = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 2049, 0xA00), + anchor(1300, 500, 5260, 3000), + placeholder(0x0E), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes()), ruler]), + ], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[body])]); + let p = open_streams(streams_with_outline(0xE391_C05F, 1, slide, None, &outline)); + let t = p.slides[0].shapes[0].text.as_ref().unwrap(); + assert_eq!(t.text(), "Indented"); + assert_eq!(t.paragraphs[0].props.margin_left, Some(72.0)); +} + +/// A slide list entry whose object isn't a slide (here the notes page) is a lost slide, not a +/// slide silently left out. +#[test] +fn a_slide_entry_naming_another_object_is_reported_lost() { + let (cu, mut stream, pics) = streams(0xE391_C05F); + // The persist directory's last two entries (the slide's, then the notes page's) end just + // before the 36-byte edit: point the slide's at the notes page. + let end = stream.len() - 36; + let notes_at: [u8; 4] = stream[end - 4..end].try_into().unwrap(); + stream[end - 8..end - 4].copy_from_slice(¬es_at); + let (p, lost) = import_checked(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert!(p.slides.is_empty()); + assert_eq!(lost, vec![format!("slide {SLIDE_ID}")]); +} + +/// A title master with a centred title and a subtitle placeholder, `extra` shapes after them. +fn title_master_with(extra: &[Vec]) -> Vec { + let ph = + |spid: u32, kind: u8, a: [i16; 4]| container(rt::SP_CONTAINER, 0, &[fsp(1, spid, 0xA00), anchor(a[0], a[1], a[2], a[3]), placeholder(kind)]); + let shapes = [vec![ph(3001, 0x0F, [1000, 600, 5160, 2000]), ph(3002, 0x10, [2200, 1200, 4540, 3200])], extra.to_vec()].concat(); + container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &shapes)]) +} + +/// The first "Title Master" layout of `p`'s first master. +fn title_layout(p: &Presentation) -> &Layout { + p.masters[0].layouts.iter().find(|l| l.name == "Title Master").expect("the title master's layout") +} + +/// A title master's placeholders place its layout's, as a main master's place the master's: the +/// title takes its box, and the subtitle the default title layout lacks is added. With the plain +/// defaults (no placeholders at all) both are added. +#[test] +fn a_title_masters_placeholders_place_its_layouts() { + let boxes = |l: &Layout| { + let at = |f: &dyn Fn(PhType) -> bool| { + let x = l.shapes.iter().find(|s| s.ph_type().is_some_and(f)).and_then(|s| s.xfrm).unwrap_or_else(|| panic!("{:?}", l.shapes)); + (x.x, x.y, x.w, x.h) + }; + (at(&|t| matches!(t, PhType::Title | PhType::CtrTitle)), at(&|t| t == PhType::SubTitle)) + }; + let expected = ((75.0, 125.0, 570.0, 125.0), (150.0, 275.0, 417.5, 125.0)); + let p = open_streams(streams_of(0xE391_C05F, 1, slide(), Some(title_master_with(&[])))); + assert_eq!(boxes(title_layout(&p)), expected); + let p = open_plain(streams_of(0xE391_C05F, 1, slide(), Some(title_master_with(&[])))); + assert_eq!(boxes(title_layout(&p)), expected); +} + +/// A second title master's layout takes nothing from the first title master's layout: not its own +/// shapes, and not its placeholders or their boxes. With the plain defaults (no title layout of +/// theirs) it holds only its own placeholder, where it puts it. +#[test] +fn a_second_title_master_doesnt_copy_the_firsts_shapes() { + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 4001, 0xA00), anchor(200, 400, 2000, 800), placeholder(0x0F)]); + let second = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[title])]); + let p = + open_plain(streams_with_title_masters(0xE391_C05F, 1, master(), slide(), vec![title_master_with(&[scheme_filled(3003)]), second], &[], &[])); + let layouts: Vec<&Layout> = p.masters[0].layouts.iter().filter(|l| l.name == "Title Master").collect(); + assert_eq!(layouts.len(), 2); + assert_eq!(layouts[0].shapes.iter().filter(|s| s.ph.is_none()).count(), 1); + assert_eq!(layouts[1].shapes.len(), 1, "only its own placeholder: {:?}", layouts[1].shapes); + let x = layouts[1].shapes[0].xfrm.unwrap(); + assert_eq!((layouts[1].shapes[0].ph_type(), x.x, x.y, x.w, x.h), (Some(PhType::CtrTitle), 50.0, 25.0, 200.0, 75.0)); +} + +/// A title slide of the main master takes an ordinary layout, not the one made for a title +/// master: that one is for the slides that name the title master. +#[test] +fn a_title_masters_layout_is_only_for_its_own_slides() { + let on_main = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[])]); + let p = open_plain(streams_of(0xE391_C05F, 1, on_main, Some(title_master_with(&[])))); + let (_, layout) = p.layout(p.slides[0].layout).unwrap(); + assert_eq!(layout.name, "Blank"); +} + +/// When the edit chain is broken and the stream holds more edits than are read, the newest are the +/// ones read: here the newest edit replaces the slide, behind 4095 edits with no directory. +#[test] +fn a_broken_chain_reads_the_newest_edits() { + let (_, mut stream, pics) = streams(0xE391_C05F); + let first_edit = stream.len() - 36; + let offsets: Vec = + (0..4).map(|i| u32::from_le_bytes(stream[first_edit - 16 + 4 * i..first_edit - 12 + 4 * i].try_into().unwrap())).collect(); + // Edits that point at themselves and name the document as their directory. + let junk_at = stream.len() as u32; + for _ in 0..4095 { + let at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, at, 0, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + } + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Newest", &[])]); + let slide_at = stream.len() as u32; + stream.extend_from_slice(&container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])])); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[1 | (4 << 20), offsets[0], offsets[1], slide_at, offsets[3]]))); + let mut edit = le32(&[0, 0x0300_03F4, first_edit as u32, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, junk_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().text(), "Newest"); +} diff --git a/crates/ppt-binary/src/text.rs b/crates/ppt-binary/src/text.rs new file mode 100644 index 000000000..5c2be1e31 --- /dev/null +++ b/crates/ppt-binary/src/text.rs @@ -0,0 +1,755 @@ +//! Text in `.ppt` ([MS-PPT] §2.9): characters in a `TextCharsAtom` (UTF-16) or `TextBytesAtom` +//! (Latin-1), formatting as runs of paragraph exceptions (`TextPFException`) and character +//! exceptions (`TextCFException`) over the master's per-level text styles. + +use crate::doc::rt; +use crate::record::{Cursor, Rec}; + +/// A colour as text formatting stores it: an RGB value or an index into the colour scheme. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextColor { + Rgb(u8, u8, u8), + Scheme(u8), +} + +fn color_index(c: &mut Cursor) -> Option> { + let (r, g, b, i) = (c.u8()?, c.u8()?, c.u8()?, c.u8()?); + Some(match i { + 0xFE => Some(TextColor::Rgb(r, g, b)), + 0..=7 => Some(TextColor::Scheme(i)), + _ => None, + }) +} + +/// Paragraph formatting; `None` fields are not set at this level. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Pf { + pub has_bullet: Option, + pub bullet_has_font: Option, + pub bullet_has_color: Option, + pub bullet_has_size: Option, + pub bullet_char: Option, + pub bullet_font: Option, + /// Positive: percent of the text size; negative: absolute size in points. + pub bullet_size: Option, + pub bullet_color: Option, + /// 0 left, 1 centre, 2 right, 3 justify, 4 distributed, 5 Thai distributed, 6 justify low. + pub align: Option, + /// Positive: percent of a line; negative: master units (−8 per point). + pub line_spacing: Option, + pub space_before: Option, + pub space_after: Option, + /// Master units from the text box's left edge. + pub left_margin: Option, + pub indent: Option, + pub default_tab: Option, + pub tabs: Option>, +} + +impl Pf { + /// Overlay `o`'s set fields on this one. + pub fn apply(&mut self, o: &Pf) { + macro_rules! over { + ($($f:ident),*) => { $( if o.$f.is_some() { self.$f.clone_from(&o.$f); } )* }; + } + over!( + has_bullet, + bullet_has_font, + bullet_has_color, + bullet_has_size, + bullet_char, + bullet_font, + bullet_size, + bullet_color, + align, + line_spacing, + space_before, + space_after, + left_margin, + indent, + default_tab, + tabs + ); + } +} + +/// Character formatting; `None` fields are not set at this level. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Cf { + pub bold: Option, + pub italic: Option, + pub underline: Option, + pub shadow: Option, + pub font: Option, + pub ea_font: Option, + pub symbol_font: Option, + /// Points. + pub size: Option, + pub color: Option, + /// Superscript (positive) or subscript (negative) offset, percent of the size. + pub position: Option, + /// `pp9rt`: the index of the paragraph's PowerPoint 2000 formatting (numbering) in the text's + /// `StyleTextProp9Atom`. + pub pp9rt: Option, +} + +impl Cf { + pub fn apply(&mut self, o: &Cf) { + macro_rules! over { + ($($f:ident),*) => { $( if o.$f.is_some() { self.$f = o.$f; } )* }; + } + over!(bold, italic, underline, shadow, font, ea_font, symbol_font, size, color, position, pp9rt); + } +} + +fn bit(m: u32, b: u32) -> bool { + m & (1 << b) != 0 +} + +/// A `TextPFException`. +pub fn read_pf(c: &mut Cursor) -> Option { + let m = c.u32()?; + let mut pf = Pf::default(); + if m & 0xF != 0 { + let flags = c.u16()?; + for (b, slot) in [(0, &mut pf.has_bullet), (1, &mut pf.bullet_has_font), (2, &mut pf.bullet_has_color), (3, &mut pf.bullet_has_size)] { + if bit(m, b) { + *slot = Some(flags & (1 << b) != 0); + } + } + } + if bit(m, 7) { + pf.bullet_char = Some(c.u16()?); + } + if bit(m, 4) { + pf.bullet_font = Some(c.u16()?); + } + if bit(m, 6) { + pf.bullet_size = Some(c.i16()?); + } + if bit(m, 5) { + pf.bullet_color = color_index(c)?; + } + if bit(m, 11) { + pf.align = Some(c.u16()?); + } + if bit(m, 12) { + pf.line_spacing = Some(c.i16()?); + } + if bit(m, 13) { + pf.space_before = Some(c.i16()?); + } + if bit(m, 14) { + pf.space_after = Some(c.i16()?); + } + if bit(m, 8) { + pf.left_margin = Some(c.u16()?); + } + if bit(m, 10) { + pf.indent = Some(c.u16()?); + } + if bit(m, 15) { + pf.default_tab = Some(c.u16()?); + } + if bit(m, 20) { + pf.tabs = Some(read_tabs(c)?); + } + if bit(m, 16) { + c.u16()?; // fontAlign + } + if m & (0x7 << 17) != 0 { + c.u16()?; // wrapFlags + } + if bit(m, 21) { + c.u16()?; // textDirection + } + Some(pf) +} + +/// Tab stops kept per paragraph exception or ruler. Every entry is still read past, so the fields +/// after the list stay aligned; the rest are dropped, since each paragraph copies the list. +const MAX_TABS: usize = 64; + +fn read_tabs(c: &mut Cursor) -> Option> { + let n = c.u16()?; + let mut v = Vec::with_capacity(usize::from(n).min(MAX_TABS)); + for _ in 0..n { + let tab = (c.i16()?, c.u16()?); + if v.len() < MAX_TABS { + v.push(tab); + } + } + Some(v) +} + +/// A `TextCFException`. +pub fn read_cf(c: &mut Cursor) -> Option { + let m = c.u32()?; + let mut cf = Cf::default(); + // fontStyle is present when any of bold, italic, underline, shadow, fehint, kumi, emboss or + // fHasStyle is in the mask. + if m & 0x3EB7 != 0 { + let s = c.u16()?; + // Emboss (bit 9) has no counterpart in the model; docs/gaps.md lists it. + for (b, slot) in [(0, &mut cf.bold), (1, &mut cf.italic), (2, &mut cf.underline), (4, &mut cf.shadow)] { + if bit(m, b) { + *slot = Some(s & (1 << b) != 0); + } + } + // fHasStyle (bits 10–13) says pp9rt, the same four bits of fontStyle, is given. + if m & 0x3C00 != 0 { + cf.pp9rt = Some(((s >> 10) & 0xF) as u8); + } + } + if bit(m, 16) { + cf.font = Some(c.u16()?); + } + if bit(m, 21) { + cf.ea_font = Some(c.u16()?); + } + if bit(m, 22) { + c.u16()?; // ansiFontRef + } + if bit(m, 23) { + cf.symbol_font = Some(c.u16()?); + } + if bit(m, 17) { + cf.size = Some(c.u16()?); + } + if bit(m, 18) { + cf.color = color_index(c)?; + } + if bit(m, 19) { + cf.position = Some(c.i16()?); + } + // The fields PowerPoint 2002 and later add are not used, but they must be read past: the next + // run's count and mask follow them, so stopping short garbles every later run's formatting. + if bit(m, 20) { + c.u32()?; // pp10runid (4 bits) and unused (28 bits) + } + if bit(m, 24) { + c.u16()?; // newEAFontRef + } + if bit(m, 25) { + c.u16()?; // csFontRef + } + if bit(m, 26) { + c.u32()?; // pp11ext + } + Some(cf) +} + +/// A paragraph's PowerPoint 2000 formatting (`TextPFException9`): its automatic numbering. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Pf9 { + /// `fBulletHasAutoNumber` with `bulletAutoNumberScheme`: the scheme and the first number. + pub auto_number: Option<(u16, i16)>, +} + +/// The entries of a `StyleTextProp9Atom` ([MS-PPT] §2.9.33): each a `TextPFException9`, a +/// `TextCFException9` and a `TextSIException`, indexed by the runs' `pp9rt`. Reading stops at an +/// entry with a field this reader can't size, keeping the entries before it. +pub fn read_style9(b: &[u8]) -> Vec { + let mut c = Cursor::new(b); + let mut out = vec![]; + // pp9rt has four bits, so sixteen entries are all a run can name. + while out.len() < 16 && c.remaining() > 0 { + let Some(pf9) = read_pf9(&mut c) else { break }; + out.push(pf9); + // TextCFException9: the extension fields of a character mask. + let Some(m) = c.u32() else { break }; + if m & !((1 << 20) | (1 << 24) | (1 << 25) | (1 << 26)) != 0 { + break; + } + let ok = (!bit(m, 20) || c.u32().is_some()) + && (!bit(m, 24) || c.u16().is_some()) + && (!bit(m, 25) || c.u16().is_some()) + && (!bit(m, 26) || c.u32().is_some()); + // TextSIException: spelling, language, alternate language, bidi, pp10 extension, smart tags. + if !ok || read_si(&mut c).is_none() { + break; + } + } + out +} + +fn read_pf9(c: &mut Cursor) -> Option { + let m = c.u32()?; + if bit(m, 23) { + c.i16()?; // bulletBlipRef + } + let has_auto = if bit(m, 25) { Some(c.u16()? != 0) } else { None }; + let scheme = if bit(m, 24) { Some((c.u16()?, c.i16()?)) } else { None }; + if bit(m, 26) { + c.u32()?; // pp10 extension + } + Some(Pf9 { auto_number: if has_auto == Some(true) { Some(scheme.unwrap_or((3, 1))) } else { None } }) +} + +fn read_si(c: &mut Cursor) -> Option<()> { + let m = c.u32()?; + if m & !0x027F != 0 { + return None; + } + for b in [0, 1, 2, 6] { + if bit(m, b) { + c.u16()?; + } + } + if bit(m, 5) { + c.u32()?; // pp10runid and reserved + } + if bit(m, 9) { + let n = c.u32()?; + for _ in 0..n { + c.u32()?; + } + } + Some(()) +} + +/// The DrawingML numbering scheme of a `TextAutoNumberSchemeEnum` value. +pub fn auto_number_scheme(v: u16) -> &'static str { + match v { + 0 => "alphaLcPeriod", + 1 => "alphaUcPeriod", + 2 => "arabicParenR", + 4 => "romanLcParenBoth", + 5 => "romanLcParenR", + 6 => "romanLcPeriod", + 7 => "romanUcPeriod", + 8 => "alphaLcParenBoth", + 9 => "alphaLcParenR", + 10 => "alphaUcParenBoth", + 11 => "alphaUcParenR", + 12 => "arabicParenBoth", + 13 => "arabicPlain", + 14 => "romanUcParenBoth", + 15 => "romanUcParenR", + 0x10 => "ea1ChsPlain", + 0x11 => "ea1ChsPeriod", + 0x12 => "circleNumDbPlain", + 0x13 => "circleNumWdWhitePlain", + 0x14 => "circleNumWdBlackPlain", + 0x15 => "ea1ChtPlain", + 0x16 => "ea1ChtPeriod", + 0x17 => "arabic1Minus", + 0x18 => "arabic2Minus", + 0x19 => "hebrew2Minus", + 0x1A => "ea1JpnKorPlain", + 0x1B => "ea1JpnKorPeriod", + 0x1C => "arabicDbPlain", + 0x1D => "arabicDbPeriod", + 0x1E => "thaiAlphaPeriod", + 0x1F => "thaiAlphaParenR", + 0x20 => "thaiAlphaParenBoth", + 0x21 => "thaiNumPeriod", + 0x22 => "thaiNumParenR", + 0x23 => "thaiNumParenBoth", + 0x24 => "hindiAlphaPeriod", + 0x25 => "hindiNumPeriod", + 0x26 => "ea1JpnChsDbPeriod", + 0x27 => "hindiNumParenR", + 0x28 => "hindiAlpha1Period", + _ => "arabicPeriod", + } +} + +/// Text types (`TextHeaderAtom.textType`). +pub mod ty { + pub const TITLE: u32 = 0; + pub const BODY: u32 = 1; + pub const NOTES: u32 = 2; + pub const OTHER: u32 = 4; + pub const CENTER_BODY: u32 = 5; + pub const CENTER_TITLE: u32 = 6; + pub const HALF_BODY: u32 = 7; + pub const QUARTER_BODY: u32 = 8; +} + +/// One master text style: up to five levels of paragraph and character formatting. +#[derive(Clone, Debug, Default)] +pub struct LevelStyles { + pub levels: Vec<(Pf, Cf)>, +} + +/// A `TextMasterStyleAtom` body. +pub fn read_master_style(r: &Rec) -> LevelStyles { + let mut c = Cursor::new(r.data); + let mut out = LevelStyles::default(); + let Some(n) = c.u16() else { return out }; + for i in 0..usize::from(n.min(5)) { + // From the centre-body type on, each level names itself (TextMasterStyleLevel.level). + let level = if u32::from(r.instance) >= ty::CENTER_BODY { + let Some(l) = c.u16() else { break }; + usize::from(l) + } else { + i + }; + let Some(pf) = read_pf(&mut c) else { break }; + let Some(cf) = read_cf(&mut c) else { break }; + // Only five levels exist; one naming another is read past. + if level >= 5 { + continue; + } + if out.levels.len() <= level { + out.levels.resize(level + 1, Default::default()); + } + if let Some(slot) = out.levels.get_mut(level) { + *slot = (pf, cf); + } + } + out +} + +/// The text styles in effect for a master: the document defaults plus the master's styles by text +/// type. +#[derive(Clone, Debug, Default)] +pub struct StyleSheet { + pub default_pf: Pf, + pub default_cf: Cf, + /// Indexed by text type (0–8). + pub types: Vec>, +} + +impl StyleSheet { + /// Read the defaults of the document environment and, over them, a master's styles. + pub fn new(environment: Option, master: Option<&Rec>) -> Self { + let mut s = StyleSheet { types: vec![None; 9], ..Default::default() }; + if let Some(env) = environment { + if let Some(pf) = env.child(rt::TEXT_PF_EXCEPTION).and_then(|r| read_pf(&mut Cursor { b: r.data, at: 2 })) { + s.default_pf = pf; + } + if let Some(cf) = env.child(rt::TEXT_CF_EXCEPTION).and_then(|r| read_cf(&mut Cursor::new(r.data))) { + s.default_cf = cf; + } + for r in env.children_of(rt::TEXT_MASTER_STYLE) { + if let Some(slot) = s.types.get_mut(usize::from(r.instance)) { + *slot = Some(read_master_style(&r)); + } + } + } + if let Some(m) = master { + for r in m.children_of(rt::TEXT_MASTER_STYLE) { + if let Some(slot) = s.types.get_mut(usize::from(r.instance)) { + *slot = Some(read_master_style(&r)); + } + } + } + s + } + + /// The formatting of text type `ty` at outline level `level`: defaults, then the base type's + /// level 1 and level, then this type's. + pub fn resolve(&self, ty: u32, level: u8) -> (Pf, Cf) { + let (mut pf, mut cf) = (self.default_pf.clone(), self.default_cf.clone()); + let base = match ty { + ty::CENTER_TITLE => Some(ty::TITLE), + ty::CENTER_BODY | ty::HALF_BODY | ty::QUARTER_BODY => Some(ty::BODY), + _ => None, + }; + for t in base.into_iter().chain(std::iter::once(ty)) { + let Some(Some(st)) = self.types.get(t as usize) else { continue }; + for l in [0usize, usize::from(level)] { + if let Some((p, c)) = st.levels.get(l) { + pf.apply(p); + cf.apply(c); + } + if level == 0 { + break; + } + } + } + (pf, cf) + } +} + +/// A field inside text: its character position and kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FieldKind { + SlideNumber, + DateTime, +} + +/// A block of text with its formatting runs. +#[derive(Clone, Debug, Default)] +pub struct TextBlock { + pub text_type: u32, + pub chars: Vec, + /// (character count, indent level, paragraph exception). + pub para_runs: Vec<(u32, u8, Pf)>, + /// (character count, character exception). + pub char_runs: Vec<(u32, Cf)>, + /// Ruler overrides per level: (left margin, indent) in master units. + pub ruler: [(Option, Option); 5], + pub fields: Vec<(u32, FieldKind)>, + /// An `OutlineTextRefAtom`: the text is the n-th outline block of the slide list entry. + pub outline_ref: Option, + /// The slide list's outline block this text was read from. + pub outline_index: Option, +} + +/// Read a text block from a run of records starting at its `TextHeaderAtom` (inside a client text +/// box, or in the slide list). Stops at the next header or slide persist atom. A client text box +/// may hold only an `OutlineTextRefAtom` ([MS-PPT] OfficeArtClientTextbox), with no header: that +/// is still a block, so the caller can follow the reference. +pub fn read_block<'a>(records: impl Iterator>) -> Option { + let mut b = TextBlock::default(); + let mut started = false; + let mut style: Option = None; + for r in records { + match r.kind { + rt::TEXT_HEADER if started => break, + rt::SLIDE_PERSIST_ATOM => break, + rt::TEXT_HEADER => { + started = true; + b.text_type = r.u32(0).unwrap_or(ty::OTHER); + } + rt::TEXT_CHARS => b.chars = r.data.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(), + rt::TEXT_BYTES => b.chars = r.data.iter().map(|&c| u16::from(c)).collect(), + rt::STYLE_TEXT_PROP => style = Some(r), + rt::TEXT_RULER => b.ruler = read_ruler(&r), + rt::OUTLINE_TEXT_REF => b.outline_ref = r.u32(0), + rt::SLIDE_NUMBER_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::SlideNumber))), + rt::DATETIME_MC | rt::GENERIC_DATE_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::DateTime))), + _ => {} + } + } + if !started && b.outline_ref.is_none() { + return None; + } + if let Some(st) = style { + // Text past u32::MAX characters can't be addressed by the runs; saturate rather than wrap. + read_style_runs(&st, u32::try_from(b.chars.len()).unwrap_or(u32::MAX).saturating_add(1), &mut b); + } + Some(b) +} + +/// The paragraph runs then the character runs of a `StyleTextPropAtom`; each set covers the text +/// plus one (the final paragraph mark). +fn read_style_runs(r: &Rec, total: u32, b: &mut TextBlock) { + let mut c = Cursor::new(r.data); + let mut covered = 0u32; + while covered < total { + let Some(n) = c.u32() else { return }; + let Some(level) = c.u16() else { return }; + let Some(pf) = read_pf(&mut c) else { return }; + b.para_runs.push((n, level.min(8) as u8, pf)); + covered = covered.saturating_add(n.max(1)); + } + covered = 0; + while covered < total { + let Some(n) = c.u32() else { return }; + let Some(cf) = read_cf(&mut c) else { return }; + b.char_runs.push((n, cf)); + covered = covered.saturating_add(n.max(1)); + } +} + +fn read_ruler(r: &Rec) -> [(Option, Option); 5] { + let mut out = [(None, None); 5]; + let mut c = Cursor::new(r.data); + let Some(m) = c.u32() else { return out }; + if bit(m, 1) && c.u16().is_none() { + return out; + } + if bit(m, 0) && c.u16().is_none() { + return out; + } + if bit(m, 2) && read_tabs(&mut c).is_none() { + return out; + } + for (l, slot) in out.iter_mut().enumerate() { + let l = l as u32; + if bit(m, 3 + l) { + slot.0 = c.u16(); + } + if bit(m, 8 + l) { + slot.1 = c.u16(); + } + } + out +} + +#[cfg(test)] +pub(crate) mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::build::*; + + /// A PF exception with alignment and bullets on or off. + pub fn pf_bytes(align: u16, bullet: bool) -> Vec { + let mut v = (0x0000_0801u32).to_le_bytes().to_vec(); // hasBullet + align + v.extend_from_slice(&u16::from(bullet).to_le_bytes()); + v.extend_from_slice(&align.to_le_bytes()); + v + } + + /// A CF exception with bold, a font, a size and an RGB colour. + pub fn cf_bytes(bold: bool, font: u16, size: u16, rgb: [u8; 3]) -> Vec { + let mut v = (0x0007_0001u32).to_le_bytes().to_vec(); // bold + typeface + size + color + v.extend_from_slice(&u16::from(bold).to_le_bytes()); + v.extend_from_slice(&font.to_le_bytes()); + v.extend_from_slice(&size.to_le_bytes()); + v.extend_from_slice(&[rgb[0], rgb[1], rgb[2], 0xFE]); + v + } + + /// The `StyleTextProp9Atom` entries as PowerPoint writes them: three, the second numbered "1." + /// from 1. Short or unknown data keeps the entries read before it. + #[test] + fn reads_numbering_entries() { + let mut b = vec![0u8; 12]; + b.extend_from_slice(&[0, 0, 0, 3, 1, 0, 3, 0, 1, 0]); + b.extend_from_slice(&[0; 8]); + b.extend_from_slice(&[0; 12]); + let e = read_style9(&b); + assert_eq!(e.iter().map(|p| p.auto_number).collect::>(), [None, Some((3, 1)), None]); + assert_eq!(read_style9(b.get(..20).unwrap()).len(), 1); + assert_eq!(read_style9(b.get(..22).unwrap()).len(), 2); + assert_eq!(read_style9(&[0xFF; 64]).len(), 1); + assert!(read_style9(&[]).is_empty()); + assert_eq!(auto_number_scheme(3), "arabicPeriod"); + assert_eq!(auto_number_scheme(0), "alphaLcPeriod"); + } + + /// The East Asian, bidi, Thai and Hindi schemes (0x10–0x28) have DrawingML names of their + /// own; only an unknown value falls back to "1.". + #[test] + fn every_numbering_scheme_has_its_drawingml_name() { + assert_eq!(auto_number_scheme(0x10), "ea1ChsPlain"); + assert_eq!(auto_number_scheme(0x13), "circleNumWdWhitePlain"); + assert_eq!(auto_number_scheme(0x19), "hebrew2Minus"); + assert_eq!(auto_number_scheme(0x26), "ea1JpnChsDbPeriod"); + assert_eq!(auto_number_scheme(0x28), "hindiAlpha1Period"); + let names: std::collections::HashSet<_> = (0..=0x28).map(auto_number_scheme).collect(); + assert_eq!(names.len(), 0x29, "each value its own scheme"); + assert_eq!(auto_number_scheme(0x29), "arabicPeriod"); + } + + /// From the centre-body type on, a master style level names its level: it is stored there, + /// and a level past the fifth is read past. + #[test] + fn master_style_levels_go_where_they_say() { + let level = |l: u16, size: u16| [&l.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, size, [0, 0, 0])].concat(); + let body = [&3u16.to_le_bytes()[..], &level(2, 20), &level(7, 30), &level(0, 40)].concat(); + let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::CENTER_BODY as u16, &body); + let st = read_master_style(&Rec::at(&rec, 0).unwrap()); + let sizes: Vec<_> = st.levels.iter().map(|(_, cf)| cf.size).collect(); + assert_eq!(sizes, [Some(40), None, Some(20)]); + // Before it, levels are in order. + let body = [&1u16.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, 12, [0, 0, 0])].concat(); + let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::BODY as u16, &body); + assert_eq!(read_master_style(&Rec::at(&rec, 0).unwrap()).levels[0].1.size, Some(12)); + } + + /// A paragraph exception with many tab stops keeps the first [`MAX_TABS`] and reads the + /// fields after the list where they are. + #[test] + fn tab_stops_are_capped_and_read_past() { + let mut b = ((1u32 << 20) | (1 << 21)).to_le_bytes().to_vec(); // tabStops + textDirection + b.extend_from_slice(&1000u16.to_le_bytes()); + for i in 0..1000u16 { + b.extend_from_slice(&(i as i16).to_le_bytes()); + b.extend_from_slice(&1u16.to_le_bytes()); + } + b.extend_from_slice(&0x1234u16.to_le_bytes()); // textDirection + b.push(0xAB); + let mut c = Cursor::new(&b); + let pf = read_pf(&mut c).unwrap(); + let tabs = pf.tabs.unwrap(); + assert_eq!(tabs.len(), MAX_TABS); + assert_eq!(tabs[MAX_TABS - 1], (MAX_TABS as i16 - 1, 1)); + assert_eq!(c.u8(), Some(0xAB), "the cursor stopped past textDirection"); + } + + #[test] + fn reads_exceptions_in_mask_order() { + let pf = read_pf(&mut Cursor::new(&pf_bytes(1, true))).unwrap(); + assert_eq!(pf.has_bullet, Some(true)); + assert_eq!(pf.align, Some(1)); + assert_eq!(pf.bullet_has_font, None); + let cf = read_cf(&mut Cursor::new(&cf_bytes(true, 3, 28, [1, 2, 3]))).unwrap(); + assert_eq!((cf.bold, cf.italic, cf.font, cf.size, cf.color), (Some(true), None, Some(3), Some(28), Some(TextColor::Rgb(1, 2, 3)))); + // A mask promising more than the bytes hold reads nothing. + assert!(read_cf(&mut Cursor::new(&0x0007_0000u32.to_le_bytes())).is_none()); + } + + #[test] + fn reads_a_text_block_with_runs() { + let chars: Vec = "Hi\rthere".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let mut style = vec![]; + for (n, lvl) in [(3u32, 0u16), (6, 1)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&lvl.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, lvl == 1)); + } + for n in [2u32, 7] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&cf_bytes(n == 2, 0, 20, [0, 0, 0])); + } + let recs = [ + atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), + atom(rt::TEXT_CHARS, 0, &chars), + atom(rt::STYLE_TEXT_PROP, 0, &style), + atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()), + ] + .concat(); + let b = read_block(crate::record::Records::new(&recs)).unwrap(); + assert_eq!(b.text_type, ty::BODY); + assert_eq!(String::from_utf16_lossy(&b.chars), "Hi\rthere"); + assert_eq!(b.para_runs.len(), 2); + assert_eq!(b.para_runs[1].1, 1); + assert_eq!(b.char_runs.len(), 2); + assert_eq!(b.char_runs[0].1.bold, Some(true)); + } + + /// A CF exception with only the fields PowerPoint 2002 and later add after `position`: + /// pp10runid (bit 20), newEAFontRef (bit 24), csFontRef (bit 25) and pp11ext (bit 26). + fn cf_later_fields() -> Vec { + let mut v = (1u32 << 20 | 1 << 24 | 1 << 25 | 1 << 26).to_le_bytes().to_vec(); + v.extend_from_slice(&0x0000_0003u32.to_le_bytes()); // pp10runid + unused + v.extend_from_slice(&7u16.to_le_bytes()); // newEAFontRef + v.extend_from_slice(&8u16.to_le_bytes()); // csFontRef + v.extend_from_slice(&0u32.to_le_bytes()); // pp11ext + v + } + + #[test] + fn later_character_fields_are_read_past() { + let bytes = cf_later_fields(); + let mut c = Cursor::new(&bytes); + assert!(read_cf(&mut c).is_some()); + assert!(c.u8().is_none(), "the cursor stopped inside the exception"); + + // A run carrying those fields, then a bold 18 pt run: the second must read as written. + let chars: Vec = "abcd".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let mut style = vec![]; + style.extend_from_slice(&5u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, false)); + style.extend_from_slice(&2u32.to_le_bytes()); + style.extend_from_slice(&cf_later_fields()); + style.extend_from_slice(&3u32.to_le_bytes()); + style.extend_from_slice(&cf_bytes(true, 1, 18, [0, 0, 0])); + let recs = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &chars), atom(rt::STYLE_TEXT_PROP, 0, &style)].concat(); + let b = read_block(crate::record::Records::new(&recs)).unwrap(); + assert_eq!(b.char_runs.len(), 2, "{:?}", b.char_runs); + let (n, cf) = &b.char_runs[1]; + assert_eq!((*n, cf.bold, cf.font, cf.size), (3, Some(true), Some(1), Some(18))); + } + + #[test] + fn styles_inherit_from_level_one_and_the_base_type() { + let mut s = StyleSheet { types: vec![None; 9], ..Default::default() }; + let lvl = |size: u16, align: u16| (Pf { align: Some(align), ..Default::default() }, Cf { size: Some(size), ..Default::default() }); + s.types[ty::BODY as usize] = Some(LevelStyles { levels: vec![lvl(32, 0), (Pf::default(), Cf { size: Some(28), ..Default::default() })] }); + s.types[ty::CENTER_BODY as usize] = Some(LevelStyles { levels: vec![(Pf { align: Some(1), ..Default::default() }, Cf::default())] }); + let (pf, cf) = s.resolve(ty::CENTER_BODY, 1); + assert_eq!(cf.size, Some(28)); + assert_eq!(pf.align, Some(1)); + let (pf, cf) = s.resolve(ty::BODY, 0); + assert_eq!((pf.align, cf.size), (Some(0), Some(32))); + } +} diff --git a/crates/ppt-binary/tests/fixtures/old-talk.pps b/crates/ppt-binary/tests/fixtures/old-talk.pps new file mode 100644 index 000000000..9c5d02004 Binary files /dev/null and b/crates/ppt-binary/tests/fixtures/old-talk.pps differ diff --git a/crates/psd/src/adjust.rs b/crates/psd/src/adjust.rs index f1f94dff7..7da9b5f03 100644 --- a/crates/psd/src/adjust.rs +++ b/crates/psd/src/adjust.rs @@ -11,6 +11,62 @@ use crate::error::Result; use crate::io::Reader; use crate::layer::LayerRecord; +/// Write the legacy brit block with raw signed brightness and contrast values. +/// +/// The seven-byte payload retains the reserved value 127 and legacy flag 0. +/// Values are not clamped or normalized; external tagged-block padding is not included. +pub fn brightness_contrast_block(brightness: i16, contrast: i16) -> crate::tagged::TaggedBlock { + let mut data = Vec::with_capacity(7); + for value in [brightness, contrast, 127] { + data.extend_from_slice(&value.to_be_bytes()); + } + data.push(0); + crate::tagged::TaggedBlock::new(*b"brit", data) +} + +/// Write the version-1 expA block without normalizing its raw floating-point values. +/// +/// All f32 bits, including NaN payloads and signed zero, are preserved in the +/// fourteen-byte payload. External tagged-block padding is not included. +pub fn exposure_block(exposure: f32, offset: f32, gamma: f32) -> crate::tagged::TaggedBlock { + let mut data = Vec::with_capacity(14); + data.extend_from_slice(&1u16.to_be_bytes()); + for value in [exposure, offset, gamma] { + data.extend_from_slice(&value.to_be_bytes()); + } + crate::tagged::TaggedBlock::new(*b"expA", data) +} + +/// Write a version-2 hue2 master adjustment from raw signed values. +/// +/// Colorize is off, its three values are zero, and all six unused 24-byte +/// color-range records are zero. The payload is exactly 160 bytes, without padding. +pub fn hue_saturation_block(hue: i16, saturation: i16, lightness: i16) -> crate::tagged::TaggedBlock { + let mut data = vec![0, 2, 0, 0]; + for value in [0i16, 0, 0, hue, saturation, lightness] { + data.extend_from_slice(&value.to_be_bytes()); + } + data.resize(160, 0); + crate::tagged::TaggedBlock::new(*b"hue2", data) +} + +/// Write a version-2 levl composite record followed by 28 default records. +/// +/// All fields are raw signed values; gamma_hundredths is already converted by +/// the caller. No clamping or normalization is applied. The payload is 292 bytes. +pub fn levels_block(in_black: i16, in_white: i16, out_black: i16, out_white: i16, gamma_hundredths: i16) -> crate::tagged::TaggedBlock { + let mut data = vec![0, 2]; + for value in [in_black, in_white, out_black, out_white, gamma_hundredths] { + data.extend_from_slice(&value.to_be_bytes()); + } + for _ in 0..28 { + for value in [0i16, 255, 0, 255, 100] { + data.extend_from_slice(&value.to_be_bytes()); + } + } + crate::tagged::TaggedBlock::new(*b"levl", data) +} + /// The adjustment a layer applies. #[derive(Clone, Debug, PartialEq)] pub enum Adjustment { @@ -182,6 +238,43 @@ mod tests { use crate::io::WriteExt; use crate::tagged::TaggedBlock; + #[test] + fn raw_adjustment_writers_preserve_exact_payloads() { + let block = brightness_contrast_block(i16::MIN, i16::MAX); + assert_eq!(block.key, *b"brit"); + assert_eq!(block.data, [0x80, 0, 0x7f, 0xff, 0, 0x7f, 0]); + assert_eq!(brightness_contrast_block(-1, 0).data, [0xff, 0xff, 0, 0, 0, 0x7f, 0]); + let block = exposure_block(0.0, -0.0, f32::INFINITY); + assert_eq!(block.key, *b"expA"); + assert_eq!(block.data, [0, 1, 0, 0, 0, 0, 0x80, 0, 0, 0, 0x7f, 0x80, 0, 0]); + assert_eq!( + exposure_block(f32::NEG_INFINITY, f32::from_bits(0x7fc1_2345), f32::from_bits(0xffc5_4321)).data, + [0, 1, 0xff, 0x80, 0, 0, 0x7f, 0xc1, 0x23, 0x45, 0xff, 0xc5, 0x43, 0x21] + ); + assert_eq!(exposure_block(1.0, -2.5, 0.125).data, [0, 1, 0x3f, 0x80, 0, 0, 0xc0, 0x20, 0, 0, 0x3e, 0, 0, 0]); + } + + #[test] + fn hue_and_levels_writers_preserve_complete_raw_records() { + let hue = hue_saturation_block(i16::MIN, i16::MAX, -1); + let mut expected = vec![0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0x7f, 0xff, 0xff, 0xff]; + expected.extend([0; 144]); + assert_eq!(hue.key, *b"hue2"); + assert_eq!(hue.data, expected); + let mut zero_hue = vec![0; 160]; + zero_hue[1] = 2; + assert_eq!(hue_saturation_block(0, 0, 0).data, zero_hue); + + let levels = levels_block(i16::MIN, i16::MAX, -1, 0, -13); + let mut expected = vec![0, 2, 0x80, 0, 0x7f, 0xff, 0xff, 0xff, 0, 0, 0xff, 0xf3]; + expected.extend([0, 0, 0, 255, 0, 0, 0, 255, 0, 100].repeat(28)); + assert_eq!(levels.key, *b"levl"); + assert_eq!(levels.data, expected); + let mut zeros = vec![0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + zeros.extend([0, 0, 0, 255, 0, 0, 0, 255, 0, 100].repeat(28)); + assert_eq!(levels_block(0, 0, 0, 0, 0).data, zeros); + } + fn layer(blocks: Vec<([u8; 4], Vec)>) -> LayerRecord { LayerRecord { blocks: blocks.into_iter().map(|(k, d)| TaggedBlock::new(k, d)).collect(), ..Default::default() } } diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index d43c8b3d3..06db52afd 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -7,6 +7,7 @@ use crate::error::{PsdError, Result}; use crate::io::{Reader, WriteExt, read_unicode_units, write_unicode_units}; +pub mod borrowed; mod lookup; /// Maximum nesting depth accepted when parsing (fuzz safety). diff --git a/crates/psd/src/descriptor/borrowed.rs b/crates/psd/src/descriptor/borrowed.rs new file mode 100644 index 000000000..cb718028f --- /dev/null +++ b/crates/psd/src/descriptor/borrowed.rs @@ -0,0 +1,449 @@ +//! Borrowed, iterative descriptor serialization into an existing output buffer. +//! +//! Views must be finite, stable and acyclic for the duration of serialization. +//! The first absent indexed item ends a container. Counts are derived from emitted +//! items (wrapping u32, like the owned writer), never supplied by a view. +//! Output growth plus O(depth) heap frames are the only proportional allocations. + +/// An identifier with its explicit wire encoding. +#[derive(Clone, Copy)] +pub enum IdRef<'a> { + /// Length zero followed by four bytes. + Code([u8; 4]), + /// Explicit byte length, even when four. + String(&'a [u8]), +} +/// A Unicode string without interpretation or normalization. +#[derive(Clone, Copy)] +pub enum UnicodeRef<'a> { + /// Encode UTF-8 and optionally append exactly one NUL. + Text(&'a str, bool), + /// Preserve UTF-16 units, including unpaired surrogates. + Units(&'a [u16]), +} +/// A borrowed class. +#[derive(Clone, Copy)] +pub struct ClassRef<'a> { + /// Display name. + pub name: UnicodeRef<'a>, + /// Class identifier. + pub id: IdRef<'a>, +} +/// A finite, stable, acyclic descriptor view. +pub trait DescriptorView { + /// Class metadata. + fn class(&self) -> ClassRef<'_>; + /// Indexed item; the first None terminates the container. + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)>; +} +/// A finite, stable, acyclic value sequence. +pub trait ValuesView { + /// Indexed value; the first None terminates the container. + fn value(&self, index: usize) -> Option>; +} +/// A finite, stable reference sequence. +pub trait ReferencesView { + /// Indexed reference; the first None terminates the container. + fn reference(&self, index: usize) -> Option>; +} +/// A borrowed value. No variant owns a child model or payload. +pub enum ValueRef<'a> { + /// Objc. + Descriptor(&'a dyn DescriptorView), + /// VlLs. + List(&'a dyn ValuesView), + /// ObAr prefix and body. + ObjectArray(u32, &'a dyn DescriptorView), + /// doub. + Double(f64), + /// UntF. + UnitFloat([u8; 4], f64), + /// UnFl. + UnitFloats([u8; 4], &'a [f64]), + /// TEXT. + Text(UnicodeRef<'a>), + /// enum. + Enumerated(IdRef<'a>, IdRef<'a>), + /// long. + Integer(i32), + /// comp. + LargeInteger(i64), + /// bool. + Boolean(bool), + /// type. + Class(ClassRef<'a>), + /// tdta. + RawData(&'a [u8]), + /// obj reference. + Reference(&'a dyn ReferencesView), +} +/// A borrowed reference item. +#[derive(Clone, Copy)] +pub enum ReferenceRef<'a> { + /// prop. + Property(ClassRef<'a>, IdRef<'a>), + /// Clss. + Class(ClassRef<'a>), + /// Enmr. + Enumerated(ClassRef<'a>, IdRef<'a>, IdRef<'a>), + /// rele. + Offset(ClassRef<'a>, i32), + /// Idnt. + Identifier(ClassRef<'a>, i32), + /// indx. + Index(ClassRef<'a>, i32), + /// name. + Name(ClassRef<'a>, UnicodeRef<'a>), +} + +fn u32_bytes(out: &mut Vec, n: u32) { + out.extend_from_slice(&n.to_be_bytes()); +} +fn id(out: &mut Vec, value: IdRef<'_>) { + match value { + IdRef::Code(bytes) => { + u32_bytes(out, 0); + out.extend_from_slice(&bytes); + } + IdRef::String(bytes) => { + u32_bytes(out, bytes.len() as u32); + out.extend_from_slice(bytes); + } + } +} +fn unicode(out: &mut Vec, value: UnicodeRef<'_>) { + match value { + UnicodeRef::Text(text, nul) => { + let count = text.encode_utf16().fold(0u32, |n, _| n.wrapping_add(1)).wrapping_add(u32::from(nul)); + u32_bytes(out, count); + for unit in text.encode_utf16().chain(nul.then_some(0)) { + out.extend_from_slice(&unit.to_be_bytes()); + } + } + UnicodeRef::Units(units) => { + u32_bytes(out, units.len() as u32); + for unit in units { + out.extend_from_slice(&unit.to_be_bytes()); + } + } + } +} +fn class(out: &mut Vec, value: ClassRef<'_>) { + unicode(out, value.name); + id(out, value.id); +} +#[derive(Clone, Copy)] +enum Container<'a> { + Descriptor(&'a dyn DescriptorView), + List(&'a dyn ValuesView), + References(&'a dyn ReferencesView), +} +struct Frame<'a> { + container: Container<'a>, + index: usize, + count: u32, + offset: usize, +} +fn begin<'a>(out: &mut Vec, container: Container<'a>) -> Frame<'a> { + if let Container::Descriptor(d) = &container { + class(out, d.class()); + } + let offset = out.len(); + u32_bytes(out, 0); + Frame { container, index: 0, count: 0, offset } +} +fn finish(out: &mut [u8], frame: Frame<'_>) { + // This offset denotes the four-byte placeholder emitted by begin, never input data. + if let Some(slot) = out.get_mut(frame.offset..).and_then(|tail| tail.get_mut(..4)) { + slot.copy_from_slice(&frame.count.to_be_bytes()); + } +} +fn reference(out: &mut Vec, value: ReferenceRef<'_>) { + match value { + ReferenceRef::Property(c, k) => { + out.extend_from_slice(b"prop"); + class(out, c); + id(out, k); + } + ReferenceRef::Class(c) => { + out.extend_from_slice(b"Clss"); + class(out, c); + } + ReferenceRef::Enumerated(c, t, v) => { + out.extend_from_slice(b"Enmr"); + class(out, c); + id(out, t); + id(out, v); + } + ReferenceRef::Offset(c, n) | ReferenceRef::Identifier(c, n) | ReferenceRef::Index(c, n) => { + let tag = match value { + ReferenceRef::Offset(..) => b"rele", + ReferenceRef::Identifier(..) => b"Idnt", + _ => b"indx", + }; + out.extend_from_slice(tag); + class(out, c); + out.extend_from_slice(&n.to_be_bytes()); + } + ReferenceRef::Name(c, n) => { + out.extend_from_slice(b"name"); + class(out, c); + unicode(out, n); + } + } +} +fn value<'a>(out: &mut Vec, v: ValueRef<'a>) -> Option> { + match v { + ValueRef::Descriptor(d) => { + out.extend_from_slice(b"Objc"); + return Some(Container::Descriptor(d)); + } + ValueRef::List(v) => { + out.extend_from_slice(b"VlLs"); + return Some(Container::List(v)); + } + ValueRef::ObjectArray(n, d) => { + out.extend_from_slice(b"ObAr"); + u32_bytes(out, n); + return Some(Container::Descriptor(d)); + } + ValueRef::Reference(v) => { + out.extend_from_slice(b"obj "); + return Some(Container::References(v)); + } + ValueRef::Double(n) => { + out.extend_from_slice(b"doub"); + out.extend_from_slice(&n.to_be_bytes()); + } + ValueRef::UnitFloat(u, n) => { + out.extend_from_slice(b"UntF"); + out.extend_from_slice(&u); + out.extend_from_slice(&n.to_be_bytes()); + } + ValueRef::UnitFloats(u, ns) => { + out.extend_from_slice(b"UnFl"); + out.extend_from_slice(&u); + u32_bytes(out, ns.len() as u32); + for n in ns { + out.extend_from_slice(&n.to_be_bytes()); + } + } + ValueRef::Text(s) => { + out.extend_from_slice(b"TEXT"); + unicode(out, s); + } + ValueRef::Enumerated(t, v) => { + out.extend_from_slice(b"enum"); + id(out, t); + id(out, v); + } + ValueRef::Integer(n) => { + out.extend_from_slice(b"long"); + out.extend_from_slice(&n.to_be_bytes()); + } + ValueRef::LargeInteger(n) => { + out.extend_from_slice(b"comp"); + out.extend_from_slice(&n.to_be_bytes()); + } + ValueRef::Boolean(b) => { + out.extend_from_slice(b"bool"); + out.push(u8::from(b)); + } + ValueRef::Class(c) => { + out.extend_from_slice(b"type"); + class(out, c); + } + ValueRef::RawData(b) => { + out.extend_from_slice(b"tdta"); + u32_bytes(out, b.len() as u32); + out.extend_from_slice(b); + } + } + None +} +/// Append without cloning the model or staging serialized output. +/// +/// Traversal uses constant call-stack depth and O(nesting depth) heap frames. +/// Views must terminate, remain stable and contain no cycles. Existing bytes in +/// out are untouched; only count placeholders in newly appended data are patched. +pub fn append_descriptor(out: &mut Vec, descriptor: &dyn DescriptorView) { + let mut frames = vec![begin(out, Container::Descriptor(descriptor))]; + while let Some(mut frame) = frames.pop() { + let child = match frame.container { + Container::Descriptor(d) => match d.item(frame.index) { + Some((key, v)) => { + id(out, key); + Some(value(out, v)) + } + None => None, + }, + Container::List(list) => list.value(frame.index).map(|v| value(out, v)), + Container::References(refs) => refs.reference(frame.index).map(|v| { + reference(out, v); + None + }), + }; + let Some(child) = child else { + finish(out, frame); + continue; + }; + frame.count = frame.count.wrapping_add(1); + if let Some(index) = frame.index.checked_add(1) { + frame.index = index; + frames.push(frame); + } else { + // No further index is representable; patch the items actually emitted. + finish(out, frame); + } + if let Some(container) = child { + frames.push(begin(out, container)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + struct Node { + next: Option>, + kind: u8, + } + impl DescriptorView for Node { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, i: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + if i != 0 { + return None; + } + self.next.as_deref().map(|n| { + ( + IdRef::Code(*b"next"), + match self.kind % 3 { + 0 => ValueRef::Descriptor(n), + 1 => ValueRef::List(n), + _ => ValueRef::ObjectArray(7, n), + }, + ) + }) + } + } + impl ValuesView for Node { + fn value(&self, i: usize) -> Option> { + if i != 0 { + return None; + } + self.next.as_deref().map(|n| ValueRef::Descriptor(n)) + } + } + #[test] + fn deeply_mixed_views_use_heap_frames_not_recursive_calls() { + let mut node = Box::new(Node { next: None, kind: 0 }); + for kind in 0..12000 { + node = Box::new(Node { next: Some(node), kind: (kind % 3) as u8 }); + } + let mut out = vec![0xaa]; + append_descriptor(&mut out, node.as_ref()); + assert_eq!(out[0], 0xaa); + assert!(out.len() > 12000 * 8); + // Tear down the test model iteratively too; serializer never owns or drops it. + while let Some(next) = node.next.take() { + node = next; + } + } + struct Custom; + impl DescriptorView for Custom { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + match index { + 0 => Some((IdRef::Code(*b"one "), ValueRef::Integer(-1))), + 1 => Some((IdRef::Code(*b"list"), ValueRef::List(self))), + 2 => Some((IdRef::Code(*b"tail"), ValueRef::Boolean(true))), + _ => None, + } + } + } + impl ValuesView for Custom { + fn value(&self, _index: usize) -> Option> { + None + } + } + #[test] + fn counts_patch_emitted_items_and_empty_children_without_touching_prefix() { + let mut out = vec![9, 8]; + append_descriptor(&mut out, &Custom); + let mut expected = vec![9, 8, 0, 0, 0, 0, 0, 0, 0, 0]; + expected.extend(b"null"); + expected.extend([0, 0, 0, 3, 0, 0, 0, 0]); + expected.extend(b"one long"); + expected.extend([255, 255, 255, 255, 0, 0, 0, 0]); + expected.extend(b"listVlLs"); + expected.extend([0, 0, 0, 0, 0, 0, 0, 0]); + expected.extend(b"tailbool"); + expected.push(1); + assert_eq!(out, expected); + } + struct Raw<'a>(&'a [u8]); + impl DescriptorView for Raw<'_> { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, i: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + (i == 0).then_some((IdRef::Code(*b"data"), ValueRef::RawData(self.0))) + } + } + #[test] + fn large_payload_is_borrowed_and_appended_without_model_conversion() { + let bytes = vec![0xa5; 1024 * 1024]; + let view = Raw(&bytes); + let Some((_, ValueRef::RawData(slice))) = view.item(0) else { + panic!("raw view"); + }; + assert_eq!(slice.as_ptr(), bytes.as_ptr()); + let mut out = Vec::with_capacity(bytes.len() + 32); + append_descriptor(&mut out, &view); + assert_eq!(&out[32..], bytes); + } + + struct Gapped; + impl DescriptorView for Gapped { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + match index { + 0 => Some((IdRef::Code(*b"list"), ValueRef::List(self))), + 1 => Some((IdRef::Code(*b"refs"), ValueRef::Reference(self))), + 3 => panic!("descriptor must stop at first None"), + _ => None, + } + } + } + impl ValuesView for Gapped { + fn value(&self, index: usize) -> Option> { + match index { + 0 => Some(ValueRef::Integer(9)), + 2 => panic!("list must stop at first None"), + _ => None, + } + } + } + impl ReferencesView for Gapped { + fn reference(&self, index: usize) -> Option> { + match index { + 1 => panic!("reference must stop at first None"), + _ => None, + } + } + } + #[test] + fn first_absent_item_terminates_each_custom_container() { + let mut out = Vec::new(); + append_descriptor(&mut out, &Gapped); + let expected: Vec = + [&b"\0\0\0\0\0\0\0\0null\0\0\0\x02"[..], b"\0\0\0\0listVlLs\0\0\0\x01long\0\0\0\x09", b"\0\0\0\0refsobj \0\0\0\0"].concat(); + assert_eq!(out, expected); + } +} diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs index 3bfc210d1..0e5b474e3 100644 --- a/crates/psd/src/tagged.rs +++ b/crates/psd/src/tagged.rs @@ -686,6 +686,36 @@ pub(crate) fn write_blocks_to( Ok(()) } +/// Append the data of an lfx2 block: fixed version words 0 and 16, then a descriptor. +/// +/// No outer signature, key, length or padding is written. Existing output is preserved. +/// Descriptor semantics are the caller's responsibility; no values are normalized. +/// Views inherit the borrowed writer's finite, stable, acyclic contract and O(depth) +/// heap traversal. No owned model conversion or serialized temporary is created. +pub fn append_layer_effects_data(out: &mut Vec, descriptor: &dyn crate::descriptor::borrowed::DescriptorView) { + out.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 16]); + crate::descriptor::borrowed::append_descriptor(out, descriptor); +} + +/// Append the data of a SoCo block: fixed descriptor version 16, then a descriptor. +/// +/// This is data-only, with the same append and borrowed-view contract as +/// [append_layer_effects_data]. The caller supplies the color descriptor unchanged. +pub fn append_solid_color_data(out: &mut Vec, descriptor: &dyn crate::descriptor::borrowed::DescriptorView) { + out.extend_from_slice(&[0, 0, 0, 16]); + crate::descriptor::borrowed::append_descriptor(out, descriptor); +} + +/// Append SoLd data: the soLD signature, version 4 and descriptor version 16. +/// +/// No outer block key, length or padding is written. The descriptor is supplied +/// unchanged by the caller. This inherits the append semantics and finite, +/// stable, acyclic borrowed-view contract of [append_layer_effects_data]. +pub fn append_smart_object_data(out: &mut Vec, descriptor: &dyn crate::descriptor::borrowed::DescriptorView) { + out.extend_from_slice(b"soLD\0\0\0\x04\0\0\0\x10"); + crate::descriptor::borrowed::append_descriptor(out, descriptor); +} + #[cfg(test)] mod tests { use super::*; @@ -938,4 +968,40 @@ mod tests { versioned.extend(raw); assert!(VersionedDescriptor::parse_prefix(&versioned).is_err()); } + + #[test] + fn borrowed_block_headers_append_literal_empty_and_nonempty_data() { + use crate::descriptor::borrowed::{ClassRef, DescriptorView, IdRef, UnicodeRef, ValueRef}; + struct View(bool); + impl DescriptorView for View { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + (self.0 && index == 0).then_some((IdRef::Code(*b"enab"), ValueRef::Boolean(true))) + } + } + for populated in [false, true] { + let mut descriptor = b"\0\0\0\0\0\0\0\0null\0\0\0".to_vec(); + descriptor.push(u8::from(populated)); + if populated { + descriptor.extend_from_slice(b"\0\0\0\0enabbool\x01"); + } + let mut effects = vec![0xa5, 0x5a]; + append_layer_effects_data(&mut effects, &View(populated)); + let mut expected = vec![0xa5, 0x5a, 0, 0, 0, 0, 0, 0, 0, 16]; + expected.extend_from_slice(&descriptor); + assert_eq!(effects, expected); + let mut color = vec![0xa5, 0x5a]; + append_solid_color_data(&mut color, &View(populated)); + let mut expected = vec![0xa5, 0x5a, 0, 0, 0, 16]; + expected.extend_from_slice(&descriptor); + assert_eq!(color, expected); + let mut placed = vec![0xa5, 0x5a]; + append_smart_object_data(&mut placed, &View(populated)); + let mut expected = vec![0xa5, 0x5a, 0x73, 0x6f, 0x4c, 0x44, 0, 0, 0, 4, 0, 0, 0, 16]; + expected.extend_from_slice(&descriptor); + assert_eq!(placed, expected); + } + } } diff --git a/crates/psd/src/text.rs b/crates/psd/src/text.rs index 3db0153f3..3e368152e 100644 --- a/crates/psd/src/text.rs +++ b/crates/psd/src/text.rs @@ -1,4 +1,4 @@ -//! Type layers: the `TySh` block as a read-only view. +//! Type layers: read-only views and borrowed data framing for the `TySh` block. //! //! Layout (Adobe's specification, "Type tool object setting"): a version, six doubles of //! transform, a text version, a descriptor version and the text descriptor, whose `Txt ` is the @@ -83,6 +83,32 @@ impl LayerRecord { } } +/// Append TySh data with fixed version fields and a zero-bounds suffix. +/// +/// Writes version 1, six raw transform doubles, text version 50 and descriptor +/// version 16, the text descriptor, warp version 1 and descriptor version 16, +/// the warp descriptor, then sixteen zero bytes. No outer key, length or padding +/// is written. Text, EngineData and warp semantics remain the caller's policy. +/// Both views inherit the finite, stable, acyclic borrowed-writer contract. +/// Existing output is preserved; traversal uses O(depth) heap frames, without +/// an owned model conversion or a full serialized temporary. +pub fn append_type_layer_data_with_zero_bounds( + out: &mut Vec, + transform: &[f64; 6], + text: &dyn crate::descriptor::borrowed::DescriptorView, + warp: &dyn crate::descriptor::borrowed::DescriptorView, +) { + out.extend_from_slice(&[0, 1]); + for value in transform { + out.extend_from_slice(&value.to_be_bytes()); + } + out.extend_from_slice(&[0, 50, 0, 0, 0, 16]); + crate::descriptor::borrowed::append_descriptor(out, text); + out.extend_from_slice(&[0, 1, 0, 0, 0, 16]); + crate::descriptor::borrowed::append_descriptor(out, warp); + out.extend_from_slice(&[0; 16]); +} + #[cfg(test)] mod tests { use super::*; @@ -203,6 +229,41 @@ mod tests { assert!(TypeLayerPrefix::from_bytes_with_limits(&data, ParseLimits { max_descriptor_items: 1, ..limits }).is_err()); assert!(TypeLayerPrefix::from_bytes_with_limits(&data, ParseLimits { max_list_items: 1, ..limits }).is_err()); } + + #[test] + fn borrowed_type_data_preserves_raw_transform_two_views_and_zero_tail() { + use crate::descriptor::borrowed::{ClassRef, DescriptorView, IdRef, UnicodeRef, ValueRef}; + struct View(bool); + impl DescriptorView for View { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + (self.0 && index == 0).then_some((IdRef::Code(*b"flag"), ValueRef::Boolean(true))) + } + } + let transform = [1.0, -0.0, f64::INFINITY, f64::NEG_INFINITY, f64::from_bits(0x7ff8_1234_5678_9abc), -3.0]; + for (text, warp) in [(false, false), (false, true), (true, false), (true, true)] { + let mut out = vec![0xa5]; + append_type_layer_data_with_zero_bounds(&mut out, &transform, &View(text), &View(warp)); + let mut expected = vec![ + 0xa5, 0, 1, 0x3f, 0xf0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0, 0x7f, 0xf0, 0, 0, 0, 0, 0, 0, 0xff, 0xf0, 0, 0, 0, 0, 0, 0, + 0x7f, 0xf8, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xc0, 8, 0, 0, 0, 0, 0, 0, 0, 50, 0, 0, 0, 16, + ]; + for (index, populated) in [text, warp].into_iter().enumerate() { + if index == 1 { + expected.extend([0, 1, 0, 0, 0, 16]); + } + expected.extend_from_slice(b"\0\0\0\0\0\0\0\0null\0\0\0"); + expected.push(u8::from(populated)); + if populated { + expected.extend_from_slice(b"\0\0\0\0flagbool\x01"); + } + } + expected.extend([0; 16]); + assert_eq!(out, expected); + } + } } /// Editable type-tool envelope with PhotoCraft-compatible recovery and geometry limits. diff --git a/crates/sheet/src/tables.rs b/crates/sheet/src/tables.rs index b30935d54..98f576170 100644 --- a/crates/sheet/src/tables.rs +++ b/crates/sheet/src/tables.rs @@ -26,10 +26,14 @@ const BUILTIN_FORMATS: [(u32, &str); 36] = [ (20, "h:mm"), (21, "h:mm:ss"), (22, "m/d/yyyy h:mm"), - (37, "#,##0 ;(#,##0)"), - (38, "#,##0 ;[Red](#,##0)"), - (39, "#,##0.00;(#,##0.00)"), - (40, "#,##0.00;[Red](#,##0.00)"), + // 37 to 40 are the codes Excel reports for these ids, not the ECMA-376 Part 1 18.8.30 text + // (`#,##0 ;(#,##0)`, `#,##0.00;(#,##0.00)` and their [Red] forms). Excel pads a positive number + // by the width of a closing parenthesis (`_)`). It writes neither a numFmt nor a FORMAT record + // for them, so these codes are what a file Excel saved means. + (37, "#,##0_);(#,##0)"), + (38, "#,##0_);[Red](#,##0)"), + (39, "#,##0.00_);(#,##0.00)"), + (40, "#,##0.00_);[Red](#,##0.00)"), (41, "_(* #,##0_);_(* \\(#,##0\\);_(* \"-\"_);_(@_)"), (42, "_(\"$\"* #,##0_);_(\"$\"* \\(#,##0\\);_(\"$\"* \"-\"_);_(@_)"), (43, "_(* #,##0.00_);_(* \\(#,##0.00\\);_(* \"-\"??_);_(@_)"), @@ -86,6 +90,17 @@ mod tests { assert_eq!(builtin_format_id("yyyy"), None); } + #[test] + fn formats_37_to_40_are_the_codes_excel_reports() { + let codes = ["#,##0_);(#,##0)", "#,##0_);[Red](#,##0)", "#,##0.00_);(#,##0.00)", "#,##0.00_);[Red](#,##0.00)"]; + for (id, code) in (37..=40).zip(codes) { + assert_eq!(builtin_format(id), Some(code), "{id}"); + assert_eq!(builtin_format_id(code), Some(id), "{id}"); + } + // The 18.8.30 text is not a built-in, so it is written as a custom format. + assert_eq!(builtin_format_id("#,##0.00;(#,##0.00)"), None); + } + #[test] fn the_palette_repeats_its_eight_fixed_colours() { assert_eq!(DEFAULT_PALETTE.get(..8), DEFAULT_PALETTE.get(8..16)); diff --git a/crates/story-render/src/main.rs b/crates/story-render/src/main.rs index 009a506aa..5efafbe36 100644 --- a/crates/story-render/src/main.rs +++ b/crates/story-render/src/main.rs @@ -25,7 +25,7 @@ //! contrast without them). A value that is not one of these is refused. `stories.tsv` lists the scale of every image. use craft_behavior::ColumnWidth; -use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface}; +use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface, Tracked}; use craft_ui::fonts::{I18nScripts, UiFonts}; use craft_ui::layout_components::{Grid, Stack}; use craft_ui::runtime::commands::CommandInput; @@ -312,7 +312,7 @@ fn render(job: &Job, renderer: &mut Renderer, env: &RootEnv, options: &Options) // The command states of the story shown, as the gallery gives them, before the first frame. The Overview gives its // cards none, so a card is rendered under none. frames.commands(match &job.shown { - Shown::Story(registration) => Story::command_input([®istration.story]), + Shown::Story(registration) => CommandInput::new().states(&Tracked::new(Story::command_states([®istration.story]))), Shown::Card(_) => CommandInput::new(), }); let (shown, dialog) = match &job.shown { diff --git a/crates/svg/src/paths.rs b/crates/svg/src/paths.rs index eb8c5026f..c16588454 100644 --- a/crates/svg/src/paths.rs +++ b/crates/svg/src/paths.rs @@ -180,7 +180,7 @@ fn clip_path_to_region( } // Some callers deliberately retain geometry even when the source has no paint. Keep that // geometry clip-able as linework instead of silently deleting it. - if has_stroke || (!has_fill && !has_stroke) { + if has_stroke || !has_fill { let polygons: Vec> = flatten_contours(region)?.into_iter().filter(|(points, closed)| *closed && points.len() >= 3).map(|(points, _)| points).collect(); for (mut points, closed) in flatten_contours(path)? { diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index c4844b832..b5f9dd435 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -1082,7 +1082,7 @@ fn a_held_space_pans_over_a_canvas_control_and_leaves_it_unchanged() { fn a_queued_space_whose_hand_the_gate_refuses_leaves_the_press_to_the_selected_tool() { let log = Log::default(); let (mut fixture, view, canvas) = momentary_canvas(Probe::new("main", &log)); - fixture.gate(CommandGate::new(|command| !matches!(MomentaryCommands::from_ref(command), Some(MomentaryCommands::Hand)))).settle(); + fixture.gate(CommandGate::new((), |_: &(), command| !matches!(MomentaryCommands::from_ref(command), Some(MomentaryCommands::Hand)))).settle(); let at = fixture.by_role(Role::CANVAS)[0].rect.center(); let before = view.get().expect("the canvas ran").center; let space = craft_keymap::Key::Space; diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index d6ee47c52..701f2643e 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -52,7 +52,7 @@ impl MeasureCx<'_, C> { /// `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above /// the component, and the enabled state of its instance. `None` when the command is scoped and no instance of /// its scope is above the component. - pub fn resolve_command(&self, command: impl Into) -> Option { + pub fn resolve_command(&self, command: impl Into) -> Option> { commands::resolve_scoped(self.ui.ctx(), self.env.command_chain(), &command.into()) } diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index c65a6cf75..1e9045c55 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -137,7 +137,7 @@ impl Lazy { let real = !sizing && !crate::runtime::measure::active(&ctx); let owner = view.map(|view| view.owner); // A run around this one that is replayed later keeps the child's entry. - replay::journal(&ctx, || move |ctx: &egui::Context| lazy::keep(ctx, owner, id)); + replay::journal(&ctx, || (owner, id), |ctx, &(owner, id)| lazy::keep(ctx, owner, id)); if let Some(view) = view { let at = |size: Vec2| { let x = if rtl { available.max.x - size.x } else { available.min.x }; diff --git a/crates/ui-contract/src/contract/steps/env.rs b/crates/ui-contract/src/contract/steps/env.rs index 1fa643e51..cbb9d58de 100644 --- a/crates/ui-contract/src/contract/steps/env.rs +++ b/crates/ui-contract/src/contract/steps/env.rs @@ -33,7 +33,7 @@ pub(crate) fn variants(asked: Option) -> (Variant, Varian /// size; variant; label. /// `(requested, variant)` comes from `variants`. pub(crate) fn env(ctx: &Context, env: &Env, common: &Common, (requested, variant): (Variant, Variant)) -> EnvStep { - let command = common.command.as_ref().map(|command| Arc::new(commands::resolve_bound(ctx, &env.commands, command))); + let command = common.command.as_ref().map(|command| commands::resolve_bound(ctx, &env.commands, command)); let label = match (&common.label, &command) { (Label::Empty, Some(command)) => Label::Shared(command.label.clone()), (label, _) => label.resolved(&env.words), diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index 8a6fe8269..7cce1927b 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -113,7 +113,7 @@ impl TextOutcome { /// A part as the sensing core registers it. // F2-MERGE: F3 (`PartBuilder` adds tooltip and `pointer_only`) -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub(crate) struct PartDecl { pub key: PartKey, pub index: Option, @@ -153,7 +153,7 @@ impl PartDecl { } /// One member's registration for this pass. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub(crate) struct MemberDecl { pub id: Id, pub rect: Rect, @@ -174,7 +174,7 @@ impl MemberDecl { } /// What a root registers at step 8: its id and rect. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] struct RootInfo { id: Id, rect: Rect, @@ -396,7 +396,7 @@ pub fn cancel_press_of(ctx: &Context, owner: Id) { /// Records the transformed body's egui layer. pub(crate) fn set_layer(ctx: &Context, arena: ArenaId, layer: Layer) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| set_layer(ctx, arena, layer)); + crate::runtime::replay::journal(ctx, || (arena, layer), |ctx, &(arena, layer)| set_layer(ctx, arena, layer)); let pass_nr = pass::pass_nr(ctx, pass::current_viewport(ctx)); with_arena(ctx, arena, pass_nr, |state| state.layer = Some(layer)); } @@ -408,7 +408,7 @@ pub(crate) fn set_layer(ctx: &Context, arena: ArenaId, layer: Layer) { // names their shapes as the press winner. /// What a root registers in its arena at step 8, kept for a replay. -#[derive(Clone)] +#[derive(Clone, Debug, PartialEq)] struct RootRegistration { info: RootInfo, own: Vec, @@ -419,10 +419,11 @@ struct RootRegistration { /// Notes a root's step-8 registration in the open records. fn journal_root(ctx: &Context, arena: ArenaId, info: RootInfo, own: &[PartDecl], widgets: &[Id], (layer, sense): (Layer, Sense)) { - crate::runtime::replay::journal(ctx, || { - let registration = RootRegistration { info, own: own.to_vec(), widgets: widgets.to_vec(), layer, sense }; - move |ctx: &Context| register_root_again(ctx, arena, registration.clone()) - }); + crate::runtime::replay::journal( + ctx, + || (arena, RootRegistration { info, own: own.to_vec(), widgets: widgets.to_vec(), layer, sense }), + |ctx, (arena, registration)| register_root_again(ctx, *arena, registration.clone()), + ); } /// A replayed root's step-8 registration: its own parts, rect, widgets, layer and sense, with no press run. @@ -439,44 +440,61 @@ fn register_root_again(ctx: &Context, arena: ArenaId, registration: RootRegistra }); } -/// Notes in the open records the members that joined `arena`, as they joined. -fn journal_join(ctx: &Context, arena: ArenaId, joined: &[MemberDecl]) { - crate::runtime::replay::journal(ctx, || { - let joined = joined.to_vec(); - move |ctx: &Context| join_again(ctx, arena, joined.clone()) - }); +/// Notes in the open records the members that joined `arena` on `layer` through `clip`, as declared: a replay joins +/// them at the stack positions the arena gives them then. +fn journal_join(ctx: &Context, arena: ArenaId, layer: Layer, clip: Rect, joined: &[MemberDecl]) { + crate::runtime::replay::journal( + ctx, + || (arena, layer, clip, joined.to_vec()), + |ctx, (arena, layer, clip, joined)| join_again(ctx, *arena, *layer, *clip, joined), + ); } -/// Replayed members join their arena again. -fn join_again(ctx: &Context, arena: ArenaId, joined: Vec) { - journal_join(ctx, arena, &joined); - let pass_nr = pass::pass_nr(ctx, pass::current_viewport(ctx)); - with_arena(ctx, arena, pass_nr, |state| { - rotate(state, pass_nr); +/// Replayed members join their arena again, after the members that joined before them in this pass. +fn join_again(ctx: &Context, arena: ArenaId, layer: Layer, clip: Rect, joined: &[MemberDecl]) { + journal_join(ctx, arena, layer, clip, joined); + let read = PassRead::of(ctx); + let mut shapes = Vec::new(); + with_arena_in(ctx, read.viewport, arena, read.pass_nr, |state| { + rotate(state, read.pass_nr); for decl in joined { - state.union_sense |= decl.parts.iter().fold(decl.sense, |sense, part| sense | part.sense); - state.members.push(decl); + join_member(state, decl.clone(), layer, read.target(), &mut shapes); } }); + pointer::add_shapes_in(ctx, read.viewport, layer, arena.0, clip, shapes); } -/// Places the `over` parts of the root of `arena` (`member` None) or of its member `member` above the members joined -/// so far, as `place_over_widgets` does; journaled for a replay. -fn place_over(ctx: &Context, arena: ArenaId, member: Option) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| place_over(ctx, arena, member)); - let pass_nr = pass::pass_nr(ctx, pass::current_viewport(ctx)); - with_arena(ctx, arena, pass_nr, |state| { - rotate(state, pass_nr); +/// Joins `decl`, as declared, to the arena `state` on `layer`: at the next stack position, its `over` parts just above +/// it, its shapes added to `shapes`. +fn join_member(state: &mut ArenaState, mut decl: MemberDecl, layer: Layer, target: f32, shapes: &mut Vec>) { + decl.local = state.layer == Some(layer); + let position = member_position(state.members.len()); + decl.over_at = position + 1; + shapes.extend(member_shapes(&decl, position, target)); + state.union_sense |= decl.parts.iter().fold(decl.sense, |sense, part| sense | part.sense); + state.members.push(decl); +} + +/// Places the `over` parts of the root `id` of `arena` (`member` false) or of its member `id` above the members joined +/// so far, as `place_over_widgets` does, and records their shapes on `layer` through `clip`; journaled, so a replay +/// places them above the members joined in the replaying pass. +fn place_over(ctx: &Context, (arena, id, member, layer, clip): (ArenaId, Id, bool, Layer, Rect)) { + crate::runtime::replay::journal(ctx, || (arena, id, member, layer, clip), |ctx, &args| place_over(ctx, args)); + let read = PassRead::of(ctx); + let shapes = with_arena_in(ctx, read.viewport, arena, read.pass_nr, |state| { + rotate(state, read.pass_nr); let at = over_position(state.members.len()); - match member { - None => state.own_over_at = at, - Some(id) => { - if let Some(joined) = state.members.iter_mut().rev().find(|joined| joined.id == id) { - joined.over_at = at; - } - } + if !member { + state.own_over_at = at; + return Some(own_over_shapes(&state.own, id, at, read.target())); } + let joined = state.members.iter_mut().rev().find(|joined| joined.id == id)?; + joined.over_at = at; + Some(member_over_shapes(joined, read.target()).collect()) }); + if let Some(shapes) = shapes { + pointer::add_shapes_in(ctx, read.viewport, layer, arena.0, clip, shapes); + } } /// What step 8 reads of the running pass, fetched once per root: the viewport, the pass number and the pointer @@ -691,20 +709,10 @@ pub(crate) fn place_over_widgets(ui: &Ui, id: Id, member: Option, decls } let arena = member.unwrap_or_else(|| ArenaId::new(id)); let layer = ui.layer_id(); - let read = PassRead::of(ctx); - place_over(ctx, arena, member.map(|_| id)); - let shapes = with_arena_in(ctx, read.viewport, arena, read.pass_nr, |state| { - if member.is_none() { - return Some(own_over_shapes(&state.own, id, state.own_over_at, read.target())); - } - let joined = state.members.iter().rev().find(|joined| joined.id == id)?; - Some(member_over_shapes(joined, read.target()).collect::>()) - }); - let Some(shapes) = shapes else { return }; - pointer::record_shapes_in(ctx, read.viewport, layer, arena.0, clip, shapes); + place_over(ctx, (arena, id, member.is_some(), layer, clip)); // A root's widgets are in its widget record from step 8. if member.is_some() && !widgets.is_empty() { - pointer::record_widgets_in(ctx, read.viewport, layer, arena.0, &widgets, decls.iter().any(|part| part.sense.contains(Sense::CLICK))); + pointer::record_widgets(ctx, layer, arena.0, &widgets, decls.iter().any(|part| part.sense.contains(Sense::CLICK))); } } @@ -758,27 +766,19 @@ pub(crate) fn sense_members(ui: &Ui, arena: ArenaId, specs: &[MemberSpec<'_>]) - let outcome = with_arena(ctx, arena, pass_nr, |state| { rotate(state, pass_nr); for spec in specs { - let mut decl = MemberDecl::new(spec.id, spec.rect, spec.sense, spec.parts); - decl.local = state.layer == Some(layer); - let position = member_position(state.members.len()); - decl.over_at = position + 1; - shapes.extend(member_shapes(&decl, position, target)); - state.union_sense |= decl.sense; - for part in &decl.parts { - state.union_sense |= part.sense; - } - joined.push((decl.local, known_in(state, spec.id))); + let decl = MemberDecl::new(spec.id, spec.rect, spec.sense, spec.parts); if recording { recorded.push(decl.clone()); } - state.members.push(decl); + join_member(state, decl, layer, target, &mut shapes); + joined.push((state.layer == Some(layer), known_in(state, spec.id))); } state.outcome.filter(|outcome| outcome.pass == pass_nr).unwrap_or_default() }); if recording { - journal_join(ctx, arena, &recorded); + journal_join(ctx, arena, layer, ui.clip_rect(), &recorded); } - pointer::record_shapes(ctx, layer, arena.0, ui.clip_rect(), shapes); + pointer::add_shapes_in(ctx, pass::current_viewport(ctx), layer, arena.0, ui.clip_rect(), shapes); specs .iter() .zip(joined) diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 2170f2050..1c84fe3dd 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -5,9 +5,12 @@ use super::{ AppCatalog, CommandChain, CommandGate, CommandInput, CommandScope, CommandSet, CommandState, EditCommands, FirePhase, FireSource, Fired, ResolvedCommand, WindowShortcut, registry, }; +use crate::contract::Revision; use crate::runtime::egui::sizing::{Rerun, request_discard}; use crate::runtime::egui::{pass, repaint}; use crate::runtime::focus::EditSet; +#[cfg(feature = "testing")] +use crate::runtime::measure::Resolve; use crate::runtime::pass_state; use crate::runtime::reads::{self, BindKey}; use crate::runtime::{focus, frame, keys, lazy, measure, overlay, replay, sampler}; @@ -48,13 +51,24 @@ impl Instances { self.list.iter() } - /// Registers `instance`, keeping the place of one already registered under the same id. - fn upsert(&mut self, instance: Instance) { + /// Registers `instance`, keeping the place of one already registered under the same id. Returns whether a + /// resolution can see the difference: the id is new or was dead, or its scope, viewport or layer changed. + fn upsert(&mut self, instance: Instance) -> bool { match self.at.get(&instance.id) { - Some(at) => self.list[*at] = instance, + Some(at) => { + let held = &self.list[*at]; + // A held instance that missed a pass is dead until it registers again: its return is seen too. + let seen = held.stamp + 1 < instance.stamp + || held.scope != instance.scope + || held.viewport != instance.viewport + || held.layer != instance.layer; + self.list[*at] = instance; + seen + } None => { self.at.insert(instance.id, self.list.len()); self.list.push(instance); + true } } } @@ -110,13 +124,25 @@ pub(crate) struct Board { app: Option, keymap: Option, gate: Option, - /// The gate's answers in this frame, by command key (`CommandRef::key`). The gate answers from what the app knew - /// before the frame, so the board asks it once per command per frame, whichever readers and passes resolve it. + /// The gate's answers under its current key, by command key (`CommandRef::key`). The gate is a `fn` of its props, + /// so the board asks it once per command until the key moves, whichever readers, passes and frames resolve it. gate_answers: HashMap, /// Command ids by number, so a state lookup allocates nothing. numbers: HashMap, + /// The app-scope states of the app's `Tracked`, by command number, and the revision they are of. + app_states: HashMap, + app_revision: Option, + /// The states instances published this frame and last frame; a resolution reads this frame's, else last frame's. this: HashMap, last: HashMap, + /// The revision of each state key that has changed: the value of `state_seq` when it last did. + revisions: HashMap, + /// Moves with every state change. + state_seq: u64, + /// The state keys that changed, with the `state_seq` of each change, since the oldest wake of a kept table. + state_log: Vec<(u64, StateKey)>, + /// The generations of the inputs every resolution reads and of the focus vantage. + gens: Gens, /// What the frame's input changed, under the root frame it arrived for (`set_input`). changed: (u64, InputChanges), /// Scoped commands waiting for their instance. @@ -133,8 +159,8 @@ pub(crate) struct Board { before: HashMap, /// Where the commands of the running pass are judged from: the key focus and the modal layers. here: Vantage, - /// The chain of the last pass in which any component held key focus. - last_focused: Vec, + /// Each viewport's own vantage facts. + views: HashMap, matcher: Matcher, held: Vec, /// The top modal layer's root container of each viewport that has one. @@ -149,8 +175,8 @@ pub(crate) struct Board { unknown: HashSet, /// App catalog ids that a linked set also defines, already logged. shadowed: HashSet, - /// What each reader was shown, by the state key it read and its viewport (`note_read`). - shown: ShownMap, + /// What each reader was shown, by viewport (`read`). + shown: HashMap, /// The scope each child scope is declared inside: an instance of the child is also an instance of the parent. parents: HashMap<&'static str, &'static str>, } @@ -168,7 +194,7 @@ fn same_state(a: Option<&CommandState>, b: Option<&CommandState>) -> bool { a.cloned().unwrap_or_default() == b.cloned().unwrap_or_default() } -/// Who read a command's resolution: the vantage `begin` resolves it from again. +/// Who read a command's resolution: the vantage it is resolved from again. #[derive(Clone, PartialEq, Eq, Hash)] enum Reader { /// A surface with no component of its own (`resolve_global`): the key focus of the running pass. @@ -182,36 +208,275 @@ enum Reader { InMenu(Id, CommandChain), } -/// What each reader was shown the last time it resolved a command, by the viewport and the state key it read. The -/// readers of a key stay in the order they first read it: the gate is app code, and `wake_shown` asks it in that order. -type ShownMap = HashMap>>; +impl Reader { + /// The reader's kind, for the testing check's message. + #[cfg(feature = "testing")] + fn kind(&self) -> &'static str { + match self { + Reader::Global => "global", + Reader::Beneath(_) => "beneath-layer", + Reader::Chain(_) => "component", + Reader::InMenu(..) => "in-menu", + } + } -/// Keeps `resolved` as what `reader` of `viewport` was shown under `key`, in place of what it was shown before. -fn keep_shown(shown: &mut ShownMap, key: StateKey, viewport: ViewportId, reader: Reader, resolved: &ResolvedCommand) { - keep_in(shown.entry(viewport).or_default().entry(key).or_default(), reader, resolved); -} - -fn keep_in(readers: &mut Vec<(Reader, ResolvedCommand)>, reader: Reader, resolved: &ResolvedCommand) { - match readers.iter_mut().find(|(kept, _)| *kept == reader) { - Some((_, kept)) => kept.clone_from(resolved), - None => readers.push((reader, resolved.clone())), + /// The layer or menu whose vantage this reader is judged from, which the reader goes with when it closes. + fn layer(&self) -> Option { + match self { + Reader::Beneath(layer) | Reader::InMenu(layer, _) => Some(*layer), + _ => None, + } } } -/// Notes, in the read record, that the running code showed the state under `key`, and keeps what `reader` was shown: a -/// settled region that showed it runs when `begin` resolves the command from the same reader to something else (a -/// state, the gate, a modal layer or an instance changed), and a change published after it in the pass runs the pass -/// again. -fn note_read(ctx: &Context, key: Option, reader: Reader, resolved: &ResolvedCommand) { - let Some((number, instance)) = key else { return }; - reads::note(ctx, BindKey::Command(number, instance), Id::NULL, measure::active(ctx), &[]); - let viewport = pass::current_viewport(ctx); - with(ctx, |board| keep_shown(&mut board.shown, (number, instance), viewport, reader, resolved)); +/// The generations of what resolutions read beside states and the gate, across the viewports. +#[derive(Clone, Copy, Default, PartialEq)] +struct Gens { + /// Read by every resolution: the keymap, the app catalog and the registry, the scope parents, the instances and + /// their liveness, and the modal facts (open layers, their roots, the states published inside them, the held-open + /// canvas). + shared: u64, + /// Read by a resolution that picks an instance: the instances around the focus in every viewport. + focus: u64, +} + +/// The generations of one viewport's own vantage facts. +#[derive(Clone, Copy, Default, PartialEq)] +struct ViewGens { + /// Read by every resolution in the viewport: a dialog owns the keys at its focus. + keys: u64, + /// Read by a resolution that picks an instance or reaches by focus: the chain last focused in the viewport and the + /// instances of its focus chain inside the top modal layer. + focus: u64, + /// Read by a resolution the focused stop answered: the edits that stop takes and those of them that do nothing now. + edits: u64, +} + +/// One viewport's vantage facts as its last `begin` set them, and their generations. A viewport's `begin` compares +/// with its own, so two windows never move each other's. +#[derive(Default)] +struct View { + /// The chain of the last pass in which any component of the viewport held key focus. + last_focused: Vec, + inside_modal: Vec, + dialog_keys: bool, + /// The focused stop's edits and those of them that do nothing now. The focus record changes only in an end hook, + /// so the value `begin` reads holds for the pass. + edits: Option<(EditSet, EditSet)>, + gens: ViewGens, +} + +/// What a resolution read besides the board's own generation and the gate. +#[derive(Default)] +struct Reads { + /// It picked an instance for a source with no component of its own, or reached by the focus. + focus: bool, + /// The focused stop answered for the command, or was asked: it read that stop's edits. + edits: bool, +} + +/// The inputs a kept resolution was made from: it holds while each is unchanged. +#[derive(Clone, PartialEq)] +struct ResolveKey { + shared: u64, + /// The viewport's keys generation. + keys: u64, + /// The focus generations, across the viewports and the viewport's own, when the resolution read the focus. + focus: Option<(u64, u64)>, + /// The state key read and its revision. + state: Option<(StateKey, u64)>, + /// The gate's key and its answer, with a gate. + gate: Option<(u128, bool)>, + /// The viewport's edits generation, when the resolution read the focused stop's edits. + edits: Option, + /// The vantage of a reader under a layer or inside a menu (`None` inside: no stop to return to). + vantage: Option>, + /// The command's number, which a resolution the focused stop answered is noted under. + number: u32, +} + +impl ResolveKey { + /// The key a region that showed the resolution read it under: the state's, else the focused stop's answer. + fn bind(&self) -> Option { + match (self.state, self.edits) { + (Some(((number, instance), _)), _) => Some(BindKey::Command(number, instance)), + (None, Some(_)) => Some(BindKey::FocusedEdit(self.number)), + (None, None) => None, + } + } +} + +/// A resolution a reader was shown, and what it was made from. +struct Kept { + resolved: Arc, + key: ResolveKey, +} + +/// The inputs as a viewport's last wake saw them. +#[derive(Clone, Copy, Default, PartialEq)] +struct Woke { + gens: Gens, + view: ViewGens, + state_seq: u64, + gate: Option, +} + +/// A kept resolution and who it was kept for. +struct Entry { + reader: Reader, + kept: Kept, +} + +/// What each reader of a viewport was shown, with indexes from each input to the entries that read it, so a wake walks +/// only the entries whose inputs moved. +#[derive(Default)] +struct Shown { + entries: HashMap, + next: u64, + /// By reader and command number (a command's parameter variants share the number). + by_reader: HashMap>>, + /// By the state key read. + by_state: HashMap>, + /// The entries that read the focus generations. + by_focus: HashSet, + /// The entries that read the focused stop's edits. + by_edits: HashSet, + /// The entries of readers under a layer or inside a menu, whose vantage every wake reads again. + layered: HashSet, + /// The inputs at the last wake. + woke: Option, +} + +impl Shown { + fn index(&mut self, id: u64) { + let Some(entry) = self.entries.get(&id) else { return }; + let key = &entry.kept.key; + if let Some((state, _)) = key.state { + self.by_state.entry(state).or_default().insert(id); + } + if key.focus.is_some() { + self.by_focus.insert(id); + } + if key.edits.is_some() { + self.by_edits.insert(id); + } + if entry.reader.layer().is_some() { + self.layered.insert(id); + } + } + + fn unindex(&mut self, id: u64) { + let Some(entry) = self.entries.get(&id) else { return }; + if let Some((state, _)) = entry.kept.key.state + && let Some(ids) = self.by_state.get_mut(&state) + { + ids.remove(&id); + if ids.is_empty() { + self.by_state.remove(&state); + } + } + self.by_focus.remove(&id); + self.by_edits.remove(&id); + self.layered.remove(&id); + } + + /// The entry `reader` keeps for `command`. + fn find(&self, reader: &Reader, number: u32, command: &CommandRef) -> Option { + let ids = self.by_reader.get(reader)?.get(&number)?; + ids.iter().copied().find(|id| self.entries.get(id).is_some_and(|entry| entry.kept.resolved.command == *command)) + } + + /// Keeps `kept` for `reader`, in place of what it kept for the same command. + fn keep(&mut self, reader: Reader, number: u32, kept: Kept) { + match self.find(&reader, number, &kept.resolved.command) { + Some(id) => self.replace(id, kept), + None => { + let id = self.next; + self.next += 1; + self.by_reader.entry(reader.clone()).or_default().entry(number).or_default().push(id); + self.entries.insert(id, Entry { reader, kept }); + self.index(id); + } + } + } + + /// `kept` in place of entry `id`'s, indexed under its inputs. + fn replace(&mut self, id: u64, kept: Kept) { + self.unindex(id); + if let Some(entry) = self.entries.get_mut(&id) { + entry.kept = kept; + } + self.index(id); + } + + /// Drops the entries `drop` names. + fn drop_where(&mut self, mut drop: impl FnMut(&Entry) -> bool) { + let gone: Vec = self.entries.iter().filter(|(_, entry)| drop(entry)).map(|(id, _)| *id).collect(); + for id in gone { + self.unindex(id); + if let Some(entry) = self.entries.remove(&id) { + let number = entry.kept.key.number; + if let Some(by_number) = self.by_reader.get_mut(&entry.reader) { + if let Some(ids) = by_number.get_mut(&number) { + ids.retain(|at| *at != id); + if ids.is_empty() { + by_number.remove(&number); + } + } + if by_number.is_empty() { + self.by_reader.remove(&entry.reader); + } + } + } + } + } +} + +/// Whether `key` still holds under the board's `gens`, the viewport's `view` generations, `revisions`, the current +/// `gate` answer and the reader's `vantage`. A gate whose key moved but whose answer is the same keeps the resolution, +/// under the new key. +fn holds( + key: &mut ResolveKey, + gens: Gens, + view: ViewGens, + revisions: &HashMap, + gate: Option<(u128, bool)>, + vantage: Option<&Option>, +) -> bool { + let same = key.shared == gens.shared + && key.keys == view.keys + && key.focus.is_none_or(|focus| focus == (gens.focus, view.focus)) + && key.edits.is_none_or(|edits| edits == view.edits) + && key.state.is_none_or(|(state, revision)| revisions.get(&state).copied().unwrap_or(0) == revision) + && key.vantage.as_ref() == vantage; + let gate = match (key.gate, gate) { + (kept, now) if kept == now => true, + (Some((_, kept)), Some((now, answer))) if kept == answer => { + key.gate = Some((now, answer)); + true + } + _ => false, + }; + same && gate +} + +/// The edits of the stop that holds key focus in `viewport`, and those of them that do nothing now. +fn focused_edits(ctx: &Context, viewport: ViewportId) -> Option<(EditSet, EditSet)> { + focus::record(ctx, viewport).keys.map(|keys| (keys.edits, keys.inactive)) +} + +/// Notes, in the read record, that the running code showed a resolution under `key` (a state's, or the focused stop's +/// answer): a settled region that showed it runs when `begin` resolves the command from the same reader to something +/// else (a state, the gate, a modal layer, an instance or the stop's edits changed), and a change published after it in +/// the pass runs the pass again. +fn note_read(ctx: &Context, key: Option) { + let Some(key) = key else { return }; + reads::note(ctx, key, Id::NULL, measure::active(ctx), &[]); } /// Where a resolution judges a command from: the modal facts and the focus. The board's own is the key focus of the /// running pass; a surface that closes before its command runs (the palette) judges from the window under it. -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq)] struct Vantage { /// A modal layer blocks a window. modal_open: bool, @@ -234,7 +499,64 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Board) -> R) -> R { pass_state::with::(ctx, f) } +/// What a reader's lookup found. +enum Lookup { + /// A kept resolution whose inputs are unchanged, and the key it was read under. + Fresh(Arc, Option), + /// A kept resolution some input of which changed. + Stale, + /// None. + Missing, +} + impl Board { + /// Notes that the state under `key` changed: the readers of it resolve again. + fn bump_state(&mut self, key: StateKey) { + self.state_seq += 1; + self.revisions.insert(key, self.state_seq); + self.state_log.push((self.state_seq, key)); + } + + /// The gate's key and its answer for `command`, asking it once per command under each key. + fn gate_answer(&mut self, command: &CommandRef) -> Option<(u128, bool)> { + let gate = self.gate.as_ref()?; + let answer = match self.gate_answers.get(command.key_text().as_ref()) { + Some(answer) => *answer, + None => { + let answer = gate.allows(command); + self.gate_answers.insert(command.key(), answer); + answer + } + }; + Some((gate.key(), answer)) + } + + /// The generations of `viewport`'s own vantage facts. + fn view_gens(&self, viewport: ViewportId) -> ViewGens { + self.views.get(&viewport).map_or_else(ViewGens::default, |view| view.gens) + } + + /// What `reader` of `viewport` was shown of `command`, judged from `vantage` (a layered reader's). + fn lookup(&mut self, viewport: ViewportId, reader: &Reader, command: &CommandRef, vantage: Option<&Option>) -> Lookup { + let Some(&number) = self.numbers.get(command.id.as_str()) else { return Lookup::Missing }; + let gate = self.gate_answer(command); + let view = self.view_gens(viewport); + let Some(shown) = self.shown.get_mut(&viewport) else { return Lookup::Missing }; + let Some(id) = shown.find(reader, number, command) else { return Lookup::Missing }; + let Some(entry) = shown.entries.get_mut(&id) else { return Lookup::Missing }; + if holds(&mut entry.kept.key, self.gens, view, &self.revisions, gate, vantage) { + Lookup::Fresh(Arc::clone(&entry.kept.resolved), entry.kept.key.bind()) + } else { + Lookup::Stale + } + } + + /// Keeps `resolved`, made from `key`, as what `reader` of `viewport` was shown. + fn keep(&mut self, viewport: ViewportId, reader: Reader, resolved: Arc, key: ResolveKey) { + let number = key.number; + self.shown.entry(viewport).or_default().keep(reader, number, Kept { resolved, key }); + } + fn live(&self, ctx: &Context, instance: &Instance) -> bool { instance.stamp + 1 >= pass::pass_nr(ctx, instance.viewport) } @@ -332,7 +654,8 @@ impl Board { fn pick(&self, ctx: &Context, scope: &str, from: &Vantage) -> Option { // The held-open canvas ranks below every instance around the focus. let focused: Vec = self.held_open.into_iter().chain(from.focused.iter().flat_map(|(_, chain)| chain.iter().copied())).collect(); - pick_instance(&self.live_instances(ctx, scope), &focused, &self.last_focused) + let last = self.views.get(&pass::current_viewport(ctx)).map_or(&[][..], |view| view.last_focused.as_slice()); + pick_instance(&self.live_instances(ctx, scope), &focused, last) } /// The non-app scopes around the focus, innermost first. An instance of a child scope also brings the scopes it @@ -370,7 +693,8 @@ impl Board { /// Who answers for `command` ahead of the app: an instance inside the top modal layer that published its state, /// else the focused component when it takes the command as an edit (inside a modal layer, only when the focus /// is in it). - fn declaring(&self, ctx: &Context, command: &CommandRef, from: &Vantage) -> Option { + fn declaring(&self, ctx: &Context, command: &CommandRef, from: &Vantage, reads: &mut Reads) -> Option { + reads.focus = true; let dialog_open = from.modal_open || from.dialog_keys; let number = *self.numbers.get(command.id.as_str())?; let published = self.modal_published.iter().chain(&self.modal_published_last).find(|(published, _)| *published == number); @@ -378,10 +702,13 @@ impl Board { return Some(Declaration::Instance(id)); } let edit = self.registry.edit_of(&command.id)?; - let keys = from - .edits - .map(|edits| (edits, from.inactive.unwrap_or(EditSet::NONE))) - .or_else(|| focus::record(ctx, pass::current_viewport(ctx)).keys.map(|keys| (keys.edits, keys.inactive))); + let keys = match from.edits { + Some(edits) => Some((edits, from.inactive.unwrap_or(EditSet::NONE))), + None => { + reads.edits = true; + focused_edits(ctx, pass::current_viewport(ctx)) + } + }; let in_reach = !dialog_open || !from.inside_modal.is_empty(); let (edits, inactive) = keys.filter(|_| in_reach)?; edits.contains(edit).then_some(Declaration::Focused { inactive: inactive.contains(edit) }) @@ -396,6 +723,7 @@ impl Board { instance: Option, reach: Reach<'_>, from: &Vantage, + reads: &mut Reads, ) -> (ResolvedCommand, Option) { let def = self.def(&command.id); let app = self.to_app(self.scope_of(command)); @@ -404,7 +732,7 @@ impl Board { // A command no set registers is never blocked. let rule = def.map(|def| def.modal); // The instance inside the top modal that declares the command, which then answers for it. - let declaring = (rule == Some(ModalRule::Declared)).then(|| self.declaring(ctx, command, from)).flatten(); + let declaring = (rule == Some(ModalRule::Declared)).then(|| self.declaring(ctx, command, from, reads)).flatten(); // The declaring instance answers for the command: it is where the command is delivered. The focused component // answers for itself, so the app's state of the command does not apply. let instance = match declaring { @@ -416,13 +744,20 @@ impl Board { Some(Declaration::Focused { .. }) => None, None => self.state_key(command, instance), }; - let this = key.and_then(|key| self.this.get(&key)); - let last = key.and_then(|key| self.last.get(&key)); + // An app-scope state is the app's held one; an instance's is this frame's publish, else last frame's. + let (this, last) = match key { + Some((number, None)) => (self.app_states.get(&number), None), + Some(key) => (self.this.get(&key), self.last.get(&key)), + None => (None, None), + }; let state = this.or(last); let flags = resolve_flags(this.map(CommandState::flags), last.map(CommandState::flags)); let reached = declaring.is_some() || instance.is_some_and(|id| match reach { - Reach::Focus => from.inside_modal.contains(&id), + Reach::Focus => { + reads.focus = true; + from.inside_modal.contains(&id) + } Reach::Chain(chain) => chain.ids().skip_while(|at| !self.is_modal_root(*at)).any(|at| at == id), }); let modal = !dialog_open @@ -494,7 +829,10 @@ fn chord_input(chord: &Chord) -> KeyInput { /// Loads the linked command sets; the stories' sets only with `stories`. pub(crate) fn install(ctx: &Context, stories: bool) -> Result<(), registry::CommandDefError> { let registry = registry::Registry::shared(stories)?; - with(ctx, |board| board.registry = registry); + with(ctx, |board| { + board.registry = registry; + board.gens.shared += 1; + }); Ok(()) } @@ -645,7 +983,9 @@ fn keymap_for(registry: &Arc, app: Option<&AppCatalog>, plat #[doc(hidden)] pub fn declare_child(ctx: &Context, child: CommandScope, parent: CommandScope) { with(ctx, |board| { - board.parents.insert(child.name(), parent.name()); + if board.parents.insert(child.name(), parent.name()) != Some(parent.name()) { + board.gens.shared += 1; + } }); } @@ -659,24 +999,48 @@ fn platform(ctx: &Context) -> Platform { crate::runtime::windows::os_of(ctx) } -/// Before each frame: last frame's state is the fallback, the app's states, gate and catalog are this frame's, and the -/// keymap follows the user's overrides and the catalog's generation. The readers of a state that changed run from -/// `begin`, which resolves again what each was shown. +/// Before each frame: the states instances published last frame are the fallback, the app's states are read again +/// when their revision moved, the gate and the catalog are this frame's, and the keymap follows the user's overrides +/// and the catalog's generation. The readers of an input that changed run from `begin`, which resolves again what each +/// was shown. pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { let platform = platform(ctx); let frame = pass::root_frame_nr(ctx); let generation = input.catalog.as_ref().map(AppCatalog::generation); let shadowed = with(ctx, |board| { - let mut states = HashMap::new(); - for (command, state) in &input.states { - let number = board.number(&command.id); - states.insert((number, None), state.clone()); + // A published state resolves from this frame's, else the last frame's: one published last frame and not again + // is gone now. + let gone: Vec = board.last.keys().filter(|key| !board.this.contains_key(key)).copied().collect(); + board.last = std::mem::take(&mut board.this); + for key in gone { + board.bump_state(key); + } + if board.modal_published_last.iter().any(|key| !board.modal_published.contains(key)) { + board.gens.shared += 1; } - // A state resolves from this frame's, else the last frame's. - board.last = std::mem::replace(&mut board.this, states); board.modal_published_last = std::mem::take(&mut board.modal_published); + let revision = input.states.as_ref().map(|(revision, _)| *revision); + if revision != board.app_revision { + board.app_revision = revision; + let mut states = HashMap::new(); + for (command, state) in input.states.iter().flat_map(|(_, states)| states.iter()) { + states.insert(board.number(&command.id), state.clone()); + } + let changed: Vec = states + .iter() + .filter(|(number, state)| board.app_states.get(number) != Some(*state)) + .map(|(number, _)| *number) + .chain(board.app_states.keys().filter(|number| !states.contains_key(number)).copied()) + .collect(); + board.app_states = states; + for number in changed { + board.bump_state((number, None)); + } + } + if input.gate.as_ref().map(CommandGate::key) != board.gate.as_ref().map(CommandGate::key) { + board.gate_answers.clear(); + } board.gate = input.gate.clone(); - board.gate_answers.clear(); board.app = input.catalog.clone(); let stale = board.keymap.as_ref().is_none_or(|cache| { cache.platform != platform @@ -693,6 +1057,7 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { keymap_for(&board.registry, input.catalog.as_ref(), platform, input.overrides.as_ref()); board.keymap = Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts, shown_text }); + board.gens.shared += 1; for def in input.catalog.as_ref().map_or(&[][..], AppCatalog::defs) { if board.registry.get(&def.command.id).is_some() && board.shadowed.insert(def.command.id.clone()) { shadowed.push(def.command.id.clone()); @@ -756,10 +1121,14 @@ pub(crate) fn register_instance(ctx: &Context, scope: CommandScope, id: Id) { /// `register_instance` in the layer `layer`, which a replay of the registration keeps. fn register_in(ctx: &Context, scope: CommandScope, id: Id, layer: Option) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_in(ctx, scope, id, layer)); + crate::runtime::replay::journal(ctx, || (scope, id, layer), |ctx, &(scope, id, layer)| register_in(ctx, scope, id, layer)); let viewport = pass::current_viewport(ctx); let stamp = pass::pass_nr(ctx, viewport); - with(ctx, |board| board.instances.upsert(Instance { id, scope, viewport, stamp, layer })); + with(ctx, |board| { + if board.instances.upsert(Instance { id, scope, viewport, stamp, layer }) { + board.gens.shared += 1; + } + }); } /// Records the instances around the component `id`, which holds key focus in the running pass of its viewport. The @@ -782,11 +1151,14 @@ pub(crate) fn note_focus(ctx: &Context, id: Id, chain: &CommandChain) { pub(crate) fn set_modal_open(ctx: &Context, open: bool, viewport: ViewportId, root: Option) { with(ctx, |board| { - board.here.modal_open = open; - match root { + let held = match root { Some(root) => board.modal_roots.insert(viewport, root), None => board.modal_roots.remove(&viewport), }; + if board.here.modal_open != open || held != root { + board.gens.shared += 1; + } + board.here.modal_open = open; }); } @@ -843,51 +1215,51 @@ fn vantage_under(ctx: &Context, layer: Id, stop: Option<(focus::StopRec, Vec } /// `command` as seen by `instance` (`None` for the app) from `from` (`None`: the key focus of the running pass), with -/// the gate applied outside the board's lock, and the key of the state it read. +/// the gate applied, and the inputs it was made from; `reads` holds what the caller read to find the instance. fn resolve_in( ctx: &Context, command: &CommandRef, instance: Option, reach: Reach<'_>, from: Option<&Vantage>, -) -> (ResolvedCommand, Option) { - let ((mut resolved, key), first_unknown, gate) = with(ctx, |board| { + mut reads: Reads, +) -> (ResolvedCommand, ResolveKey) { + let (resolved, key, first_unknown) = with(ctx, |board| { let first_unknown = board.def(&command.id).is_none() && board.unknown.insert(command.id.clone()); // A command no state named yet has a key too, so a state given later reaches the regions that read it. board.number(&command.id); - let resolved = board.resolve(ctx, command, instance, reach, from.unwrap_or(&board.here)); - // This frame's answer, else the gate to ask. - let gate = board.gate.as_ref().map(|gate| board.gate_answers.get(command.key_text().as_ref()).copied().ok_or_else(|| gate.clone())); - (resolved, first_unknown, gate) + let (mut resolved, state) = board.resolve(ctx, command, instance, reach, from.unwrap_or(&board.here), &mut reads); + let gate = board.gate_answer(command); + if gate.is_some_and(|(_, allowed)| !allowed) { + resolved.enabled = false; + } + let view = board.view_gens(pass::current_viewport(ctx)); + let key = ResolveKey { + shared: board.gens.shared, + keys: view.keys, + focus: reads.focus.then_some((board.gens.focus, view.focus)), + state: state.map(|state| (state, board.revisions.get(&state).copied().unwrap_or(0))), + gate, + edits: reads.edits.then_some(view.edits), + vantage: None, + number: board.numbers.get(command.id.as_str()).copied().unwrap_or(u32::MAX), + }; + (resolved, key, first_unknown) }); if first_unknown { log::warn!("the command {} is in no registered command set: it is an app command with its id as its label", command.id); } - let allowed = match gate { - None => true, - Some(Ok(answer)) => answer, - Some(Err(gate)) => { - let answer = gate.allows(command); - with(ctx, |board| { - board.gate_answers.insert(command.key(), answer); - }); - answer - } - }; - if !allowed { - resolved.enabled = false; - } (resolved, key) } /// `command` for a surface with no component of its own: against the instance that `fire` would target. -pub(crate) fn resolve_global(ctx: &Context, command: &CommandRef) -> ResolvedCommand { +pub(crate) fn resolve_global(ctx: &Context, command: &CommandRef) -> Arc { read(ctx, Reader::Global, command) } /// `command` for a surface with no component of its own that closes before its command runs, from the window under /// the modal layer `layer` (`beneath`). -pub(crate) fn resolve_beneath(ctx: &Context, layer: Id, command: &CommandRef) -> ResolvedCommand { +pub(crate) fn resolve_beneath(ctx: &Context, layer: Id, command: &CommandRef) -> Arc { read(ctx, Reader::Beneath(layer), command) } @@ -897,7 +1269,7 @@ pub(crate) fn resolve_beneath(ctx: &Context, layer: Id, command: &CommandRef) -> /// group whose button opened it, focused or not), judged from the stop focus returns to once the menus close, which /// gives the edits, the modal facts and the instance when the chain holds none (Cut in a text field's edit menu follows /// the field's selection; an Edit menu row reaches the field that held focus); its activation fires that resolution. -pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> ResolvedCommand { +pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Arc { let reader = match focus::running_menu(ctx) { Some(menu) => Reader::InMenu(menu, chain.clone()), None => Reader::Chain(chain.clone()), @@ -905,89 +1277,198 @@ pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &Comma read(ctx, reader, command) } -/// `command` as `reader` is shown it, noted as its read. -fn read(ctx: &Context, reader: Reader, command: &CommandRef) -> ResolvedCommand { - let (resolved, key) = resolve_as(ctx, &reader, command); - note_read(ctx, key, reader, &resolved); +/// `command` as `reader` is shown it, noted as its read: the kept resolution while its inputs are unchanged, else a new +/// one, kept. +fn read(ctx: &Context, reader: Reader, command: &CommandRef) -> Arc { + let viewport = pass::current_viewport(ctx); + let vantage = vantage_of(ctx, &reader); + let found = with(ctx, |board| board.lookup(viewport, &reader, command, vantage.as_ref())); + let (resolved, bind) = match found { + Lookup::Fresh(resolved, bind) => (resolved, bind), + found => { + #[cfg(feature = "testing")] + measure::count_resolve(ctx, if matches!(found, Lookup::Stale) { Resolve::Again } else { Resolve::New }); + let _ = found; + let (resolved, key) = resolve_as(ctx, &reader, command, vantage); + let (resolved, bind) = (Arc::new(resolved), key.bind()); + with(ctx, |board| board.keep(viewport, reader, Arc::clone(&resolved), key)); + (resolved, bind) + } + }; + note_read(ctx, bind); resolved } -/// `command` from the vantage of `reader`, and the key of the state it read. The readers' first resolution and the one -/// `begin` makes again both come from here. -fn resolve_as(ctx: &Context, reader: &Reader, command: &CommandRef) -> (ResolvedCommand, Option) { +/// The vantage a layered reader is judged from: the window under its layer, or where focus goes once its menus close +/// (`None` when no stop is there). `None` for the other readers, which are judged from the board's own. +fn vantage_of(ctx: &Context, reader: &Reader) -> Option> { match reader { - Reader::Global => resolve_from(ctx, command, None), - Reader::Beneath(layer) => { - let from = beneath(ctx, *layer); - resolve_from(ctx, command, Some(&from)) - } - Reader::Chain(chain) => resolve_chain(ctx, command, chain), - Reader::InMenu(menu, chain) => { - let from = out_of_menu(ctx, *menu); - let instance = with(ctx, |board| { - board.innermost(chain, board.scope_of(command)).or_else(|| board.target_of(ctx, command, from.as_ref().unwrap_or(&board.here)).1) - }); - resolve_in(ctx, command, instance, Reach::Chain(chain), from.as_ref()) - } + Reader::Beneath(layer) => Some(Some(beneath(ctx, *layer))), + Reader::InMenu(menu, _) => Some(out_of_menu(ctx, *menu)), + Reader::Global | Reader::Chain(_) => None, } } -/// `command` against the instances of `chain`. -fn resolve_chain(ctx: &Context, command: &CommandRef, chain: &CommandChain) -> (ResolvedCommand, Option) { - let instance = with(ctx, |board| board.innermost(chain, board.scope_of(command)).or_else(|| board.target_of(ctx, command, &board.here).1)); - resolve_in(ctx, command, instance, Reach::Chain(chain), None) +/// `command` from the vantage of `reader` (`vantage`, from `vantage_of`), and the inputs it was made from. The +/// readers' first resolution and the one `begin` makes again both come from here. +fn resolve_as(ctx: &Context, reader: &Reader, command: &CommandRef, vantage: Option>) -> (ResolvedCommand, ResolveKey) { + let from = vantage.as_ref().and_then(Option::as_ref); + let (resolved, mut key) = match reader { + Reader::Global | Reader::Beneath(_) => resolve_from(ctx, command, from), + Reader::Chain(chain) => resolve_chain(ctx, command, chain, None), + Reader::InMenu(_, chain) => resolve_chain(ctx, command, chain, from), + }; + key.vantage = vantage; + (resolved, key) } -fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) -> (ResolvedCommand, Option) { - let (_, instance) = with(ctx, |board| board.target_of(ctx, command, from.unwrap_or(&board.here))); - resolve_in(ctx, command, instance, Reach::Focus, from) +/// The instance a source with no component of its own delivers `command` to from `from`, noting in `reads` that it +/// read the focus when it picked one. +fn target_read(ctx: &Context, board: &Board, command: &CommandRef, from: &Vantage, reads: &mut Reads) -> (bool, Option) { + let (app, instance) = board.target_of(ctx, command, from); + reads.focus |= !app; + (app, instance) } -/// fx.F23: resolves every command a reader of `viewport` was shown again, from that reader's own vantage under this -/// pass's gate, states, modal facts and instances, and notes an edit of the state key of each whose resolution differs -/// in any shown part (label, chord, enabled, checked, marked, hint), so a settled region that shows it runs; the entry -/// keeps the new resolution. Readers of regions that did not run keep their entries: a settled region is the reader -/// this exists for. It reads no input: a second pass of a frame compares against what the first pass's runs were shown -/// and what the first pass's call kept, so it wakes only the readers whose resolution the first pass changed (a modal +/// `command` against the instances of `chain`, judged from `from` (`None`: the board's own vantage). +fn resolve_chain(ctx: &Context, command: &CommandRef, chain: &CommandChain, from: Option<&Vantage>) -> (ResolvedCommand, ResolveKey) { + let mut reads = Reads::default(); + let instance = with(ctx, |board| { + board.innermost(chain, board.scope_of(command)).or_else(|| target_read(ctx, board, command, from.unwrap_or(&board.here), &mut reads).1) + }); + resolve_in(ctx, command, instance, Reach::Chain(chain), from, reads) +} + +fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) -> (ResolvedCommand, ResolveKey) { + let mut reads = Reads::default(); + let (_, instance) = with(ctx, |board| target_read(ctx, board, command, from.unwrap_or(&board.here), &mut reads)); + resolve_in(ctx, command, instance, Reach::Focus, from, reads) +} + +/// `command` resolved once, for a key press or a fire: nothing keeps it. +fn resolve_once(ctx: &Context, command: &CommandRef, instance: Option, reach: Reach<'_>, from: Option<&Vantage>) -> ResolvedCommand { + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::New); + resolve_in(ctx, command, instance, reach, from, Reads::default()).0 +} + +/// fx.F23: resolves again what a reader of `viewport` was shown when an input of it changed since the viewport's last +/// wake, from that reader's own vantage under this pass's gate, states, modal facts and instances, and notes an edit of +/// the key each was read under when its resolution differs in any shown part (label, chord, enabled, checked, marked, +/// hint), so a settled region that shows it runs; the entry keeps the new resolution. Readers of regions that did not +/// run keep their entries: a settled region is the reader this exists for. It walks only the entries whose inputs +/// moved, through the table's indexes: every entry when a generation all of them read moved (the shared one, the +/// viewport's keys, the gate), else the readers of the focus, of the focused stop's edits and of each changed state, +/// and the readers under a layer or in a menu, whose vantage it reads again. A second pass of a frame compares against +/// what the first pass's runs were shown, so it wakes only the readers whose resolution the first pass changed (a modal /// layer it opened or closed), once. fn wake_shown(ctx: &Context, viewport: ViewportId) { - let mut table = with(ctx, |board| board.shown.remove(&viewport)).unwrap_or_default(); + let taken = with(ctx, |board| { + let now = + Woke { gens: board.gens, view: board.view_gens(viewport), state_seq: board.state_seq, gate: board.gate.as_ref().map(CommandGate::key) }; + let shown = board.shown.get(&viewport)?; + let woke = shown.woke; + if woke == Some(now) && shown.layered.is_empty() { + return None; + } + let all = woke.is_none_or(|woke| woke.gens.shared != now.gens.shared || woke.view.keys != now.view.keys || woke.gate != now.gate); + let mut walk: HashSet = if all { shown.entries.keys().copied().collect() } else { shown.layered.clone() }; + if let Some(woke) = woke.filter(|_| !all) { + if (woke.gens.focus, woke.view.focus) != (now.gens.focus, now.view.focus) { + walk.extend(&shown.by_focus); + } + if woke.view.edits != now.view.edits { + walk.extend(&shown.by_edits); + } + for (_, state) in board.state_log.iter().filter(|(seq, _)| *seq > woke.state_seq) { + walk.extend(shown.by_state.get(state).into_iter().flatten()); + } + } + Some((now, walk, board.shown.remove(&viewport)?)) + }); + let Some((now, walk, mut table)) = taken else { return }; let mut changed = Vec::new(); - for (key, readers) in &mut table { - // A reader beneath a layer or inside a menu that is no longer shown is gone with it. - readers.retain(|(reader, _)| match reader { - Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, *layer), - _ => true, + // A reader beneath a layer or inside a menu that is no longer shown is gone with it. + table.drop_where(|entry| entry.reader.layer().is_some_and(|layer| !overlay::is_open(ctx, layer))); + let mut vantages: HashMap>> = HashMap::new(); + for id in walk { + let Some(entry) = table.entries.get_mut(&id) else { continue }; + #[cfg(feature = "testing")] + measure::count_wake_walk(ctx); + let vantage = match entry.reader.layer() { + Some(layer) => vantages.entry(layer).or_insert_with(|| vantage_of(ctx, &entry.reader)).clone(), + None => None, + }; + let fresh = with(ctx, |board| { + let gate = board.gate_answer(&entry.kept.resolved.command); + holds(&mut entry.kept.key, board.gens, board.view_gens(viewport), &board.revisions, gate, vantage.as_ref()) }); - for (reader, kept) in readers.iter_mut() { - // The gate is app code and may resolve commands itself, so no board lock is held here. - let (resolved, _) = resolve_as(ctx, reader, &kept.command); - if resolved != *kept { - *kept = resolved; - changed.push(*key); - } + if fresh { + continue; } + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::Again); + let (resolved, key) = resolve_as(ctx, &entry.reader, &entry.kept.resolved.command, vantage); + let was = entry.kept.key.bind(); + let resolved = if resolved == *entry.kept.resolved { + Arc::clone(&entry.kept.resolved) + } else { + changed.extend(was); + changed.extend(key.bind().filter(|bind| Some(*bind) != was)); + Arc::new(resolved) + }; + table.replace(id, Kept { resolved, key }); } - table.retain(|_, readers| !readers.is_empty()); + table.woke = Some(now); with(ctx, |board| { - // Reads the gate made while the entries were out of the board. - let added = board.shown.remove(&viewport).unwrap_or_default(); - for (key, readers) in added { - for (reader, resolved) in readers { - keep_in(table.entry(key).or_default(), reader, &resolved); + // Resolutions read nothing into the table while it is out of the board; keep any that arrived all the same. + if let Some(added) = board.shown.remove(&viewport) { + for (_, entry) in added.entries { + let number = entry.kept.key.number; + table.keep(entry.reader, number, entry.kept); } } - if !table.is_empty() { + if !table.entries.is_empty() { board.shown.insert(viewport, table); } }); - for (number, instance) in changed { - lazy::note_edit(ctx, BindKey::Command(number, instance)); + for key in changed { + lazy::note_edit(ctx, key); } } +/// Testing check, every 100th pass of a viewport: every kept resolution of `viewport` equals a full resolution from its +/// reader, and every kept gate answer equals the gate's answer asked again apart from the cache. A difference is an +/// input the keys miss. +#[cfg(feature = "testing")] +fn check_kept(ctx: &Context, viewport: ViewportId) { + let Some(table) = with(ctx, |board| board.shown.remove(&viewport)) else { return }; + for entry in table.entries.values() { + if entry.reader.layer().is_some_and(|layer| !overlay::is_open(ctx, layer)) { + continue; + } + let command = &entry.kept.resolved.command; + measure::count_resolve(ctx, Resolve::Checked); + let (fresh, _) = resolve_as(ctx, &entry.reader, command, vantage_of(ctx, &entry.reader)); + assert!( + fresh == *entry.kept.resolved, + "the kept resolution of {} for a {} reader differs from a full resolve: kept {:?}, resolved {fresh:?}", + command, + entry.reader.kind(), + entry.kept.resolved, + ); + let (cached, gate) = with(ctx, |board| (board.gate_answers.get(command.key_text().as_ref()).copied(), board.gate.clone())); + if let (Some(cached), Some(gate)) = (cached, gate) { + assert!(cached == gate.allows(command), "the kept gate answer for {command} differs from the gate's"); + } + } + with(ctx, |board| { + board.shown.insert(viewport, table); + }); +} + /// Step-1 resolution for a context in `chain`; `None` when the command's scope has no instance in the chain. -pub(crate) fn resolve_scoped(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Option { +pub(crate) fn resolve_scoped(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Option> { let (found, app) = with(ctx, |board| { let scope = board.scope_of(command); (board.innermost(chain, scope).is_some(), board.to_app(scope)) @@ -1017,7 +1498,9 @@ fn queue(ctx: &Context, fired: Fired) { pub(crate) fn fall_through(ctx: &Context, command: craft_behavior::EditCommand) { let Some(command) = EditCommands::of(command) else { return }; let command = CommandRef::from(command); - let target = with(ctx, |board| board.resolve(ctx, &command, None, Reach::Focus, &board.here).0.instance); + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::New); + let target = with(ctx, |board| board.resolve(ctx, &command, None, Reach::Focus, &board.here, &mut Reads::default()).0.instance); let fired = Fired { target, ..Fired::new(command, FireSource::Key, FirePhase::Press, pass::now(ctx)) }; with(ctx, |board| if fired.target.is_some() { board.queue.push(fired) } else { board.out.push(fired) }); repaint::request_of(ctx, ViewportId::ROOT); @@ -1053,7 +1536,7 @@ fn fire_in(ctx: &Context, command: &CommandRef, source: FireSource, from: Option if !app && instance.is_none() { return false; } - let (resolved, _) = resolve_in(ctx, command, instance, Reach::Focus, from); + let resolved = resolve_once(ctx, command, instance, Reach::Focus, from); if !resolved.enabled { return false; } @@ -1073,10 +1556,11 @@ pub(crate) fn publish(ctx: &Context, chain: &CommandChain, command: &CommandRef, if !measure::effect(ctx, "commands::publish") { return; } - replay::journal(ctx, || { - let (chain, command, state) = (chain.clone(), command.clone(), state.clone()); - move |ctx: &Context| publish(ctx, &chain, &command, state.clone()) - }); + replay::journal( + ctx, + || (chain.clone(), command.clone(), state.clone()), + |ctx, (chain, command, state)| publish(ctx, chain, command, state.clone()), + ); let changed = with(ctx, |board| { let scope = board.scope_of(command); let declared = board.def(&command.id).is_some_and(|def| def.modal == ModalRule::Declared); @@ -1092,11 +1576,14 @@ pub(crate) fn publish(ctx: &Context, chain: &CommandChain, command: &CommandRef, let key = (number, Some(instance)); // The pass that publishes is the one that knows the layers around the caller. let in_modal = chain.ids().any(|id| board.is_modal_root(id)); - if in_modal { - board.modal_published.insert(key); + if in_modal && board.modal_published.insert(key) && !board.modal_published_last.contains(&key) { + board.gens.shared += 1; } let changed = !same_state(board.this.get(&key).or_else(|| board.last.get(&key)), Some(&state)); board.this.insert(key, state); + if changed { + board.bump_state(key); + } changed.then_some((number, instance)) }); if let Some((number, instance)) = changed { @@ -1158,7 +1645,7 @@ pub fn bound_around(ctx: &Context, at: Id, around: &CommandChain, S::from_ref(&hit.command)?; Some((hit.command, board.instance_around(at, around, S::SCOPE.name()))) })?; - let (resolved, _) = resolve_in(ctx, &command, instance, Reach::Chain(around), None); + let resolved = resolve_once(ctx, &command, instance, Reach::Chain(around), None); if resolved.enabled { S::from_ref(&command) } else { None } } @@ -1179,7 +1666,7 @@ pub(crate) fn binds_scoped(ctx: &Context, chord: &Chord) -> bool { let (_, instance) = board.target_of(ctx, &command, &board.here); Some((command, instance)) }); - found.is_some_and(|(command, instance)| resolve_in(ctx, &command, instance, Reach::Focus, None).0.enabled) + found.is_some_and(|(command, instance)| resolve_once(ctx, &command, instance, Reach::Focus, None).enabled) } /// Where a shortcut pressed with focus in a menu or on a menu bar matches, and where a hit gives the focus back. The @@ -1241,8 +1728,12 @@ pub(crate) fn begin(ctx: &Context) { // A shortcut pressed in a menu or on a menu bar matches where the focus returns to once the menus close. let returning = focused.filter(|_| !shortcuts.keys.is_empty()).and_then(|focused| Returning::of(ctx, focused)); let shell = frame::shell_root(ctx, viewport); + let edits = focused_edits(ctx, viewport); let taken = with(ctx, |board| { - board.held_open = held_open; + if board.held_open != held_open { + board.held_open = held_open; + board.gens.shared += 1; + } let returned = returning .map(Returning::id) .and_then(|held| [board.before.get(&viewport), board.chains.get(&viewport)].into_iter().flatten().find(|(id, _)| *id == held)) @@ -1255,18 +1746,42 @@ pub(crate) fn begin(ctx: &Context) { (true, Some(root)) => vec![*root], _ => chain, }; - if !chain.is_empty() { - board.last_focused.clone_from(&chain); + let view = board.views.entry(viewport).or_default(); + if !chain.is_empty() && view.last_focused != chain { + view.last_focused.clone_from(&chain); + view.gens.focus += 1; } // Nothing focused outside a modal: the window's shell root takes the commands, so a window command's key comes // before an app command's. Nothing holds focus there, so the chain last focused stays. let chain = if chain.is_empty() && focused.is_none() { shell.into_iter().collect() } else { chain }; match board.here.focused.iter_mut().find(|(v, _)| *v == viewport) { - Some(entry) => entry.1.clone_from(&chain), - None => board.here.focused.push((viewport, chain.clone())), + Some(entry) if entry.1 == chain => {} + Some(entry) => { + entry.1.clone_from(&chain); + board.gens.focus += 1; + } + None => { + board.here.focused.push((viewport, chain.clone())); + board.gens.focus += 1; + } } - board.here.dialog_keys = shortcuts.dialog; - board.here.inside_modal = Board::inside_modal_of(&chain, |id| board.is_modal_root(id)); + // The viewport's own facts move its own generations; `here` holds the running viewport's for the pass. + let inside_modal = Board::inside_modal_of(&chain, |id| board.is_modal_root(id)); + let view = board.views.entry(viewport).or_default(); + if view.dialog_keys != shortcuts.dialog { + view.dialog_keys = shortcuts.dialog; + view.gens.keys += 1; + } + if view.inside_modal != inside_modal { + view.inside_modal = inside_modal; + view.gens.focus += 1; + } + if view.edits != edits { + view.edits = edits; + view.gens.edits += 1; + } + board.here.dialog_keys = view.dialog_keys; + board.here.inside_modal.clone_from(&view.inside_modal); if shortcuts.keys.is_empty() { return None; } @@ -1282,6 +1797,10 @@ pub(crate) fn begin(ctx: &Context) { }); // With this pass's vantage set, what the readers were shown is resolved again before any of them runs. wake_shown(ctx, viewport); + #[cfg(feature = "testing")] + if pass::pass_nr(ctx, viewport).is_multiple_of(100) { + check_kept(ctx, viewport); + } let Some((keys, mut matcher)) = taken else { return }; let mut fired = Vec::new(); for shortcut in &shortcuts.keys { @@ -1309,7 +1828,7 @@ pub(crate) fn begin(ctx: &Context) { continue; }; let (app, instance) = with(ctx, |board| board.target_of(ctx, &hit.command, &board.here)); - let (resolved, _) = resolve_in(ctx, &hit.command, instance, Reach::Focus, None); + let resolved = resolve_once(ctx, &hit.command, instance, Reach::Focus, None); if !resolved.enabled { continue; } @@ -1362,9 +1881,22 @@ pub(crate) fn begin(ctx: &Context) { /// The end hook: instances that stopped registering are gone, and so are the commands queued for them and the readers /// inside them. pub(crate) fn end(ctx: &Context) { + let viewport = pass::current_viewport(ctx); with(ctx, |board| { let live = pass::live_viewports(ctx); let alive: Vec = board.instances.iter().map(|i| board.live(ctx, i) && live.contains(&i.viewport)).collect(); + // An instance of this viewport this pass did not register is dead from the viewport's next pass: resolutions + // see it. + let dies = board.instances.iter().zip(&alive).any(|(i, alive)| *alive && i.viewport == viewport && i.stamp < pass::pass_nr(ctx, viewport)); + let gone: HashSet = board.instances.iter().zip(&alive).filter(|(_, alive)| !**alive).map(|(i, _)| i.id).collect(); + // The revisions of a removed instance's states go in the same step as a shared move, which makes every entry + // that holds one stale first. + if !gone.is_empty() { + board.revisions.retain(|(_, instance), _| instance.is_none_or(|id| !gone.contains(&id))); + } + if dies || !gone.is_empty() { + board.gens.shared += 1; + } let mut keep = alive.iter(); board.instances.retain(|_| keep.next().copied().unwrap_or(false)); let instances = &board.instances; @@ -1373,16 +1905,20 @@ pub(crate) fn end(ctx: &Context) { board.held.retain(|held| held.target.is_none_or(ids)); board.chains.retain(|viewport, _| live.contains(viewport)); board.before.retain(|viewport, _| live.contains(viewport)); + board.views.retain(|viewport, _| live.contains(viewport)); board.here.focused.retain(|(viewport, _)| live.contains(viewport)); board.shown.retain(|viewport, table| { - table.retain(|_, readers| { - readers.retain(|(reader, _)| match reader { - Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(&ids), - _ => true, - }); - !readers.is_empty() + table.drop_where(|entry| match &entry.reader { + Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_some_and(|id| !ids(id)), + _ => false, }); - live.contains(viewport) && !table.is_empty() + live.contains(viewport) && !table.entries.is_empty() }); + // The state log keeps the changes no kept table has woken past. + let oldest = board.shown.values().map(|table| table.woke.map_or(0, |woke| woke.state_seq)).min(); + match oldest { + Some(oldest) => board.state_log.retain(|(seq, _)| *seq > oldest), + None => board.state_log.clear(), + } }); } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 2a041d071..cb38ae629 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -33,6 +33,7 @@ pub use board::{bound_around, take_around}; pub use board::{chord_text_builds, keymap_builds}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; +use crate::contract::{MemoKey, MemoProps, PlainData, Revision, Tracked}; use craft_behavior::CommandFlags; use craft_behavior::edit_history::Step; use craft_keymap::{Chord, Overrides}; @@ -282,17 +283,72 @@ pub struct ResolvedCommand { /// The app's one gate over commands: a dialog is open, a workspace is not ready, a recorder has the keys or an /// operation is pending. A command the gate refuses resolves disabled and does not fire. +/// +/// The gate is a `fn` of its props, as a memoized view's `show` is: the props hold everything the gate reads, so the +/// runtime asks it once per command while the props' key stays the same, and again only when it changes. #[derive(Clone)] -pub struct CommandGate(Arc bool + Send + Sync>); +pub struct CommandGate { + key: u128, + allows: Arc bool + Send + Sync>, +} impl CommandGate { - /// A gate that lets `allows` commands through. - pub fn new(allows: impl Fn(&CommandRef) -> bool + Send + Sync + 'static) -> Self { - CommandGate(Arc::new(allows)) + /// A gate that lets through the commands `allows` accepts under `props`. + pub fn new(props: P, allows: fn(&P, &CommandRef) -> bool) -> Self { + let mut key = MemoKey::new(); + key.feed_hash(&std::any::TypeId::of::

()); + key.write(&(allows as usize).to_le_bytes()); + props.key(&mut key); + CommandGate { key: key.finish(), allows: Arc::new(move |command| allows(&props, command)) } + } + + /// The key of the gate's props and `fn`: equal keys give equal answers. + pub(crate) fn key(&self) -> u128 { + self.key } pub(crate) fn allows(&self, command: &CommandRef) -> bool { - (self.0)(command) + (self.allows)(command) + } +} + +/// The app-scope command states an app holds, in a [`Tracked`] it hands to [`CommandInput::states`] every frame. The +/// runtime reads them again only when the revision moves. +#[derive(Clone, Debug, Default, PartialEq, PlainData)] +pub struct CommandStates { + #[plain_data(assume = "command refs and states are plain values; the list is copied on write")] + states: Arc>, +} + +impl CommandStates { + /// No states. + pub fn new() -> Self { + CommandStates::default() + } + + /// Gives `command` `state`, in place of the state it had. + pub fn set(&mut self, command: impl Into, state: CommandState) { + let command = command.into(); + let states = Arc::make_mut(&mut self.states); + match states.iter_mut().find(|(held, _)| *held == command) { + Some((_, held)) => *held = state, + None => states.push((command, state)), + } + } + + /// Removes the state of `command`, which then resolves with its own label, enabled. + pub fn remove(&mut self, command: &CommandRef) -> Option { + let at = self.states.iter().position(|(held, _)| held == command)?; + Some(Arc::make_mut(&mut self.states).remove(at).1) + } + + /// The state of `command`. + pub fn get(&self, command: &CommandRef) -> Option<&CommandState> { + self.states.iter().find(|(held, _)| held == command).map(|(_, state)| state) + } + + pub(crate) fn iter(&self) -> impl Iterator { + self.states.iter() } } @@ -300,7 +356,7 @@ impl CommandGate { #[derive(Clone, Default)] #[non_exhaustive] pub struct CommandInput { - pub(crate) states: Vec<(CommandRef, CommandState)>, + pub(crate) states: Option<(Revision, CommandStates)>, pub(crate) overrides: Option>, pub(crate) gate: Option, pub(crate) catalog: Option, @@ -312,10 +368,11 @@ impl CommandInput { CommandInput::default() } - /// The state of an app-scope command. + /// The app-scope command states the app holds. The runtime keeps the revision and reads the states again only + /// when it moves. #[must_use] - pub fn state(mut self, command: impl Into, state: CommandState) -> Self { - self.states.push((command.into(), state)); + pub fn states(mut self, states: &Tracked) -> Self { + self.states = Some((states.revision(), (**states).clone())); self } @@ -333,8 +390,8 @@ impl CommandInput { self } - /// The one gate over commands. It answers from what the app knew before the frame: the runtime asks it once per - /// command per frame, whichever components and passes resolve the command. + /// The one gate over commands. The runtime asks it once per command while the gate's props keep their key, whichever + /// components, passes and frames resolve the command. #[must_use] pub fn gate(mut self, gate: CommandGate) -> Self { self.gate = Some(gate); @@ -345,7 +402,7 @@ impl CommandInput { /// The chain of container instances that receive scoped commands, innermost last. A private inherited field of /// the env. #[doc(hidden)] -#[derive(Clone, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct CommandChain(Arc<[(CommandScope, Id)]>); impl CommandChain { @@ -440,7 +497,7 @@ pub trait Commands: CommandAccess { /// `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above /// the context, and the enabled state of its instance. `None` when the command is scoped and no instance of its /// scope is above the context. - fn resolve_command(&self, command: impl Into) -> Option { + fn resolve_command(&self, command: impl Into) -> Option> { board::resolve_scoped(self.command_ctx(), self.command_chain(), &command.into()) } } @@ -459,7 +516,7 @@ pub fn fire(ctx: &Context, command: impl Into, source: FireSource) - /// `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state /// and hint, against the instance that [`fire`] would deliver it to. A scoped command with no live instance /// resolves disabled. -pub fn resolve(ctx: &Context, command: impl Into) -> ResolvedCommand { +pub fn resolve(ctx: &Context, command: impl Into) -> Arc { board::resolve_global(ctx, &command.into()) } @@ -487,7 +544,7 @@ pub fn holder(ctx: &Context, chord: &Chord) -> Option { /// once the layer closes: for a surface that closes before its command runs (the command palette), whose own layer /// does not block the command. Outside a modal layer it is [`resolve`]. #[doc(hidden)] -pub fn resolve_beneath(ctx: &Context, command: impl Into) -> ResolvedCommand { +pub fn resolve_beneath(ctx: &Context, command: impl Into) -> Arc { match crate::runtime::overlay::modal_drawing(ctx) { Some(layer) => board::resolve_beneath(ctx, layer, &command.into()), None => resolve(ctx, command), diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index 3e161c614..fdfea4948 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -505,10 +505,11 @@ pub(crate) fn show_mark(ctx: &Context, mark: Option) { /// Records that `owner`'s `ordinal`th target on `layer` accepts at the pointer, with its mark in layer space and the /// tokens of the target's region. A `window` target covers the whole window. pub(crate) fn register(ctx: &Context, owner: Id, layer: Layer, mark: DropMark, tokens: Arc, window: bool) { - crate::runtime::replay::journal(ctx, || { - let tokens = tokens.clone(); - move |ctx: &Context| register(ctx, owner, layer, mark, tokens.clone(), window) - }); + crate::runtime::replay::journal( + ctx, + || (owner, layer, mark, tokens.clone(), window), + |ctx, (owner, layer, mark, tokens, window)| register(ctx, *owner, *layer, *mark, tokens.clone(), *window), + ); let mark = match areas::layer_map(ctx, layer) { Some(map) => mark.mapped(|point| map.to_screen(point)), None => mark, diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index e3c46f6c8..3639a7c71 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -137,7 +137,7 @@ pub(crate) fn register_parent(ctx: &Context, id: Id, parent: Id) { /// Notes that the runtime emitted the node of `id`. fn emit(ctx: &Context, id: Id) { with_emitted(ctx, |emitted| emitted.emit(id)); - crate::runtime::replay::journal(ctx, || move |ctx: &Context| emit(ctx, id)); + crate::runtime::replay::journal(ctx, || id, |ctx, &id| emit(ctx, id)); } /// Notes that the node of the text widget `widget` folds into the node of `owner`. @@ -145,7 +145,7 @@ fn note_folded(ctx: &Context, widget: Id, owner: Id) { with_emitted(ctx, |emitted| { emitted.folded.insert(widget, owner); }); - crate::runtime::replay::journal(ctx, || move |ctx: &Context| note_folded(ctx, widget, owner)); + crate::runtime::replay::journal(ctx, || (widget, owner), |ctx, &(widget, owner)| note_folded(ctx, widget, owner)); } /// Notes that the runtime wrote the node of `id`. @@ -153,7 +153,7 @@ pub(crate) fn note_written(ctx: &Context, id: Id) { with_emitted(ctx, |emitted| { emitted.written.insert(id); }); - crate::runtime::replay::journal(ctx, || move |ctx: &Context| note_written(ctx, id)); + crate::runtime::replay::journal(ctx, || id, |ctx, &id| note_written(ctx, id)); } /// The pass-end step: the children of each node the runtime wrote follow the order the runtime emitted them in, diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 7695a8ac7..2ed2d6157 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -137,6 +137,45 @@ fn window_focus_facts(ctx: &Context, events: &[Event], native_pixels_per_point: #[derive(Default)] struct WindowFocus(Option); +/// The child windows of the root that are open: each opens with its first frame and stays listed in every frame's +/// viewports, as eframe lists every open viewport, until a test closes it ([`close_viewport`]) or the app sends it +/// `ViewportCommand::Close`. +#[derive(Default)] +struct OpenChildren(Vec); + +/// The open child windows, with `viewport` opened first when it is a child. +fn open_children(ctx: &Context, viewport: egui::ViewportId) -> Vec { + Service::::run(ctx, |open| { + if viewport != egui::ViewportId::ROOT && !open.0.contains(&viewport) { + open.0.push(viewport); + } + open.0.clone() + }) +} + +/// One run of `ui` on `input`; a root pass declares the open `children` after it, as an eframe app shows each of its +/// windows every frame: egui keeps a child viewport only while its parent's passes show it. Each child's content runs +/// in its own frames, so the declaration shows nothing. +fn run_ui(ctx: &Context, input: RawInput, children: &[egui::ViewportId], mut ui: impl FnMut(&mut Ui)) -> egui::FullOutput { + let root = input.viewport_id == egui::ViewportId::ROOT; + ctx.run_ui(input, |top| { + ui(top); + if root && !children.is_empty() { + let embedded = ctx.embed_viewports(); + ctx.set_embed_viewports(false); + for child in children { + ctx.show_viewport_deferred(*child, egui::ViewportBuilder::default(), |_, _| {}); + } + ctx.set_embed_viewports(embedded); + } + }) +} + +/// Closes the child window `viewport`: later frames no longer list it. +pub(crate) fn close_viewport(ctx: &Context, viewport: egui::ViewportId) { + Service::::run(ctx, |open| open.0.retain(|held| *held != viewport)); +} + /// The fixture's reset bridge, as egui-winit keeps one per window: the reset request it holds for each viewport, and /// the requests it dropped, which the next frame reports as `Event::ImeResetRetired`. #[derive(Default)] @@ -187,7 +226,8 @@ impl ImeResets { } /// Runs one pass of `viewport` at `time` seconds with `events` and `files`, on a window of `native_pixels_per_point` -/// (egui's default when `None`). A viewport other than the root is a child window of the root, which stays live. +/// (egui's default when `None`). A viewport other than the root is a child window of the root, which stays live; the +/// child stays open in every later frame, the root's included, until it is closed. #[expect(clippy::too_many_arguments, reason = "the arguments are the facts of one frame, and every caller passes them all")] pub(crate) fn run_frame( ctx: &Context, @@ -204,9 +244,10 @@ pub(crate) fn run_frame( let dropped_files = files.dropped.iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect(); Service::::run(ctx, |resets| resets.input(viewport, &mut events)); let mut viewports = window_focus_facts(ctx, &events, native_pixels_per_point); - if viewport != egui::ViewportId::ROOT { + let children = open_children(ctx, viewport); + for child in &children { viewports - .insert(viewport, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), native_pixels_per_point, ..egui::ViewportInfo::default() }); + .insert(*child, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), native_pixels_per_point, ..egui::ViewportInfo::default() }); } let input = RawInput { screen_rect: Some(screen), @@ -218,7 +259,7 @@ pub(crate) fn run_frame( viewports, ..RawInput::default() }; - let mut output = drive(|| ctx.run_ui(input, ui)); + let mut output = drive(|| run_ui(ctx, input, &children, ui)); Service::::run(ctx, |resets| resets.output(viewport, &output.platform_output)); let mut flat = Vec::new(); for clipped in &output.shapes { @@ -257,6 +298,15 @@ pub(crate) fn run_frame( }) .collect(); let closed = output.viewport_output.values().any(|viewport| viewport.commands.iter().any(|command| matches!(command, ViewportCommand::Close))); + let closing: Vec = output + .viewport_output + .iter() + .filter(|(id, out)| **id != egui::ViewportId::ROOT && out.commands.iter().any(|command| matches!(command, ViewportCommand::Close))) + .map(|(id, _)| *id) + .collect(); + for child in closing { + close_viewport(ctx, child); + } let repaint_delay = output.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |viewport| viewport.repaint_delay); let copied = output .platform_output @@ -370,8 +420,14 @@ pub(crate) fn reordered_fonts() -> egui::FontDefinitions { /// Runs one frame like `run_frame` and returns the shapes it painted, nested shapes flattened. pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl FnMut(&mut Ui)) -> Vec { let screen = Rect::from_min_size(Pos2::ZERO, screen); - let input = RawInput { screen_rect: Some(screen), time: Some(time), ..RawInput::default() }; - let mut output = drive(|| ctx.run_ui(input, ui)); + let children = open_children(ctx, egui::ViewportId::ROOT); + let mut viewports = egui::ViewportIdMap::default(); + viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo::default()); + for child in &children { + viewports.insert(*child, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), ..egui::ViewportInfo::default() }); + } + let input = RawInput { screen_rect: Some(screen), time: Some(time), viewports, ..RawInput::default() }; + let mut output = drive(|| run_ui(ctx, input, &children, ui)); output.textures_delta.clear(); let mut flat = Vec::new(); for clipped in output.shapes { diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index e4615e280..03b786668 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -42,7 +42,7 @@ pub enum FocusShape { pub(crate) type StopKey = (Id, Option); /// A registered stop with its place in the scope tree. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] #[doc(hidden)] pub struct StopRec { #[doc(hidden)] @@ -50,7 +50,7 @@ pub struct StopRec { pub(crate) scope: Option, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct ScopeRec { pub(crate) policy: FocusPolicy, pub(crate) parent: Option, @@ -116,7 +116,7 @@ pub(crate) struct BeginIn { /// The row groups of one collection's visible rows in a pass: every one is a flat roving group of the same owner /// and direction, so the collection registers them as one record. -#[derive(Clone)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct RowGroups { owner: Id, rtl: bool, @@ -260,8 +260,9 @@ pub(crate) struct Mark { /// What one run of a child registered with the focus service: its stops, the scopes it pushed, the roving groups /// its stops belong to and its collections' row groups. A child out of view registers it again without running -/// (`runtime::lazy`), so its stops keep their place in Tab and F6 order. -#[derive(Clone, Default)] +/// (`runtime::lazy`), so its stops keep their place in Tab and F6 order. Two transcripts are equal when their replays +/// register the same records under the same open scope (`Transcript::placed`). +#[derive(Clone, Debug, Default)] pub(crate) struct Transcript { stops: Vec, scopes: Vec<(Id, ScopeRec)>, @@ -276,8 +277,34 @@ impl Transcript { pub(crate) fn stop_ids(&self) -> impl Iterator + '_ { self.stops.iter().map(|rec| rec.stop.id) } + + /// The transcript as a replay registers it with `outer` the innermost open scope: a record under the scope that + /// was open around the run goes under `outer`, and a replayed scope is no new scope (`entering` is false). + fn placed(&self, outer: Option) -> Transcript { + let place = |scope: Option| if scope == self.outer { outer } else { scope }; + Transcript { + stops: self.stops.iter().map(|rec| StopRec { stop: rec.stop.clone(), scope: place(rec.scope) }).collect(), + scopes: self + .scopes + .iter() + .map(|(id, scope)| (*id, ScopeRec { parent: place(scope.parent), entering: scope.entering.map(|_| false), ..scope.clone() })) + .collect(), + groups: self.groups.clone(), + row_sets: self.row_sets.clone(), + outer, + } + } } +impl PartialEq for Transcript { + fn eq(&self, other: &Self) -> bool { + let [a, b] = [self.placed(None), other.placed(None)]; + (a.stops, a.scopes, a.groups, a.row_sets) == (b.stops, b.scopes, b.groups, b.row_sets) + } +} + +impl Eq for Transcript {} + /// Where the running pass's registrations stand. pub(crate) fn mark(ctx: &Context) -> Mark { with(ctx, |state| Mark { @@ -310,21 +337,19 @@ pub(crate) fn transcript(ctx: &Context, mark: Mark) -> Transcript { pub(crate) fn replay(ctx: &Context, transcript: &Transcript) { let frame = crate::runtime::egui::pass::frame_nr(ctx, viewport(ctx)); with(ctx, |state| { - let outer = state.open.last().map(|(id, _)| *id); - let place = |scope: Option| if scope == transcript.outer { outer } else { scope }; - for (id, scope) in &transcript.scopes { - let parent = place(scope.parent); - state.scopes.insert(*id, ScopeRec { parent, entering: scope.entering.map(|_| false), ..scope.clone() }); - state.scope_order.push(*id); + let placed = transcript.placed(state.open.last().map(|(id, _)| *id)); + for (id, scope) in placed.scopes { if scope.entering.is_none() { - state.seen.insert(*id, frame); + state.seen.insert(id, frame); } + state.scopes.insert(id, scope); + state.scope_order.push(id); } - state.stops.extend(transcript.stops.iter().map(|rec| StopRec { stop: rec.stop.clone(), scope: place(rec.scope) })); - for group in &transcript.groups { - state.groups.insert(group.id, *group); + state.stops.extend(placed.stops); + for group in placed.groups { + state.groups.insert(group.id, group); } - state.row_sets.extend(transcript.row_sets.iter().cloned()); + state.row_sets.extend(placed.row_sets); }); } @@ -431,7 +456,7 @@ pub(crate) fn pop_scope(ctx: &Context) { /// Registers that the menu bar `bar` takes the menu-bar keys of the next input hook (spec 9.7). A settled bar /// registers again when it replays its last run, and the keys it takes run it (`keys::routed_to`). pub(crate) fn register_menu_bar(ctx: &Context, bar: Id) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_menu_bar(ctx, bar)); + crate::runtime::replay::journal(ctx, || bar, |ctx, &bar| register_menu_bar(ctx, bar)); with(ctx, |state| state.menu_bar = Some(bar)); } diff --git a/crates/ui-contract/src/runtime/focus/policy.rs b/crates/ui-contract/src/runtime/focus/policy.rs index 93e8500b0..db028b674 100644 --- a/crates/ui-contract/src/runtime/focus/policy.rs +++ b/crates/ui-contract/src/runtime/focus/policy.rs @@ -250,7 +250,7 @@ pub enum EndKey { } /// A component's declared keys. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct KeyUse { /// The keys kept from the key stage. diff --git a/crates/ui-contract/src/runtime/focus/registration.rs b/crates/ui-contract/src/runtime/focus/registration.rs index 5c525d8f7..f2d9fb531 100644 --- a/crates/ui-contract/src/runtime/focus/registration.rs +++ b/crates/ui-contract/src/runtime/focus/registration.rs @@ -8,7 +8,7 @@ use craft_behavior::{KeyRole, PartRef}; use egui::{Context, Id}; /// A stop as registered at step 7 of the pipeline. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Stop { /// The component. @@ -124,7 +124,7 @@ impl Stop { } /// A roving group's registration: one Tab stop whose members take moves. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Group { /// The group. diff --git a/crates/ui-contract/src/runtime/keys/nodes.rs b/crates/ui-contract/src/runtime/keys/nodes.rs index f6e13fbac..2266a989b 100644 --- a/crates/ui-contract/src/runtime/keys/nodes.rs +++ b/crates/ui-contract/src/runtime/keys/nodes.rs @@ -10,7 +10,7 @@ use egui::{Context, Id}; pub(crate) fn redirect_node(ctx: &Context, node: Id, owner: Id, part: PartRef) { // Journaled after the `register_node` it amends, so a settled region's replay leaves the row's node with the // collection, as a run does. - crate::runtime::replay::journal(ctx, || move |ctx: &Context| redirect_node(ctx, node, owner, part)); + crate::runtime::replay::journal(ctx, || (node, owner, part), |ctx, &(node, owner, part)| redirect_node(ctx, node, owner, part)); current(ctx, |stage| { if let Some(entry) = stage.nodes.get_mut(&node_key(node)) { entry.owner = owner; @@ -22,7 +22,7 @@ pub(crate) fn redirect_node(ctx: &Context, node: Id, owner: Id, part: PartRef) { /// Records the expanded state of the node registered by `register_node`: an `Expand` or `Collapse` request on a node /// with the state asks to change it, and acts as the node's activation. pub(crate) fn register_expanded(ctx: &Context, node: Id, expanded: Option) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_expanded(ctx, node, expanded)); + crate::runtime::replay::journal(ctx, || (node, expanded), |ctx, &(node, expanded)| register_expanded(ctx, node, expanded)); current(ctx, |stage| { if let Some(entry) = stage.nodes.get_mut(&node_key(node)) { entry.expanded = expanded; @@ -32,7 +32,11 @@ pub(crate) fn register_expanded(ctx: &Context, node: Id, expanded: Option) /// Registers an AccessKit node so a request that targets it reaches `owner`. pub(crate) fn register_node(ctx: &Context, node: Id, owner: Id, part: Option, focusable: bool) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_node(ctx, node, owner, part, focusable)); + crate::runtime::replay::journal( + ctx, + || (node, owner, part, focusable), + |ctx, &(node, owner, part, focusable)| register_node(ctx, node, owner, part, focusable), + ); current(ctx, |stage| { stage.nodes.insert(node_key(node), Node { owner, part, focusable, expanded: None }); }); diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index e2c4c79a3..a1b6b9832 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1117,19 +1117,21 @@ pub(crate) fn ask_discard(ctx: &Context) { /// Notes in the run records open around the running code that a replay keeps the entry and the kept transcript of /// `id`: the replayed run does not reach them, and an entry no pass touched in a frame is dropped. fn journal_keep(ctx: &Context, id: Id) { - crate::runtime::replay::journal(ctx, || { - move |ctx: &Context| { + crate::runtime::replay::journal( + ctx, + || id, + |ctx, id| { let moment = Moment::of(ctx); with(ctx, &moment, |memory| { - if let Some(entry) = memory.entries.get_mut(&id) { + if let Some(entry) = memory.entries.get_mut(id) { entry.touched = moment.frame; } - if let Some(kept) = memory.kept.get_mut(&id) { + if let Some(kept) = memory.kept.get_mut(id) { kept.touched = moment.frame; } }); - } - }); + }, + ); } /// The end hook: asks egui for at most one discard pass per frame, and for a repaint when a change cannot get one, so diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 71e2cf685..969020d63 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -297,6 +297,43 @@ pub fn chord_texts(ctx: &Context) -> u32 { last_totals(ctx, |log| log.chord_texts, 0) } +/// What a command resolution was for. +#[cfg(feature = "testing")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Resolve { + /// A resolution nothing kept: a reader's first, or one for a key press or a fire. + New, + /// A kept resolution made again because an input of it changed. + Again, + /// A kept resolution compared with a full one by the testing check every 100th pass. + Checked, +} + +/// Counts a command resolution in this pass. +#[cfg(feature = "testing")] +pub(crate) fn count_resolve(ctx: &Context, what: Resolve) { + totals(ctx, |log| log.resolves[what as usize] += 1); +} + +/// The command resolutions of the last pass of kind `what`. +#[cfg(feature = "testing")] +pub fn last_pass_resolves(ctx: &Context, what: Resolve) -> u32 { + last_totals(ctx, |log| log.resolves[what as usize], 0) +} + +/// Counts a kept resolution a wake walked to compare its key. +#[cfg(feature = "testing")] +pub(crate) fn count_wake_walk(ctx: &Context) { + totals(ctx, |log| log.wake_walks += 1); +} + +/// The kept resolutions the wakes of the last pass walked. +#[cfg(feature = "testing")] +pub fn last_pass_wake_walks(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.wake_walks, 0) +} + /// Counts a sweep of the row `id` that asks its body units for their least widths in this pass. #[cfg(feature = "testing")] pub(crate) fn count_least(ctx: &Context, id: Id) { @@ -362,29 +399,49 @@ pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { /// Bytes fed into memo keys in one pass, and the layouts, measure asks and chord texts of that pass. #[cfg(feature = "testing")] #[derive(Default)] -pub(crate) struct PassTotals { +pub(crate) struct Totals { pass: u64, key_bytes: usize, text_layouts: u32, chord_texts: u32, + resolves: [u32; 3], + wake_walks: u32, asks: Vec<(&'static str, u32)>, } +/// The totals of the running pass and of the one before it, which a pass's own counting does not overwrite: a pass +/// that counts in its begin hook keeps the last pass readable. #[cfg(feature = "testing")] -fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { +#[derive(Default)] +pub(crate) struct PassTotals { + current: Totals, + previous: Totals, +} + +#[cfg(feature = "testing")] +fn totals(ctx: &Context, f: impl FnOnce(&mut Totals) -> R) -> R { let pass = ctx.cumulative_pass_nr(); pass_state::with::(ctx, |log| { - if log.pass != pass { - *log = PassTotals { pass, ..PassTotals::default() }; + if log.current.pass != pass { + let current = std::mem::replace(&mut log.current, Totals { pass, ..Totals::default() }); + log.previous = current; } - f(log) + f(&mut log.current) }) } #[cfg(feature = "testing")] -fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { +fn last_totals(ctx: &Context, f: impl FnOnce(&Totals) -> R, none: R) -> R { let last = ctx.cumulative_pass_nr().saturating_sub(1); - pass_state::with::(ctx, |log| if log.pass == last { f(log) } else { none }) + pass_state::with::(ctx, |log| { + if log.current.pass == last { + f(&log.current) + } else if log.previous.pass == last { + f(&log.previous) + } else { + none + } + }) } /// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index 4ebedc657..4088ec89c 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -230,7 +230,7 @@ struct Seen(u64); /// Registers `owner`'s pass, at step 3: eviction tests only owners. Shown entries of an owner not registered /// for 3 passes of the viewport that last showed it and 0.5 s are evicted by `evict`. pub(crate) fn register_owner(ctx: &Context, owner: Id) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_owner(ctx, owner)); + crate::runtime::replay::journal(ctx, || owner, |ctx, &owner| register_owner(ctx, owner)); let facts = frame::facts(ctx); pass_state::with::(ctx, |reg| { reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now }); diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 352ebbdd5..df9e472eb 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -369,10 +369,17 @@ pub(crate) fn record_shapes(ctx: &Context, layer: Layer, root: Id, clip: Rect, s /// `record_shapes` for a caller that already read the running viewport. pub(crate) fn record_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, clip: Rect, shapes: impl IntoIterator>) { let shapes: Vec> = shapes.into_iter().collect(); - crate::runtime::replay::journal(ctx, || { - let shapes = shapes.clone(); - move |ctx: &Context| record_shapes(ctx, layer, root, clip, shapes.iter().cloned()) - }); + crate::runtime::replay::journal( + ctx, + || (layer, root, clip, shapes.clone()), + |ctx, (layer, root, clip, shapes)| record_shapes(ctx, *layer, *root, *clip, shapes.iter().cloned()), + ); + add_shapes_in(ctx, viewport, layer, root, clip, shapes); +} + +/// `record_shapes_in` with no note in the run records, for a caller whose own note makes the shapes again: shapes at +/// stack positions a replay takes from the arena it joins (`sensing`), not from the recorded run. +pub(crate) fn add_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, clip: Rect, shapes: Vec>) { PerViewport::::with(ctx, viewport, |record| { let order = record.next; record.next += 1; @@ -385,7 +392,7 @@ pub(crate) fn record_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer /// Records the egui widget `widget` that the component `owner` made for its own text (a field's text, a selection /// part): a press egui gives it is the widget's own and goes to no root, and the hover goes to `owner`. pub(crate) fn record_text_widget(ctx: &Context, widget: Id, owner: Id) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| record_text_widget(ctx, widget, owner)); + crate::runtime::replay::journal(ctx, || (widget, owner), |ctx, &(widget, owner)| record_text_widget(ctx, widget, owner)); PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { record.this_texts.insert(widget, owner); }); @@ -403,7 +410,7 @@ pub(crate) fn record_layer_widget(ctx: &Context, widget: Id) { /// Records that `layer` shows the transformed body of the root `root`, which is itself shown on `parent`: a press on /// the body layer reaches the root's own shapes beneath the body's. pub(crate) fn record_body_layer(ctx: &Context, layer: Layer, parent: Layer, root: Id) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| record_body_layer(ctx, layer, parent, root)); + crate::runtime::replay::journal(ctx, || (layer, parent, root), |ctx, &(layer, parent, root)| record_body_layer(ctx, layer, parent, root)); PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { record.this_bodies.insert(layer, (root, parent)); }); @@ -417,10 +424,11 @@ pub(crate) fn record_widgets(ctx: &Context, layer: Layer, root: Id, widgets: &[I /// `record_widgets` for a caller that already read the running viewport. pub(crate) fn record_widgets_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, widgets: &[Id], click: bool) { - crate::runtime::replay::journal(ctx, || { - let widgets = widgets.to_vec(); - move |ctx: &Context| record_widgets(ctx, layer, root, &widgets, click) - }); + crate::runtime::replay::journal( + ctx, + || (layer, root, widgets.to_vec(), click), + |ctx, (layer, root, widgets, click)| record_widgets(ctx, *layer, *root, widgets, *click), + ); PerViewport::::with(ctx, viewport, |record| { let entry = record.this.entry(layer).or_default().entry(root).or_default(); entry.widgets.extend_from_slice(widgets); diff --git a/crates/ui-contract/src/runtime/reads.rs b/crates/ui-contract/src/runtime/reads.rs index ce184f479..ca91aecb4 100644 --- a/crates/ui-contract/src/runtime/reads.rs +++ b/crates/ui-contract/src/runtime/reads.rs @@ -25,6 +25,8 @@ pub(crate) enum BindKey { Record(Id), /// A command's state on the board: the command's number and the instance whose state it is, `None` for the app's. Command(u32, Option), + /// A command the focused stop answers for (an edit it takes): the command's number. + FocusedEdit(u32), } /// One measure a reader made from the value it read: what it was offered and the size it took. @@ -35,7 +37,7 @@ pub(crate) struct Sample { pub took: Vec2, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] struct Read { key: BindKey, reader: Id, @@ -94,10 +96,7 @@ pub(crate) fn note(ctx: &Context, key: BindKey, reader: Id, measuring: bool, sam } else { let read = Read { key, reader, measuring, runs, samples }; crate::runtime::replay::note_read(ctx, key); - crate::runtime::replay::journal(ctx, || { - let read = read.clone(); - move |ctx: &Context| with(ctx, |reads| reads.reads.push(read.clone())) - }); + crate::runtime::replay::journal(ctx, || read.clone(), |ctx, read| with(ctx, |reads| reads.reads.push(read.clone()))); with(ctx, |reads| reads.reads.push(read)); } } diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index f4a317b18..3b970c883 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -16,12 +16,63 @@ use crate::runtime::frame; use crate::runtime::pass_state; use crate::runtime::reads::BindKey; use egui::{Context, IdSet}; +use std::any::Any; use std::collections::HashSet; +use std::fmt; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; -/// A registration of the recorded run, made again by calling it. -type Entry = Arc; +/// A registration of the recorded run: the call that makes it again and what it is called with. Two entries are equal +/// when they come from the same call (the same `again` of [`journal`]) with equal arguments. +#[derive(Clone)] +pub(crate) struct Entry(Arc); + +trait Noted: Send + Sync { + fn call(&self, ctx: &Context); + fn as_any(&self) -> &dyn Any; + fn same(&self, other: &dyn Noted) -> bool; + fn describe(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result; +} + +struct Note { + args: A, + again: F, +} + +impl Noted for Note +where + A: PartialEq + fmt::Debug + Send + Sync + 'static, + F: Fn(&Context, &A) + Send + Sync + 'static, +{ + fn call(&self, ctx: &Context) { + (self.again)(ctx, &self.args); + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn same(&self, other: &dyn Noted) -> bool { + // `F` is capture-free, so its type names the call: the same type is the same call. + other.as_any().downcast_ref::().is_some_and(|other| other.args == self.args) + } + + fn describe(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}({:?})", std::any::type_name::(), self.args) + } +} + +impl PartialEq for Entry { + fn eq(&self, other: &Self) -> bool { + self.0.same(&*other.0) + } +} + +impl fmt::Debug for Entry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.describe(f) + } +} /// Records open across all contexts, so a registration made while none is open takes no lock. static OPEN: AtomicUsize = AtomicUsize::new(0); @@ -68,7 +119,7 @@ pub(crate) struct Facts { /// What one real run of a region added to its pass. pub(crate) struct Record { pub(crate) focus: Transcript, - journal: Vec, + pub(crate) journal: Vec, egui: egui::PassRecords, /// The egui widgets of the run. pub(crate) widgets: IdSet, @@ -136,7 +187,7 @@ pub(crate) fn replay(ctx: &Context, record: &Record) { ctx.replay_pass_records(&record.egui); focus::replay(ctx, &record.focus); for entry in &record.journal { - entry(ctx); + entry.0.call(ctx); } if let Some(at) = record.facts.wake { crate::runtime::egui::repaint::request_after(ctx, crate::runtime::egui::pass::current_viewport(ctx), at - frame::clock(ctx)); @@ -160,12 +211,21 @@ fn with_open(ctx: &Context, f: impl FnOnce(&mut Facts)) { } } -/// Notes, in the records open around the running code, the registration `make` builds: called again, it registers -/// what the running code registered. A service outside this crate that keeps registrations per pass (a dock's drop -/// spots) notes each one here, so a settled region's replay makes it again. -pub fn journal(ctx: &Context, make: impl FnOnce() -> F) { +/// Notes, in the records open around the running code, the registration the running code made: `again(ctx, &args)` +/// registers it again. `args` builds the arguments only while a record is open. `again` captures nothing (a function +/// or a closure without captures), so everything the registration depends on is in the arguments. A capture fails +/// the build, not `cargo check`: the size assert is a constant that is evaluated only when the code is generated. +/// Two notes of the same `again` with equal arguments are the same registration. A service outside this crate that +/// keeps registrations per pass (a dock's drop spots) notes each one here, so a settled region's replay makes it +/// again. +pub fn journal(ctx: &Context, args: impl FnOnce() -> A, again: F) +where + A: PartialEq + fmt::Debug + Send + Sync + 'static, + F: Fn(&Context, &A) + Send + Sync + 'static, +{ + const { assert!(std::mem::size_of::() == 0, "`journal`'s `again` captures nothing: pass its state in `args`") }; if recording(ctx) { - let entry: Entry = Arc::new(make()); + let entry = Entry(Arc::new(Note { args: args(), again })); pass_state::with::(ctx, |recorder| recorder.journal.push(entry)); } } diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index f9763b1aa..6ad4df5e2 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -25,7 +25,7 @@ pub(crate) struct State { /// Registers a taker for next pass's split. pub(crate) fn register(ctx: &Context, taker: WheelTaker) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register(ctx, taker)); + crate::runtime::replay::journal(ctx, || taker, |ctx, &taker| register(ctx, taker)); PerViewport::::with(ctx, pass::current_viewport(ctx), |state| state.this.push(taker)); } diff --git a/crates/ui-contract/src/runtime/windows/hit.rs b/crates/ui-contract/src/runtime/windows/hit.rs index c4dadbb42..c09d143a5 100644 --- a/crates/ui-contract/src/runtime/windows/hit.rs +++ b/crates/ui-contract/src/runtime/windows/hit.rs @@ -311,7 +311,7 @@ pub(super) fn with_exclusive(ctx: &Context, viewport: ViewportId, f: impl FnO /// A part declared again in the same pass replaces its entry. A settled region that replays its last run declares /// its parts again, so a settled title bar keeps its caption regions. pub(crate) fn note_exclusive(ctx: &Context, owner: Id, part: PartRef, hit: WindowHit, rect: Rect) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| note_exclusive(ctx, owner, part, hit, rect)); + crate::runtime::replay::journal(ctx, || (owner, part, hit, rect), |ctx, &(owner, part, hit, rect)| note_exclusive(ctx, owner, part, hit, rect)); with_exclusive(ctx, pass::current_viewport(ctx), |exclusive| { let entry = ExclusivePart { owner, part, hit, rect }; match exclusive.current.iter_mut().find(|held| held.owner == owner && held.part == part) { diff --git a/crates/ui-contract/src/style/tokens.rs b/crates/ui-contract/src/style/tokens.rs index 504731b04..2f0cc8428 100644 --- a/crates/ui-contract/src/style/tokens.rs +++ b/crates/ui-contract/src/style/tokens.rs @@ -42,6 +42,15 @@ pub struct UiTokens { key: u64, } +/// Two sets are equal when their content keys are: equal sets share a key. +impl PartialEq for UiTokens { + fn eq(&self, other: &Self) -> bool { + self.key == other.key + } +} + +impl Eq for UiTokens {} + impl UiTokens { /// A token set resolved under `contrast` and `density`, with no theme values for token groups, drawing the default /// icon set. diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index aff8228e8..5065b8d83 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -2,8 +2,9 @@ use super::Frames; use super::story::{Story, StoryData, StoryOutput}; +use crate::contract::Tracked; use crate::runtime::access::Role; -use crate::runtime::commands::{CommandGate, CommandInput, CommandRef, CommandState}; +use crate::runtime::commands::{CommandGate, CommandInput, CommandRef, CommandState, CommandStates}; use crate::runtime::egui::access::{AccessTree, NodeKey}; use crate::runtime::egui::fixture::{self, AccessActionKind}; use crate::runtime::egui::injected; @@ -114,6 +115,8 @@ pub struct Fixture { show: Box, root: RootEnv, commands: CommandInput, + /// The app-scope command states, held as an app holds them. + states: Tracked, room: Vec2, tree: AccessTree, shown: Rect, @@ -153,6 +156,7 @@ impl Fixture { show: Box::new(show), root: RootEnv::default(), commands: CommandInput::new(), + states: Tracked::default(), room: Vec2::new(400.0, 300.0), tree: AccessTree::none(), shown: Rect::NOTHING, @@ -203,7 +207,8 @@ impl Fixture { fixture.data = data; fixture.outputs = outputs; fixture.root_id = root_id; - fixture.commands = Story::command_input([story]); + fixture.states = Tracked::new(Story::command_states([story])); + fixture.commands = CommandInput::new().states(&fixture.states); fixture.frames.commands(fixture.commands.clone()); fixture } @@ -230,9 +235,8 @@ impl Fixture { /// Gives app-scope `command` this state in every following pass, as an app's `FrameInput.commands` does; a later /// call for the same command replaces the earlier one. pub fn command_state(&mut self, command: impl Into, state: CommandState) -> &mut Self { - let command = command.into(); - self.commands.states.retain(|(held, _)| *held != command); - self.commands.states.push((command, state)); + self.states.set(command, state); + self.commands = self.commands.clone().states(&self.states); self.frames.commands(self.commands.clone()); self } diff --git a/crates/ui-contract/src/testing/frames.rs b/crates/ui-contract/src/testing/frames.rs index 0b27e14fe..938170f56 100644 --- a/crates/ui-contract/src/testing/frames.rs +++ b/crates/ui-contract/src/testing/frames.rs @@ -186,9 +186,13 @@ impl Frames { } /// One frame of `viewport`, a child window of the root while the root stays live, with `events`; `ui` runs once - /// per pass. Returns the number of passes. + /// per pass. Returns the number of passes. The child opens with its first frame and stays open, listed in the root's + /// frames too, until [`close_viewport`](Self::close_viewport) or a `ViewportCommand::Close` for it. pub fn frame_in_viewport(&mut self, viewport: egui::ViewportId, events: Vec, mut ui: impl FnMut(&mut Ui)) -> usize { - set_input(&self.ctx, self.input()); + // The app's input is the root's, once per app frame: a child window's frame runs inside it. + if viewport == egui::ViewportId::ROOT { + set_input(&self.ctx, self.input()); + } let mut passes = 0; self.run(viewport, events, |root| { passes += 1; @@ -253,6 +257,11 @@ impl Frames { self.time += seconds; } + /// Closes the child window `viewport`, as its user would: later frames no longer list it. + pub fn close_viewport(&mut self, viewport: egui::ViewportId) { + fixture::close_viewport(&self.ctx, viewport); + } + /// `n` frames with no events. pub fn idle(&mut self, n: usize, mut ui: impl FnMut(&mut Ui)) { for _ in 0..n { diff --git a/crates/ui-contract/src/testing/replay_trials.rs b/crates/ui-contract/src/testing/replay_trials.rs index 69b9f5c35..83eb6fa47 100644 --- a/crates/ui-contract/src/testing/replay_trials.rs +++ b/crates/ui-contract/src/testing/replay_trials.rs @@ -1,8 +1,15 @@ -//! Trials of the replay records' notes. +//! Trials of the replay records: their notes and their comparison. +#![allow(clippy::expect_used, reason = "trial code: clippy.toml allows expect in tests, and trials are compiled into the library")] + +use crate::primitives::sensing::{self, MemberSpec}; use crate::runtime::egui::{fixture, repaint}; +use crate::runtime::env::ArenaId; +use crate::runtime::focus::{self, FocusPolicy, KeyUse, Stop}; use crate::runtime::replay; -use crate::testing::{Frames, trial}; +use crate::testing::{Frames, pointer, trial}; +use craft_behavior::Sense; +use egui::{Pos2, Rect, Vec2}; // A job's thread asks for a pass (a finished job's wake, a progress report) while a pass of the same context records a // region on the UI thread: the request notes nothing in that pass's records and leaves its pass state alone. @@ -19,3 +26,151 @@ fn a_repaint_from_a_job_thread_leaves_the_running_pass_s_records_alone() { }); assert_eq!(joined, Some(true), "the job thread's repaint request returns"); } + +/// Records one frame's run of `run` in `frames`. +fn record(frames: &mut Frames, mut run: impl FnMut(&egui::Context)) -> replay::Record { + let mut record = None; + frames.frame(Vec::new(), |ui| { + let ctx = ui.ctx().clone(); + replay::open(&ctx); + run(&ctx); + record = Some(replay::close(&ctx, fixture::layer_of(ui))); + }); + record.expect("the frame ran") +} + +fn note_a(_: &egui::Context, _: &(egui::Id, u32)) {} + +fn note_b(_: &egui::Context, _: &(egui::Id, u32)) {} + +// A journal entry is the same registration as another only when both come from the same call with equal arguments: a +// replay and a real run compare by it. +#[trial] +fn journal_entries_compare_by_their_call_and_arguments() { + let mut frames = Frames::new(); + let id = fixture::named_id("owner"); + let notes = |calls: [(bool, u32); 2]| { + move |ctx: &egui::Context| { + for (a, n) in calls { + if a { + replay::journal(ctx, || (id, n), note_a); + } else { + replay::journal(ctx, || (id, n), note_b); + } + } + } + }; + let first = record(&mut frames, notes([(true, 1), (true, 2)])); + let again = record(&mut frames, notes([(true, 1), (true, 2)])); + let changed_argument = record(&mut frames, notes([(true, 1), (true, 3)])); + let other_call = record(&mut frames, notes([(true, 1), (false, 2)])); + assert_eq!(first.journal.len(), 2, "both notes are in the record"); + assert_eq!(first.journal, again.journal, "the same calls with the same arguments"); + assert_ne!(first.journal[1], changed_argument.journal[1], "one argument changed"); + assert_eq!(first.journal[0], changed_argument.journal[0]); + assert_ne!(first.journal[1], other_call.journal[1], "another call with the same arguments"); +} + +// A focus transcript with one changed stop compares unequal to the run before it; one with the same stops equal. +#[trial] +fn a_transcript_with_one_changed_stop_compares_unequal() { + let mut frames = Frames::new(); + let [one, two] = [fixture::named_id("one"), fixture::named_id("two")]; + let stops = |second: KeyUse| { + move |ctx: &egui::Context| { + focus::register_stop(ctx, Stop::new(one, KeyUse::CODE)); + focus::register_stop(ctx, Stop::new(two, second)); + } + }; + let first = record(&mut frames, stops(KeyUse::CODE)); + let again = record(&mut frames, stops(KeyUse::CODE)); + let changed = record(&mut frames, stops(KeyUse::TEXT_MULTILINE)); + assert_eq!(first.focus.stop_ids().count(), 2, "both stops are in the transcript"); + assert_eq!(first.focus, again.focus); + assert_ne!(first.focus, changed.focus, "the second stop's keys changed"); +} + +/// Records `stops` run inside a record, with `entering` the first-pass flag of the layer scope it pushes, inside the +/// scope `outer` when one is given. +fn layer_scope_record(frames: &mut Frames, outer: Option, entering: bool) -> replay::Record { + let [scope, stop] = [fixture::named_id("layer scope"), fixture::named_id("stop")]; + let mut record = None; + frames.frame(Vec::new(), |ui| { + let ctx = ui.ctx().clone(); + if let Some(outer) = outer { + focus::push_scope(&ctx, outer, FocusPolicy::NONE, None); + } + replay::open(&ctx); + focus::register_stop(&ctx, Stop::new(fixture::named_id("beside"), KeyUse::CODE)); + focus::push_scope_from(&ctx, scope, FocusPolicy::NONE, None, None, false, Some(entering)); + focus::register_stop(&ctx, Stop::new(stop, KeyUse::CODE)); + focus::pop_scope(&ctx); + record = Some(replay::close(&ctx, fixture::layer_of(ui))); + if outer.is_some() { + focus::pop_scope(&ctx); + } + }); + record.expect("the frame ran") +} + +// A view recorded in the pass its layer appeared (`entering`) and the real run of the next pass register the same +// once replayed: a replayed scope is no new scope. +#[trial] +fn a_first_pass_transcript_equals_the_next_real_run() { + let mut frames = Frames::new(); + let first = layer_scope_record(&mut frames, None, true); + let next = layer_scope_record(&mut frames, None, false); + assert_eq!(first.focus, next.focus); +} + +// The same view shown inside two different scopes registers the same records under each. +#[trial] +fn a_transcript_under_another_open_scope_compares_equal() { + let mut frames = Frames::new(); + let one = layer_scope_record(&mut frames, Some(fixture::named_id("outer one")), false); + let other = layer_scope_record(&mut frames, Some(fixture::named_id("outer other")), false); + assert_eq!(one.focus, other.focus); +} + +// A child recorded as the arena's first member and replayed after two members that cover it stacks above them, as a +// real run after them would: its stack positions come from the arena it joins, not from the recorded run. +#[trial] +fn a_replayed_member_stacks_above_the_members_before_it() { + let mut frames = Frames::new(); + let arena = ArenaId::new(fixture::named_id("arena")); + let [before, cover, child] = [fixture::named_id("before"), fixture::named_id("cover"), fixture::named_id("child")]; + let rect = Rect::from_min_size(Pos2::new(20.0, 20.0), Vec2::splat(40.0)); + let spec = |id, rect| MemberSpec { id, rect, sense: Sense::HOVER | Sense::CLICK, parts: &[], enabled: true }; + let mut recorded = None; + frames.frame(Vec::new(), |ui| { + let ctx = ui.ctx().clone(); + replay::open(&ctx); + sensing::sense_members(ui, arena, &[spec(child, rect)]); + recorded = Some(replay::close(&ctx, fixture::layer_of(ui))); + }); + let recorded = recorded.expect("the frame ran"); + let shown = |ui: &mut egui::Ui, replayed: bool| { + sensing::sense_members(ui, arena, &[spec(before, Rect::from_min_size(Pos2::ZERO, Vec2::splat(10.0))), spec(cover, rect)]); + if replayed { + replay::replay(ui.ctx(), &recorded); + return None; + } + let ctx = ui.ctx().clone(); + replay::open(&ctx); + sensing::sense_members(ui, arena, &[spec(child, rect)]); + Some(replay::close(&ctx, fixture::layer_of(ui))) + }; + let mut real = None; + frames.frame(Vec::new(), |ui| real = shown(ui, false)); + let real = real.expect("the frame ran"); + assert_eq!(recorded.journal, real.journal, "the join is noted as declared, without its stack positions"); + frames.frame(Vec::new(), |ui| { + let _ = shown(ui, true); + }); + let mut hovered = None; + frames.frame(vec![pointer::moved(rect.center())], |ui| { + hovered = Some([crate::runtime::pointer::hovers(ui.ctx(), child), crate::runtime::pointer::hovers(ui.ctx(), cover)]); + let _ = shown(ui, true); + }); + assert_eq!(hovered, Some([true, false]), "the replayed child is above the member that covers it"); +} diff --git a/crates/ui-contract/src/testing/story.rs b/crates/ui-contract/src/testing/story.rs index a60f60d16..516fe73a6 100644 --- a/crates/ui-contract/src/testing/story.rs +++ b/crates/ui-contract/src/testing/story.rs @@ -2,7 +2,7 @@ use super::Fixture; use crate::contract::{CollectionEvent, Inner, Outcome, TooltipSpec}; -use crate::runtime::commands::CommandInput; +use crate::runtime::commands::CommandStates; use craft_behavior::{EditEvent, EditEvents, PartKey, PartRef, Value}; use egui::{Id, Response, Ui, Vec2}; use std::any::{Any, TypeId}; @@ -102,9 +102,9 @@ pub struct Story { pub drive: Drive, /// The reason a disabled control shows (`disabled_text` of its tooltip), when the story gives its control one. pub disabled_text: Option<&'static str>, - /// Adds this story's app-scope command states to the frame's command input; runners fold the shown stories' - /// functions over `CommandInput::new()` before the first frame. - pub commands: Option CommandInput>, + /// Sets this story's app-scope command states; runners apply the shown stories' functions in order to one + /// `CommandStates` before the first frame and hold it as the app's. + pub commands: Option, /// The caption a viewer shows over the story; `None` for the title made of its name (`contract::story_title`). pub title: Option<&'static str>, /// The group a viewer shows the story in, with the other stories of the type that name it, as the cases of one @@ -118,16 +118,20 @@ impl Story { Story { name, covers: &[], show, drive: Drive::Auto, disabled_text: None, commands: None, title: None, group: None } } - /// Sets the function that adds the story's command states to the frame's command input. - pub const fn commands(mut self, add: fn(CommandInput) -> CommandInput) -> Self { + /// Sets the function that sets the story's app-scope command states. + pub const fn commands(mut self, add: fn(&mut CommandStates)) -> Self { self.commands = Some(add); self } - /// The command input of `stories` shown together: each story's command function applied in order over an empty - /// input, so a later story's state for a command replaces an earlier one's. Runners call this before the first frame. - pub fn command_input<'a>(stories: impl IntoIterator) -> CommandInput { - stories.into_iter().filter_map(|story| story.commands).fold(CommandInput::new(), |input, add| add(input)) + /// The command states of `stories` shown together: each story's command function applied in order to empty + /// states, so a later story's state for a command replaces an earlier one's. Runners call this before the first frame. + pub fn command_states<'a>(stories: impl IntoIterator) -> CommandStates { + let mut states = CommandStates::new(); + for add in stories.into_iter().filter_map(|story| story.commands) { + add(&mut states); + } + states } /// The caption a viewer shows over the story. diff --git a/crates/ui-contract/tests/it/runtime/frame.rs b/crates/ui-contract/tests/it/runtime/frame.rs index 78eea00a9..16ae912b5 100644 --- a/crates/ui-contract/tests/it/runtime/frame.rs +++ b/crates/ui-contract/tests/it/runtime/frame.rs @@ -94,9 +94,9 @@ enum Shown { Apply, } -/// A gate that refuses `Shown::Apply` when `refuses`, else lets every command through. Each call makes a new closure. +/// A gate that refuses `Shown::Apply` when `refuses`, else lets every command through. Each call makes a new gate. fn gate(refuses: bool) -> CommandInput { - CommandInput::new().gate(CommandGate::new(move |command: &CommandRef| !refuses || Shown::from_ref(command).is_none())) + CommandInput::new().gate(CommandGate::new(refuses, |refuses: &bool, command: &CommandRef| !*refuses || Shown::from_ref(command).is_none())) } /// A modal layer with an empty body. diff --git a/crates/ui-gallery/src/chrome/shell.rs b/crates/ui-gallery/src/chrome/shell.rs index 1be5fbced..8fc707763 100644 --- a/crates/ui-gallery/src/chrome/shell.rs +++ b/crates/ui-gallery/src/chrome/shell.rs @@ -9,10 +9,11 @@ use crate::viewer::{Browser, Catalog, GalleryCommands, GallerySettings, PanelId, use craft_behavior::dock::{PanelState, Workspace as Dock}; use craft_theme::AppSizes; use craft_theme_editor::{ThemeSubject, parse_sizes}; -use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _}; +use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _, Tracked}; use craft_ui::docking::DockConfig; use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; +use craft_ui::runtime::commands::{CommandInput, CommandStates}; use craft_ui::runtime::drag::OsFile; use craft_ui::runtime::env::WindowKey; use craft_ui::runtime::frame::{FrameInput, FrameOutput}; @@ -34,6 +35,9 @@ pub struct Gallery { noted: HashSet, /// A command changed the viewer since the settings were last compared. command_ran: bool, + /// The app-scope command states of the front component's stories, and that component: rebuilt only when another + /// component comes to the front, so an idle frame keeps one revision. + command_states: (Option<&'static str>, Tracked), } impl Gallery { @@ -45,7 +49,7 @@ impl Gallery { /// The viewer of `catalog` over `persisted`. pub fn new(catalog: Catalog, persisted: Persisted) -> Self { let viewer = Viewer::new(catalog, persisted.get()); - Gallery { viewer, persisted, drop_note: None, noted: HashSet::new(), command_ran: false } + Gallery { viewer, persisted, drop_note: None, noted: HashSet::new(), command_ran: false, command_states: (None, Tracked::default()) } } /// Shows what the settings and a dropped file have to say, once each, as toasts. @@ -143,10 +147,14 @@ impl ShellApp for Gallery { // App-scope command states are one input per frame, so only the stories of the component shown reach it; the // Overview, the Theme dock and a frame with no such tab give none. let browser = &self.viewer.browser; - let stories = front_component(&self.viewer) - .into_iter() - .flat_map(|type_name| browser.catalog.stories_of(type_name).iter().map(|&at| &browser.catalog.entries[at].registration.story)); - FrameInput::new(self.viewer.env.clone()).commands(craft_ui::testing::Story::command_input(stories)) + let front = front_component(&self.viewer); + if front != self.command_states.0 { + let stories = front + .into_iter() + .flat_map(|type_name| browser.catalog.stories_of(type_name).iter().map(|&at| &browser.catalog.entries[at].registration.story)); + self.command_states = (front, Tracked::new(craft_ui::testing::Story::command_states(stories))); + } + FrameInput::new(self.viewer.env.clone()).commands(CommandInput::new().states(&self.command_states.1)) } fn output(&mut self, output: FrameOutput) { diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index 2cc3757c7..dfa079698 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -212,7 +212,7 @@ fn pick(ui: &Ui, state: &mut MockState, tool: Tool, step: PickStep) { /// Makes `tool` the current tool and says so in the status bar. fn select(ui: &Ui, state: &mut MockState, tool: Tool) { state.tool = tool; - let name = commands::resolve(ui.ctx(), CommandRef::from(tool)).label; + let name = commands::resolve(ui.ctx(), CommandRef::from(tool)).label.clone(); let text = Env::of(ui).words::().tool_status.fill(&[("tool", &*name)]); state.status = Some(StatusMessage::new(text)); } diff --git a/crates/ui-macros/src/lib.rs b/crates/ui-macros/src/lib.rs index 75eafaf22..94e807f0a 100644 --- a/crates/ui-macros/src/lib.rs +++ b/crates/ui-macros/src/lib.rs @@ -228,7 +228,7 @@ impl Parse for StoryArgs { /// reason to show while disabled, which the story takes from `StoryData::tooltip`. `title = ".."` is the caption a /// viewer shows over the story. `group = ".."` puts the story in a named group with the type's other stories that /// name it, in declaration order; a viewer shows a group together, each story under its caption. -/// `commands = ` names a `fn(CommandInput) -> CommandInput` that sets the command states the story runs under. +/// `commands = ` names a `fn(&mut CommandStates)` that sets the app-scope command states the story runs under. /// The type's registration and the story meet by the type's registered name. #[proc_macro_attribute] pub fn story(attr: TokenStream, item: TokenStream) -> TokenStream { diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 79c290a81..ec71ec5e6 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -20,6 +20,7 @@ use craft_behavior::divider::{self as push, Segment}; use craft_behavior::dock::{Column, DockEdge, Group}; use craft_behavior::{Axis, DockSide, Flow, Metrics, PartKey, Sense, Value}; use egui::{Context, Id, Pos2, Rect, Response, Ui}; +use std::fmt::Debug; use std::hash::Hash; #[cfg(feature = "suite")] @@ -207,7 +208,7 @@ pub struct DockColumn<'a, P: Value + Hash + 'static> { collapse: bool, } -impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { +impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { /// A column named `label` of the dock `dock`, over `column`; `spec` reads each panel's limits and heights. pub fn new(label: impl Into

, spec: &'a dyn Fn(&P) -> PanelSpec) -> Self { let props = ContainerProps::new().sizing(Sizing::Fill).pad(Pad::None); @@ -386,7 +387,7 @@ impl Plan { } } -impl Component for DockColumn<'_, P> { +impl Component for DockColumn<'_, P> { const ROLE: Role = Role::GROUP; const KEYS: KeyUse = KeyUse::SPLITTER; type Style = DockColumnStyle; @@ -531,7 +532,14 @@ pub(super) fn column_grip(column: &Column

, spec: &dyn Fn(&P) /// Registers the drop bands of the two edges of the column in `rect` with the dock `dock`: a drop there makes a new /// column beside the one that holds `anchor`. -pub(super) fn register_edges(ctx: &Context, dock: Id, anchor: &P, rect: Rect, rtl: bool, sizes: &DockSizes) { +pub(super) fn register_edges( + ctx: &Context, + dock: Id, + anchor: &P, + rect: Rect, + rtl: bool, + sizes: &DockSizes, +) { let flow = Flow::new(rect, rtl); // A narrow column keeps a third of its width between its two edge bands, so a drop inside it still reaches its // groups. @@ -550,7 +558,7 @@ pub(super) fn register_edges(ctx: &Context, do } } -impl DockColumn<'_, P> { +impl DockColumn<'_, P> { /// Registers the drop bands of the column's two edges, for a dock column, and of the seams between its groups. fn register(&self, ctx: &Context, rect: Rect, rtl: bool, plan: &Plan, sizes: &DockSizes) { let Some(first) = self.anchor(0) else { return }; @@ -568,4 +576,4 @@ impl DockColumn<'_, P> { } } -impl Container for DockColumn<'_, P> {} +impl Container for DockColumn<'_, P> {} diff --git a/crates/ui-panels/src/docking/frame.rs b/crates/ui-panels/src/docking/frame.rs index 4c4468bbd..e57718e4c 100644 --- a/crates/ui-panels/src/docking/frame.rs +++ b/crates/ui-panels/src/docking/frame.rs @@ -9,6 +9,7 @@ use craft_behavior::dock::{Column, Floating, Group, Layout, Node, PanelPlace, Sp use egui::{Context, Id, Pos2, Rect, Vec2}; use std::borrow::Cow; use std::collections::HashMap; +use std::fmt::Debug; use std::hash::Hash; /// A layout as it is shown: a maximized frame alone, hidden panels left out. @@ -251,7 +252,7 @@ pub fn edge_bands( /// Registers the bands as the dock's edge spots, for the next pass's drops; over a tab strip each reaches /// `strip_reach` from its edge (`DockSizes::strip_reach`). -pub fn register_edge_bands(ctx: &Context, dock: Id, bands: &[EdgeBand], strip_reach: f32) { +pub fn register_edge_bands(ctx: &Context, dock: Id, bands: &[EdgeBand], strip_reach: f32) { for band in bands { DockTargets::

::register_band(ctx, dock, DockSpot::Edge(band.side), band.band, band.line, strip_reach); } diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 299406a8b..fb1899f91 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -22,6 +22,7 @@ use craft_behavior::{DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keye use craft_theme::{ControlSize, Tokens}; use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; use std::borrow::Cow; +use std::fmt::Debug; use std::hash::Hash; /// The style of a group grip: its size comes from the tokens. @@ -265,7 +266,7 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { reported: Reported, } -impl<'a, P: Clone + Hash + Send + Sync + 'static> DockGroup<'a, P> { +impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup<'a, P> { /// The group named by `anchor` (one of its panels) with its `panels`, `active` showing. The group is named by the /// active panel's title. pub fn new(anchor: P, panels: &'a [PanelTitle], active: PanelKey) -> Self { @@ -313,7 +314,7 @@ impl<'a, P: Clone + Hash + Send + Sync + 'static> DockGroup<'a, P> { } } -impl Component for DockGroup<'_, P> { +impl Component for DockGroup<'_, P> { const ROLE: Role = Role::TAB_PANEL; type Style = DockGroupStyle; type Output = DockGroupOutput; @@ -427,7 +428,7 @@ impl Component for DockGroup<'_, P> { } } -impl Container for DockGroup<'_, P> { +impl Container for DockGroup<'_, P> { /// Closed while minimized: the body step runs the header alone, and the body leaves no node, shape or stop. fn open(&mut self) -> Option> { self.open = Bind::given(!self.minimized); @@ -527,7 +528,7 @@ impl Container for DockGroup<'_, P> { /// Registers the tab insertion spots of a group: the half of each shown tab nearer the start edge inserts before /// it, the other half after it, and each spot's mark is the line at the boundary it inserts at. -fn register_insertions( +fn register_insertions( ctx: &egui::Context, dock: Id, anchor: &P, diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index eead14a11..e64e75df6 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -24,6 +24,7 @@ use craft_behavior::overlay::Side; use craft_behavior::{Axis, CursorIcon, DockSide, Metrics, PartKey, PressPhase, Sense, Value}; use craft_theme::ControlSize; use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; +use std::fmt::Debug; use std::hash::Hash; #[cfg(feature = "suite")] @@ -235,7 +236,7 @@ struct Plan { body: Rect, } -impl<'a, P: Value + Hash + 'static> IconicColumn<'a, P> { +impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { /// A column named `label` of the dock `dock`, over `column`, whose open flyout is the panel in `open`; `spec` /// reads each panel's label, icon and limits. pub fn new(label: impl Into

, open: Bind<'a, Option

>, spec: &'a dyn Fn(&P) -> PanelSpec) -> Self { @@ -388,7 +389,7 @@ impl<'a, P: Value + Hash + 'static> IconicColumn<'a, P> { /// What measures and shows the group of an open flyout. type FlyoutView<'a, P> = Box, GroupAt, &mut Ui, &mut BodyCx<'_>) -> Option + 'a>; -impl Component for IconicColumn<'_, P> { +impl Component for IconicColumn<'_, P> { const ROLE: Role = Role::GROUP; const KEYS: KeyUse = KeyUse::SPLITTER; type Style = IconicColumnStyle; @@ -635,7 +636,7 @@ impl Component for IconicColumn<'_, P> { } } -impl IconicColumn<'_, P> { +impl IconicColumn<'_, P> { /// Registers the drop spots of the column the way an expanded column registers them: the bands of a dock /// column's two edges (a new column beside it), the seam on the separator between two icon groups (a new group /// between them), the top of the first group and the bottom of the last down to the column's foot (a new group @@ -692,7 +693,7 @@ fn chevron_edge(edge: DockEdge) -> HeaderEdge { if edge == DockEdge::End { HeaderEdge::End } else { HeaderEdge::Start } } -impl Container for IconicColumn<'_, P> { +impl Container for IconicColumn<'_, P> { /// The chevron's square at the bar's outer end; nothing in a floating window, whose title row is the bar. fn header_parts(&self, cx: &MeasureCx<'_, Self>) -> HeaderParts { if self.bar == ColumnBar::Window { diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 887483f21..0698d501b 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -11,6 +11,7 @@ use crate::style::StyleCx; use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Layout, Node, ZoneSize, node_at, zones}; use egui::{Context, Id, Pos2, Rect, Vec2}; +use std::fmt::Debug; pub use craft_behavior::dock::{SIDE_ZONE_DEPTH_SHARE, SIDE_ZONE_FRACTION}; @@ -453,8 +454,9 @@ impl DockTargets

{ } } -/// The registrations of a pass. A settled region's run record keeps each one to make it again, so the panel type is `Sync`. -impl DockTargets

{ +/// The registrations of a pass. A settled region's run record keeps each one to make it again and compares it with a +/// real run's, so the panel type is `Sync`, `PartialEq` and `Debug`. +impl DockTargets

{ /// Registers `spot` over `rect` for the dock `dock` in the running pass of this viewport. Group and column /// rendering call it; it does nothing outside a pass. A floating window registers on its own egui layer, and /// the drag session orders the layers, so no registry orders them. @@ -468,10 +470,13 @@ impl DockTargets

{ if !crate::runtime::measure::effect(ctx, "dock::register_target") { return; } - Self::journal(ctx, || { - let spot = spot.clone(); - move |ctx: &Context| Self::register_in(ctx, dock, spot.clone(), hit, applies) - }); + Self::journal( + ctx, + || (dock, spot.clone(), hit, applies), + |ctx, (dock, spot, hit, applies)| { + Self::register_in(ctx, *dock, spot.clone(), *hit, *applies); + }, + ); Self::with_dock(ctx, dock, |targets| targets.add(spot, hit, applies, hit)); } @@ -482,10 +487,13 @@ impl DockTargets

{ if !crate::runtime::measure::effect(ctx, "dock::register_target") { return; } - Self::journal(ctx, || { - let spot = spot.clone(); - move |ctx: &Context| Self::register_band(ctx, dock, spot.clone(), band, line, reach) - }); + Self::journal( + ctx, + || (dock, spot.clone(), band, line, reach), + |ctx, (dock, spot, band, line, reach)| { + Self::register_band(ctx, *dock, spot.clone(), *band, *line, *reach); + }, + ); let near = line.expand(reach).intersect(band); Self::with_dock(ctx, dock, |targets| targets.add(spot, band, band, near)); } @@ -497,14 +505,18 @@ impl DockTargets

{ if !crate::runtime::measure::effect(ctx, "dock::register_room") { return; } - Self::journal(ctx, || move |ctx: &Context| Self::register_room(ctx, dock, room)); + Self::journal(ctx, || (dock, room), |ctx, &(dock, room)| Self::register_room(ctx, dock, room)); Self::with_dock(ctx, dock, |targets| targets.room = Some(room)); } /// Notes a registration in the records of the settling regions around the running code, so a region that settles /// registers its drop spots again when it replays its last run. - fn journal(ctx: &Context, make: impl FnOnce() -> F) { - crate::runtime::journal(ctx, make); + fn journal(ctx: &Context, args: impl FnOnce() -> A, again: F) + where + A: PartialEq + Debug + Send + Sync + 'static, + F: Fn(&Context, &A) + Send + Sync + 'static, + { + crate::runtime::journal(ctx, args, again); } } diff --git a/crates/ui-panels/src/rails/drawer.rs b/crates/ui-panels/src/rails/drawer.rs index 24cec62d9..794b54825 100644 --- a/crates/ui-panels/src/rails/drawer.rs +++ b/crates/ui-panels/src/rails/drawer.rs @@ -167,11 +167,11 @@ enum DrawerKey { /// headings. struct Rows<'a> { keys: Vec, - resolved: &'a [Vec], + resolved: &'a [Vec>], } impl<'a> Rows<'a> { - fn new(resolved: &'a [Vec]) -> Self { + fn new(resolved: &'a [Vec>]) -> Self { let mut keys = Vec::new(); for (group, tools) in resolved.iter().enumerate().filter(|(_, tools)| !tools.is_empty()) { keys.push(DrawerKey::Group(group)); @@ -221,7 +221,7 @@ impl ToolbarDrawer<'_, T> { let words = env.words::(); let os = os_of(ui.ctx()); let ctx = ui.ctx().clone(); - let resolved: Vec> = + let resolved: Vec>> = groups.iter().map(|group| group.tools.iter().map(|tool| commands::resolve(&ctx, tool.command.clone())).collect()).collect(); let mut edits: Vec> = dropped.and_then(|dropped| drop_edit(dropped.drag, dropped.at, groups, toolbar)).into_iter().collect(); let mut select: Option = None; diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index dcf0318b8..fdcdafaf0 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -90,9 +90,9 @@ struct Held(bool); /// What the parts step resolved for the tools this pass. struct Laid { - resolved: Vec>, + resolved: Vec>>, /// The click command as resolved, when the button has one. - click: Option, + click: Option>, shown: usize, } @@ -185,7 +185,7 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> { /// The command the face stands for: the click command when there is one, else the shown tool's. fn lead<'l>(&self, laid: &'l Laid) -> Option<&'l ResolvedCommand> { - if self.click.is_some() { laid.click.as_ref() } else { laid.resolved.get(laid.shown).and_then(Option::as_ref) } + if self.click.is_some() { laid.click.as_deref() } else { laid.resolved.get(laid.shown).and_then(Option::as_deref) } } } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 72ccb3ce0..a4813635a 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -673,7 +673,12 @@ fn show_area( /// Registers the outer-edge bands and the new-dock bands as the dock's drop spots for the next pass, from the leaves /// the split area placed this pass (each as its tree path and rect). A new-dock band runs along a start or end edge /// that holds no dock. -fn register_bands(scene: &Scene<'_, P>, ctx: &Context, area: Rect, leaves: &[(Vec, Rect)]) { +fn register_bands( + scene: &Scene<'_, P>, + ctx: &Context, + area: Rect, + leaves: &[(Vec, Rect)], +) { if scene.layout.root.is_none() { return; } diff --git a/crates/ui-patterns/src/patterns/panels/palette/stories.rs b/crates/ui-patterns/src/patterns/panels/palette/stories.rs index da81dbb08..c15197308 100644 --- a/crates/ui-patterns/src/patterns/panels/palette/stories.rs +++ b/crates/ui-patterns/src/patterns/panels/palette/stories.rs @@ -3,7 +3,7 @@ use super::CommandPalette; use crate::contract::Bind; use crate::menu::search::HelpEntry; -use crate::runtime::commands::{CommandInput, CommandRef, CommandState, EditCommands}; +use crate::runtime::commands::{CommandRef, CommandState, CommandStates, EditCommands}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use std::sync::LazyLock; @@ -69,8 +69,8 @@ fn palette(ui: &mut Ui, data: &mut StoryData, recents: Vec) -> Story } /// The command states the stories run under: Redo is disabled, as the entries list it. -fn commands(input: CommandInput) -> CommandInput { - input.state(EditCommands::Redo, CommandState::new().enabled(false)) +fn commands(states: &mut CommandStates) { + states.set(EditCommands::Redo, CommandState::new().enabled(false)); } #[story(CommandPalette<'static>, covers = [], drive = Drive::Never, title = "PhotoCraft", commands = commands)] diff --git a/crates/ui-shell/tests/it/commands/app_catalog.rs b/crates/ui-shell/tests/it/commands/app_catalog.rs index ef6ecaff4..d8e3a6b03 100644 --- a/crates/ui-shell/tests/it/commands/app_catalog.rs +++ b/crates/ui-shell/tests/it/commands/app_catalog.rs @@ -2,9 +2,10 @@ //! rules every app command follows, and a frame builds a keymap only for a catalog generation it has not built. // The catalog is given through `Frames::commands`, which keeps it for every later frame. -use craft_ui::contract::{Bind, Props as _, Show as _}; +use craft_ui::contract::{Bind, Props as _, Show as _, Tracked}; use craft_ui::runtime::commands::{ - AppCatalog, Binding, CommandDef, CommandInput, CommandKind, CommandRef, CommandState, EditCommands, FirePhase, Scope, keymap_builds, + AppCatalog, Binding, CommandDef, CommandInput, CommandKind, CommandRef, CommandState, CommandStates, EditCommands, FirePhase, Scope, + keymap_builds, }; use craft_ui::runtime::env::WindowKey; use craft_ui::runtime::frame::take_output; @@ -198,11 +199,9 @@ fn a_press_without_a_physical_key_fires_its_command_once() { fn an_app_catalogs_alternate_key_for_a_registry_command_runs_it() { let cut = CommandRef::from(EditCommands::Cut); let alternate = CommandDef::new(cut.clone(), "Cut", Scope::app()).with_default(Binding::parse("F2").expect("the trial's chord parses")); - let input = || { - CommandInput::new() - .catalog(AppCatalog::new(vec![alternate.clone()], 1).expect("the trial's catalog is valid")) - .state(cut.clone(), CommandState::new()) - }; + let mut states = Tracked::new(CommandStates::new()); + states.set(cut.clone(), CommandState::new()); + let input = || CommandInput::new().catalog(AppCatalog::new(vec![alternate.clone()], 1).expect("the trial's catalog is valid")).states(&states); let mut show = |ui: &mut Ui| { AppShell::new(WindowKey::main()).show(ui, &mut ()); }; diff --git a/crates/ui-shell/tests/it/commands/board.rs b/crates/ui-shell/tests/it/commands/board.rs index d4bb19304..2b5beb33a 100644 --- a/crates/ui-shell/tests/it/commands/board.rs +++ b/crates/ui-shell/tests/it/commands/board.rs @@ -1,8 +1,6 @@ use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Silent, Tap}; use craft_ui::contract::{Props as _, Show as _, ShowContainer as _}; -use craft_ui::runtime::commands::{ - CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve, -}; +use craft_ui::runtime::commands::{CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve}; use craft_ui::runtime::focus::{FocusTarget, request}; use craft_ui::runtime::frame::take_output; use craft_ui::runtime::measure::chord_texts; @@ -82,58 +80,6 @@ fn an_enclosing_scopes_shortcut_beats_the_applications() { assert_eq!((closed.get(), ids(&take_output(&frames.ctx).fired)), (1, vec!["trial.jump"]), "outside the dock the application's command fires"); } -/// 1.8 and 7.2: the gate is app code, so it runs with no runtime lock held and may use the board. -#[trial] -fn the_gate_may_resolve_commands() { - let mut frames = Frames::new(); - let ctx = frames.ctx.clone(); - let inside = std::sync::atomic::AtomicBool::new(false); - frames.commands(CommandInput::new().gate(CommandGate::new(move |_: &CommandRef| { - // The nested `resolve` runs the gate again, which stops here. - inside.swap(true, std::sync::atomic::Ordering::SeqCst) || { - let enabled = resolve(&ctx, AppCommand::Go).enabled; - inside.store(false, std::sync::atomic::Ordering::SeqCst); - enabled - } - }))); - let mut show = |ui: &mut Ui| { - Tap::new().id_salt("go").command(AppCommand::Save).show(ui); - }; - frames.idle(2, &mut show); - frames.frame(vec![key_press(Key::K, Modifiers::COMMAND)], &mut show); - assert_eq!(ids(&take_output(&frames.ctx).fired), ["trial.save"]); -} - -/// The gate answers from what the app knew before the frame: a frame asks it once per command, however many components -/// show the command and however many passes and readers resolve it. -#[trial] -fn a_frame_asks_the_gate_once_per_command() { - use std::sync::{Arc, Mutex}; - let asked = Arc::new(Mutex::new(Vec::::new())); - let log = Arc::clone(&asked); - let mut frames = Frames::new(); - frames.commands(CommandInput::new().gate(CommandGate::new(move |command: &CommandRef| { - log.lock().expect("the gate's log").push(command.key()); - true - }))); - let mut show = |ui: &mut Ui| { - for salt in ["a", "b", "c"] { - Tap::new().id_salt(salt).command(AppCommand::Save).show(ui); - } - }; - frames.idle(2, &mut show); - for at in [5.0, 6.0, 7.0] { - asked.lock().expect("the gate's log").clear(); - frames.frame(vec![moved(Pos2::new(at, at))], &mut show); - let asked = asked.lock().expect("the gate's log").clone(); - let mut once = asked.clone(); - once.sort(); - once.dedup(); - assert!(once.contains(&"trial.save".to_owned()), "the frame resolves the taps' command: {asked:?}"); - assert_eq!(asked.len(), once.len(), "a frame asked the gate for a command twice: {asked:?}"); - } -} - /// 11.3: a scoped entry waits for its instance and is dropped when the instance stops being live. #[trial] fn an_untaken_scoped_entry_is_dropped_with_its_instance() { diff --git a/crates/ui-shell/tests/it/commands/mod.rs b/crates/ui-shell/tests/it/commands/mod.rs index 6b817c16a..50a35dd00 100644 --- a/crates/ui-shell/tests/it/commands/mod.rs +++ b/crates/ui-shell/tests/it/commands/mod.rs @@ -4,3 +4,4 @@ pub(crate) mod app_catalog; pub(crate) mod app_scope; pub(crate) mod board; pub(crate) mod kit; +pub(crate) mod resolve; diff --git a/crates/ui-shell/tests/it/commands/resolve.rs b/crates/ui-shell/tests/it/commands/resolve.rs new file mode 100644 index 000000000..955bc8677 --- /dev/null +++ b/crates/ui-shell/tests/it/commands/resolve.rs @@ -0,0 +1,384 @@ +//! Command resolution runs only when an input of it changed: count trials over fifty shown commands. + +use super::kit::{AppCommand, DOCK, Dock, PANE, Pane, PaneCommand, Tap}; +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Lazy, Trigger}; +use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, Tracked}; +use craft_ui::dialog::Dialog; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::runtime::commands::{ + AppCatalog, Binding, CommandDef, CommandGate, CommandInput, CommandRef, CommandSet as _, CommandState, CommandStates, Commands as _, Scope, +}; +use craft_ui::runtime::commands::{EditCommands, declare_child, resolve, resolve_beneath}; +use craft_ui::runtime::focus::{FocusTarget, request}; +use craft_ui::runtime::measure::last_pass_wake_walks; +use craft_ui::runtime::measure::{Resolve, last_pass_resolves}; +use craft_ui::sections::{DialogRole, FooterButton}; +use craft_ui::testing::input::key_press; +use craft_ui::testing::pointer::moved; +use craft_ui::testing::pointer::{press, release}; +use craft_ui::testing::{Frames, trial}; +use craft_ui::text::TextField; +use egui::{Id, Pos2, Ui}; +use egui::{Key, Modifiers, ViewportId}; +use std::cell::{Cell, RefCell}; + +/// The panes: each is an instance of the pane scope, so each is its own reader of the commands its taps show. +const PANES: [&str; 5] = ["a", "b", "c", "d", "e"]; + +/// The commands the taps of a pane show, each by two taps. +fn shown(at: usize) -> CommandRef { + match at % 5 { + 0 => AppCommand::Save.into(), + 1 => AppCommand::Go.into(), + 2 => AppCommand::Play.into(), + 3 => AppCommand::Jump.into(), + _ => PaneCommand::ZoomIn.into(), + } +} + +/// Readers kept: one per pane and command. +const KEPT: u32 = 25; +/// Readers of Save: one per pane. +const SAVE_READERS: u32 = 5; +/// Distinct commands shown. +const COMMANDS: u32 = 5; + +/// Fifty taps in five panes; pane `a` publishes Zoom In enabled as `zoom` says. `ids` gets each tap's id. With +/// `global`, a surface with no component of its own reads Zoom In after the panes, which picks an instance by the focus. +struct Scene { + zoom: Cell, + ids: RefCell>, + global: bool, + /// Pane `a` is left out of the next pass. + skip_a: Cell, + /// Salts the panes' ids, so two windows show panes of their own. + window: &'static str, +} + +impl Scene { + fn new() -> Self { + Scene { zoom: Cell::new(true), ids: RefCell::new(Vec::new()), global: false, skip_a: Cell::new(false), window: "" } + } + + fn show(&self, ui: &mut Ui) { + self.ids.borrow_mut().clear(); + let skip_a = self.skip_a.replace(false); + for (pane, salt) in PANES.iter().enumerate() { + if pane == 0 && skip_a { + continue; + } + Pane::new().id_salt((self.window, *salt)).show(ui, |ui, cx| { + if pane == 0 { + cx.publish(PaneCommand::ZoomIn, CommandState::new().enabled(self.zoom.get())); + } + for at in 0..10 { + let id = Tap::new().id_salt(at).command(shown(at)).show(ui).id; + self.ids.borrow_mut().push(id); + } + }); + } + if self.global { + resolve(ui.ctx(), PaneCommand::ZoomIn); + } + } +} + +fn counts(ctx: &egui::Context) -> (u32, u32) { + (last_pass_resolves(ctx, Resolve::New), last_pass_resolves(ctx, Resolve::Again)) +} + +/// One frame of `scene`, and its new and repeated resolutions summed over every pass of the frame: each pass after +/// the first reads the one before it as it starts, and the last is read after the frame. +fn frame(frames: &mut Frames, scene: &Scene) -> (u32, u32) { + let (new, again, _) = frame_walks(frames, ViewportId::ROOT, &mut |ui| scene.show(ui)); + (new, again) +} + +/// One frame of `viewport` running `show`, and its new and repeated resolutions and the kept resolutions its wakes +/// walked, summed over every pass of the frame. +fn frame_walks(frames: &mut Frames, viewport: ViewportId, show: &mut dyn FnMut(&mut Ui)) -> (u32, u32, u32) { + let ctx = frames.ctx.clone(); + let (mut new, mut again, mut walks, mut pass) = (0, 0, 0, 0); + let mut add = |ctx: &egui::Context| { + let (n, a) = counts(ctx); + (new, again, walks) = (new + n, again + a, walks + last_pass_wake_walks(ctx)); + }; + frames.frame_in_viewport(viewport, vec![], |ui| { + if pass > 0 { + add(&ctx); + } + pass += 1; + show(ui); + }); + add(&ctx); + (new, again, walks) +} + +thread_local! { + static ASKS: Cell = const { Cell::new(0) }; +} + +/// The gate: refuses Save while `refuses`; counts its asks. +fn refuse_save(refuses: &bool, command: &CommandRef) -> bool { + ASKS.with(|asks| asks.set(asks.get() + 1)); + !(*refuses && AppCommand::from_ref(command) == Some(AppCommand::Save)) +} + +fn gated(states: &Tracked, refuses: bool) -> CommandInput { + CommandInput::new().states(states).gate(CommandGate::new(refuses, refuse_save)) +} + +/// An idle frame with fifty shown commands resolves nothing, and neither does a pointer move over none of them. +#[trial] +fn an_idle_frame_resolves_no_command() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + assert_eq!(scene.ids.borrow().len(), 50, "fifty commands are shown"); + assert_eq!(frames.frame(vec![], |ui| scene.show(ui)), 1, "an idle frame takes one pass"); + assert_eq!(counts(&frames.ctx), (0, 0), "an idle frame resolves nothing"); + assert_eq!(frames.frame(vec![moved(Pos2::new(900.0, 900.0))], |ui| scene.show(ui)), 1, "so does a pointer move"); + assert_eq!(counts(&frames.ctx), (0, 0), "a pointer move away from the taps resolves nothing"); +} + +/// Two windows with frames alternating between them, idle: each frame resolves nothing and walks nothing, as the +/// child stays open across the root's frames and the root's across the child's. +#[trial] +fn idle_frames_alternating_between_two_windows_resolve_nothing() { + let root = Scene::new(); + let other = Scene { window: "child", ..Scene::new() }; + let child = ViewportId::from_hash_of("second window"); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + for _ in 0..3 { + frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| root.show(ui)); + frame_walks(&mut frames, child, &mut |ui| other.show(ui)); + } + for round in 0..4 { + assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| root.show(ui)), (0, 0, 0), "root frame {round}"); + assert_eq!(frame_walks(&mut frames, child, &mut |ui| other.show(ui)), (0, 0, 0), "child frame {round}"); + } +} + +/// Editing one app-scope state resolves again only that command's readers, once. +#[trial] +fn one_state_change_resolves_only_its_readers() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let mut states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + states.set(AppCommand::Save, CommandState::new().enabled(false)); + frames.commands(gated(&states, false)); + assert_eq!( + frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), + (0, SAVE_READERS, SAVE_READERS), + "the wake walks and resolves again only Save's readers" + ); + assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), (0, 0, 0), "the next frame walks nothing"); +} + +/// An instance publishing a new state resolves again only the readers of that instance's state. +#[trial] +fn a_published_state_change_resolves_only_its_readers() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + scene.zoom.set(false); + // The publish runs before its reader, which resolves again as it reads; a wake walks only that reader. + let (new, again, first) = frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)); + let (_, _, second) = frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)); + assert_eq!((new, again), (0, 1), "only pane a's Zoom In reader resolves again"); + assert_eq!(first + second, 1, "the wakes walk only the reader of the published key"); + assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), (0, 0, 0), "publishing the same state again walks nothing"); +} + +/// A change of the gate's props asks the gate once per shown command and resolves again only the readers whose answer +/// changed; a new gate with the same props asks nothing. +#[trial] +fn a_gate_props_change_resolves_only_the_readers_whose_answer_changed() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + ASKS.with(|asks| asks.set(0)); + frames.commands(gated(&states, true)); + assert_eq!(frame(&mut frames, &scene), (0, SAVE_READERS), "only Save's readers, which the gate now refuses, resolve again"); + assert_eq!(ASKS.with(Cell::get), COMMANDS, "the gate is asked once per shown command"); + ASKS.with(|asks| asks.set(0)); + frames.commands(gated(&states, true)); + assert_eq!(frame(&mut frames, &scene), (0, 0), "a gate with the same props resolves nothing"); + assert_eq!(ASKS.with(Cell::get), 0, "and is not asked"); +} + +/// Moving the focus between taps resolves none of them: each finds its command's instance in its own chain, or the +/// command is the app's, so none reads the focus. +#[trial] +fn a_focus_move_resolves_no_reader_that_does_not_read_the_focus() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + for at in [0, 17, 42] { + let id = scene.ids.borrow()[at]; + request(&frames.ctx, FocusTarget::Id(id)); + for _ in 0..2 { + assert_eq!(frame(&mut frames, &scene), (0, 0), "focusing tap {at} resolves nothing"); + } + } +} + +/// An instance that misses exactly one pass and registers again is live again for every kept resolution in the +/// frame it comes back in: its return moves the inputs every resolution reads. +#[trial] +fn an_instance_back_after_one_missed_pass_is_live_again() { + let shown = Cell::new(true); + let enabled = Cell::new(false); + let mut show = |ui: &mut Ui| { + if shown.get() { + Pane::new().id_salt("b").show(ui, |ui, _| { + Tap::new().id_salt("zoom").command(PaneCommand::ZoomIn).show(ui); + }); + } + enabled.set(resolve(ui.ctx(), PaneCommand::ZoomIn).enabled); + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + assert!(enabled.get(), "Zoom In reaches the pane"); + shown.set(false); + assert_eq!(frames.frame(vec![], &mut show), 1, "the pane misses one pass"); + shown.set(true); + frames.frame(vec![], &mut show); + assert!(enabled.get(), "the pane is live again in the frame it comes back in"); + frames.frame(vec![], &mut show); + assert!(enabled.get(), "and stays so"); +} + +/// A settled region that shows a command the focused stop answers for (Cut, which a text field takes) runs when that +/// stop's answer changes: with the focus moving from the field to a tap, which takes no edits, Cut no longer waits for a +/// selection. +#[trial] +fn a_settled_region_runs_when_the_focused_stops_answer_changes() { + let text = RefCell::new("hello".to_owned()); + let (field, tap, cut) = (Cell::new(Id::NULL), Cell::new(Id::NULL), Cell::new(Id::NULL)); + let runs = Cell::new(0); + let mut show = |ui: &mut Ui| { + field.set(TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui).response.id); + tap.set(Tap::new().id_salt("plain").show(ui).id); + Lazy::new("edits", 0.0).settles(true).show(ui, |ui| { + runs.set(runs.get() + 1); + cut.set(Button::command(EditCommands::Cut).show(ui).id); + }); + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show); + request(&frames.ctx, FocusTarget::Id(field.get())); + frames.idle(30, &mut show); + assert!(frames.tree().is_disabled(cut.get()), "Cut does nothing with no text selected"); + runs.set(0); + frames.idle(2, &mut show); + assert_eq!(runs.get(), 0, "the region is settled"); + request(&frames.ctx, FocusTarget::Id(tap.get())); + frames.idle(2, &mut show); + assert_eq!(runs.get(), 1, "the new answer for Cut runs the region once"); + assert!(!frames.tree().is_disabled(cut.get()), "which shows Cut enabled"); +} + +/// The testing check every 100th pass compares every kept resolution with a full one, and every kept gate answer with +/// the gate's. The script changes, a few passes before each check, every kind of input a resolution reads: app and +/// published states, the gate, the keymap, the focus and the focused stop's edits, a menu and a modal layer with readers +/// inside (a palette's reader under the layer), an instance that misses one pass and a scope's parent. +#[trial] +fn the_hundredth_pass_check_finds_every_kept_resolution_current() { + let scene = Scene { global: true, ..Scene::new() }; + let text = RefCell::new("hello".to_owned()); + let (field, opener) = (Cell::new(Id::NULL), Cell::new(Pos2::ZERO)); + let modal = Cell::new(false); + let mut show = |ui: &mut Ui| { + scene.show(ui); + field.set(TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui).response.id); + Tap::new().id_salt("cut").command(EditCommands::Cut).show(ui); + Dock::new().id_salt("dock").show(ui, |ui, _| { + Tap::new().id_salt("zoom").command(PaneCommand::ZoomIn).show(ui); + }); + let open = Tap::new().id_salt("opener").show(ui); + opener.set(open.rect.center()); + Menu::new("Menu").opened_by(&open, Trigger::Click).show(ui, |ui, _| { + MenuItem::command(AppCommand::Save).show(ui); + MenuItem::command(EditCommands::Cut).show(ui); + }); + let mut open = modal.get(); + Dialog::new("Options").opened(Bind::bound(&mut open)).buttons([FooterButton::new("OK", DialogRole::Accept)]).show(ui, |ui, cx| { + cx.publish(EditCommands::Undo, CommandState::new()); + resolve_beneath(ui.ctx(), AppCommand::Save); + Tap::new().id_salt("in dialog").command(EditCommands::Undo).show(ui); + }); + modal.set(open); + }; + let mut frames = Frames::new(); + let mut states = Tracked::new(CommandStates::new()); + let mut refuses = false; + // A new catalog generation rebuilds the keymap. + let mut generation = 1; + let input = |states: &Tracked, refuses: bool, generation: u64| { + let extra = CommandDef::new(CommandRef::new("trial.extra"), "Extra", Scope::app()) + .with_default(Binding::parse(if generation.is_multiple_of(2) { "F7" } else { "F6" }).expect("the trial's chord parses")); + gated(states, refuses).catalog(AppCatalog::new(vec![extra], generation).expect("the trial's catalog is valid")) + }; + frames.commands(input(&states, refuses, generation)); + // Each step at the pass it names, relative to a check at 100 and 200. + let script: Vec<(usize, &str)> = [100, 200] + .into_iter() + .flat_map(|check| { + let steps: &[(usize, &str)] = if check == 100 { + &[(14, "focus field"), (12, "select all"), (10, "press opener"), (9, "release opener"), (6, "parent"), (3, "skip a"), (1, "state")] + } else { + &[(14, "focus field"), (12, "collapse"), (10, "modal"), (8, "keymap"), (6, "gate"), (3, "skip a"), (1, "publish")] + }; + steps.iter().map(move |(before, step)| (check - before, *step)).collect::>() + }) + .chain([(103, "escape"), (203, "close modal")]) + .collect(); + let mut script = script.into_iter().peekable(); + let (mut passes, mut checked) = (0, Vec::new()); + while passes < 260 { + let mut events = Vec::new(); + if let Some((_, step)) = script.next_if(|(at, _)| passes + 1 >= *at) { + match step { + "focus field" => { + request(&frames.ctx, FocusTarget::Id(field.get())); + } + "select all" => events.push(key_press(Key::A, Modifiers::COMMAND)), + "collapse" => events.push(key_press(Key::ArrowRight, Modifiers::NONE)), + "press opener" => events.push(press(opener.get())), + "release opener" => events.push(release(opener.get())), + "escape" => events.push(key_press(Key::Escape, Modifiers::NONE)), + "skip a" => scene.skip_a.set(true), + "parent" => declare_child(&frames.ctx, DOCK, PANE), + "state" => states.set(AppCommand::Go, CommandState::new().checked(true)), + "gate" => refuses = !refuses, + "keymap" => generation += 1, + "publish" => scene.zoom.set(!scene.zoom.get()), + "modal" => modal.set(true), + _ => modal.set(false), + } + } + frames.commands(input(&states, refuses, generation)); + passes += frames.frame(events, &mut show); + let compared = last_pass_resolves(&frames.ctx, Resolve::Checked); + if compared > 0 { + checked.push(compared); + } + } + assert_eq!(script.next().map(|(_, step)| step), None, "every step ran"); + assert_eq!(checked.len(), 2, "two checks ran: {checked:?}"); + assert!(checked.iter().all(|compared| *compared > KEPT), "each compared the panes' readers and the script's: {checked:?}"); +} diff --git a/crates/ui-widgets/src/bars/items.rs b/crates/ui-widgets/src/bars/items.rs index 471a841f2..97163b91e 100644 --- a/crates/ui-widgets/src/bars/items.rs +++ b/crates/ui-widgets/src/bars/items.rs @@ -108,7 +108,7 @@ pub struct BarItemsStyle { #[derive(Clone)] struct Present { item: BarItem, - resolved: ResolvedCommand, + resolved: std::sync::Arc, } /// Where the parts of a strip sit this pass. diff --git a/crates/ui-widgets/src/notices/notice.rs b/crates/ui-widgets/src/notices/notice.rs index 0cfb90755..9c3bdce04 100644 --- a/crates/ui-widgets/src/notices/notice.rs +++ b/crates/ui-widgets/src/notices/notice.rs @@ -343,7 +343,7 @@ impl<'a> Notice<'a> { self.actions .iter() .map(|action| match &action.command { - Some(command) => cx.resolve_command(command.clone()).map_or(Label::Empty, |resolved| Label::from(resolved.label)), + Some(command) => cx.resolve_command(command.clone()).map_or(Label::Empty, |resolved| Label::from(resolved.label.clone())), None => action.label.clone(), }) .collect() diff --git a/crates/ui-widgets/src/table/view.rs b/crates/ui-widgets/src/table/view.rs index 697e9edaf..6f11bd7e0 100644 --- a/crates/ui-widgets/src/table/view.rs +++ b/crates/ui-widgets/src/table/view.rs @@ -161,7 +161,7 @@ impl Component for Table<'_, K> { Divider::horizontal().show(ui); } for (command, enabled) in &commands { - let label = crate::runtime::commands::resolve(&ctx, *command).label; + let label = crate::runtime::commands::resolve(&ctx, *command).label.clone(); if MenuItem::new(label.to_string()).enabled(*enabled).show(ui).ran { picks.push(ColumnRequest::Command(*command)); } diff --git a/crates/ui-widgets/tests/it/body/settle.rs b/crates/ui-widgets/tests/it/body/settle.rs index 317b8d902..7774f7a8c 100644 --- a/crates/ui-widgets/tests/it/body/settle.rs +++ b/crates/ui-widgets/tests/it/body/settle.rs @@ -6,10 +6,10 @@ use crate::values::kit::{AT, INITIAL, Scrub, Seen}; use craft_theme::{Contrast, Mode, Size}; use craft_ui::buttons::Button; use craft_ui::choice::{Radio, RadioGroup}; -use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowContainer as _, Sizing, Tracked}; use craft_ui::display::Spinner; use craft_ui::layout_components::Stack; -use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Commands as _}; +use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, CommandStates, Commands as _}; use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::layout::in_region; use craft_ui::testing::pointer::{moved, press, release}; @@ -381,7 +381,11 @@ fn an_app_command_state_runs_the_settled_child_that_shows_it() { let mut frames = Frames::new(); scene.settle(&mut frames); assert!(!scene.disabled(&mut frames, 0), "Shown starts enabled"); - let disable = |enabled: bool| CommandInput::new().state(Shown::Visible, CommandState::new().enabled(enabled)); + let mut states = Tracked::new(CommandStates::new()); + let mut disable = |enabled: bool| { + states.set(Shown::Visible, CommandState::new().enabled(enabled)); + CommandInput::new().states(&states) + }; frames.commands(disable(false)); let (_, [reader, beside]) = scene.frame(&mut frames); assert!(reader > 0 && beside == 0, "only the child that shows Shown runs: {reader}, {beside}"); @@ -425,7 +429,9 @@ fn a_command_read_in_a_measured_body_settles_and_runs_when_its_state_changes() { let mut frames = Frames::new(); scene.settle(&mut frames); assert_eq!(scene.frame(&mut frames).1, [0, 0], "the child holding the measured body settles"); - frames.commands(CommandInput::new().state(Shown::Measured, CommandState::new().enabled(false))); + let mut states = Tracked::new(CommandStates::new()); + states.set(Shown::Measured, CommandState::new().enabled(false)); + frames.commands(CommandInput::new().states(&states)); let (_, [reader, beside]) = scene.frame(&mut frames); assert!(reader > 0 && beside == 0, "only the child that shows Measured runs: {reader}, {beside}"); assert!(scene.disabled(&mut frames, 3), "it shows Measured disabled in the frame the app disables it"); diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index 14cc8b77a..4ef66a5e1 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -25,19 +25,19 @@ apv-decode = ["craft-media/bitstream"] apv-encode = ["craft-media/bitstream"] # VP8 (RFC 6386): decoder and encoder; `vp8-decode` or `vp8-encode` for one of them. vp8 = ["vp8-decode", "vp8-encode"] -vp8-decode = [] +vp8-decode = ["dep:craft-media"] vp8-encode = [] # MPEG-2 video (ITU-T H.262) and MPEG-1 video (ISO/IEC 11172-2): decoder (`mpeg2-decode`) and # MPEG-2 encoder (`mpeg2-encode`). The encoder reuses the decoder's code tables, IDCT and motion # compensation, so it turns on the decoder too. mpeg2 = ["mpeg2-decode", "mpeg2-encode"] -mpeg2-decode = [] +mpeg2-decode = ["dep:craft-media"] mpeg2-encode = ["mpeg2-decode"] # MPEG-4 Part 2 video (ISO/IEC 14496-2, the Xvid/DivX format): Simple profile encoder. mpeg4 = ["mpeg4-encode"] mpeg4-encode = ["craft-media/bitstream"] # FFV1 lossless video (RFC 9043): version 3, range coder, decoder and encoder. -ffv1 = [] +ffv1 = ["dep:craft-media"] # Hap (Vidvox): decoder and encoder, with Snappy and chunked second stages. hap = [] # Motion JPEG: a frame-level decoder and encoder over `craft-jpeg`. @@ -80,8 +80,13 @@ rav1e = { version = "0.8", default-features = false, optional = true } [dev-dependencies] craft-media-testkit = { workspace = true } -# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test, and the VMD demuxer for the VMD decoder's. -craft-media = { workspace = true, features = ["avi", "vmd"] } +# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test; the MP4, MPEG-TS and AVI +# demuxers, for the track decoder's tests; the VMD demuxer, for the VMD decoder's. +craft-media = { workspace = true, features = ["avi", "isobmff", "mpegts", "vmd"] } + +# Built with any decoder feature; each codec's tests need its own. +[[test]] +name = "track" [[test]] name = "vmd" diff --git a/crates/video/README.md b/crates/video/README.md index c2c5b2745..0413e658d 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -55,3 +55,42 @@ comes with its codec's feature): The constructors check that every plane's buffer, stride and size fit the frame, so a picture with inconsistent fields is an error, not an out-of-bounds read. + +## Decoding a track + +`TrackDecoder` is the counterpart of `craft_audio::TrackDecoder` for an app with its own demuxer. +It picks the decoder from a track's `CodecParams`, takes packets in decode order with their +timestamps, and returns `VideoFrame`s in display order. `flush` returns the frames still held at +the end of the stream, and `reset` prepares for decoding from another key frame after a seek. It +is built with any of the decoder features below and decodes the codecs whose feature is on. + +| Codec | Feature | `extradata` | +|---|---|---| +| H.264 | `h264-decode` | an `avcC` record (length-prefixed packets), Annex B parameter sets, or empty (Annex B packets) | +| HEVC | `hevc-decode` | an `hvcC` record (length-prefixed packets), Annex B parameter sets, or empty (Annex B packets) | +| VP9 | `vp9-decode` | ignored | +| AV1 | `av1-decode` | an `av1C` record, or empty | +| MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty | +| ProRes | `prores` | ignored (frame headers carry the format) | +| DNxHD / DNxHR | `dnx` | ignored (frame headers carry the format) | +| APV | `apv-decode` | ignored (access units carry the format) | +| FFV1 | `ffv1` | required version 3 configuration record; container width and height are required too | +| VP8 | `vp8-decode` | ignored (key frames carry the format) | + +Configuration that holds picture data (a slice, a frame OBU, an MPEG-2 picture) is refused. +Errors are `VideoError`: `Unsupported`, `Malformed`, or a picture that did not convert. + +When a picture does not convert, the frames finished with it are kept and the next call returns +them first. When the codec itself fails, the pictures it had finished are up to the codec: + +- H.264 keeps them for later calls, also when the error comes at `flush`. +- HEVC does too, but only its newest 32 while calls keep failing, which bounds its memory. +- VP9 keeps those of earlier packets. +- MPEG-2 returns them with the call, unless the packet made too many pictures. +- AV1 drops those the failing `decode` or `flush` had finished. + +ProRes, DNx, APV and FFV1 return one frame per successful packet, with its packet timestamp; +VP8 returns no picture for a hidden reference frame. These codecs have no delayed output. +APV uses the codec's default selection of the first decodable primary frame and its alpha. +FFV1 has the underlying decoder's version 3, range-coded, key-frame-only support. Reset keeps +its configuration and container dimensions; VP8 reset discards its reference pictures. diff --git a/crates/video/src/av1/decode/mod.rs b/crates/video/src/av1/decode/mod.rs index 63f66120a..b5e410341 100644 --- a/crates/video/src/av1/decode/mod.rs +++ b/crates/video/src/av1/decode/mod.rs @@ -5,7 +5,7 @@ #![allow(clippy::needless_range_loop, clippy::type_complexity)] -mod bits; +pub(crate) mod bits; mod cdef; mod cdf; mod decoder; diff --git a/crates/video/src/error.rs b/crates/video/src/error.rs new file mode 100644 index 000000000..36802a685 --- /dev/null +++ b/crates/video/src/error.rs @@ -0,0 +1,117 @@ +//! [`VideoError`], the error of the codec-agnostic layer (`TrackDecoder`). + +use crate::frame::FrameError; + +/// Errors from the codec-agnostic layer. +/// +/// Codec errors convert into it, so code mixing `TrackDecoder` with the codec modules can +/// use `?` throughout: a codec's "unsupported" stays [`VideoError::Unsupported`], anything else in +/// the input is [`VideoError::Malformed`]. The message starts with the codec's name. +#[non_exhaustive] +#[derive(Debug, thiserror::Error)] +pub enum VideoError { + /// The codec, or a feature of the stream, is valid but not supported (or its decoder is not + /// in this build). + #[error("unsupported video: {0}")] + Unsupported(String), + /// The input is corrupt or not what it claims to be. + #[error("malformed video: {0}")] + Malformed(String), + /// A decoded picture did not convert into a [`crate::frame::VideoFrame`]. + #[error(transparent)] + Frame(#[from] FrameError), +} + +#[cfg(feature = "h264-decode")] +impl From for VideoError { + fn from(e: crate::h264::decode::Error) -> Self { + match e { + crate::h264::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("H.264: {e}")), + _ => VideoError::Malformed(format!("H.264: {e}")), + } + } +} + +#[cfg(feature = "hevc-decode")] +impl From for VideoError { + fn from(e: crate::hevc::decode::Error) -> Self { + match e { + crate::hevc::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("HEVC: {e}")), + _ => VideoError::Malformed(format!("HEVC: {e}")), + } + } +} + +#[cfg(feature = "vp9-decode")] +impl From for VideoError { + fn from(e: crate::vp9::decode::Error) -> Self { + match e { + crate::vp9::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("VP9: {e}")), + _ => VideoError::Malformed(format!("VP9: {e}")), + } + } +} + +#[cfg(feature = "av1-decode")] +impl From for VideoError { + fn from(e: crate::av1::decode::Error) -> Self { + match e { + crate::av1::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("AV1: {e}")), + _ => VideoError::Malformed(format!("AV1: {e}")), + } + } +} + +#[cfg(feature = "mpeg2-decode")] +impl From for VideoError { + fn from(e: crate::mpeg2::Error) -> Self { + match e { + crate::mpeg2::Error::Unsupported(_) => VideoError::Unsupported(format!("MPEG-2: {e}")), + crate::mpeg2::Error::Invalid(_) => VideoError::Malformed(format!("MPEG-2: {e}")), + } + } +} + +#[cfg(feature = "prores")] +impl From for VideoError { + fn from(e: crate::prores::Error) -> Self { + match e { + crate::prores::Error::Unsupported(_) => VideoError::Unsupported(format!("ProRes: {e}")), + _ => VideoError::Malformed(format!("ProRes: {e}")), + } + } +} + +#[cfg(feature = "dnx")] +impl From for VideoError { + fn from(e: crate::dnx::Error) -> Self { + match e { + crate::dnx::Error::UnknownCid(_) => VideoError::Unsupported(format!("DNx: {e}")), + _ => VideoError::Malformed(format!("DNx: {e}")), + } + } +} + +#[cfg(feature = "apv-decode")] +impl From for VideoError { + fn from(e: crate::apv::Error) -> Self { + VideoError::Malformed(format!("APV: {e}")) + } +} + +#[cfg(feature = "ffv1")] +impl From for VideoError { + fn from(e: crate::ffv1::Error) -> Self { + match e { + crate::ffv1::Error::Unsupported(_) => VideoError::Unsupported(format!("FFV1: {e}")), + _ => VideoError::Malformed(format!("FFV1: {e}")), + } + } +} + +#[cfg(feature = "vp8-decode")] +impl From for VideoError { + fn from(e: crate::vp8::Error) -> Self { + VideoError::Malformed(format!("VP8: {e}")) + } +} diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index afe6926cc..81a4e5b0e 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -28,12 +28,46 @@ //! Each decoder returns its own picture type. [`frame::VideoFrame`] is the codec-agnostic form //! they all convert into (`VideoFrame::try_from`). //! +//! `TrackDecoder` picks the decoder for a track from its `craft_media::CodecParams` and returns +//! `VideoFrame`s, for H.264, HEVC, VP9, AV1, MPEG-2, ProRes, DNx, APV, FFV1 and VP8 +//! (built with any of their decoder features). +//! //! Containers and bit-level I/O are in `craft-media`; the codecs here share its `bitstream` //! module and describe their streams with `craft_media::CodecParams`. pub mod budget; +mod error; pub mod frame; +pub use error::VideoError; + +#[cfg(any( + feature = "h264-decode", + feature = "hevc-decode", + feature = "vp9-decode", + feature = "av1-decode", + feature = "mpeg2-decode", + feature = "prores", + feature = "dnx", + feature = "apv-decode", + feature = "ffv1", + feature = "vp8-decode" +))] +mod track; +#[cfg(any( + feature = "h264-decode", + feature = "hevc-decode", + feature = "vp9-decode", + feature = "av1-decode", + feature = "mpeg2-decode", + feature = "prores", + feature = "dnx", + feature = "apv-decode", + feature = "ffv1", + feature = "vp8-decode" +))] +pub use track::TrackDecoder; + #[cfg(any(feature = "apv-decode", feature = "apv-encode"))] pub mod apv; diff --git a/crates/video/src/track.rs b/crates/video/src/track.rs new file mode 100644 index 000000000..d89eeaeac --- /dev/null +++ b/crates/video/src/track.rs @@ -0,0 +1,513 @@ +//! [`TrackDecoder`]: one video track's packets in, [`VideoFrame`]s out, whatever the codec. The +//! counterpart of `craft_audio::TrackDecoder`, for an app with its own demuxer. + +#[cfg(feature = "av1-decode")] +use crate::av1; +use crate::error::VideoError; +use crate::frame::{FrameError, VideoFrame}; +#[cfg(feature = "h264-decode")] +use crate::h264; +#[cfg(feature = "hevc-decode")] +use crate::hevc; +#[cfg(feature = "mpeg2-decode")] +use crate::mpeg2; +#[cfg(feature = "vp9-decode")] +use crate::vp9; +use craft_media::{CodecId, CodecParams}; + +/// The codec-specific decoder behind a [`TrackDecoder`]. +enum Inner { + /// The decoder, and the `avcC` record or Annex B parameter sets that [`TrackDecoder::reset`] + /// applies again (the decoder's own reset forgets them). + #[cfg(feature = "h264-decode")] + H264 { dec: Box, config: Vec }, + /// The decoder, and the `hvcC` record or Annex B parameter sets a reset rebuilds it from. + #[cfg(feature = "hevc-decode")] + Hevc { dec: Box, config: Vec }, + #[cfg(feature = "vp9-decode")] + Vp9(Box), + /// The decoder, and the `av1C` config OBUs a reset rebuilds it from. + #[cfg(feature = "av1-decode")] + Av1 { dec: Box, config_obus: Vec }, + #[cfg(feature = "mpeg2-decode")] + Mpeg2(Box), + #[cfg(feature = "prores")] + ProRes, + #[cfg(feature = "dnx")] + Dnx, + #[cfg(feature = "apv-decode")] + Apv, + #[cfg(feature = "ffv1")] + Ffv1(Box), + #[cfg(feature = "vp8-decode")] + Vp8(Box), +} + +/// A decoder for one video track, whatever its codec: built from the track's [`CodecParams`], +/// it takes the track's packets in decode order and returns [`VideoFrame`]s in display order. +/// +/// | Codec | Feature | `extradata` | +/// |---|---|---| +/// | H.264 | `h264-decode` | an `avcC` record, Annex B parameter sets, or empty | +/// | HEVC | `hevc-decode` | an `hvcC` record, Annex B parameter sets, or empty | +/// | VP9 | `vp9-decode` | ignored (the frame headers repeat the `vpcC` values) | +/// | AV1 | `av1-decode` | an `av1C` record, or empty | +/// | MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty | +/// | ProRes | `prores` | ignored (frame headers carry the format) | +/// | DNxHD / DNxHR | `dnx` | ignored (frame headers carry the format) | +/// | APV | `apv-decode` | ignored (access units carry the format) | +/// | FFV1 | `ffv1` | required version 3 configuration record; container width and height are required too | +/// | VP8 | `vp8-decode` | ignored (key frames carry the format) | +/// +/// With an `avcC` or `hvcC` record, packets are length-prefixed NAL units, as MP4 and Matroska +/// store them. Otherwise they are Annex B, as MPEG-TS and AVI store them, and the parameter sets +/// may come in the packets themselves. The configuration must not hold picture data: an `avcC` +/// or `hvcC` record holds parameter sets (and SEI for `hvcC`), Annex B `extradata` holds +/// parameter sets, SEI and access unit delimiters, `av1C` config OBUs are sequence headers and +/// metadata, and MPEG-2 `extradata` holds sequence headers, their extensions, user data and GOP +/// headers. +/// +/// ProRes, DNx, APV and FFV1 return one frame per packet. APV selects the first decodable +/// primary frame and its alpha, as the codec's default decoder does. FFV1 supports version 3, +/// range-coded key frames. VP8 hidden frames update references without returning a picture. +/// These five decoders have no delayed output; reset keeps FFV1 configuration and dimensions. +/// +/// Other codecs are [`VideoError::Unsupported`], as is a codec whose decoder feature is off. +/// +/// A packet carries its presentation timestamp, in any unit; each frame returns with the timestamp +/// of the packet that coded it, through reordering ([`VideoFrame::pts`]). +/// +/// ```no_run +/// # fn run(params: &craft_media::CodecParams, packets: &[(Vec, i64)]) -> Result<(), craft_video::VideoError> { +/// use craft_video::TrackDecoder; +/// +/// let mut dec = TrackDecoder::new(params)?; +/// for (packet, pts) in packets { +/// for frame in dec.decode(packet, *pts)? { +/// println!("{}x{} at {:?}", frame.width(), frame.height(), frame.pts); +/// } +/// } +/// for frame in dec.flush()? { +/// let _ = frame; +/// } +/// # Ok(()) } +/// ``` +pub struct TrackDecoder { + inner: Inner, + codec: CodecId, + /// Frames finished by a call that then failed, which the next call returns first. + held: Vec, +} + +impl std::fmt::Debug for TrackDecoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TrackDecoder").field("codec", &self.codec).field("held", &self.held.len()).finish_non_exhaustive() + } +} + +impl TrackDecoder { + /// A decoder for the track `params` describes. `codec` and `extradata` select and configure it; + /// FFV1 also requires nonzero `width` and `height` from the container. Other codecs get the + /// picture size and format from the stream. + /// + /// Invalid configuration, or configuration containing picture data where only headers are + /// allowed, is [`VideoError::Malformed`]. Unsupported codec features are + /// [`VideoError::Unsupported`]. + pub fn new(params: &CodecParams) -> Result { + Ok(TrackDecoder { inner: Inner::new(params)?, codec: params.codec, held: Vec::new() }) + } + + /// The track's codec, as `params` gave it. + pub fn codec(&self) -> CodecId { + self.codec + } + + /// Decode one packet (an access unit, a VP9 frame or superframe, an AV1 temporal unit) with + /// its presentation timestamp. Returns the frames that became ready for display, in display + /// order; a decoder that reorders or decodes on worker threads returns a packet's frame from a + /// later call or from [`TrackDecoder::flush`]. + /// + /// When a call fails because a picture does not convert, the frames finished with it are + /// kept: the next call returns them first. When the codec itself fails, the pictures it had + /// finished are up to the codec. H.264 keeps them for later calls. HEVC does too, but only + /// its newest 32 while calls keep failing, which bounds its memory. VP9 keeps those of earlier + /// packets. MPEG-2 returns them with the call, unless the packet made too many pictures. AV1 + /// drops those the failing call had finished. + /// + /// Decoding can go on with the next packet; a decoder that lost its references waits for the + /// next random access point or conceals, as the codec does. + pub fn decode(&mut self, packet: &[u8], pts: i64) -> Result, VideoError> { + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, .. } => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, .. } => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, .. } => { + let pics = dec.decode_pts(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(dec) => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "prores")] + Inner::ProRes => self.single(crate::prores::decode_frame(packet)?, pts), + #[cfg(feature = "dnx")] + Inner::Dnx => self.single(crate::dnx::decode_frame(packet)?, pts), + #[cfg(feature = "apv-decode")] + Inner::Apv => self.single(crate::apv::decode_frame(packet)?, pts), + #[cfg(feature = "ffv1")] + Inner::Ffv1(dec) => { + let pic = dec.decode(packet)?; + self.single(pic, pts) + } + #[cfg(feature = "vp8-decode")] + Inner::Vp8(dec) => { + let pic = dec.decode(packet, pts)?; + self.output(pic.into_iter().collect(), None) + } + } + } + + /// End of stream: every frame the decoder still holds, in display order. + /// + /// A decoding error found while finishing them is returned instead; the H.264 and HEVC frames + /// are then kept for the next call, while the AV1 decoder drops its own. + pub fn flush(&mut self) -> Result, VideoError> { + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, .. } => { + let pics = dec.flush(); + let err = dec.take_error().map(VideoError::from); + self.output(pics, err) + } + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, .. } => { + let pics = dec.flush(); + let err = dec.take_error().map(VideoError::from); + self.output(pics, err) + } + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => { + let pics = dec.flush(); + self.output(pics, None) + } + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, .. } => { + let pics = dec.flush_result()?; + self.output(pics, None) + } + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(dec) => { + let pics = dec.flush(); + self.output(pics, None) + } + #[cfg(feature = "prores")] + Inner::ProRes => Ok(std::mem::take(&mut self.held)), + #[cfg(feature = "dnx")] + Inner::Dnx => Ok(std::mem::take(&mut self.held)), + #[cfg(feature = "apv-decode")] + Inner::Apv => Ok(std::mem::take(&mut self.held)), + #[cfg(feature = "ffv1")] + Inner::Ffv1(_) => Ok(std::mem::take(&mut self.held)), + #[cfg(feature = "vp8-decode")] + Inner::Vp8(_) => Ok(std::mem::take(&mut self.held)), + } + } + + /// Forget the pictures and references, and the frames kept from a failed call, before decoding + /// from another random access point (after a seek). The track's configuration is kept: H.264 + /// and HEVC parameter sets from `extradata`, the AV1 sequence header from `av1C`, and the + /// MPEG-2 sequence; parameter sets that came in packets are forgotten (MPEG-2 keeps its + /// latest sequence header). + /// + /// An error is the configuration failing to apply again, which it did not when the decoder was + /// built. + pub fn reset(&mut self) -> Result<(), VideoError> { + self.held.clear(); + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, config } => { + dec.reset(); + configure_h264(dec, config) + } + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, config } => { + // The HEVC decoder has no reset of its own: a new one starts from nothing. + let mut fresh = Box::new(hevc::decode::Decoder::new()); + configure_hevc(&mut fresh, config)?; + *dec = fresh; + Ok(()) + } + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => { + dec.reset(); + Ok(()) + } + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, config_obus } => { + // The AV1 decoder has no reset of its own: a new one starts from nothing. + let mut fresh = Box::new(av1::decode::Decoder::new()); + configure_av1(&mut fresh, config_obus)?; + *dec = fresh; + Ok(()) + } + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(dec) => { + dec.reset(); + Ok(()) + } + #[cfg(feature = "prores")] + Inner::ProRes => Ok(()), + #[cfg(feature = "dnx")] + Inner::Dnx => Ok(()), + #[cfg(feature = "apv-decode")] + Inner::Apv => Ok(()), + #[cfg(feature = "ffv1")] + Inner::Ffv1(_) => Ok(()), + #[cfg(feature = "vp8-decode")] + Inner::Vp8(dec) => { + dec.reset(); + Ok(()) + } + } + } + + /// Frame-only decoders do not take timestamps; attach the packet timestamp after conversion. + #[cfg(any(feature = "prores", feature = "dnx", feature = "apv-decode", feature = "ffv1"))] + fn single

(&mut self, pic: P, pts: i64) -> Result, VideoError> + where + VideoFrame: TryFrom, + { + let mut frame = VideoFrame::try_from(pic)?; + frame.pts = Some(pts); + let mut frames = std::mem::take(&mut self.held); + frames.push(frame); + Ok(frames) + } + + /// The frames kept from a failed call, then `pics` converted. On `err`, or on a picture that + /// does not convert, the frames are kept for the next call and the (first) error returned. + #[cfg(any( + feature = "h264-decode", + feature = "hevc-decode", + feature = "vp9-decode", + feature = "av1-decode", + feature = "mpeg2-decode", + feature = "vp8-decode" + ))] + fn output

(&mut self, pics: Vec

, err: Option) -> Result, VideoError> + where + VideoFrame: TryFrom, + { + let mut frames = std::mem::take(&mut self.held); + frames.reserve(pics.len()); + let mut err = err; + for pic in pics { + match VideoFrame::try_from(pic) { + Ok(frame) => frames.push(frame), + Err(e) => { + err.get_or_insert(e.into()); + } + } + } + match err { + None => Ok(frames), + Some(e) => { + self.held = frames; + Err(e) + } + } + } +} + +impl Inner { + fn new(params: &CodecParams) -> Result { + let codec = params.codec; + let extradata = ¶ms.extradata; + let _ = extradata; + match codec { + #[cfg(feature = "h264-decode")] + CodecId::H264 => { + let mut dec = Box::new(h264::decode::Decoder::new()); + configure_h264(&mut dec, extradata)?; + Ok(Inner::H264 { dec, config: extradata.to_vec() }) + } + #[cfg(feature = "hevc-decode")] + CodecId::Hevc => { + let mut dec = Box::new(hevc::decode::Decoder::new()); + configure_hevc(&mut dec, extradata)?; + Ok(Inner::Hevc { dec, config: extradata.to_vec() }) + } + #[cfg(feature = "vp9-decode")] + CodecId::Vp9 => Ok(Inner::Vp9(Box::default())), + #[cfg(feature = "av1-decode")] + CodecId::Av1 => { + let config_obus = av1c_config_obus(extradata)?.to_vec(); + let mut dec = Box::new(av1::decode::Decoder::new()); + configure_av1(&mut dec, &config_obus)?; + Ok(Inner::Av1 { dec, config_obus }) + } + #[cfg(feature = "mpeg2-decode")] + CodecId::Mpeg2Video => { + let mut dec = Box::new(mpeg2::Decoder::new()); + if !extradata.is_empty() { + check_mpeg2_config(extradata)?; + dec.decode(extradata, 0)?; + } + Ok(Inner::Mpeg2(dec)) + } + #[cfg(feature = "prores")] + CodecId::ProRes => Ok(Inner::ProRes), + #[cfg(feature = "dnx")] + CodecId::Dnxhd => Ok(Inner::Dnx), + #[cfg(feature = "apv-decode")] + CodecId::Apv => Ok(Inner::Apv), + #[cfg(feature = "vp8-decode")] + CodecId::Vp8 => Ok(Inner::Vp8(Box::default())), + #[cfg(feature = "ffv1")] + CodecId::Ffv1 => { + let (width, height) = params + .width + .zip(params.height) + .filter(|&(w, h)| w > 0 && h > 0) + .ok_or_else(|| VideoError::Malformed("FFV1: container dimensions are required".into()))?; + Ok(Inner::Ffv1(Box::new(crate::ffv1::Decoder::new(extradata, width, height)?))) + } + other => Err(VideoError::Unsupported(format!("no {} decoder in this build", other.name()))), + } + } +} + +/// Whether `extradata` is Annex B (starts with a start code) rather than an `avcC` / `hvcC` record. +#[cfg(any(feature = "h264-decode", feature = "hevc-decode"))] +fn is_annex_b(extradata: &[u8]) -> bool { + extradata.starts_with(&[0, 0, 1]) || extradata.starts_with(&[0, 0, 0, 1]) +} + +/// Annex B `extradata` holds only NAL units whose type `allowed` accepts (`codec` names it in the +/// error). +#[cfg(any(feature = "h264-decode", feature = "hevc-decode"))] +fn check_annex_b(codec: &str, extradata: &[u8], nal_type: fn(u8) -> u8, allowed: &[u8]) -> Result<(), VideoError> { + for nal in craft_media::bitstream::annexb_nals(extradata) { + let t = nal.first().map_or(u8::MAX, |&b| nal_type(b)); + if !allowed.contains(&t) { + return Err(VideoError::Malformed(format!("{codec}: configuration holds NAL unit type {t}, not a parameter set"))); + } + } + Ok(()) +} + +/// H.264 NAL unit types Annex B `extradata` may hold: SEI, SPS, PPS, access unit delimiter, SPS +/// extension and subset SPS. +#[cfg(feature = "h264-decode")] +const H264_CONFIG_NALS: [u8; 6] = [6, 7, 8, 9, 13, 15]; + +/// HEVC NAL unit types Annex B `extradata` may hold: VPS, SPS, PPS, access unit delimiter, prefix +/// and suffix SEI. +#[cfg(feature = "hevc-decode")] +const HEVC_CONFIG_NALS: [u8; 6] = [32, 33, 34, 35, 39, 40]; + +/// Apply H.264 `extradata`: an `avcC` record, Annex B parameter sets, or nothing. +#[cfg(feature = "h264-decode")] +fn configure_h264(dec: &mut h264::decode::Decoder, extradata: &[u8]) -> Result<(), VideoError> { + if extradata.is_empty() { + Ok(()) + } else if is_annex_b(extradata) { + check_annex_b("H.264", extradata, |b| b & 0x1f, &H264_CONFIG_NALS)?; + dec.decode(extradata, 0)?; + Ok(()) + } else { + Ok(dec.configure_avcc(extradata)?) + } +} + +/// Apply HEVC `extradata`: an `hvcC` record, Annex B parameter sets, or nothing. +#[cfg(feature = "hevc-decode")] +fn configure_hevc(dec: &mut hevc::decode::Decoder, extradata: &[u8]) -> Result<(), VideoError> { + if extradata.is_empty() { + Ok(()) + } else if is_annex_b(extradata) { + check_annex_b("HEVC", extradata, |b| (b >> 1) & 0x3f, &HEVC_CONFIG_NALS)?; + dec.decode(extradata, 0)?; + Ok(()) + } else { + Ok(dec.configure_hvcc(extradata)?) + } +} + +/// MPEG-2 start codes `extradata` may hold: user data, sequence header, extension and GOP header. +#[cfg(feature = "mpeg2-decode")] +const MPEG2_CONFIG_CODES: [u8; 4] = [0xb2, 0xb3, 0xb5, 0xb8]; + +/// MPEG-2 `extradata` holds no picture: every start code in it is one of [`MPEG2_CONFIG_CODES`]. +#[cfg(feature = "mpeg2-decode")] +fn check_mpeg2_config(extradata: &[u8]) -> Result<(), VideoError> { + for w in extradata.windows(4) { + if let [0, 0, 1, code] = *w + && !MPEG2_CONFIG_CODES.contains(&code) + { + return Err(VideoError::Malformed(format!("MPEG-2: configuration holds start code {code:#04x}, not a sequence header"))); + } + } + Ok(()) +} + +/// The config OBUs of an `av1C` record (empty for empty `extradata`), once they are checked to +/// hold only sequence headers and metadata. +#[cfg(feature = "av1-decode")] +fn av1c_config_obus(extradata: &[u8]) -> Result<&[u8], VideoError> { + const SEQUENCE_HEADER: u8 = 1; + const METADATA: u8 = 5; + if extradata.is_empty() { + return Ok(&[]); + } + // marker (1) and version (1), then three bytes of profile, level and chroma fields + let obus = match extradata { + [0x81, _, _, _, obus @ ..] => obus, + _ => return Err(VideoError::Malformed("AV1: configuration is not an av1C record (version 1)".into())), + }; + let mut rest = obus; + while let Some(&header) = rest.first() { + let obu_type = (header >> 3) & 0xf; + if obu_type != SEQUENCE_HEADER && obu_type != METADATA { + return Err(VideoError::Malformed(format!("AV1: av1C holds OBU type {obu_type}, not a sequence header or metadata"))); + } + // obu_extension_flag adds a byte; without obu_has_size_field the OBU runs to the end + let start = 1 + usize::from(header & 4 != 0); + let body = rest.get(start..).ok_or_else(|| VideoError::Malformed("AV1: av1C OBU header truncated".into()))?; + rest = if header & 2 != 0 { + let (size, n) = av1::decode::bits::leb128(body)?; + let end = usize::try_from(size).ok().and_then(|s| s.checked_add(n)); + end.and_then(|end| body.get(end..)).ok_or_else(|| VideoError::Malformed("AV1: av1C OBU truncated".into()))? + } else { + &[] + }; + } + Ok(obus) +} + +/// Apply `av1C` config OBUs (sequence headers and metadata, checked by [`av1c_config_obus`]). +#[cfg(feature = "av1-decode")] +fn configure_av1(dec: &mut av1::decode::Decoder, config_obus: &[u8]) -> Result<(), VideoError> { + if !config_obus.is_empty() { + dec.decode_pts(config_obus, 0)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/video/src/track/tests.rs b/crates/video/src/track/tests.rs new file mode 100644 index 000000000..42d3ab861 --- /dev/null +++ b/crates/video/src/track/tests.rs @@ -0,0 +1,391 @@ +//! Unit tests of the track decoder: codec selection, configuration checks and the frames kept +//! from a failed call. Decoding real streams is in `tests/track`. + +use super::*; + +fn params(codec: CodecId, extradata: &[u8]) -> CodecParams { + CodecParams::new(codec).with_extradata(extradata.to_vec()) +} + +fn new_err(codec: CodecId, extradata: &[u8]) -> VideoError { + match TrackDecoder::new(¶ms(codec, extradata)) { + Ok(_) => panic!("{codec:?} with extradata {extradata:02x?} was accepted"), + Err(e) => e, + } +} + +#[test] +fn a_codec_without_a_decoder_is_unsupported() { + let off = [ + CodecId::Theora, + CodecId::Aac, + CodecId::Unknown, + #[cfg(not(feature = "prores"))] + CodecId::ProRes, + #[cfg(not(feature = "dnx"))] + CodecId::Dnxhd, + #[cfg(not(feature = "apv-decode"))] + CodecId::Apv, + #[cfg(not(feature = "ffv1"))] + CodecId::Ffv1, + #[cfg(not(feature = "vp8-decode"))] + CodecId::Vp8, + #[cfg(not(feature = "h264-decode"))] + CodecId::H264, + #[cfg(not(feature = "hevc-decode"))] + CodecId::Hevc, + #[cfg(not(feature = "vp9-decode"))] + CodecId::Vp9, + #[cfg(not(feature = "av1-decode"))] + CodecId::Av1, + #[cfg(not(feature = "mpeg2-decode"))] + CodecId::Mpeg2Video, + ]; + for codec in off { + let err = new_err(codec, &[]); + assert!(matches!(err, VideoError::Unsupported(_)), "{codec:?}: {err}"); + assert!(err.to_string().contains(codec.name()), "{err}"); + } +} + +#[test] +fn decoders_other_than_ffv1_start_without_configuration() { + let on = [ + #[cfg(feature = "prores")] + CodecId::ProRes, + #[cfg(feature = "dnx")] + CodecId::Dnxhd, + #[cfg(feature = "apv-decode")] + CodecId::Apv, + #[cfg(feature = "vp8-decode")] + CodecId::Vp8, + #[cfg(feature = "h264-decode")] + CodecId::H264, + #[cfg(feature = "hevc-decode")] + CodecId::Hevc, + #[cfg(feature = "vp9-decode")] + CodecId::Vp9, + #[cfg(feature = "av1-decode")] + CodecId::Av1, + #[cfg(feature = "mpeg2-decode")] + CodecId::Mpeg2Video, + ]; + for codec in on { + let mut dec = TrackDecoder::new(¶ms(codec, &[])).unwrap(); + assert_eq!(dec.codec(), codec); + assert!(dec.flush().unwrap().is_empty(), "{codec:?}"); + dec.reset().unwrap(); + assert!(dec.decode(&[], 0).unwrap_or_default().is_empty(), "{codec:?}"); + } +} + +#[test] +fn track_decoder_is_send() { + fn send() {} + send::(); +} + +/// An Annex B configuration that holds a slice would start a picture: it is refused before any +/// NAL unit reaches the decoder (which would report the slice's missing parameter set instead). +#[cfg(feature = "h264-decode")] +#[test] +fn h264_annex_b_configuration_with_a_slice_is_refused() { + let err = new_err(CodecId::H264, &[0, 0, 0, 1, 0x65, 0x88, 0x84, 0x00]); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("NAL unit type 5"), "{err}"); +} + +#[cfg(feature = "hevc-decode")] +#[test] +fn hevc_annex_b_configuration_with_a_slice_is_refused() { + // IDR_W_RADL (19): (19 << 1) = 0x26 + let err = new_err(CodecId::Hevc, &[0, 0, 1, 0x26, 0x01, 0xaf, 0x00]); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("NAL unit type 19"), "{err}"); +} + +/// A picture after a valid sequence header is refused, not decoded and then dropped. +#[cfg(feature = "mpeg2-decode")] +#[test] +fn mpeg2_configuration_with_a_picture_is_refused() { + // 32x32, 4:3, 25 fps + let header = [0, 0, 1, 0xb3, 0x02, 0x00, 0x20, 0x23, 0xff, 0xff, 0xe0, 0x18]; + assert!(TrackDecoder::new(¶ms(CodecId::Mpeg2Video, &header)).is_ok()); + // a picture header (I picture) and the start of its first slice + let picture = [0, 0, 1, 0x00, 0x00, 0x0f, 0xff, 0xf8, 0, 0, 1, 0x01, 0x12, 0x34]; + let err = new_err(CodecId::Mpeg2Video, &[&header[..], &picture].concat()); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("start code 0x00"), "{err}"); +} + +/// A record that is neither Annex B nor version 1 is the codec's own error. +#[cfg(feature = "h264-decode")] +#[test] +fn h264_configuration_that_is_not_avcc_is_refused() { + let err = new_err(CodecId::H264, &[2, 0x42, 0, 0x1e, 0xff, 0xe0, 0]); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("avcC"), "{err}"); +} + +#[cfg(feature = "av1-decode")] +mod av1c { + use super::*; + + const HEADER: [u8; 4] = [0x81, 0x00, 0x0c, 0x00]; + + fn with_obus(obus: &[u8]) -> Vec { + [&HEADER[..], obus].concat() + } + + #[test] + fn empty_and_header_only_records_hold_no_obus() { + assert_eq!(av1c_config_obus(&[]).unwrap(), &[] as &[u8]); + assert_eq!(av1c_config_obus(&HEADER).unwrap(), &[] as &[u8]); + } + + #[test] + fn sequence_headers_and_metadata_pass() { + // a sequence header (size 2), one with an extension byte (size 0), metadata (size 1), and + // a sequence header without a size field that runs to the end + let obus = [0x0a, 2, 0xaa, 0xbb, 0x0e, 0x00, 0, 0x2a, 1, 0xcc, 0x08, 0xdd, 0xee]; + assert_eq!(av1c_config_obus(&with_obus(&obus)).unwrap(), &obus); + } + + #[test] + fn a_record_that_is_not_av1c_version_1_is_refused() { + for bad in [&[0x81, 0, 0][..], &[0x80, 0, 0, 0], &[0x82, 0, 0, 0], &[0x0a, 0, 0, 0, 0]] { + let err = av1c_config_obus(bad).unwrap_err(); + assert!(err.to_string().contains("not an av1C record"), "{bad:02x?}: {err}"); + } + } + + #[test] + fn a_frame_or_temporal_delimiter_is_refused() { + // temporal delimiter (2), frame header (3), tile group (4), frame (6), after a valid OBU + for t in [2u8, 3, 4, 6] { + let obus = [0x0a, 0, (t << 3) | 2, 0]; + let err = av1c_config_obus(&with_obus(&obus)).unwrap_err(); + assert!(err.to_string().contains(&format!("OBU type {t}")), "{t}: {err}"); + } + assert!(matches!(new_err(CodecId::Av1, &with_obus(&[0x32, 0])), VideoError::Malformed(_))); + } + + #[test] + fn truncated_obus_are_refused() { + for obus in [&[0x0a, 5, 1, 2][..], &[0x0a, 0x80], &[0x0a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], &[0x0e]] { + let err = av1c_config_obus(&with_obus(obus)).unwrap_err(); + assert!(matches!(err, VideoError::Malformed(_)), "{obus:02x?}: {err}"); + } + } + + #[test] + fn hostile_records_do_not_panic() { + let seed = with_obus(&[0x0a, 2, 0xaa, 0xbb, 0x2a, 1, 0xcc]); + craft_media_testkit::hostile::hammer("av1C config OBUs", &seed, 2000, |data| { + let _ = av1c_config_obus(data); + }); + } +} + +/// Configuration bytes of every codec, damaged, never panic the decoder that applies them. +#[test] +fn hostile_configuration_does_not_panic() { + let seeds: &[(CodecId, &[u8])] = &[ + #[cfg(feature = "h264-decode")] + (CodecId::H264, &[1, 0x42, 0xc0, 0x1e, 0xff, 0xe1, 0x00, 0x04, 0x67, 0x42, 0xc0, 0x1e, 0x01, 0x00, 0x02, 0x68, 0xce]), + #[cfg(feature = "h264-decode")] + (CodecId::H264, &[0, 0, 0, 1, 0x67, 0x42, 0xc0, 0x1e, 0, 0, 1, 0x68, 0xce]), + #[cfg(feature = "hevc-decode")] + (CodecId::Hevc, &[0, 0, 0, 1, 0x40, 0x01, 0x0c, 0, 0, 1, 0x42, 0x01, 0x01, 0, 0, 1, 0x44, 0x01, 0xc1]), + #[cfg(feature = "av1-decode")] + (CodecId::Av1, &[0x81, 0x00, 0x0c, 0x00, 0x0a, 0x0b, 0x00, 0x00, 0x00, 0x24, 0xc4, 0xff, 0xdf, 0x00, 0x68, 0x02, 0x10]), + #[cfg(feature = "mpeg2-decode")] + (CodecId::Mpeg2Video, &[0, 0, 1, 0xb3, 0x02, 0x00, 0x20, 0x13, 0xff, 0xff, 0xe0, 0x18, 0, 0, 1, 0xb5, 0x14, 0x8a, 0x00, 0x01, 0x00, 0x00]), + ]; + for &(codec, seed) in seeds { + craft_media_testkit::hostile::hammer(codec.name(), seed, 300, move |data| { + if let Ok(mut dec) = TrackDecoder::new(¶ms(codec, data)) { + let _ = dec.reset(); + } + }); + } +} + +#[cfg(feature = "h264-decode")] +mod held { + use super::*; + + /// A 4x2 picture with timestamp `pts`; `y_len` other than 8 makes it fail to convert. + fn picture(y_len: usize, pts: i64) -> h264::decode::Picture { + h264::decode::Picture { + width: 4, + height: 2, + chroma_width: 2, + chroma_height: 1, + y: vec![16; y_len], + u: vec![128; 2], + v: vec![128; 2], + y_stride: 4, + uv_stride: 2, + pts, + poc: 0, + key: true, + color: h264::decode::ColorInfo { full_range: false, primaries: 1, transfer: 1, matrix: 1 }, + sar: (0, 0), + draft: false, + } + } + + fn decoder() -> TrackDecoder { + TrackDecoder::new(¶ms(CodecId::H264, &[])).unwrap() + } + + fn pts(frames: &[VideoFrame]) -> Vec> { + frames.iter().map(|f| f.pts).collect() + } + + /// A picture that does not convert fails the call; the others come with the next call, ahead + /// of its own frames and in order. + #[test] + fn frames_around_a_picture_that_does_not_convert_come_next() { + let mut dec = decoder(); + let err = dec.output(vec![picture(8, 1), picture(3, 2), picture(8, 3)], None).unwrap_err(); + assert!(matches!(err, VideoError::Frame(FrameError::Plane(_))), "{err}"); + assert_eq!(pts(&dec.output(vec![picture(8, 4)], None).unwrap()), [Some(1), Some(3), Some(4)]); + assert!(dec.output(Vec::::new(), None).unwrap().is_empty()); + } + + /// An error reported with the pictures (a flush whose decoding job failed) keeps them too. + #[test] + fn frames_finished_with_an_error_come_next() { + let mut dec = decoder(); + let err = dec.output(vec![picture(8, 1)], Some(VideoError::Malformed("job".into()))).unwrap_err(); + assert!(matches!(err, VideoError::Malformed(_))); + assert_eq!(pts(&dec.flush().unwrap()), [Some(1)]); + } + + /// An error from the codec itself leaves the kept frames for the call after it. + #[test] + fn a_failed_packet_does_not_drop_kept_frames() { + let mut dec = decoder(); + assert!(dec.output(vec![picture(8, 1), picture(0, 2)], None).is_err()); + // an IDR slice without parameter sets + assert!(dec.decode(&[0, 0, 1, 0x65, 0x88, 0x84], 5).is_err()); + assert_eq!(pts(&dec.decode(&[], 6).unwrap()), [Some(1)]); + } + + #[test] + fn reset_drops_kept_frames() { + let mut dec = decoder(); + assert!(dec.output(vec![picture(8, 1), picture(0, 2)], None).is_err()); + dec.reset().unwrap(); + assert!(dec.flush().unwrap().is_empty()); + } +} + +#[cfg(any(feature = "prores", feature = "dnx", feature = "apv", feature = "ffv1", feature = "vp8"))] +fn check_packet(params: CodecParams, packet: &[u8], mut expected: VideoFrame) { + let mut dec = TrackDecoder::new(¶ms).unwrap(); + assert_eq!(dec.codec(), params.codec); + for pts in [-17, 91] { + expected.pts = Some(pts); + assert_eq!(dec.decode(packet, pts).unwrap(), [expected.clone()]); + assert!(dec.flush().unwrap().is_empty()); + assert!(dec.flush().unwrap().is_empty()); + assert!(matches!(dec.decode(&[], 0), Err(VideoError::Malformed(_)))); + dec.reset().unwrap(); + assert!(dec.flush().unwrap().is_empty()); + } +} + +#[cfg(feature = "prores")] +#[test] +fn prores_packet_timestamps_and_reset() { + use crate::prores::*; + let frame = Frame::new(32, 32, ChromaFormat::Yuv422, 10, false).unwrap(); + let mut enc = Encoder::new(Profile::Proxy, 32, 32); + let packet = enc.encode(&frame).unwrap(); + check_packet(enc.codec_params(), &packet, decode_frame(&packet).unwrap().try_into().unwrap()); +} + +#[cfg(feature = "dnx")] +#[test] +fn dnx_packet_timestamps_and_reset() { + use crate::dnx::*; + let frame = Frame::new(64, 64, ChromaFormat::Yuv422, 8, false); + let mut enc = Encoder::new(Profile::Lb, 64, 64).unwrap(); + let packet = enc.encode(&frame).unwrap(); + check_packet(enc.codec_params(), &packet, decode_frame(&packet).unwrap().try_into().unwrap()); +} + +#[cfg(feature = "apv")] +#[test] +fn apv_packet_timestamps_and_reset() { + use crate::apv::*; + let frame = Frame::new(32, 32, ChromaFormat::Yuv422, 10, false); + let mut enc = Encoder::new(Profile::P422_10, 32, 32).unwrap(); + let packet = enc.encode(&frame).unwrap(); + check_packet(params(CodecId::Apv, &enc.decoder_config_record()), &packet, decode_frame(&packet).unwrap().try_into().unwrap()); +} + +#[cfg(feature = "ffv1")] +#[test] +fn ffv1_configuration_dimensions_timestamps_and_reset() { + use crate::ffv1::*; + let frame = Frame { + width: 16, + height: 16, + colorspace: Colorspace::Rgb, + bit_depth: 10, + chroma_shift: (0, 0), + planes: vec![vec![128; 256], vec![512; 256], vec![768; 256], vec![1023; 256]], + }; + let enc = Encoder::new(&frame, EncoderConfig::default()).unwrap(); + let config = enc.config_record(); + let packet = enc.encode(&frame).unwrap(); + let p = params(CodecId::Ffv1, &config).with_size(16, 16); + check_packet(p.clone(), &packet, frame.try_into().unwrap()); + for (width, height) in [(None, Some(16)), (Some(16), None), (Some(0), Some(16)), (Some(16), Some(0))] { + let mut bad = p.clone(); + bad.width = width; + bad.height = height; + assert!(matches!(TrackDecoder::new(&bad), Err(VideoError::Malformed(_)))); + } + for config in [&[][..], &config[..config.len() - 1]] { + assert!(matches!(TrackDecoder::new(¶ms(CodecId::Ffv1, config).with_size(16, 16)), Err(VideoError::Malformed(_)))); + } +} + +#[cfg(feature = "vp8")] +#[test] +fn vp8_hidden_frames_timestamps_and_reset() { + use crate::vp8::*; + let packet = encode_rgba(&vec![128; 32 * 32 * 4], 32, 32, &Vp8Params::default()).unwrap().data; + let expected = Decoder::new().decode(&packet, 0).unwrap().unwrap().try_into().unwrap(); + check_packet(params(CodecId::Vp8, &[]), &packet, expected); + let mut dec = TrackDecoder::new(¶ms(CodecId::Vp8, &[])).unwrap(); + let mut hidden = packet.clone(); + hidden[0] &= !0x10; // show_frame = 0: updates references, produces no displayed picture. + assert!(dec.decode(&hidden, 33).unwrap().is_empty()); + assert!(dec.flush().unwrap().is_empty()); + dec.reset().unwrap(); + // An inter-frame tag with one byte of first partition must fail for missing references + // before its payload is parsed. Keeping the previous key frame would give a syntax error. + let err = dec.decode(&[0x31, 0, 0, 0], 34).unwrap_err(); + assert!(err.to_string().contains("missing reference frame"), "{err}"); + assert_eq!(dec.decode(&packet, 35).unwrap()[0].pts, Some(35)); +} + +#[test] +fn new_codec_errors_keep_their_category() { + #[cfg(feature = "prores")] + assert!(matches!(VideoError::from(crate::prores::Error::Unsupported("profile")), VideoError::Unsupported(_))); + #[cfg(feature = "dnx")] + assert!(matches!(VideoError::from(crate::dnx::Error::UnknownCid(0)), VideoError::Unsupported(_))); + #[cfg(feature = "apv-decode")] + assert!(matches!(VideoError::from(crate::apv::Error::Truncated), VideoError::Malformed(_))); + #[cfg(feature = "ffv1")] + assert!(matches!(VideoError::from(crate::ffv1::Error::Unsupported("inter frames")), VideoError::Unsupported(_))); + #[cfg(feature = "vp8-decode")] + assert!(matches!(VideoError::from(crate::vp8::Error::Invalid("header".into())), VideoError::Malformed(_))); +} diff --git a/crates/video/tests/track/av1.rs b/crates/video/tests/track/av1.rs new file mode 100644 index 000000000..cef856f2b --- /dev/null +++ b/crates/video/tests/track/av1.rs @@ -0,0 +1,72 @@ +//! AV1 in MP4 (an `av1C` record whose config OBUs hold the sequence header). + +use crate::common; +use craft_media::CodecId; + +/// libaom when ffmpeg has it, else SVT-AV1: a fixture name and the encoder arguments. +fn encoder() -> Option<(&'static str, &'static [&'static str])> { + if common::has_encoder("libaom-av1") { + Some(("av1_aom", &["-c:v", "libaom-av1", "-cpu-used", "8", "-b:v", "300k", "-g", "12", "-pix_fmt", "yuv420p"])) + } else if common::has_encoder("libsvtav1") { + Some(("av1_svt", &["-c:v", "libsvtav1", "-preset", "12", "-g", "12", "-pix_fmt", "yuv420p"])) + } else { + craft_media_testkit::skip("ffmpeg has neither libaom-av1 nor libsvtav1") + } +} + +fn fixture() -> Option<(common::Track, common::Fixture)> { + let (name, args) = encoder()?; + let f = common::fixture(name, "mp4", args, "yuv420p")?; + let track = common::mp4(&f.file); + assert_eq!(track.params.codec, CodecId::Av1); + Some((track, f)) +} + +/// The OBUs of a packet as (type, bytes); every OBU has a size field, as MP4 stores them. +fn obus(data: &[u8]) -> Vec<(u8, &[u8])> { + let mut out = Vec::new(); + let mut pos = 0; + while pos < data.len() { + let header = data[pos]; + assert!(header & 2 != 0, "an OBU without a size field"); + let mut p = pos + 1 + usize::from(header & 4 != 0); + let mut size = 0usize; + for i in 0.. { + let b = data[p]; + p += 1; + size |= usize::from(b & 0x7f) << (7 * i); + if b & 0x80 == 0 { + break; + } + } + out.push(((header >> 3) & 0xf, &data[pos..p + size])); + pos = p + size; + } + out +} + +#[test] +fn mp4_av1c() { + let Some((track, f)) = fixture() else { return }; + common::check_track(&track, &f); +} + +/// With every sequence header taken out of the packets, the one in `av1C` is what decodes them. +/// +/// The record's config OBUs are the stream's own sequence header: SVT-AV1 writes `av1C` before it +/// encodes, with a sequence header that differs from the one it then puts in the stream. +#[test] +fn sequence_header_from_av1c() { + let Some((mut track, f)) = fixture() else { return }; + let header = obus(&track.packets[0].data).into_iter().find(|o| o.0 == 1).unwrap().1.to_vec(); + track.params.extradata = [&track.params.extradata[..4], &header].concat(); + for p in &mut track.packets { + p.data = obus(&p.data).into_iter().filter(|o| o.0 != 1).flat_map(|o| o.1.to_vec()).collect(); + } + let mut bare = track.clone(); + bare.params.extradata.clear(); + let mut dec = craft_video::TrackDecoder::new(&bare.params).unwrap(); + let decoded = bare.packets.iter().filter_map(|p| dec.decode(&p.data, p.pts).ok()).flatten().count(); + assert_eq!(decoded, 0, "the packets decode without a sequence header"); + common::check_track(&track, &f); +} diff --git a/crates/video/tests/track/common/mod.rs b/crates/video/tests/track/common/mod.rs new file mode 100644 index 000000000..bd3f14461 --- /dev/null +++ b/crates/video/tests/track/common/mod.rs @@ -0,0 +1,201 @@ +//! Fixtures (ffmpeg encodes a short clip into a container), demuxing with craft-media, ffmpeg's +//! own decode of each fixture as the reference, and the checks every codec runs. +#![allow(dead_code)] + +use craft_media::CodecParams; +use craft_video::TrackDecoder; +use craft_video::frame::{Samples, VideoFrame}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Frames in every fixture. +pub const FRAMES: usize = 24; + +/// One packet of a demuxed track, in decode order. +#[derive(Clone)] +pub struct Packet { + pub data: Vec, + pub pts: i64, + /// The container marks it as a random access point. + pub key: bool, +} + +/// A demuxed video track. +#[derive(Clone)] +pub struct Track { + pub params: CodecParams, + pub packets: Vec, +} + +/// A fixture and ffmpeg's decode of it. +pub struct Fixture { + pub file: PathBuf, + /// Raw frames in display order, planes one after another, 16-bit samples little-endian. + pub reference: Vec, + /// How far a sample may be from the reference: 0 (bit-exact) unless a test sets it. + pub max_diff: u8, +} + +/// Lowest PSNR of a frame decoded within a tolerance, as the MPEG-2 oracle tests require. +const MIN_PSNR: f64 = 58.0; + +/// `name.ext` made by ffmpeg from 24 frames of a noisy test pattern at 176x144, with `args` +/// choosing the encoder, and its decode as `pix_fmt` raw video. `None` (a skip) without ffmpeg or +/// the encoder; a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`. +pub fn fixture(name: &str, ext: &str, args: &[&str], pix_fmt: &str) -> Option { + let ff = craft_media_testkit::ffmpeg()?; + let dir = craft_media_testkit::fixture_subdir("video-track"); + let required = craft_media_testkit::oracles_required(); + let file = dir.join(format!("{name}.{ext}")); + let raw = dir.join(format!("{name}.{ext}.{pix_fmt}.raw")); + craft_media_testkit::generate_and_report(name, &[file.clone(), raw.clone()], || { + if !file.exists() { + let tmp = craft_media_testkit::temp_path(&file); + let mut cmd = Command::new(&ff); + cmd.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i"]) + .arg("testsrc2=size=176x144:rate=25,noise=alls=12:allf=t+u") + .args(["-frames:v", &FRAMES.to_string(), "-an"]) + .args(args) + .arg(&tmp); + craft_media_testkit::run_generator(&mut cmd, &tmp, &file, required)?; + } + if !raw.exists() { + let tmp = craft_media_testkit::temp_path(&raw); + let mut cmd = Command::new(&ff); + cmd.args(["-hide_banner", "-loglevel", "error", "-y", "-i"]) + .arg(&file) + .args(["-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt]) + .arg(&tmp); + craft_media_testkit::run_generator(&mut cmd, &tmp, &raw, required)?; + } + Some(Fixture { reference: std::fs::read(&raw).unwrap(), file: file.clone(), max_diff: 0 }) + }) +} + +/// Whether ffmpeg has `encoder`, without skipping. +pub fn has_encoder(encoder: &str) -> bool { + craft_media_testkit::tool("ffmpeg").is_some_and(|ff| craft_media_testkit::ffmpeg_has_encoder(&ff, encoder)) +} + +/// The video track of an MP4 file. +pub fn mp4(path: &Path) -> Track { + use craft_media::isobmff::{TrackKind, open}; + let bytes = std::fs::read(path).unwrap(); + let file = open(bytes.as_slice()).unwrap(); + let t = file.track_of_kind(TrackKind::Video).unwrap(); + let track = &file.tracks[t]; + let packets = (track.samples.iter().enumerate()) + .map(|(i, s)| Packet { data: file.read_sample(bytes.as_slice(), t, i).unwrap(), pts: s.pts, key: s.is_sync }) + .collect(); + Track { params: track.codec_params(), packets } +} + +/// The video stream of an MPEG transport stream. +pub fn ts(path: &Path) -> Track { + use craft_media::mpegts::{Kind, open}; + let bytes = std::fs::read(path).unwrap(); + let file = open(bytes.as_slice()).unwrap(); + let s = file.find(Kind::Video, |_| true).unwrap(); + let stream = &file.streams[s]; + let packets = (stream.units.iter().enumerate()) + .map(|(i, u)| Packet { data: file.read_unit(bytes.as_slice(), s, i).unwrap(), pts: u.pts.unwrap(), key: u.key }) + .collect(); + Track { params: stream.codec_params(), packets } +} + +/// The video stream of an AVI file. AVI has no timestamps: a chunk's index stands in. +pub fn avi(path: &Path) -> Track { + use craft_media::avi::{StreamKind, open}; + let bytes = std::fs::read(path).unwrap(); + let file = open(bytes.as_slice()).unwrap(); + let s = file.streams.iter().position(|s| s.kind == StreamKind::Video).unwrap(); + let stream = &file.streams[s]; + let packets = (stream.chunks.iter().enumerate()) + .map(|(i, c)| Packet { data: file.read_chunk(bytes.as_slice(), s, i).unwrap(), pts: i as i64, key: c.key }) + .collect(); + Track { params: stream.codec_params(), packets } +} + +/// Decode `packets` with `dec` and flush it. +pub fn run(dec: &mut TrackDecoder, packets: &[Packet]) -> Vec { + let mut frames = Vec::new(); + for (i, p) in packets.iter().enumerate() { + frames.extend(dec.decode(&p.data, p.pts).unwrap_or_else(|e| panic!("packet {i}: {e}"))); + } + frames.extend(dec.flush().unwrap()); + frames +} + +/// Every frame of `track`, from a new decoder. +pub fn decode(track: &Track) -> Vec { + run(&mut TrackDecoder::new(&track.params).unwrap(), &track.packets) +} + +/// The samples of `frame`, planes one after another, as ffmpeg's raw video has them: a byte per +/// sample up to 8 bits (whatever the storage; AV1 stores 8-bit samples in `u16`), else two bytes +/// little-endian. +pub fn frame_bytes(frame: &VideoFrame) -> Vec { + let mut out = Vec::new(); + for p in frame.planes() { + for y in 0..p.height() { + match p.samples() { + Samples::U8(_) => out.extend_from_slice(p.row_u8(y).unwrap()), + Samples::U16(_) if p.bit_depth() <= 8 => out.extend(p.row_u16(y).unwrap().iter().map(|&s| u8::try_from(s).unwrap())), + Samples::U16(_) => out.extend(p.row_u16(y).unwrap().iter().flat_map(|s| s.to_le_bytes())), + } + } + } + out +} + +/// `frames` are every frame of `track` in display order, each with the timestamp of the packet +/// that coded it, and their samples are ffmpeg's (within `fixture.max_diff`). +pub fn check_frames(track: &Track, frames: &[VideoFrame], fixture: &Fixture) { + let reference = &fixture.reference; + assert_eq!(frames.len(), FRAMES, "frame count"); + let got: Vec = frames.iter().map(|f| f.pts.unwrap()).collect(); + let mut want: Vec = track.packets.iter().map(|p| p.pts).collect(); + want.sort_unstable(); + assert_eq!(got, want, "timestamps in display order"); + let size = reference.len() / FRAMES; + assert_eq!(size * FRAMES, reference.len(), "reference size"); + for (i, (frame, want)) in frames.iter().zip(reference.chunks(size)).enumerate() { + assert_eq!((frame.width(), frame.height()), (176, 144), "frame {i} size"); + let got = frame_bytes(frame); + assert_eq!(got.len(), want.len(), "frame {i} bytes"); + let diff: Vec = (0..got.len()).filter(|&k| got[k] != want[k]).collect(); + let max = diff.iter().map(|&k| got[k].abs_diff(want[k])).max().unwrap_or(0); + let what = format!("frame {i} (pts {:?}): {} of {} bytes differ from ffmpeg's decode, by up to {max}", frame.pts, diff.len(), got.len()); + if fixture.max_diff == 0 { + assert!(diff.is_empty(), "{what}"); + } else { + let sse: f64 = diff.iter().map(|&k| f64::from(got[k].abs_diff(want[k])).powi(2)).sum(); + let psnr = if sse == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64.powi(2) * got.len() as f64 / sse).log10() }; + assert!(max <= fixture.max_diff && psnr >= MIN_PSNR, "{what}, PSNR {psnr:.1} dB"); + } + } +} + +/// Decode `track`, check it against `fixture`'s reference, then reset the decoder twice: once +/// halfway through, decoding the whole track again, and once to decode from its last key packet +/// (a seek), which gives the frames of the packets from there on. +pub fn check_track(track: &Track, fixture: &Fixture) { + let frames = decode(track); + check_frames(track, &frames, fixture); + + let mut dec = TrackDecoder::new(&track.params).unwrap(); + let half = track.packets.len() / 2; + for p in &track.packets[..half] { + dec.decode(&p.data, p.pts).unwrap(); + } + dec.reset().unwrap(); + assert!(run(&mut dec, &track.packets) == frames, "decoding again after a reset"); + + let key = track.packets.iter().rposition(|p| p.key).unwrap(); + assert!(key > 0, "the track has a second key packet"); + dec.reset().unwrap(); + let seek = run(&mut dec, &track.packets[key..]); + let pts: Vec = track.packets[key..].iter().map(|p| p.pts).collect(); + let want: Vec<&VideoFrame> = frames.iter().filter(|f| pts.contains(&f.pts.unwrap())).collect(); + assert!(seek.iter().eq(want.iter().copied()), "decoding from key packet {key} after a reset"); +} diff --git a/crates/video/tests/track/h264.rs b/crates/video/tests/track/h264.rs new file mode 100644 index 000000000..74a9477de --- /dev/null +++ b/crates/video/tests/track/h264.rs @@ -0,0 +1,63 @@ +//! H.264 in MP4 (an `avcC` record, length-prefixed packets), MPEG-TS (Annex B, no configuration) +//! and AVI with the parameter sets in the stream header only (an Annex B configuration). + +use crate::common; +use craft_media::CodecId; +use craft_video::{TrackDecoder, VideoError}; + +const X264: &[&str] = &["-c:v", "libx264", "-preset", "fast", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p"]; + +/// The NAL unit types of an Annex B packet. +fn nal_types(data: &[u8]) -> Vec { + craft_media::bitstream::annexb_nals(data).iter().filter_map(|n| n.first()).map(|b| b & 0x1f).collect() +} + +/// The parameter sets are in the `avcC` record only, so decoding again after a reset needs them +/// applied again. +#[test] +fn mp4_avcc() { + let Some(f) = common::fixture("h264_avcc", "mp4", X264, "yuv420p") else { return }; + let track = common::mp4(&f.file); + assert_eq!((track.params.codec, track.params.extradata.first()), (CodecId::H264, Some(&1)), "an avcC record"); + common::check_track(&track, &f); +} + +#[test] +fn ts_annex_b() { + let Some(f) = common::fixture("h264", "ts", X264, "yuv420p") else { return }; + let track = common::ts(&f.file); + assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::H264, 0)); + common::check_track(&track, &f); +} + +fn global_header_avi() -> Option<(common::Track, common::Fixture)> { + let args = ["-c:v", "libx264", "-preset", "fast", "-bf", "0", "-g", "12", "-pix_fmt", "yuv420p", "-flags", "+global_header"]; + let f = common::fixture("h264_global_header", "avi", &args, "yuv420p")?; + let track = common::avi(&f.file); + assert_eq!(track.params.codec, CodecId::H264); + assert_eq!(nal_types(&track.params.extradata).iter().filter(|&&t| t == 7 || t == 8).count(), 2, "an SPS and a PPS in the stream header"); + for (i, p) in track.packets.iter().enumerate() { + assert!(!nal_types(&p.data).contains(&7), "chunk {i} repeats the SPS"); + } + Some((track, f)) +} + +/// AVI written with global headers: the chunks need the parameter sets from the stream header. +#[test] +fn avi_annex_b_configuration() { + let Some((track, f)) = global_header_avi() else { return }; + common::check_track(&track, &f); +} + +/// Annex B configuration with the first picture's slice after the parameter sets is refused, +/// rather than decoding that picture into the reference store. +#[test] +fn annex_b_configuration_with_a_slice_is_refused() { + let Some((mut track, _)) = global_header_avi() else { return }; + track.params.extradata.extend_from_slice(&track.packets[0].data); + assert!(nal_types(&track.params.extradata).contains(&5), "an IDR slice"); + match TrackDecoder::new(&track.params) { + Err(VideoError::Malformed(m)) => assert!(m.contains("NAL unit type 5"), "{m}"), + other => panic!("{other:?}"), + } +} diff --git a/crates/video/tests/track/hevc.rs b/crates/video/tests/track/hevc.rs new file mode 100644 index 000000000..ac2cf672d --- /dev/null +++ b/crates/video/tests/track/hevc.rs @@ -0,0 +1,68 @@ +//! HEVC in MP4 (an `hvcC` record, length-prefixed packets) and MPEG-TS (Annex B, no +//! configuration), 8-bit and 10-bit. + +use crate::common; +use craft_media::CodecId; + +/// Closed GOPs every 12 frames with B-frames, so decoding from a key packet gives every frame +/// from there on. +const X265: &[&str] = &["-c:v", "libx265", "-preset", "fast", "-x265-params", "log-level=error:keyint=12:min-keyint=12:open-gop=0:bframes=2"]; + +fn args(pix_fmt: &str, mp4: bool) -> Vec<&str> { + let mut a = X265.to_vec(); + a.extend(["-pix_fmt", pix_fmt]); + if mp4 { + a.extend(["-tag:v", "hvc1"]); + } + a +} + +/// The parameter sets are in the `hvcC` record only, so decoding again after a reset needs them +/// applied again. +#[test] +fn mp4_hvcc() { + let Some(f) = common::fixture("hevc_hvcc", "mp4", &args("yuv420p", true), "yuv420p") else { return }; + let track = common::mp4(&f.file); + assert_eq!((track.params.codec, track.params.extradata.first()), (CodecId::Hevc, Some(&1)), "an hvcC record"); + common::check_track(&track, &f); +} + +#[test] +fn mp4_hvcc_10bit() { + let Some(f) = common::fixture("hevc_hvcc_10bit", "mp4", &args("yuv420p10le", true), "yuv420p10le") else { return }; + let track = common::mp4(&f.file); + let frames = common::decode(&track); + assert!(frames.iter().all(|f| f.bit_depth() == 10)); + common::check_track(&track, &f); +} + +#[test] +fn ts_annex_b() { + let Some(f) = common::fixture("hevc", "ts", &args("yuv420p", false), "yuv420p") else { return }; + let track = common::ts(&f.file); + assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::Hevc, 0)); + common::check_track(&track, &f); +} + +/// The NAL unit types of an Annex B packet. +fn nal_types(data: &[u8]) -> Vec { + craft_media::bitstream::annexb_nals(data).iter().filter_map(|n| n.first()).map(|b| (b >> 1) & 0x3f).collect() +} + +/// AVI written with global headers: the chunks need the VPS, SPS and PPS from the stream header. +/// (ffmpeg writes an empty FourCC for HEVC in AVI unless it is given one.) +#[test] +fn avi_annex_b_configuration() { + // AVI has no timestamps (a chunk's index stands in), so no B-frames. + let params = "log-level=error:keyint=12:min-keyint=12:open-gop=0:bframes=0"; + let a = ["-c:v", "libx265", "-preset", "fast", "-x265-params", params, "-pix_fmt", "yuv420p", "-flags", "+global_header", "-tag:v", "HEVC"]; + let Some(f) = common::fixture("hevc_global_header", "avi", &a, "yuv420p") else { return }; + let track = common::avi(&f.file); + assert_eq!(track.params.codec, CodecId::Hevc); + let sets = nal_types(&track.params.extradata); + assert!([32, 33, 34].iter().all(|t| sets.contains(t)), "a VPS, an SPS and a PPS in the stream header: {sets:?}"); + for (i, p) in track.packets.iter().enumerate() { + assert!(!nal_types(&p.data).contains(&33), "chunk {i} repeats the SPS"); + } + common::check_track(&track, &f); +} diff --git a/crates/video/tests/track/main.rs b/crates/video/tests/track/main.rs new file mode 100644 index 000000000..425302df4 --- /dev/null +++ b/crates/video/tests/track/main.rs @@ -0,0 +1,18 @@ +//! `TrackDecoder` on real streams: ffmpeg encodes a short clip into MP4, MPEG-TS or AVI, +//! craft-media demuxes it, and the decoder's frames must be ffmpeg's decode of the file, in display +//! order, with the timestamps of the packets that coded them. Each codec also checks that a reset +//! decodes the track again and decodes from a later key packet. +#![cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))] + +mod common; + +#[cfg(feature = "av1-decode")] +mod av1; +#[cfg(feature = "h264-decode")] +mod h264; +#[cfg(feature = "hevc-decode")] +mod hevc; +#[cfg(feature = "mpeg2-decode")] +mod mpeg2; +#[cfg(feature = "vp9-decode")] +mod vp9; diff --git a/crates/video/tests/track/mpeg2.rs b/crates/video/tests/track/mpeg2.rs new file mode 100644 index 000000000..e0fc19328 --- /dev/null +++ b/crates/video/tests/track/mpeg2.rs @@ -0,0 +1,55 @@ +//! MPEG-2 video in MPEG-TS (no configuration), and with its sequence header moved from the +//! packets into `extradata`. + +use crate::common; +use craft_media::CodecId; + +/// Closed GOPs every 12 frames with B-frames (ffmpeg's encoder needs scene change detection off +/// for closed GOPs). +const MPEG2: &[&str] = + &["-c:v", "mpeg2video", "-bf", "2", "-g", "12", "-flags", "+cgop", "-sc_threshold", "1000000000", "-q:v", "4", "-pix_fmt", "yuv420p"]; + +/// MPEG-2's IDCT is not bit-exact by definition (any IEEE 1180-accurate IDCT conforms), so the +/// frames are compared with ffmpeg's within the MPEG-2 oracle tests' tolerance. +fn fixture() -> Option<(common::Track, common::Fixture)> { + let mut f = common::fixture("mpeg2", "ts", MPEG2, "yuv420p")?; + f.max_diff = 4; + let track = common::ts(&f.file); + assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::Mpeg2Video, 0)); + Some((track, f)) +} + +/// The byte range of the sequence header and its extensions in `data`: from the sequence header +/// start code to the next start code that is not an extension. +fn sequence_header(data: &[u8]) -> Option> { + let codes: Vec<(usize, u8)> = (0..data.len().saturating_sub(3)).filter(|&i| data[i..i + 3] == [0, 0, 1]).map(|i| (i, data[i + 3])).collect(); + let k = codes.iter().position(|c| c.1 == 0xb3)?; + let end = codes[k + 1..].iter().find(|c| c.1 != 0xb5).map_or(data.len(), |c| c.0); + Some(codes[k].0..end) +} + +#[test] +fn ts() { + let Some((track, f)) = fixture() else { return }; + common::check_track(&track, &f); +} + +/// With every sequence header taken out of the packets, the one in `extradata` is what decodes +/// them, before and after a reset. +#[test] +fn sequence_header_from_extradata() { + let Some((mut track, f)) = fixture() else { return }; + let first = sequence_header(&track.packets[0].data).unwrap(); + track.params.extradata = track.packets[0].data[first].to_vec(); + for p in &mut track.packets { + while let Some(r) = sequence_header(&p.data) { + p.data.drain(r); + } + } + let mut bare = track.clone(); + bare.params.extradata.clear(); + let mut dec = craft_video::TrackDecoder::new(&bare.params).unwrap(); + let decoded = bare.packets.iter().filter_map(|p| dec.decode(&p.data, p.pts).ok()).flatten().count(); + assert_eq!(decoded, 0, "the packets decode without a sequence header"); + common::check_track(&track, &f); +} diff --git a/crates/video/tests/track/vp9.rs b/crates/video/tests/track/vp9.rs new file mode 100644 index 000000000..3fd75484c --- /dev/null +++ b/crates/video/tests/track/vp9.rs @@ -0,0 +1,14 @@ +//! VP9 in MP4 (a `vpcC` record, which the decoder does not need). + +use crate::common; +use craft_media::CodecId; + +#[test] +fn mp4() { + let args = ["-c:v", "libvpx-vp9", "-deadline", "good", "-cpu-used", "5", "-b:v", "400k", "-g", "12", "-pix_fmt", "yuv420p"]; + let Some(f) = common::fixture("vp9", "mp4", &args, "yuv420p") else { return }; + let track = common::mp4(&f.file); + assert_eq!(track.params.codec, CodecId::Vp9); + assert!(!track.params.extradata.is_empty(), "a vpcC record"); + common::check_track(&track, &f); +} diff --git a/design/layers/craft-ui-contract/contract.toml b/design/layers/craft-ui-contract/contract.toml index b39d88b37..6206cbe3c 100644 --- a/design/layers/craft-ui-contract/contract.toml +++ b/design/layers/craft-ui-contract/contract.toml @@ -3,3 +3,8 @@ config_version = 1 [[module]] path = "contract" layer = 4 + +# memo depends only on std and runtime::env, so it sits with the runtime modules that use it. +[[module]] +path = "contract::memo" +layer = 2 diff --git a/docs/contract-api.md b/docs/contract-api.md index 5dab0dbaa..b69e2aac7 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2134,7 +2134,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::MeasureCx`: `pub struct MeasureCx<'a, C: Component> { pub env: EnvView<'a>, pub style: &'a C::Style, pub resolved: &'a Resolved<'a>, pub proposal: Proposal, pub room: Option, pub ui: &'a Ui, pub tokens: &'a UiTokens, pub id: Id }`. What `measure` reads: step 5's view of the environment, the style, the resolved props and the shown value. - `pub fn value(&self) -> Option<&'a ValueOf>`. The shown value; it has the stage's lifetime, so a borrow of `cx` is not held. - `pub fn command(&self) -> Option<&ResolvedCommand>`. The bound command as step 1 resolved it, with the scoped bindings of the scopes above the component. - - `pub fn resolve_command(&self, command: impl Into) -> Option`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above + - `pub fn resolve_command(&self, command: impl Into) -> Option>`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above - `pub fn column_room(&self) -> Option`. The width a component whose height follows its width (wrapped text, a square plot) sizes at: the room the - `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a picture sizes at (a plot, a wheel, a well): it takes the room it is offered, down to `least` and up - `pub fn label(&self) -> Label`. The label as given. @@ -3107,10 +3107,12 @@ Per-pass and per-frame services and the one egui adapter. The command board: the registry and typed sets, per-frame state, the queue, firing and the gate (spec 11). - `craft_ui::runtime::commands::CommandGate`: `pub struct CommandGate`. The app's one gate over commands: a dialog is open, a workspace is not ready, a recorder has the keys or an - - `pub fn new(allows: impl Fn(&CommandRef) -> bool + Send + Sync + 'static) -> Self`. A gate that lets `allows` commands through. + - `pub fn new(props: P, allows: fn(&P, &CommandRef) -> bool) -> Self`. A gate that lets through the commands `allows` accepts under `props`; the runtime asks it once per command while the props' key stays the same. +- `craft_ui::runtime::commands::CommandStates`: `pub struct CommandStates`. The app-scope command states an app holds, in a `Tracked` it hands to `CommandInput::states`. + - `pub fn new() -> Self`, `pub fn set(&mut self, command: impl Into, state: CommandState)`, `pub fn remove(&mut self, command: &CommandRef) -> Option`, `pub fn get(&self, command: &CommandRef) -> Option<&CommandState>`. - `craft_ui::runtime::commands::CommandInput`: `pub struct CommandInput`. App-scope command state for this frame, set from app state before the pass. - `pub fn new() -> Self`. No state, no overrides and no gate. - - `pub fn state(mut self, command: impl Into, state: CommandState) -> Self`. The state of an app-scope command. + - `pub fn states(mut self, states: &Tracked) -> Self`. The app-scope command states the app holds; the runtime reads them again only when the revision moves. - `pub fn overrides(mut self, overrides: Arc) -> Self`. The user's binding overrides; the keymap is rebuilt when the `Arc` changes. - `pub fn gate(mut self, gate: CommandGate) -> Self`. The one gate over commands. - `craft_ui::runtime::commands::CommandSet`: `pub trait CommandSet: Copy + Send + Sync + 'static`. A typed set of commands, written by `#[derive(CommandSet)]`. @@ -3133,13 +3135,13 @@ The command board: the registry and typed sets, per-frame state, the queue, firi - `fn publish(&mut self, command: impl Into, state: CommandState)`. This frame's state of a scoped command, for this instance. Publishing an app-scope command here is a - `fn take_command(&mut self) -> Option<(S, Fired)>`. The next command of set `S` routed to this instance this pass; each is taken once, so a discard pass does - `fn take_step(&mut self, can_undo: bool, can_redo: bool) -> Option`. Declares Undo and Redo on the innermost instance around this context, enabled as `can_undo` and `can_redo` - - `fn resolve_command(&self, command: impl Into) -> Option`. `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above + - `fn resolve_command(&self, command: impl Into) -> Option>`. `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above - `craft_ui::runtime::commands::FirePhase`: `pub enum FirePhase { Press, Repeat, Release }`. The phase of the key press that fired a command. - `craft_ui::runtime::commands::FireSource`: `pub enum FireSource { Key, Menu, Palette, Pointer, Automation, Access }`. Where a fired command came from. - `craft_ui::runtime::commands::Fired`: `pub struct Fired { pub command: CommandRef, pub target: Option, pub source: FireSource, pub phase: FirePhase, pub cycle: bool, pub alt_variant: bool }`. A command a surface or a key fired, as the instance or the app takes it. - `craft_ui::runtime::commands::ResolvedCommand`: `pub struct ResolvedCommand { pub label: Arc, pub icon: Option>, pub chord: Option, pub enabled: bool, pub checked: Option, pub marked: bool, pub hint: Option>, pub kind: CommandKind, pub instance: Option }`. A command as a surface shows and fires it. - `craft_ui::runtime::commands::fire`: `pub fn fire(ctx: &Context, command: impl Into, source: FireSource) -> bool`. Fires `command` from a surface that has no component of its own: a menu, the palette or automation. Scoped -- `craft_ui::runtime::commands::resolve`: `pub fn resolve(ctx: &Context, command: impl Into) -> ResolvedCommand`. `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state +- `craft_ui::runtime::commands::resolve`: `pub fn resolve(ctx: &Context, command: impl Into) -> Arc`. `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state - `craft_ui::runtime::commands::Binding`: re-export of `craft_keymap::Binding` (outside these crates). - `craft_ui::runtime::commands::ChromeCommand`: `pub enum ChromeCommand { TogglePanels, TogglePanelsKeepTools }`. The `window` commands that hide the panels of the window they run in. - `pub const ALL: [ChromeCommand; 2]`. Both commands. diff --git a/docs/glossary.md b/docs/glossary.md index f49a9d90a..317b2a858 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -49,7 +49,7 @@ One row per name in the author table (Overview) and per `pub` item a component a | `CommandGate` | The one gate that can disable commands (dialog open, workspace, recorder, pending operation) | `craft_ui::runtime::commands` | 11.3 | | `Commands` | The context trait on `Cx`, `BodyCx` and `ItemCx` for commands and the clipboard | `craft_ui::runtime::commands` | 11.3 | | `CommandSet` | A typed set of commands with one scope, written by `#[derive(CommandSet)]` and read with `take_command::()` | craft-keymap (trait), `craft_ui::runtime::commands` (board) | 11.2, 11.3 | -| `CommandState`, `CommandInput` | A command's state this frame, and the app-scope states in `FrameInput.commands` | `craft_ui::runtime::commands` | 11.3 | +| `CommandState`, `CommandStates`, `CommandInput` | A command's state, the app-scope states an app holds in a `Tracked`, and the frame's command input in `FrameInput.commands` | `craft_ui::runtime::commands` | 11.3 | | `Common` | The props every component has, with no public fields | `craft_ui::contract` | 3.1 | | Component | Any type implementing the core trait | `craft_ui::contract` | 1.2 | | `ComponentStyle` | The trait every `type Style` implements, usually with `#[derive(ComponentStyle)]` | `craft_ui::style` | 4.3 | diff --git a/docs/gpu-backends.md b/docs/gpu-backends.md new file mode 100644 index 000000000..6e2246e91 --- /dev/null +++ b/docs/gpu-backends.md @@ -0,0 +1,61 @@ +# GPU backends + +| Crate | Role | +|-------|------| +| `craft-gpu` | Traits, `GpuJob`, `ProviderRegistry` | +| `craft-gpu-wgpu` | wgpu → WebGPU (wasm) / Vulkan·DX12·Metal (native) | +| `craft-gpu-null` | In-memory context for CI | + +Feature flags on `craft-gpu-wgpu`: + +- `adapter-probe`: native only; uses pollster to `request_adapter`/`request_device` and build real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no GPU, e.g. CI with no backend feature enabled). +- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles`: enable the matching wgpu backend. `adapter-probe` alone compiles the probing code but finds no adapter unless at least one of these is also on. + +## Real device, device-truth caps (RFC-0022 requirement 1) + +With `adapter-probe` and a `native-*` backend, `WgpuContext::new` calls `Adapter::request_device` after `request_adapter`, creating a real device. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()`, never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `required_features` is the adapter's features intersected with what this context asks for (currently nothing, since no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)); `required_limits` is the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. + +Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`). The host-staged `Vec>` form survives only on the no-device path. + +**The no-adapter path is still a defined path.** Without a usable adapter (`adapter-probe` off, no backend feature on, no GPU present, or `wasm32`, see below), `WgpuContext` degrades to the same in-memory staging behavior as `craft-gpu-null`. `WgpuContext::has_device()` tells a caller which path it got; `probe_caps()` (no context) stays the quick, adapter-only, advisory estimate it always was. + +**`wasm32` gap, acknowledged, not hidden.** RFC-0022 itself describes browser capability probing moving "from static defaults to real adapter queries once async initialization lands in the worker". That landing hasn't happened yet. `request_adapter`/`request_device` are JS promises. Driving them synchronously the way `pollster::block_on` does natively is unavailable on `wasm32`. Wiring the async worker-init path is a larger, separate piece of work. Until then, `WgpuContext` on `wasm32` reports the same conservative, adapter-free defaults it always has. This is the RFC's own acknowledged follow-up, not new scope invented for this PR. + +## Device loss (RFC-0022 requirement 1) + +`WgpuContext` registers `Device::set_device_lost_callback` when it creates a real device. Loss (a driver reset, OS-level eviction, or an explicit `destroy()`) surfaces as `GpuFault::DeviceLost`, from the next buffer call and from `poll_reads()`, never as a panic. + +Once a context has reported `GpuFault::DeviceLost`, every `DeviceCaps` it reported before that point is stale. The stated recovery, per the trait docs on [`GpuContext`](../crates/gpu/src/context.rs): + +1. fall back to the portable path for the rest of the session, or +2. construct a fresh `GpuContext` and re-probe `caps()` before resuming GPU jobs. + +No backend here supports continuing to dispatch jobs against a context that already reported loss, using caps read before it. + +## Async readback (RFC-0022 requirement 3) + +`GpuContext::read_buffer` used to be synchronous. WebGPU can only map a buffer asynchronously (`map_async`), so the trait's real primitives are now `request_read` (queue a readback, get a `ReadRequest`) and `poll_reads` (drain completions). This mirrors `craft-worker-host`'s own async shape: a `HostMessage::GpuJobs { batch_id, .. }` is answered later by `WorkerMessage::GpuBatchDone { batch_id, outcomes }`, not inline; `request_read`/`poll_reads` is the same split one level down, for one buffer instead of one job batch. + +`read_buffer` stays as a blocking convenience with a default body built on those two primitives, for callers that need bytes now (the CPU-stand-in providers in `craft-gpu-providers`). Both bundled backends override that default body. The default has nowhere to put completions belonging to other outstanding requests. The overrides keep those queued for the next `poll_reads`: + +- `craft-gpu-null`: overrides to take only its own completion; every request resolves immediately, with nothing to wait for. +- `craft-gpu-wgpu`, native, with a real device: overrides to block by calling `Device::poll(PollType::wait_indefinitely())` between polls. It waits on the GPU without busy-spinning the CPU, re-queuing other requests' completions. +- `craft-gpu-wgpu`, native, staging path (no device): resolves immediately, same as the null context. +- `craft-gpu-wgpu`, `wasm32`: **serves the staging read.** The only backing on this target today is the in-memory staging store, since real device creation needs the async worker-init path that has not landed. Staging reads resolve synchronously. `read_buffer` returns their bytes. Only a read that did not resolve synchronously returns `GpuFault::Operation`. That refusal will matter once a real device backing exists there: `wasm32` is single-threaded and blocking the one thread the browser needs to run `map_async`'s own completion callback on would hang the tab. A caller on a future device backing must drive `request_read` + `poll_reads` from the worker's own message loop. + +**Consumed on `craft-libs#662`.** That branch's `RuntimeContext` wrapper now forwards `request_read`, `poll_reads`, `free_buffer` and `device_status` to its inner context. It forwards `read_buffer` too, letting the inner backend's completion-preserving override apply. No logic in `craft-worker-host` or the runtime facade changed shape beyond that: `HostMessage::GpuJobs` still dispatches a whole batch synchronously today, answered per job. + +## Named consumers (RFC-0022's "what this RFC decides") + +- **First: the runtime slice**, `craft-libs#662` (`craft-worker-host`, the worker-host executing `GpuJob` batches; `craft-runtime`, the facade `RuntimeBuilder`/`Runtime` build on top of `GpuContext`). +- **Second: the render-path apps**, EffectCraft and FilmCraft. Neither has adopted these crates yet (see `docs/pilot-effectcraft.md`, `docs/pilot-filmcraft.md`); both already carry their own hand-rolled wgpu code today: + - **FilmCraft** (`storytold/filmcraft`, `crates/gpu` = `filmcraft-gpu`): a monitor/preview `GpuCompositor` over `composite.wgsl`, `mask.rs`/`mask.wgsl`, `lut.rs`/`lut.wgsl`, `transition.rs`/`transition.wgsl`, plus its own adapter-selection policy (`adapter.rs`, see device ownership below) and a separate off-screen `ExportRenderer`. The pilot doc orders `craft.mask`, `craft.lut`, `craft.transition`, then `craft.composite`/`craft.readback` as the extraction sequence into `craft-gpu-providers`. + - **EffectCraft** (`storytold/effectcraft`, `apps/effectcraft-web`): its own `store.rs`/`persist.rs`/`diskcache.rs` and dedicated-worker GPU dispatch (`worker.rs`, `frames.rs`); app-specific jobs route through `effectcraft.*` provider ids once it adopts `craft-runtime`, with the shared `craft.*` ids from this slice used alongside them. + +## Device ownership, when egui's wgpu renderer is also running + +The question that decides whether a render-path app can adopt `WgpuContext` as-is: who owns the `Device`/`Queue` when egui (via `eframe`/`egui-wgpu`) is also drawing? + +**FilmCraft's answer today is "it depends on which device."** Its on-screen monitor compositor adopts egui's own device: both the native desktop app and the web app call `app.set_wgpu(cc.wgpu_render_state.clone())` (or the equivalent on native), so the compositor draws through the exact `Device`/`Queue` `eframe`'s `RenderState` already created. One device, shared, no second adapter opened for the window. Its **export** path is deliberately the opposite: a separate, off-screen `wgpu::Device` with no surface, created once and kept for the process (`export_renderer.rs`), specifically because export runs independent of the UI's lifecycle (worker threads, no window) and must keep working even if the UI's device were ever lost or recreated. + +`WgpuContext::new` in this PR always opens its own device (or degrades to staging) and has no constructor that accepts an externally-supplied `(Device, Queue)`. That is **documented here as the named follow-up, not implemented in this PR**: accepting an existing device/queue pair (with `DeviceCaps` built from that pair, the same device-truth way `create_device` builds it today) is a small, additive constructor that does not change `GpuContext`'s trait shape, but it needs a decision this PR's scope doesn't force: whether the shared constructor should require the caller to prove the features/limits it needs were already granted (since a second caller can't call `request_device` again on a device that already exists), or whether it should accept whatever was granted and fail a job if it needs more. FilmCraft's own split (share for render, separate for export) is a reasonable default for this layer too: a render-path app wanting GPU compute on the same frame it draws with egui should share; a worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and no reason to share, and keeps its own device exactly as implemented here. diff --git a/docs/gpu-providers.md b/docs/gpu-providers.md new file mode 100644 index 000000000..a1282b8a1 --- /dev/null +++ b/docs/gpu-providers.md @@ -0,0 +1,18 @@ +# GPU providers + +Provider ids: + +- `craft.*`: shared ops in **craft-gpu-providers** (no app crate deps) +- `craft.noop`, `craft.test.echo`, `craft.mask`, `craft.composite.premul`, `craft.readback`: registered by [`register_all()`](../crates/gpu-providers/src/lib.rs) for worker/runtime init + - `craft.mask`: CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu + - `craft.composite.premul`: CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu + - `craft.readback`: CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu** +- `{app}.*`: registered by application wasm at init + +Generic worker code must only call `ProviderRegistry::dispatch`: never import app gpu crates. + +Dependency lint: **craft-gpu-providers** must not depend on `effectcraft-*`, `filmcraft-*`, or `*-engine`. + +## Readback is async underneath; these providers don't see it + +`GpuContext::read_buffer`, the method every provider above calls, is a blocking convenience over the trait's real primitives, `request_read` + `poll_reads` (see [gpu-backends.md](./gpu-backends.md)). Nothing in this crate changed for that. `craft-gpu-null` still resolves `read_buffer` immediately. `craft-gpu-wgpu`'s native path now does too, blocking on the device between polls. `crates/gpu-wgpu/src/tests.rs` runs these same providers (`craft.test.echo`, `craft.composite.premul`, `craft.readback`) against a real `WgpuContext` as well as the null one, when a real adapter is available (RFC-0022 requirement 2). A provider dispatching a real WGSL job will be the one that actually needs the non-blocking `request_read`/`poll_reads` shape directly. On `wasm32` today `read_buffer` serves the staging read, the only backing on that target. A read that did not resolve synchronously faults. A future real device backing there will refuse blocking outright, per `gpu-backends.md`. diff --git a/scripts/ci-full-validation.sh b/scripts/ci-full-validation.sh index 3b413ec88..593a3ee09 100644 --- a/scripts/ci-full-validation.sh +++ b/scripts/ci-full-validation.sh @@ -2,11 +2,11 @@ # Restore both runtime feature configurations, docs and ordinary example linking, without fuzz caps. set -euo pipefail unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES -if [ "${RUNNER_OS:-}" = Windows ]; then +if [[ "${RUNNER_OS:-}" = Windows ]]; then powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' fi # Windows cannot spawn one rustfmt command with every workspace target (#2200). -if [ "${RUNNER_OS:-}" = Windows ]; then +if [[ "${RUNNER_OS:-}" = Windows ]]; then python scripts/ci-format-workspace.py else cargo fmt --check diff --git a/scripts/ci-test-inputs.sh b/scripts/ci-test-inputs.sh index 32af3ea77..dcccec61c 100755 --- a/scripts/ci-test-inputs.sh +++ b/scripts/ci-test-inputs.sh @@ -13,7 +13,7 @@ set -euo pipefail photocraft=74330157cb601573ae4523a95bb9132822fc3918 fetcher=.test-inputs/photocraft -if [ -z "$(ls -A "$fetcher/corpus" 2>/dev/null)" ]; then +if [[ -z "$(ls -A "$fetcher/corpus" 2>/dev/null)" ]]; then rm -rf "$fetcher" mkdir -p "$fetcher" git -C "$fetcher" init --quiet diff --git a/scripts/test-full-validation.py b/scripts/test-full-validation.py index b37e979c8..f3394c1cd 100644 --- a/scripts/test-full-validation.py +++ b/scripts/test-full-validation.py @@ -26,10 +26,10 @@ COMMANDS = [ SOURCE = r""" set -euo pipefail unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES -if [ "${RUNNER_OS:-}" = Windows ]; then +if [[ "${RUNNER_OS:-}" = Windows ]]; then powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' fi -if [ "${RUNNER_OS:-}" = Windows ]; then +if [[ "${RUNNER_OS:-}" = Windows ]]; then python scripts/ci-format-workspace.py else cargo fmt --check diff --git a/scripts/test-workspace-tests.py b/scripts/test-workspace-tests.py index 484079f23..364ccf815 100644 --- a/scripts/test-workspace-tests.py +++ b/scripts/test-workspace-tests.py @@ -32,9 +32,10 @@ cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings """ TEST_SOURCE = """ -cargo nextest run --workspace --all-features --locked --profile ci +cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests +cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench cargo test --workspace --doc --all-features --locked -cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci +cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests """ WINDOWS_SETUP = """powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'""" EXPECTED_SOURCE = { @@ -90,9 +91,10 @@ COMMON = [ "clippy --workspace --all-targets --all-features --locked -- -D warnings", ] TESTS = [ - "nextest run --workspace --all-features --locked --profile ci", + "nextest run --workspace --all-features --locked --profile ci --lib --bins --tests", + "nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench", "test --workspace --doc --all-features --locked", - "nextest run -p craft-image-codecs -p craft-text --locked --profile ci", + "nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests", ] diff --git a/vendor/README.craft-reader.md b/vendor/README.craft-reader.md index 6487d1a59..405799ceb 100644 --- a/vendor/README.craft-reader.md +++ b/vendor/README.craft-reader.md @@ -42,12 +42,17 @@ Consuming workspaces need a `hayro-cmap` patch entry beside the other Hayro entr `hayro-postscript` 0.1.0 is the crates.io package (upstream revision a2354aebaf86f5ab13e5fd6b6b0521306488bf9d), the PostScript token scanner `hayro-cmap` uses -to parse the CMap streams PDFs embed. One local patch: the scanner, which does not parse +to parse the CMap streams PDFs embed. Two local patches. The scanner, which does not parse dictionaries yet, skips runs of `<<` and `>>` in a loop and returns the next object, instead of recursing once per delimiter, so a long run of `<` or `>` bytes no longer overflows the stack. Tests: `object::tests::long_open_dict_run_does_not_overflow`, `object::tests::long_close_dict_run_does_not_overflow`, `object::tests::dict_delimiters_are_skipped` -and `object::tests::nested_dict_delimiters_are_skipped`. Its `SOURCE.json` records the +and `object::tests::nested_dict_delimiters_are_skipped`. A literal string's `\ddd` escape keeps +the low eight bits of its value, as ISO 32000-2 §7.3.4.2 asks ("high-order overflow shall be +ignored"), so `\737` decodes to `0xDF` instead of being dropped; code comments label it +`Craft patch (octal overflow, craft-libs #2321)`. Tests: +`string::tests::literal_octal_overflow_keeps_the_low_eight_bits` and +`string::tests::literal_octal_short_escape_stops_at_a_non_octal_byte`. Its `SOURCE.json` records the registry hashes. Consuming workspaces need a `hayro-postscript` patch entry beside the other Hayro entries. diff --git a/vendor/hayro-postscript/SOURCE.json b/vendor/hayro-postscript/SOURCE.json index 2e4cc5a70..06e922bcc 100644 --- a/vendor/hayro-postscript/SOURCE.json +++ b/vendor/hayro-postscript/SOURCE.json @@ -8,7 +8,8 @@ "upstream_revision": "a2354aebaf86f5ab13e5fd6b6b0521306488bf9d", "upstream_directory": "hayro-postscript", "local_patches": [ - "Skip runs of `<<` and `>>` in a loop in `object::read` instead of recursing once per delimiter, so a long run cannot overflow the stack." + "Skip runs of `<<` and `>>` in a loop in `object::read` instead of recursing once per delimiter, so a long run cannot overflow the stack.", + "Keep the low eight bits of a literal string's `\\ddd` escape in `string::literal::decode_into` (ISO 32000-2 §7.3.4.2), instead of dropping an escape above `\\377`." ], "files": [ { @@ -99,7 +100,7 @@ "path": "src/string.rs", "source_sha256": "1c47947beb5ce7c56036d5b115a47e703a5a276cb9f3faf5e9b2a4304e4a518f", "source_git_blob": null, - "sha256": "1c47947beb5ce7c56036d5b115a47e703a5a276cb9f3faf5e9b2a4304e4a518f" + "sha256": "42bb4c6a7291165f3841333032f582c74145109443f9161065afc6881d2e9f2b" }, { "path": "src/string/ascii_85.rs", @@ -117,7 +118,7 @@ "path": "src/string/literal.rs", "source_sha256": "8633efbb282227512ef506d020ea69d4ef47c549ae9248e7b0d4fcefd2aaf933", "source_git_blob": null, - "sha256": "8633efbb282227512ef506d020ea69d4ef47c549ae9248e7b0d4fcefd2aaf933" + "sha256": "0feae923df7807fe671bc3d320bdcf5e1a65cb7b652aa9245b0b918376c1daf9" } ] } diff --git a/vendor/hayro-postscript/src/lib.rs b/vendor/hayro-postscript/src/lib.rs index e16d55562..b93571e04 100644 --- a/vendor/hayro-postscript/src/lib.rs +++ b/vendor/hayro-postscript/src/lib.rs @@ -60,6 +60,30 @@ impl<'a> Scanner<'a> { object::read(&mut self.reader) } + /// Parse the next object, stepping over an unreadable token if parsing fails. + pub fn parse_object_or_skip(&mut self) -> Result> { + // The whitespace and comments before the token are not the token: skipped first, they + // don't count as progress, so a token after a space fails once, not twice. + object::skip_whitespace_and_comments(&mut self.reader); + let start = self.reader.offset(); + // `object::read` reads a token starting with one of these bytes as a number. + let number = matches!( + self.reader.peek_byte(), + Some(b'.' | b'+' | b'-' | b'0'..=b'9') + ); + let read = object::read(&mut self.reader); + // A number read stops at the first byte that can't be part of a number, which may be + // inside the token; the rest of the token goes with it. + if read.is_err() && number { + self.reader.forward_while(reader::is_regular); + } + if read.is_err() && self.reader.offset() <= start { + self.reader + .jump(start.saturating_add(1).min(self.reader.data.len())); + } + read + } + /// Parse the next object as a [`Number`]. pub fn parse_number(&mut self) -> Result { match self.parse_object()? { @@ -176,4 +200,59 @@ endcmap"#; let mut scanner = Scanner::new(b"42 "); assert!(scanner.parse_name().is_err()); } + #[test] + fn parse_object_or_skip_steps_over_an_unreadable_token() { + let mut s = Scanner::new(b"/A> /B % note\n > /C"); + assert_eq!( + s.parse_object_or_skip(), + Ok(Object::Name(Name::new(b"A", true))) + ); + assert!(s.parse_object_or_skip().is_err()); + assert_eq!( + s.parse_object_or_skip(), + Ok(Object::Name(Name::new(b"B", true))) + ); + assert!(s.parse_object_or_skip().is_err()); + assert_eq!( + s.parse_object_or_skip(), + Ok(Object::Name(Name::new(b"C", true))) + ); + assert!(s.at_end()); + } + + #[test] + fn parse_object_or_skip_skips_the_rest_of_an_unreadable_number() { + let mut s = Scanner::new(b"1beginbfchar 2.5.3x 16#zz! -x /C"); + for _ in 0..4 { + assert!(s.parse_object_or_skip().is_err()); + } + assert_eq!( + s.parse_object_or_skip(), + Ok(Object::Name(Name::new(b"C", true))) + ); + assert!(s.at_end()); + } + + #[test] + fn parse_object_or_skip_does_not_read_a_failed_read_again() { + let mut s = Scanner::new(b"/A (((( x"); + assert_eq!( + s.parse_object_or_skip(), + Ok(Object::Name(Name::new(b"A", true))) + ); + assert!(s.parse_object_or_skip().is_err()); + assert!(s.at_end()); + } + + #[test] + fn parse_object_or_skip_stays_at_the_end() { + for input in [&b""[..], b" ", b">"] { + let mut s = Scanner::new(input); + for _ in 0..3 { + assert!(s.parse_object_or_skip().is_err()); + assert!(s.reader.offset() <= input.len()); + } + assert!(s.at_end()); + } + } } diff --git a/vendor/hayro-postscript/src/string.rs b/vendor/hayro-postscript/src/string.rs index ed39d57c7..26a899847 100644 --- a/vendor/hayro-postscript/src/string.rs +++ b/vendor/hayro-postscript/src/string.rs @@ -187,6 +187,21 @@ mod tests { assert_eq!(decode_literal(b"(\\3)").unwrap(), b"\x03"); } + #[test] + fn literal_octal_overflow_keeps_the_low_eight_bits() { + assert_eq!(decode_literal(b"(\\737)").unwrap(), b"\xDF"); + assert_eq!(decode_literal(b"(\\400\\777)").unwrap(), b"\x00\xFF"); + assert_eq!(decode_literal(b"(\\1234)").unwrap(), b"S4"); + } + + #[test] + fn literal_octal_short_escape_stops_at_a_non_octal_byte() { + assert_eq!( + decode_literal(b"(\\36a\\3z\\0089)").unwrap(), + b"\x1ea\x03z\x0089" + ); + } + #[test] fn literal_line_continuation_lf() { assert_eq!(decode_literal(b"(Hi \\\nthere)").unwrap(), b"Hi there"); diff --git a/vendor/hayro-postscript/src/string/literal.rs b/vendor/hayro-postscript/src/string/literal.rs index 37a15934f..be994f9f3 100644 --- a/vendor/hayro-postscript/src/string/literal.rs +++ b/vendor/hayro-postscript/src/string/literal.rs @@ -12,38 +12,26 @@ pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { b'\\' => { let next = r.read_byte()?; - if is_octal_digit(next) { - let second = r.read_byte(); - let third = r.read_byte(); - - let bytes = match (second, third) { - (Some(n1), Some(n2)) => match (is_octal_digit(n1), is_octal_digit(n2)) { - (true, true) => [next, n1, n2], - (true, _) => { - r.jump(r.offset() - 1); - [b'0', next, n1] - } - _ => { - r.jump(r.offset() - 2); - [b'0', b'0', next] - } - }, - (Some(n1), None) => { - if is_octal_digit(n1) { - [b'0', next, n1] - } else { - r.jump(r.offset() - 1); - [b'0', b'0', next] - } - } - _ => [b'0', b'0', next], - }; - - let str = core::str::from_utf8(&bytes).unwrap(); - - if let Ok(num) = u8::from_str_radix(str, 8) { - out.push(num); + if let Some(first) = octal_digit(next) { + // Craft patch (octal overflow, craft-libs #2321): read one + // to three octal digits and keep the low eight bits of + // the value. "The number ddd may consist of one, two, or + // three octal digits; high-order overflow shall be + // ignored" (ISO 32000-2 §7.3.4.2; PostScript Language + // Reference, third edition, §3.2.2), so `\737` is 0xDF. + // Previously an escape above `\377` was dropped. + let mut value = first; + for _ in 0..2 { + let Some(digit) = r.peek_byte().and_then(octal_digit) else { + break; + }; + r.forward(); + // At most 0o777 after three digits, so no overflow. + value = value * 8 + digit; } + + // Truncation to the low byte is the overflow rule above. + out.push((value & 0xFF) as u8); } else { match next { b'n' => out.push(0xA), @@ -80,6 +68,9 @@ pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { Some(()) } -fn is_octal_digit(byte: u8) -> bool { - matches!(byte, b'0'..=b'7') +fn octal_digit(byte: u8) -> Option { + match byte { + b'0'..=b'7' => Some(u16::from(byte - b'0')), + _ => None, + } }